diff --git a/.editorconfig b/.editorconfig deleted file mode 100644 index 4e80cee17b1..00000000000 --- a/.editorconfig +++ /dev/null @@ -1,42 +0,0 @@ -[*] -charset=utf-8 -end_of_line=lf -insert_final_newline=false -indent_style=space -indent_size=4 - -[{.babelrc,.stylelintrc,jest.config,.eslintrc,*.sample,*.json,*.jsb3,*.jsb2,*.bowerrc,*.js}] -indent_style=tab -indent_size=4 - -[*.feature] -indent_style=space -indent_size=2 - -[{jshint.json,*.jshintrc}] -indent_style=tab -indent_size=2 - -[{*.jscs.json,*.jscsrc}] -indent_style=tab -indent_size=2 - -[*.js.map] -indent_style=tab -indent_size=2 - -[{*.ddl,*.sql}] -indent_style=space -indent_size=2 - -[*.less] -indent_style=tab -indent_size=2 - -[*.scss] -indent_style=tab -indent_size=2 - -[{*.yaml,*.yml}] -indent_style=space -indent_size=2 diff --git a/.eslintignore b/.eslintignore deleted file mode 100644 index 3be2c555150..00000000000 --- a/.eslintignore +++ /dev/null @@ -1,19 +0,0 @@ -assets/dist -node_modules -acceptance_tests -admin_pages -caffeinated -/bin/ -/core/ -docs -languages -modules -payment_methods -public -shortcodes -tests -ui -widgets -wp-assets -coverage -assets/vendor \ No newline at end of file diff --git a/.eslintrc.js b/.eslintrc.js deleted file mode 100644 index 49aee08f2fd..00000000000 --- a/.eslintrc.js +++ /dev/null @@ -1,29 +0,0 @@ -module.exports = { - root: true, - extends: [ - './eslint/config.js', - ], - overrides: [ - { - files: [ 'test/e2e/**/*.js' ], - globals: { - page: true, - browser: true, - wp:true, - eejsdata:true, - }, - env: { - browser:true, - } - }, - { - files: [ '*.js' ], - rules: { - "react/react-in-jsx-scope": "off", - }, - globals: { - eejsdata:true - } - } - ], -}; \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index b90482216f6..00000000000 --- a/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,57 +0,0 @@ - - - -## Issue Overview - - - - -## Bug report or feature request? - -* [ ] Bug -* [ ] Feature -* [ ] Neither - - -## Environment Data: - -Version of EE: - -Version of WordPress: - -PHP Version: - -Browser used: - - -## Steps to Reproduce (for bugs) - - - - -## Expected Behaviour - - - - -## Current Behaviour - - - - -## Related Information: - diff --git a/.github/ISSUE_TEMPLATE/Bug_report.md b/.github/ISSUE_TEMPLATE/Bug_report.md deleted file mode 100644 index c5184890e38..00000000000 --- a/.github/ISSUE_TEMPLATE/Bug_report.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -name: Bug report -about: Create a report to help us improve - ---- - - - -**Describe the bug** - - -**To Reproduce** - - -**Expected behavior** - - -**Screenshots** - - -**Environment:** - - Version of Event Espresso: - - Version of WordPress: - - Browser - - PHP Version - -**Additional context** - diff --git a/.github/ISSUE_TEMPLATE/Feature_request.md b/.github/ISSUE_TEMPLATE/Feature_request.md deleted file mode 100644 index 945ef8201d1..00000000000 --- a/.github/ISSUE_TEMPLATE/Feature_request.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -name: Feature request -about: Suggest an idea for this project - ---- - - - -**Is your feature request related to a problem? Please describe.** - - -**Describe the solution you'd like** - - -**Describe alternatives you've considered** - - -**Additional context** - diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 201e0e5f1ef..00000000000 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,21 +0,0 @@ - - - - -## Problem this Pull Request solves - - -## How has this been tested - - - - -## Checklist - -* [ ] I have read the documentation relating to systems affected by this pull request, see https://github.com/eventespresso/event-espresso-core/tree/master/docs -* [ ] User input is adequately validated and sanitized -* [ ] all publicly displayed strings are internationalized (usually using `esc_html__()`, see https://codex.wordpress.org/I18n_for_WordPress_Developers) -* [ ] My code is tested. -* [ ] My code follows the Event Espresso code style. -* [ ] My code has proper inline documentation. -* [ ] My code accounts for when the site is in Maintenance Mode (MM2 especially disallows usage of models) diff --git a/.github/codecov.yml b/.github/codecov.yml deleted file mode 100644 index 83afcb7af6e..00000000000 --- a/.github/codecov.yml +++ /dev/null @@ -1,9 +0,0 @@ -coverage: - status: - project: - default: - target: auto - threshold: 0.5% - patch: no - -comment: off \ No newline at end of file diff --git a/.github/config.yml b/.github/config.yml deleted file mode 100644 index e54e75aa079..00000000000 --- a/.github/config.yml +++ /dev/null @@ -1,15 +0,0 @@ -# Configuration for request-info - https://github.com/behaviorbot/request-info - -# *Required* Comment to reply with -requestInfoReplyComment: > - We need more info before we can work on this issue/pr. Can you elaborate please? - -# *OPTIONAL* default titles to check against for lack of descriptiveness -# MUST BE ALL LOWERCASE -requestInfoDefaultTitles: - - update readme.md - - updates - - help - -# *OPTIONAL* Label to be added to Issues and Pull Requests with insufficient information given -requestInfoLabelToAdd: status:needs-more-info \ No newline at end of file diff --git a/.github/label-sync.yml b/.github/label-sync.yml deleted file mode 100644 index 0e449092fef..00000000000 --- a/.github/label-sync.yml +++ /dev/null @@ -1,318 +0,0 @@ -# github label sync configuration file for EE repos -# install `https://github.com/Xiphe/github-sync-labels-milestones` -- repositories: - - eventespresso/event-espresso-core - - eventespresso/ee4-events-calendar - - eventespresso/eea-authnet-accept - - eventespresso/eea-stripe-gateway - - eventespresso/eea-wait-lists - - eventespresso/eea-barcode-scanner - - eventespresso/eea-attendee-mover - - eventespresso/eea-wpuser-integration - - eventespresso/eea-mailchimp - - eventespresso/eea-gutenberg - - eventespresso/eea-people-addon - - eventespresso/ee4-infusionsoft - - eventespresso/ee4-promotions - - eventespresso/eea-ticketing - - eventespresso/eea-beaver-builder - - eventespresso/eea-flexible-payment-method - - eventespresso/ee4-mer - - eventespresso/eea-affiliatewp - - eventespresso/eea-payment-methods-pro - - eventespresso/eea-automated-upcoming-event-notifications - - eventespresso/eea-buddypress - - eventespresso/eea-events-blog - - eventespresso/eea-chase-orbital - - eventespresso/eea-vanco-pm - - eventespresso/eea-authnet-sim - - eventespresso/eventsmart.com-website - - eventespresso/eea-ipay88-gateway - - eventespresso/eea-calendar-table-template - - eventespresso/eea-category-accordian-template - - eventespresso/eea-events-grid-view-template - - eventespresso/eea-aim-echeck - - eventespresso/eea-braintree-gateway - - eventespresso/eea-evertec - - eventespresso/eea-ideal-mollie-gateway - - eventespresso/eea-migs-payment-method - - eventespresso/eea-payflow-pro-gateway - - eventespresso/eea-recurring-events-manager - - eventespresso/eea-events-table-template - - eventespresso/eea-social-buttons - - eventespresso/eea-paygov-payment-method - - eventespresso/eea-multisite - - eventespresso/connect-oauth-middleman - - eventespresso/eventespresso.com-website - - eventespresso/eea-transfirst-gateway - - eventespresso/eea-sage-pay-gateway - - eventespresso/eea-quickbooks-gateway - - eventespresso/eea-omise-payment-method - - eventespresso/eea-firstdata-payeezy - - eventespresso/eea-cybersource-gateway - - eventespresso/eea-chase-orbital - - eventespresso/eea-event-app-customization - - eventespresso/grunt-wp-plugin-buildmachine - - eventespresso/eea-paypal-smart-buttons - - eventespresso/event-espresso-private - - eventespresso/eea-attendee-importer - milestones: [] - labels: - # status labels - - name: "status:needs-documentation" - color: 3297c3 - - name: "status:backlog" - color: 5c7145 - - name: "status:on-hold" - color: 4f4a33 - - name: "status:waiting-refresh" - color: 2460a7 - - name: "status:in-progress" - color: 93b343 - - name: "status:next" - color: 5c7145 - - name: "status:needs-testing" - color: eb4f21 - - name: "status:merge" - color: 66b3aa - - name: "status:review" - color: f7d500 - - name: "status:feedback-needed" - color: a16ec6 - - name: "status:needs-more-info" - color: e47e33 - - name: "status:add-sales-page" - color: 9ddde4 - - name: "status: duplicate?" - color: e5ff00 - previousNames: - - status:duplicate - - duplicate - - name: "status:stale" - color: a08e58 - - name: "status:unit-tests-required" - color: 9ddde4 - - name: "status:triage" - color: f06291 - previousNames: - - "triage" - - name: "status:please-fix" - color: c52e75 - - name: "status:potential-duplicate" - color: c2d800 - previousNames: - - "potential-duplicate" - # category labels - - name: "category:security" - color: abc2c1 - - name: "category:assets" - color: abc2c1 - previousNames: - - assets - - name: "category:payment-methods" - color: abc2c1 - previousNames: - - "category:payment-methods-&-gateways" - - name: "category:admin-pages" - color: abc2c1 - previousNames: - - "category:admin-pages-&-functionality" - - name: "category:spco-&-registration" - color: abc2c1 - - name: "category:core-plugin" - color: abc2c1 - - name: "category:frontend-ui-&-ux" - color: abc2c1 - - name: "category:admin-page-ui-&-ux" - color: abc2c1 - - name: "category:messaging-&-messengers" - color: abc2c1 - - name: "category:i18n" - color: abc2c1 - previousNames: - - i18n - - name: "category:templates-shortcodes-and-widgets" - color: abc2c1 - - name: "category:models-and-data-infrastructure" - color: abc2c1 - - name: "category:general" - color: abc2c1 - - name: "category:activation-installation-and-migration" - color: abc2c1 - - name: "category:wp-multi-site" - color: abc2c1 - - name: "category:3rd-party-integrations" - color: abc2c1 - - name: "category:decision-analytics" - color: abc2c1 - - name: "category:pue-uxip-and-licensing" - color: abc2c1 - - name: "category:unit-tests" - color: abc2c1 - - name: "category:forms-systems" - color: abc2c1 - - name: "category:reports-exporting-importing" - color: abc2c1 - - name: "category:user-management" - color: abc2c1 - - name: "category:accessibility" - color: abc2c1 - - name: "category:command-bus" - color: abc2c1 - previousNames: - - "category:command-bus-and-command-handlers" - - name: "category:gutenberg" - color: abc2c1 - previousNames: - - gutenberg - - name: "category:has-codebase-ticket" - color: abc2c1 - previousNames: - - has codebase ticket - - name: "category:community-contribution" - color: abc2c1 - previousNames: - - community-contribution - # priority labels - - name: "priority:critical ๐Ÿ”ฅ" - color: b60205 - previousNames: - - "priority:critical" - - name: "priority:high" - color: f7d500 - - name: "priority:normal" - color: 93b343 - - name: "priority:low" - color: 9ddde4 - # type labels - - name: "type:support ๐Ÿ†˜" - color: efefef - previousNames: - - "type:support" - - name: "type:bug ๐Ÿž" - color: efefef - previousNames: - - bug - - "type:bug" - - "type:bug ๐Ÿ›" - - name: "type:build-process ๐Ÿ”จ" - color: efefef - previousNames: - - build-process - - "type:build-process" - - name: "type:code-quality ๐Ÿ‘พ" - color: efefef - - name: "type:edge-case โš " - color: efefef - - name: "type:enhancement ๐ŸŽ‰" - color: efefef - previousNames: - - enhancement - - "type:enhancement" - - name: "type:task ๐Ÿงน" - color: efefef - previousNames: - - "type:task โœ…" - - "type:task" - - name: "type:feature-request ๐Ÿ™" - color: efefef - previousNames: - - feature request - - "type:feature-request" - - name: "type:documentation ๐Ÿ“–" - color: efefef - previousNames: - - documentation - - "type:documentation" - - name: "type:design ๐Ÿ“" - color: efefef - previousNames: - - "type:design" - - name: "type:user-proofing ๐Ÿ›ก" - color: efefef - previousNames: - - "type:user-proofing" - - name: "type:theme/plugin-conflict ๐Ÿ’ฅ" - color: efefef - previousNames: - - "type:theme/plugin-conflict" - - name: "type:question โ“" - color: efefef - previousNames: - - question - - "type:question" - - name: "type:invalid ๐Ÿฆ„" - color: efefef - previousNames: - - invalid - - "type:invalid" - - "type-invalid ๐Ÿฆ„" - - name: "type:impacts-eventsmart ๐ŸŽซ" - color: 00f2ff - previousNames: - - "type:impacts-eventsmart" - - name: "requires:WP5.0+ ๐Ÿงฉ" - color: 2a1f78 - ## depends-on-labels - - name: "requires:WP5.0 ๐Ÿงฉ" - color: 2a1f78 - previousNames: - - requires:WP5.0+ ๐Ÿงฉ - - name: "requires:WP5.2 ๐Ÿงฉ" - color: 2a1f78 - - name: "EZ" - color: 91ff50 - options: - ignoreMilestones: - - eventespresso/event-espresso-core - - eventespresso/ee4-events-calendar - - eventespresso/eea-authnet-accept - - eventespresso/eea-stripe-gateway - - eventespresso/eea-wait-lists - - eventespresso/eea-barcode-scanner - - eventespresso/eea-attendee-mover - - eventespresso/eea-wpuser-integration - - eventespresso/eea-mailchimp - - eventespresso/eea-gutenberg - - eventespresso/eea-people-addon - - eventespresso/ee4-infusionsoft - - eventespresso/ee4-promotions - - eventespresso/eea-ticketing - - eventespresso/eea-beaver-builder - - eventespresso/eea-flexible-payment-method - - eventespresso/ee4-mer - - eventespresso/eea-affiliatewp - - eventespresso/eea-payment-methods-pro - - eventespresso/eea-automated-upcoming-event-notifications - - eventespresso/eea-buddypress - - eventespresso/eea-events-blog - - eventespresso/eea-chase-orbital - - eventespresso/eea-vanco-pm - - eventespresso/eea-authnet-sim - - eventespresso/eventsmart.com-website - - eventespresso/eea-ipay88-gateway - - eventespresso/eea-calendar-table-template - - eventespresso/eea-category-accordian-template - - eventespresso/eea-events-grid-view-template - - eventespresso/eea-aim-echeck - - eventespresso/eea-braintree-gateway - - eventespresso/eea-evertec - - eventespresso/eea-ideal-mollie-gateway - - eventespresso/eea-migs-payment-method - - eventespresso/eea-payflow-pro-gateway - - eventespresso/eea-recurring-events-manager - - eventespresso/eea-events-table-template - - eventespresso/eea-social-buttons - - eventespresso/eea-paygov-payment-method - - eventespresso/eea-multisite - - eventespresso/connect-oauth-middleman - - eventespresso/eventespresso.com-website - - eventespresso/eea-transfirst-gateway - - eventespresso/eea-sage-pay-gateway - - eventespresso/eea-quickbooks-gateway - - eventespresso/eea-omise-payment-method - - eventespresso/eea-firstdata-payeezy - - eventespresso/eea-cybersource-gateway - - eventespresso/eea-chase-orbital - - eventespresso/eea-event-app-customization - - eventespresso/grunt-wp-plugin-buildmachine \ No newline at end of file diff --git a/.github/potential-duplicates.yml b/.github/potential-duplicates.yml deleted file mode 100644 index 8c219e7b406..00000000000 --- a/.github/potential-duplicates.yml +++ /dev/null @@ -1,13 +0,0 @@ -# Label name and color to set, when potential duplicates are detected -issueLabel: "status:potential-duplicate" -labelColor: efd954 - -# If similarity is higher than this threshold, issue will be marked as duplicate -threshold: 0.8 - -# Comment to post when potential duplicates are detected -referenceComment: > - Potential duplicates: - {{#issues}} - - [#{{ number }}] {{ title }} ({{ accuracy }}%) - {{/issues}} diff --git a/.github/stale.yml b/.github/stale.yml deleted file mode 100644 index 1776a1430d6..00000000000 --- a/.github/stale.yml +++ /dev/null @@ -1,20 +0,0 @@ -# Number of days of inactivity before an issue becomes stale -daysUntilStale: 120 -# Number of days of inactivity before a stale issue is closed -daysUntilClose: 14 -# Issues with these labels will never be considered stale -exemptLabels: - - category:security - - status:on-hold - -# Label to use when marking an issue as stale -staleLabel: status:stale -# Comment to post when marking an issue as stale. Set to `false` to disable -markComment: > - This issue has been automatically marked as stale because it has not had - recent activity. It will be closed if no further activity occurs. Thank you - for your contributions. -# Comment to post when closing a stale issue. Set to `false` to disable -closeComment: > - This issue has been automatically closed because it has been stale for a - significant period of time without any activity. \ No newline at end of file diff --git a/.github/support.yml b/.github/support.yml deleted file mode 100644 index a2f91613495..00000000000 --- a/.github/support.yml +++ /dev/null @@ -1,14 +0,0 @@ -# Configuration for support-requests - https://github.com/dessant/support-requests - -# Label used to mark issues as support requests -supportLabel: category:support -# Comment to post on issues marked as support requests. Add a link -# to a support page, or set to `false` to disable -supportComment: > - We use the issue tracker exclusively for bug reports and feature requests. - However, this issue appears to be a support request. Please use our - [support forums](https://eventespresso/support/forums) to get help with the project. -# Whether to close issues marked as support requests -close: true -# Whether to lock issues marked as support requests -lock: false \ No newline at end of file diff --git a/.github/triage.yml b/.github/triage.yml deleted file mode 100644 index 0d13af855b5..00000000000 --- a/.github/triage.yml +++ /dev/null @@ -1,3 +0,0 @@ -label: "status:triage" -assignee: tn3rb -enabled: true \ No newline at end of file diff --git a/.nvmrc b/.nvmrc deleted file mode 100644 index 1a2f5bd2045..00000000000 --- a/.nvmrc +++ /dev/null @@ -1 +0,0 @@ -lts/* \ No newline at end of file diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index b64e1004d98..00000000000 --- a/.travis.yml +++ /dev/null @@ -1,144 +0,0 @@ -dist: xenial - -os: linux - -language: php - -services: - - mysql - -cache: - apt: true - directories: - - $HOME/.composer/cache - - $HOME/.npm - -env: - global: - - WP_VERSION=latest WP_MULTISITE=0 - -before_install: - - npm install npm@^6.13 -g - - | - if [[ "$SKIP_XDEBUG_REMOVE" != "true" ]]; then - cp $HOME/.phpenv/versions/$(phpenv global)/etc/conf.d/xdebug.ini /tmp - phpenv config-rm xdebug.ini - echo "xdebug removed"; - fi -before_script: - - bash tests/bin/install-wp-tests.sh wordpress_test root '' localhost $WP_VERSION - - export PATH="$HOME/.composer/vendor/bin:$PATH" - - | - # Install the specified version of PHPUnit depending on the PHP version: - if [[ -n "$TRAVIS_PHP_VERSION" ]]; then - case "$TRAVIS_PHP_VERSION" in - 7.3|7.4|nightly) - # when wp tests support phpunit 7 we'll update this. - echo "Using PHPUnit 6" - composer global require "phpunit/phpunit=6.5.*" - ;; - 7.2|7.1|7.0) - echo "Using PHPUnit 6" - composer global require "phpunit/phpunit=6.5.*" - ;; - 5.6) - echo "Using PHPUnit 5.7.22" - composer global require "phpunit/phpunit=5.7.22" - ;; - *) - echo "No PHPUnit version handling for PHP version $TRAVIS_PHP_VERSION" - exit 1 - ;; - esac - fi - - mysql --version - - phpunit --version - - phpenv versions - - npm --version - - node --version - -script: npm run test-php - -jobs: - fast_finish: true - allow_failures: - - php: nightly - - php: 7.4 - env: - - PHP_LINT=1 - - PHP_LINT_WITH_WARNINGS=yes - include: - - stage: test - language: node_js - node_js: 11.0.0 - env: - - JS_LINT=1 - before_script: - - npm --version - - node --version - script: - - npm run ci:lint || exit 1 - - language: node_js - node_js: 11.0.0 - env: - - JAVASCRIPT_TESTS=1 - before_script: - - npm --version - - node --version - script: - - npm run ci:test || exit 1 - - language: node_js - node_js: 11.0.0 - env: - - BUILD_TEST=1 - before_script: - - npm --version - - node --version - script: - - npm run ci:build || exit 1 - - php: 7.3 - if: NOT commit_message =~ js_only AND NOT commit_message =~ dependabot AND NOT sender =~ dependabot - env: - - PHP_LINT=1 - - PHP_LINT_WITH_WARNINGS=no - script: - - composer install || exit 1 - - composer config-eventespressocs || exit 1 - - npm run lint-php:skip-warnings || exit 1 - - php: 7.4 - if: NOT commit_message =~ js_only AND NOT commit_message =~ dependabot AND NOT sender =~ dependabot - - php: 7.3 - if: NOT commit_message =~ js_only AND NOT commit_message =~ dependabot AND NOT sender =~ dependabot - - php: 7.2 - if: NOT commit_message =~ js_only AND NOT commit_message =~ dependabot AND NOT sender =~ dependabot - - php: 7.1 - if: NOT commit_message =~ js_only AND NOT commit_message =~ dependabot AND NOT sender =~ dependabot - - php: 7.0 - if: NOT commit_message =~ js_only AND NOT commit_message =~ dependabot AND NOT sender =~ dependabot - - php: 5.6 - if: NOT commit_message =~ js_only AND NOT commit_message =~ dependabot AND NOT sender =~ dependabot - # multisite - - php: 7.2 - env: WP_MULTISITE=1 - if: NOT commit_message =~ js_only AND NOT commit_message =~ dependabot AND NOT sender =~ dependabot - - php: nightly - if: NOT commit_message =~ js_only AND NOT commit_message =~ dependabot AND NOT sender =~ dependabot - - language: node_js - node_js: 11.0.0 - env: - - LICENSE_CHECK=1 - before_script: - - npm --version - - node --version - script: - - npm run lc || exit 1 - -notifications: - slack: - rooms: - secure: e2xmbwOoagh/rZIqUnx15HcTv5hZGxykvg8Tj0ENGi/bLcXgrEYxs2hpW+nzGggmSl22Eh+6wLRo62L0dEIIo1n+yknqDdAbVG7lmnX7Tc45JNgxWtSmAPzC3wAp0e9w1hy8HILPjYLxl0G7eXUvo3mKVRCCyD/Cyz5dDicE8tQ= - on_success: change - on_failure: always - template: - - "Build <%{build_url}|#%{build_number}> (<%{compare_url}|%{commit}>) of %{repository}@%{branch} by %{author} %{result} in %{duration}" - - "%{commit_message}" diff --git a/acceptance_tests/Helpers/BaseCoreAdmin.php b/acceptance_tests/Helpers/BaseCoreAdmin.php deleted file mode 100644 index 65680a468e7..00000000000 --- a/acceptance_tests/Helpers/BaseCoreAdmin.php +++ /dev/null @@ -1,84 +0,0 @@ -actor()->amOnAdminPage(CoreAdmin::adminUrl($page, $action, $additional_params)); - } - - - /** - * Helper method for returning an instance of the Actor. Intended to help with IDE fill out of methods. - * @return \EventEspressoAcceptanceTester; - */ - protected function actor() - { - /** @var \EventEspressoAcceptanceTester $this */ - return $this; - } - - - /** - * Use this to set the per page option for a list table page. - * Assumes you are on a page that has this field exposed. - * - * @param int|string $per_page_value - * @throws \Codeception\Exception\TestRuntimeException - */ - public function setPerPageOptionForScreen($per_page_value) - { - $this->actor()->click(CoreAdmin::WP_SCREEN_SETTINGS_LINK_SELECTOR); - $this->actor()->fillField(CoreAdmin::WP_SCREEN_SETTINGS_PER_PAGE_FIELD_SELECTOR, $per_page_value); - $this->actor()->click(CoreAdmin::WP_SCREEN_OPTIONS_APPLY_SETTINGS_BUTTON_SELECTOR); - $this->actor()->wait(8); - } - - - - /** - * Use this to append a given value to a wpEditor instance. - * How it works is it first switched the instance to the text (or html) view so that the textarea is exposed and - * the value is added to the text area. - * - * @param $field_reference - * @param $value - * @throws \Codeception\Exception\ElementNotFound - */ - public function appendToWPEditorField($field_reference, $value) - { - $this->actor()->click(CoreAdmin::wpEditorTextTabSelector($field_reference)); - $this->actor()->appendField(CoreAdmin::wpEditorTextAreaSelector($field_reference), $value); - } - - - /** - * Use to select and submit the given bulk action. - * @param string $bulk_action_option - */ - public function submitBulkActionOnListTable($bulk_action_option) - { - $this->actor()->selectOption( - CoreAdmin::SELECTOR_LIST_TABLE_BULK_ACTION_FIELD, - $bulk_action_option - ); - $this->actor()->click(CoreAdmin::SELECTOR_LIST_TABLE_BULK_ACTTION_APPLY); - } -} diff --git a/acceptance_tests/Helpers/Checkout.php b/acceptance_tests/Helpers/Checkout.php deleted file mode 100644 index 052511459b2..00000000000 --- a/acceptance_tests/Helpers/Checkout.php +++ /dev/null @@ -1,87 +0,0 @@ -actor()->fillField(CheckoutPage::firstNameFieldSelectorForAttendeeNumber($attendee_number, $admin), $value); - } - - /** - * @param $value - * @param int $attendee_number - * @param bool $admin Used to indicate whether we're filling out the field from the context of the admin or not. - */ - public function fillOutLastNameFieldForAttendee($value, $attendee_number = 1, $admin = false) - { - $this->actor()->fillField(CheckoutPage::lastNameFieldSelectorForAttendeeNumber($attendee_number, $admin), $value); - } - - /** - * @param $value - * @param int $attendee_number - * @param bool $admin Used to indicate whether we're filling out the field from the context of the admin or not. - */ - public function fillOutEmailFieldForAttendee($value, $attendee_number = 1, $admin = false) - { - $this->actor()->fillField(CheckoutPage::emailFieldSelectorForAttendeeNumber($attendee_number, $admin), $value); - } - - - /** - * Clicks the next registration step button. - */ - public function goToNextRegistrationStep() - { - $this->actor()->click(CheckoutPage::NEXT_STEP_BUTTON_SELECTOR); - } - - - /** - * Selects the payment option for the given payment method slug. - * - * @param string $payment_method_slug - * @param bool $verify_selected If true, this will wait for the "Important Information" info box after the - * payment option select box is complete. Otherwise its up to calling code to - * wait for whatever is needed after selecting the payment method. - */ - public function selectPaymentOptionFor($payment_method_slug = 'invoice', $verify_selected = true) - { - $this->waitForElementVisible(CheckoutPage::SELECTOR_PAYMENT_OPTIONS_CONTAINER); - $this->wait(5); - $this->actor()->selectOption( - CheckoutPage::PAYMENT_METHOD_STEP_FORM, - $payment_method_slug - ); - if ($verify_selected) { - $this->actor()->waitForText('Important information regarding your payment'); - } - } - - - /** - * Submits the payment options step form. - * Assumes the actor is in the context of the payment options SPCO step. - */ - public function submitPaymentOptionsRegistrationStepForm() - { - $this->actor()->submitForm(CheckoutPage::PAYMENT_METHOD_STEP_FORM, array()); - } - -} \ No newline at end of file diff --git a/acceptance_tests/Helpers/CountrySettingsAdmin.php b/acceptance_tests/Helpers/CountrySettingsAdmin.php deleted file mode 100644 index 1403a01cc1d..00000000000 --- a/acceptance_tests/Helpers/CountrySettingsAdmin.php +++ /dev/null @@ -1,64 +0,0 @@ -actor()->amOnAdminPage(CountrySettings::url($additional_params)); - } - - - /** - * Instructs the actor to select the given decimal places radio option. - * Assumes the actor is already on the country settings page. - * @param string $decimal_places - * @param string $country_code - */ - public function setCurrencyDecimalPlacesTo($decimal_places = '2', $country_code = 'US') - { - $this->actor()->click(CountrySettings::currencyDecimalPlacesRadioField($decimal_places, $country_code)); - } - - - /** - * Instructs the actor to select the given decimal mark radio option. - * Assumes the actor is already on the country settings page. - * @param string $decimal_mark - */ - public function setCurrencyDecimalMarkTo($decimal_mark = '.') - { - $this->actor()->click(CountrySettings::currencyDecimalMarkRadioField($decimal_mark)); - } - - - /** - * Instructs the actor to select the given thousands separator radio option. - * Assumes the actor is already on the country settings page. - * @param string $thousands_seperator - */ - public function setCurrencyThousandsSeparatorTo($thousands_seperator = ',') - { - $this->actor()->click(CountrySettings::currencyThousandsSeparatorField($thousands_seperator)); - } - - - /** - * Clicks the country settings submit button. - * Assumes the actor is on the country settings admin page. - */ - public function saveCountrySettings() - { - $this->actor()->click(CountrySettings::COUNTRY_SETTINGS_SAVE_BUTTON); - //no indicator on the page when stuff has been updated so just give a bit of time for it to finish. - $this->actor()->wait(10); - } -} \ No newline at end of file diff --git a/acceptance_tests/Helpers/EventsAdmin.php b/acceptance_tests/Helpers/EventsAdmin.php deleted file mode 100644 index e1e7cb1f012..00000000000 --- a/acceptance_tests/Helpers/EventsAdmin.php +++ /dev/null @@ -1,146 +0,0 @@ -actor()->amOnAdminPage(EventsPage::defaultEventsListTableUrl($additional_params)); - } - - - /** - * Triggers the publishing of the Event. - */ - public function publishEvent() - { - $this->actor()->scrollTo(EventsPage::EVENT_EDITOR_TITLE_FIELD_SELECTOR); - $this->actor()->wait(3); - $this->actor()->click(EventsPage::EVENT_EDITOR_PUBLISH_BUTTON_SELECTOR); - $this->actor()->waitForText('Event published.', 30); - } - - - /** - * Triggers saving the Event. - */ - public function saveEvent() - { - $this->actor()->scrollTo(EventsPage::EVENT_EDITOR_TITLE_FIELD_SELECTOR); - $this->actor()->wait(2); - $this->actor()->click(EventsPage::EVENT_EDITOR_SAVE_BUTTON_SELECTOR); - } - - - /** - * Navigates the actor to the event list table page and will attempt to edit the event for the given title. - * First this will search using the given title and then attempt to edit from the results of the search. - * - * Assumes actor is already logged in. - * @param $event_title - */ - public function amEditingTheEventWithTitle($event_title) - { - $this->amOnDefaultEventsListTablePage(); - $this->actor()->fillField(EventsPage::EVENT_LIST_TABLE_SEARCH_INPUT_SELECTOR, $event_title); - $this->actor()->click(CoreAdmin::LIST_TABLE_SEARCH_SUBMIT_SELECTOR); - $this->actor()->waitForText($event_title, 15); - $this->actor()->click(EventsPage::eventListTableEventTitleEditLinkSelectorForTitle($event_title)); - } - - - /** - * Navigates the user to the single event page (frontend view) for the given event title via clicking the "View" - * link for the event in the event list table. - * Assumes the actor is already logged in and on the Event list table page. - * - * @param string $event_title - */ - public function amOnEventPageAfterClickingViewLinkInListTableForEvent($event_title) - { - $this->actor()->moveMouseOver(EventsPage::eventListTableEventTitleEditLinkSelectorForTitle($event_title)); - $this->actor()->click(EventsPage::eventListTableEventTitleViewLinkSelectorForTitle($event_title)); - } - - - /** - * Used to retrieve the event id for the event via the list table and for the given event. - * @param string $event_title - */ - public function observeEventIdInListTableForEvent($event_title) - { - return $this->actor()->observeValueFromInputAt(EventsPage::eventListTableEventIdSelectorForTitle($event_title)); - } - - - /** - * This performs the click action on the gear icon that triggers the advanced settings view state. - * Assumes the actor is already logged in and editing an event. - * - * @param int $row_number What ticket row to toggle open/close. - */ - public function toggleAdvancedSettingsViewForTicketRow($row_number = 1) - { - $this->actor()->click(EventsPage::eventEditorTicketAdvancedDetailsSelector($row_number)); - } - - - /** - * Toggles the TKT_is_taxable checkbox for the ticket in the given row. - * Assumes the actor is already logged in and editing an event and that the advanced settings view state for that - * ticket is "open". - * - * @param int $row_number What ticket row to toggle the checkbox for. - */ - public function toggleTicketIsTaxableForTicketRow($row_number = 1) - { - $this->actor()->click(EventsPage::eventEditorTicketTaxableCheckboxSelector($row_number)); - } - - - /** - * Use to change the default registration status for the event. - * Assumes the view is already on the event editor. - * @param $registration_status - */ - public function changeDefaultRegistrationStatusTo($registration_status) - { - $this->actor()->selectOption( - EventsPage::EVENT_EDITOR_DEFAULT_REGISTRATION_STATUS_FIELD_SELECTOR, - $registration_status - ); - } - - - /** - * Use this from the context of the event editor to select the given custom template for a given message type and - * messenger. - * - * @param string $message_type_label The visible label for the message type (eg Registration Approved) - * @param string $messenger_slug The slug for the messenger (eg 'email') - * @param string $custom_template_label The visible label in the select input for the custom template you want - * selected. - */ - public function selectCustomTemplateFor($message_type_label, $messenger_slug, $custom_template_label) - { - $this->actor()->click(EventsPage::eventEditorNotificationsMetaBoxMessengerTabSelector($messenger_slug)); - $this->actor()->selectOption( - EventsPage::eventEditorNotificationsMetaBoxSelectSelectorForMessageType($message_type_label), - $custom_template_label - ); - } -} \ No newline at end of file diff --git a/acceptance_tests/Helpers/MessagesAdmin.php b/acceptance_tests/Helpers/MessagesAdmin.php deleted file mode 100644 index 593d460852b..00000000000 --- a/acceptance_tests/Helpers/MessagesAdmin.php +++ /dev/null @@ -1,303 +0,0 @@ -actor()->amOnAdminPage(MessagesPage::messageActivityListTableUrl($additional_params)); - } - - /** - * @param string $additional_params Any additional request parameters for the generated url should be included as - * a string. - */ - public function amOnDefaultMessageTemplateListTablePage($additional_params = '') - { - $this->actor()->amOnAdminPage(MessagesPage::defaultMessageTemplateListTableUrl($additional_params)); - } - - - /** - * @param string $additional_params Any additional request parameters for the generated url should be included as - * a string. - */ - public function amOnCustomMessageTemplateListTablePage($additional_params = '') - { - $this->actor()->amOnAdminPage(MessagesPage::customMessageTemplateListTableUrl($additional_params)); - } - - - /** - * Directs to message settings page - */ - public function amOnMessageSettingsPage() - { - $this->actor()->amOnAdminPage(MessagesPage::messageSettingsUrl()); - } - - - public function activateMessageTypeForMessenger($message_type_slug, $messenger_slug = 'email') - { - $this->actor()->dragAndDrop( - MessagesPage::draggableSettingsBoxSelectorForMessageTypeAndMessenger($message_type_slug, $messenger_slug), - MessagesPage::MESSAGES_SETTINGS_ACTIVE_MESSAGE_TYPES_CONTAINER_SELECTOR - ); - } - - - /** - * Assumes you are already on the list table page that has the ui for editing the template. - * @param string $message_type_slug - * @param string $context [optional] if you want to click directly to the given context in the editor - */ - public function clickToEditMessageTemplateByMessageType($message_type_slug, $context = '') - { - $this->actor()->click(MessagesPage::editMessageTemplateClassByMessageType($message_type_slug, $context)); - } - - - /** - * Use this action to verify that the count for the given text in the specified field is as expected. For example - * filling the condition of, "There should only be 1 instance of `someaddress@email.com` in all the 'to' column. - * - * @param int $expected_occurence_count - * @param string $text_to_check_for - * @param string $field - * @param string $message_type_label - * @param string $message_status - * @param string $messenger - * @param string $context - */ - public function verifyMatchingCountofTextInMessageActivityListTableFor( - $expected_occurence_count, - $text_to_check_for, - $field, - $message_type_label, - $message_status = MessagesPage::MESSAGE_STATUS_SENT, - $messenger = 'Email', - $context = 'Event Admin' - ) { - $elements = $this->actor()->grabMultiple(MessagesPage::messagesActivityListTableCellSelectorFor( - $field, - $message_type_label, - $message_status, - $messenger, - $context, - $text_to_check_for, - 0 - )); - $actual_count = count($elements); - $this->actor()->assertEquals( - $expected_occurence_count, - $actual_count, - sprintf( - 'Expected %s of the %s text for the %s field but there were actually %s counted.', - $expected_occurence_count, - $text_to_check_for, - $field, - $actual_count - ) - ); - } - - - /** - * This will create a custom message template for the given messenger and message type from the context of the - * default (global) message template list table. - * Also takes care of verifying the template was created. - * @param string $message_type_label - * @param string $messenger_label - */ - public function createCustomMessageTemplateFromDefaultFor($message_type_label, $messenger_label) - { - $this->amOnDefaultMessageTemplateListTablePage(); - $this->actor()->click( - MessagesPage::createCustomButtonForMessageTypeAndMessenger( - $message_type_label, - $messenger_label - ) - ); - $this->actor()->seeInField('#title', 'New Custom Template'); - } - - - /** - * This switches the context of the current messages template to the given reference. - * @param string $context_reference This should be the visible label for the option. - */ - public function switchContextTo($context_reference) - { - $this->actor()->selectOption(MessagesPage::MESSAGES_CONTEXT_SWITCHER_SELECTOR, $context_reference); - $this->actor()->click(MessagesPage::MESSAGES_CONTEXT_SWITCHER_BUTTON_SELECTOR); - $this->actor()->waitForText($context_reference, 10, 'h1'); - } - - - /** - * Toggles Context so its turned off or on (depending on where it started) and verifies the expected state after - * toggling. - * - * @param string $context_string What context is being switched (used for the expected state text) - * @param bool $expected_state_is_active Used to indicate whether the expected state is active (true) or inactive - * (false) - */ - public function toggleContextState($context_string, $expected_state_is_active = true) - { - $this->actor()->scrollTo(MessagesPage::MESSAGES_CONTEXT_SWITCHER_SELECTOR); - $this->actor()->click(MessagesPage::MESSAGES_CONTEXT_ACTIVE_STATE_TOGGLE); - if ($expected_state_is_active) { - $this->actor()->waitForText("The template for $context_string is currently active."); - } else { - $this->actor()->waitForText("The template for $context_string is currently inactive"); - } - } - - - /** - * Triggers saving the message template. - * @param bool $and_close Use to indicate to click the Save and Close button. - */ - public function saveMessageTemplate($and_close = false) - { - $this->actor()->scrollTo(MessagesPage::MESSAGES_CONTEXT_SWITCHER_SELECTOR); - if ($and_close) { - $this->actor()->click('Save and Close'); - } else { - $this->actor()->click('Save'); - } - $this->actor()->waitForText('successfully updated'); - } - - - /** - * This takes care of clicking the View Message icon for the given parameters. - * Assumes you are already viewing the messages activity list table. - * @param $message_type_label - * @param $message_status - * @param string $messenger - * @param string $context - * @param int $number_in_set - */ - public function viewMessageInMessagesListTableFor( - $message_type_label, - $message_status = MessagesPage::MESSAGE_STATUS_SENT, - $messenger = 'Email', - $context = 'Event Admin', - $number_in_set = 1 - ) { - $this->actor()->click(MessagesPage::messagesActivityListTableViewButtonSelectorFor( - $message_type_label, - $message_status, - $messenger, - $context, - $number_in_set - )); - } - - - /** - * Takes care of deleting a message matching the given parameters via the message activity list table. - * Assumes you are already viewing the messages activity list table. - * @param $message_type_label - * @param $message_status - * @param string $messenger - * @param string $context - * @param int $number_in_set - */ - public function deleteMessageInMessagesListTableFor( - $message_type_label, - $message_status = MessagesPage::MESSAGE_STATUS_SENT, - $messenger = 'Email', - $context = 'Event Admin', - $number_in_set = 1 - ) { - $delete_action_selector = MessagesPage::messagesActivityListTableDeleteActionSelectorFor( - $message_type_label, - $message_status, - $messenger, - $context, - $number_in_set - ); - $cell_selector = MessagesPage::messagesActivityListTableCellSelectorFor( - 'to', - $message_type_label, - $message_status, - $messenger, - $context, - '', - $number_in_set - ); - $this->actor()->scrollTo($cell_selector, 0, -30); - $this->actor()->moveMouseOver( - $cell_selector, - 5, - 5 - ); - $this->actor()->waitForElementVisible( - $delete_action_selector - ); - $this->actor()->click( - $delete_action_selector - ); - $this->actor()->waitForText('successfully deleted', 20); - } - - - /** - * Assuming you have already triggered the view modal for a single message from the context of the message activity - * list table, this will take care of validating the given text is in that window. - * @param string $text_to_view - */ - public function seeTextInViewMessageModal($text_to_view, $should_not_see = false) - { - $this->actor()->wait(2); - $this->actor()->waitForElementVisible('.ee-admin-dialog-container-inner-content'); - $this->actor()->switchToIframe('message-view-window'); - $should_not_see ? $this->actor()->dontSee($text_to_view) : $this->actor()->see($text_to_view); - $this->actor()->switchToIframe(); - } - - - /** - * This returns the value for the link at the given selector in the message modal. - * @param string $selector (any selector string accepted by WebDriver) - */ - public function observeLinkAtSelectorInMessageModal($selector) - { - $this->actor()->wait(2); - $this->actor()->waitForElementVisible('.ee-admin-dialog-container-inner-content'); - $this->actor()->switchToIframe('message-view-window'); - $link = $this->actor()->observeLinkUrlAt($selector); - $this->actor()->switchToIframe(); - return $link; - } - - - /** - * Assuming you have already triggered the view modal for a single message from the context of the message activity - * list table, this will take care of validating the given text is NOT that window. - * @param string $text_to_view - */ - public function dontSeeTextInViewMessageModal($text_to_view) - { - $this->seeTextInViewMessageModal($text_to_view, true); - } - - - public function dismissMessageModal() - { - $this->actor()->executeJs('window.dialogHelper.closeModal()'); - } -} diff --git a/acceptance_tests/Helpers/RegistrationsAdmin.php b/acceptance_tests/Helpers/RegistrationsAdmin.php deleted file mode 100644 index 8e0d05502fb..00000000000 --- a/acceptance_tests/Helpers/RegistrationsAdmin.php +++ /dev/null @@ -1,153 +0,0 @@ -actor()->checkOption( - RegistrationsAdminPage::listTableCheckBoxSelectorForRegistrationId($registration_id) - ); - } - } - - - /** - * Navigates the actor to the default registration list table page. - * @param string $additional_params - */ - public function amOnDefaultRegistrationsListTableAdminPage($additional_params = '') - { - $this->actor()->amOnAdminPage( - RegistrationsAdminPage::registrationsDefaultAdminListTableUrl($additional_params) - ); - //wait for page to fully load - $this->actor()->wait(5); - } - - - /** - * Will enter the provided value in the registration list table search field and execute a search for that value. - * @param string $search_text - */ - public function searchForRegistrationOnRegistrationListTableWithText($search_text) - { - $this->amOnDefaultRegistrationsListTableAdminPage(); - $this->actor()->fillField(RegistrationsAdminPage::SEARCH_INPUT_SELECTOR_LIST_TABLE_REGISTRATION, $search_text); - $this->actor()->click(CoreAdmin::LIST_TABLE_SEARCH_SUBMIT_SELECTOR); - $this->actor()->waitForText('Displaying search results for'); - } - - - - /** - * This will filter the registration list table to view registrations for the given event id. - * Assumption is made that you are logged into the admin but you do not need to be on the registration list table - * page. - * - * @param int $event_id The id of the event viewing registrations for. - */ - public function amViewingRegistrationsForEvent($event_id) - { - $this->actor()->amOnDefaultEventsListTablePage(); - $this->actor()->click(EventsAdmin::listTableActionLinkRegistrationsForEvent($event_id)); - $this->actor()->waitForText('Viewing registrations for the event'); - } - - - /** - * This helper will initiate registering for the given event via the backend. - * @param int $event_id The event to initiate registration for. - */ - public function amOnAdminRegistrationPageForEvent($event_id) - { - $this->actor()->amViewingRegistrationsForEvent($event_id); - $this->actor()->click(RegistrationsAdminPage::BUTTON_ADD_NEW_REGISTRATION); - $this->actor()->waitForText('Adding Registration For'); - } - - - - /** - * This clicks the View Details Link for Registration with the given Id - * @param $registration_id - */ - public function clickViewDetailsLinkForRegistrationWithId($registration_id) - { - $this->actor()->click(RegistrationsAdminPage::viewDetailsLinkSelectorForRegistrationId($registration_id)); - } - - - /** - * /** - * This assumes you are on the admin details page for a registration in EE. It selects the given status in the - * dropdown for changing registration status. - * - * @param string $status_label_or_value Either the label for the dropdown option or the value for the option. - * @param $status_label_or_value - */ - public function selectRegistrationStatusOnRegistrationDetailsPageFor($status_label_or_value) - { - $this->actor()->selectOption( - RegistrationsAdminPage::DROPDOWN_REGISTRATION_STATUS, - $status_label_or_value - ); - } - - - /** - * This selects (or deselects) the "Send Related Messages" checkbox on the Registration Details page. - * @param bool $send_related_messages - */ - public function selectSendRelatedMessagesOptionOnRegistrationDetailsPage($send_related_messages = true) - { - $send_related_messages - ? $this->actor()->selectOption( - RegistrationsAdminPage::DROPDOWN_SEND_RELATED_MESSAGES, - 'Yes' - ) - : $this->actor()->selecOption( - RegistrationsAdminPage::DROPDOWN_SEND_RELATED_MESSAGES, - 'No' - ); - } - - - - /** - * This assumes you are on the admin details page for a registration in EE. It selects the given status in the - * dropdown for changing registration status and submits the change. - * - * @param string $status_label_or_value Either the label for the dropdown option or the value for the option. - * @param bool $send_related_messages Whether or not to send related messages after changing the bulk action. - */ - public function changeRegistrationStatusOnRegistrationDetailsPageTo( - $status_label_or_value, - $send_related_messages = true - ) { - $this->actor()->selectRegistrationStatusOnRegistrationDetailsPageFor($status_label_or_value); - $this->actor()->selectSendRelatedMessagesOptionOnRegistrationDetailsPage($send_related_messages); - $this->actor()->click(RegistrationsAdminPage::BUTTON_UPDATE_REGISTRATION_STATUS); - $this->actor()->waitForText('Registration status has been set to'); - } - -} \ No newline at end of file diff --git a/acceptance_tests/Helpers/TicketSelector.php b/acceptance_tests/Helpers/TicketSelector.php deleted file mode 100644 index ebc7373d018..00000000000 --- a/acceptance_tests/Helpers/TicketSelector.php +++ /dev/null @@ -1,34 +0,0 @@ -actor()->selectOption(TicketSelectorElements::ticketOptionByEventIdSelector($event_id), $quantity); - } - - - /** - * Used to submit the ticket selection for the given event id (so this can be used on an event archive page). - * @param int|string $event_id - */ - public function submitTicketSelectionsForEventId($event_id) - { - $this->actor()->click(TicketSelectorElements::ticketSelectionSubmitSelectorByEventId($event_id)); - } -} \ No newline at end of file diff --git a/acceptance_tests/Page/Checkout.php b/acceptance_tests/Page/Checkout.php deleted file mode 100644 index faae8d9eabf..00000000000 --- a/acceptance_tests/Page/Checkout.php +++ /dev/null @@ -1,83 +0,0 @@ - "//input[@id='title']"]; - - /** - * Selector for the publish submit button in the event editor. - * @var string - */ - const EVENT_EDITOR_PUBLISH_BUTTON_SELECTOR = ['xpath'=>"//div[@id='major-publishing-actions']//input[@id='publish']"]; - - - /** - * Selector for the save button in the event editor - */ - const EVENT_EDITOR_SAVE_BUTTON_SELECTOR = ['xpath' => "//div[@id='minor-publishing-actions']//input[@id='save-post']"]; - - - /** - * @var string - */ - const EVENT_EDITOR_DEFAULT_REGISTRATION_STATUS_FIELD_SELECTOR = '#EVT_default_registration_status'; - - /** - * Selector for the view link after publishing an event. - * @var string - */ - const EVENT_EDITOR_VIEW_LINK_AFTER_PUBLISH_SELECTOR = "//span[@id='sample-permalink']/a"; - - - /** - * Selector for the ID of the event in the event editor - * @var string - */ - const EVENT_EDITOR_EVT_ID_SELECTOR = "//input[@id='post_ID']"; - - - /** - * Selector for the search input on the event list table page. - * @var string - */ - const EVENT_LIST_TABLE_SEARCH_INPUT_SELECTOR = '#toplevel_page_espresso_events-search-input'; - - - - - /** - * @param string $additional_params - * @return string - */ - public static function defaultEventsListTableUrl($additional_params = '') - { - return self::adminUrl('espresso_events', 'default', $additional_params); - } - - - /** - * The selector for the DTTname field for the given row in the event editor. - * @param int $row_number - * @return string - */ - public static function eventEditorDatetimeNameFieldSelector($row_number = 1) - { - return self::eventEditorDatetimeFieldSelectorForField('DTT_name', $row_number); - } - - - /** - * The selector for the DTT_EVT_start field for the given row in the event editor.d - * @param int $row_number - * @return string - */ - public static function eventEditorDatetimeStartDateFieldSelector($row_number = 1) - { - return self::eventEditorDatetimeFieldSelectorForField('DTT_EVT_start', $row_number); - } - - - /** - * Wrapper for getting the selector for a given field and given row of a datetime in the event editor. - * - * @param string $field_name - * @param int $row_number - * @return string - */ - public static function eventEditorDatetimeFieldSelectorForField($field_name, $row_number = 1) - { - return "//input[@id='event-datetime-$field_name-$row_number']"; - } - - - /** - * The selector for the TKT_name field for the given display row in the event editor. - * @param int $row_number - * @return string - */ - public static function eventEditorTicketNameFieldSelector($row_number = 1) - { - return self::eventEditorTicketFieldSelectorForFieldInDisplayRow('TKT_name', $row_number); - } - - - /** - * Selector for the TKT_base_price field for the given display row in the event editor. - * @param int $row_number - * @return string - */ - public static function eventEditorTicketPriceFieldSelector($row_number = 1) - { - return self::eventEditorTicketFieldSelectorForFieldInDisplayRow('TKT_base_price', $row_number); - } - - - /** - * Selector for the TKT_qty field for the given display row in the event editor. - * @param int $row_number - * @return string - */ - public static function eventEditorTicketQuantityFieldSelector($row_number = 1) - { - return self::eventEditorTicketFieldSelectorForFieldInDisplayRow('TKT_qty', $row_number); - } - - - /** - * Selector for the advanced details toggle for the ticket for the given display row in the event editor. - * @param int $row_number - * @return string - */ - public static function eventEditorTicketAdvancedDetailsSelector($row_number = 1) - { - return "//tr[@id='display-ticketrow-$row_number']//span[contains(@class, 'gear-icon')]"; - } - - - /** - * Selector for the subtotal amount for the given display row of the ticket in the event editor. - * @param int $row_number - * @return string - */ - public static function eventEditorTicketAdvancedDetailsSubtotalSelector($row_number = 1) - { - return "//span[@id='price-total-amount-$row_number']"; - } - - - /** - * Selector for the Total element for the given display row of the ticket in the event editor. - * @param int $row_number - * @return string - */ - public static function eventEditorTicketAdvancedDetailsTotalSelector($row_number = 1) - { - return "//span[@id='price-total-amount-$row_number']"; - } - - - /** - * Selector for the taxable selector for the ticket for the given display row in the event editor. - * @param int $row_number - * @return string - */ - public static function eventEditorTicketTaxableCheckboxSelector($row_number = 1) - { - return "//input[@id='edit-ticket-TKT_taxable-$row_number']"; - } - - - /** - * This returns the xpath locater for the Tax amount display container within the advanced settings view for the - * given ticket (row) and the given tax id (PRC_ID). - * - * @param int $tax_id The PRC_ID for the tax you want the locater for. Note, this defaults to the default tax - * setup on a fresh install. - * @param int $row_number What row representing the ticket you want the locator for. - * @return string - */ - public static function eventEditorTicketTaxAmountDisplayForTaxIdAndTicketRowSelector($tax_id = 2, $row_number = 1) - { - return "//span[@id='TKT-tax-amount-display-$tax_id-$row_number']"; - } - - - /** - * Wrapper for getting the selector for a given field and given display row of a ticket in the event editor. - * @param $field_name - * @param int $row_number - * @return string - */ - public static function eventEditorTicketFieldSelectorForFieldInDisplayRow($field_name, $row_number = 1) - { - return "//tr[@id='display-ticketrow-$row_number']//input[contains(@class, 'edit-ticket-$field_name')]"; - } - - - /** - * Returns the selector for the event title edit link in the events list table for the given Event Title. - * @param string $event_title - * @return string - */ - public static function eventListTableEventTitleEditLinkSelectorForTitle($event_title) - { - return "//td[contains(@class, 'column-name')]/strong/a[text()='$event_title']"; - } - - - /** - * Locator for for the ID column in the event list table for a given event title. - * @param string $event_title - * @return string - */ - public static function eventListTableEventIdSelectorForTitle($event_title) - { - return "//td[contains(@class, 'column-name')]/strong/a[text()='$event_title']" - . "//ancestor::tr/th[contains(@class, 'check-column')]/input"; - } - - - /** - * Locator for the view link in the row of an event list table for the given event title. - * @param string $event_title - * @return string - */ - public static function eventListTableEventTitleViewLinkSelectorForTitle($event_title) - { - return "//td[contains(@class, 'column-name')]/strong/a[text()='$event_title']" - . "//ancestor::td//span[@class='view']/a"; - } - - - /** - * Locator for the messenger tab in the Notifications metabox in the event editor. - * @param string $messenger_slug The slug for the messenger (it's reference slug). - * @return string - */ - public static function eventEditorNotificationsMetaBoxMessengerTabSelector($messenger_slug) - { - return "//div[@id='espresso_events_Messages_Hooks_Extend_messages_metabox_metabox']" - . "//a[@rel='ee-tab-$messenger_slug']"; - } - - - /** - * Locator for the select input within the notifications metabox. - * Note, this assumes the tab content for the related messenger is already visible. - * @param string $message_type_label The message type label (visible string in the table) you want the selector for. - * @return string - */ - public static function eventEditorNotificationsMetaBoxSelectSelectorForMessageType($message_type_label) - { - return "//div[@id='espresso_events_Messages_Hooks_Extend_messages_metabox_metabox']" - . "//table[@class='messages-custom-template-switcher']" - . "//tr/td[contains(.,'Registration Approved')]" - . "//ancestor::tr//select[contains(@class,'message-template-selector')]"; - } - - - /** - * Returns the selector for the action link to the registrations list table view filtered by the given event_id. - * Assumes one is in the context of the Events List Table - * @param int $event_id - * @return string - */ - public static function listTableActionLinkRegistrationsForEvent($event_id) - { - return "//tbody[@id='the-list']/tr/td[contains(@class, 'column-id') and contains(.,$event_id)]" - . "//ancestor::tr/td//a[div[contains(@class, 'dashicons-groups')]]"; - } -} diff --git a/acceptance_tests/Page/MessagesAdmin.php b/acceptance_tests/Page/MessagesAdmin.php deleted file mode 100644 index 171e5f7af2b..00000000000 --- a/acceptance_tests/Page/MessagesAdmin.php +++ /dev/null @@ -1,305 +0,0 @@ - 0 ? Locator::elementAt($selector, $number_in_set) : $selector; - } - - - /** - * Selector for the Create Custom button found in the message template list table. - * @param string $message_type_label - * @param string $messenger_label - * @return string - */ - public static function createCustomButtonForMessageTypeAndMessenger($message_type_label, $messenger_label) - { - $selector = "//tr/td[contains(@class, 'message_type') and text()='$message_type_label']" - . "//ancestor::tr/td[contains(@class, 'messenger') and contains(., '$messenger_label')]" - . "//ancestor::tr/td/a[@class='button button-small']"; - return $selector; - } - - - /** - * Note, this could potentially match multiple buttons in the view so the selector is intentionally restricted to - * the FIRST match (which will be the latest message sent if the table is default sorted). - * - * @param string $message_type_label The visible message type label for the row you want to match - * @param string $message_status The status of the message for the row you want to match. - * @param string $messenger The visible messenger label for the row you want to match. - * @param string $context The visible context label for the row you want to match. - * @param int $number_in_set It's possible that the given parameters could match multiple items in the - * view. This allows you to indicate which item from the set to match. - * @return string - * @throws \InvalidArgumentException - */ - public static function messagesActivityListTableViewButtonSelectorFor( - $message_type_label, - $message_status = self::MESSAGE_STATUS_SENT, - $messenger = 'Email', - $context = 'Event Admin', - $number_in_set = 1 - ) { - $selector = self::messagesActivityListTableCellSelectorFor( - 'action', - $message_type_label, - $message_status, - $messenger, - $context, - '', - $number_in_set - ); - $selector .= "/a/span[contains(@class, 'ee-message-action-link-view')" - . " and not(contains(@class, 'ee-message-action-link-view_transaction'))]"; - return $selector; - } - - - /** - * Locator for the delete action link for a message item in the message activity list table. - * Note: The link is not visible by default, so the column would need hovered over for the link to appear. - * - * @param $message_type_label - * @param string $message_status - * @param string $messenger - * @param string $context - * @param int $number_in_set - * @return string - * @throws \InvalidArgumentException - */ - public static function messagesActivityListTableDeleteActionSelectorFor( - $message_type_label, - $message_status = self::MESSAGE_STATUS_SENT, - $messenger = 'Email', - $context = 'Event Admin', - $number_in_set = 1 - ) { - $selector = self::messagesActivityListTableCellSelectorFor( - 'to', - $message_type_label, - $message_status, - $messenger, - $context, - '', - $number_in_set - ); - $selector .= "/div/span[@class='delete']/a"; - return $selector; - } - - - - /** - * Returns the input selector for a given field in the message template editor. - * Assumes one is already viewing the Message Template Editor. - * @param string $field - * @return string - */ - public static function messageInputFieldSelectorFor($field) - { - return "//div[@id='post-body']//input[@id='$field-content']"; - } - - - /** - * Wrapper for self::messageInputFieldSelectorFor('to') that takes care of getting the input for the To field. - */ - public static function messageTemplateToFieldSelector() - { - return self::messageInputFieldSelectorFor('to'); - } -} \ No newline at end of file diff --git a/acceptance_tests/Page/RegistrationsAdmin.php b/acceptance_tests/Page/RegistrationsAdmin.php deleted file mode 100644 index 1bb281ae812..00000000000 --- a/acceptance_tests/Page/RegistrationsAdmin.php +++ /dev/null @@ -1,58 +0,0 @@ -loginAsAdmin(20); -$I->amOnMessageSettingsPage(); -$I->selectOption(MessagesAdmin::GLOBAL_MESSAGES_SETTINGS_ON_REQUEST_SELECTION_SELECTOR, '1'); -$I->click(MessagesAdmin::GLOBAL_MESSAGES_SETTINGS_SUBMIT_SELECTOR); diff --git a/acceptance_tests/tests/b-TestRegistrationSummaryCept.php b/acceptance_tests/tests/b-TestRegistrationSummaryCept.php deleted file mode 100644 index 290f0160071..00000000000 --- a/acceptance_tests/tests/b-TestRegistrationSummaryCept.php +++ /dev/null @@ -1,158 +0,0 @@ -wantTo('Test that the Registration Summary Message type works as expected.'); - -//need the MER plugin active for this test (we'll deactivate it after). -$I->ensurePluginActive( - 'event-espresso-mer-multi-event-registration', - 'activated' -); - -//k now we need to make sure the registration multi-status message type is active because it isn't by default -$I->loginAsAdmin(); -$I->amOnMessageSettingsPage(); -$I->activateMessageTypeForMessenger('registration_summary'); - - -//k now we need to create a couple events to use for testing. -$I->amOnDefaultEventsListTablePage(); -$I->click(EventsAdmin::ADD_NEW_EVENT_BUTTON_SELECTOR); -$I->fillField(EventsAdmin::EVENT_EDITOR_TITLE_FIELD_SELECTOR, 'Event RSM A'); -$I->publishEvent(); -$event_a_link = $I->observeLinkUrlAt(EventsAdmin::EVENT_EDITOR_VIEW_LINK_AFTER_PUBLISH_SELECTOR); -$event_a_id = $I->observeValueFromInputAt(EventsAdmin::EVENT_EDITOR_EVT_ID_SELECTOR); - -//do another event except we'll set the default reg status to not approved. -$I->amOnDefaultEventsListTablePage(); -$I->click(EventsAdmin::ADD_NEW_EVENT_BUTTON_SELECTOR); -$I->fillField(EventsAdmin::EVENT_EDITOR_TITLE_FIELD_SELECTOR, 'Event RSM B'); -$I->changeDefaultRegistrationStatusTo(RegistrationsAdmin::REGISTRATION_STATUS_NOT_APPROVED); -$I->publishEvent(); -$event_b_link = $I->observeLinkUrlAt(EventsAdmin::EVENT_EDITOR_VIEW_LINK_AFTER_PUBLISH_SELECTOR); -$event_b_id = $I->observeValueFromInputAt(EventsAdmin::EVENT_EDITOR_EVT_ID_SELECTOR); - -$I->amOnDefaultEventsListTablePage(); -$I->click(EventsAdmin::ADD_NEW_EVENT_BUTTON_SELECTOR); -$I->fillField(EventsAdmin::EVENT_EDITOR_TITLE_FIELD_SELECTOR, 'Event RSM C'); -$I->publishEvent(); -$event_c_link = $I->observeLinkUrlAt(EventsAdmin::EVENT_EDITOR_VIEW_LINK_AFTER_PUBLISH_SELECTOR); -$event_c_id = $I->observeValueFromInputAt(EventsAdmin::EVENT_EDITOR_EVT_ID_SELECTOR); - -//k now that our events are setup lets do some registrations -$I->logOut(); -$I->amOnUrl($event_a_link); -$I->see('Event RSM A'); -$I->selectOption(TicketSelector::ticketOptionByEventIdSelector($event_a_id), '1'); -$I->click(TicketSelector::ticketSelectionSubmitSelectorByEventId($event_a_id)); -$I->waitForText('successfully added'); -$I->click('.cart-results-go-back-button'); -$I->amOnUrl($event_b_link); -$I->see('Event RSM B'); -$I->selectOption(TicketSelector::ticketOptionByEventIdSelector($event_b_id), '1'); -$I->click(TicketSelector::ticketSelectionSubmitSelectorByEventId($event_b_id)); -$I->waitForText('successfully added'); -$I->click('.cart-results-register-button'); -$I->waitForText('Personal Information'); -$I->fillOutFirstNameFieldForAttendee('RSM Tester'); -$I->fillOutLastNameFieldForAttendee('Guy'); -$I->fillOutEmailFieldForAttendee('rsm_tester@example.org'); -$I->goToNextRegistrationStep(); -$I->waitForText('Congratulations', 15); - -//now let's go to the messages list table and make sure the registration message summary is there. -$I->loginAsAdmin(); -$I->amOnMessagesActivityListTablePage(); -$I->see( - 'rsm_tester@example.org', - MessagesAdmin::messagesActivityListTableCellSelectorFor( - 'to', - 'Registration Multi-status Summary', - MessagesAdmin::MESSAGE_STATUS_SENT, - '', - 'Primary Registrant' - ) -); -$I->see( - 'admin@example.com', - MessagesAdmin::messagesActivityListTableCellSelectorFor( - 'to', - 'Registration Multi-status Summary', - MessagesAdmin::MESSAGE_STATUS_SENT - ) -); -//verify count -$I->verifyMatchingCountofTextInMessageActivityListTableFor( - 1, - 'rsm_tester@example.org', - 'to', - 'Registration Multi-status Summary', - MessagesAdmin::MESSAGE_STATUS_SENT, - 'Email', - 'Primary Registrant' -); -$I->verifyMatchingCountofTextInMessageActivityListTableFor( - 1, - 'admin@example.com', - 'to', - 'Registration Multi-status Summary' -); - -//okay now let's do some registrations for just the first event and verify that registration multi-status summary is NOT -//generated -$I->amGoingTo('Register for Event RSM A and C and verify registration multi-status message type is not used for generated message'); -$I->logOut(); -$I->amOnUrl($event_a_link); -$I->see('Event RSM A'); -$I->selectOption(TicketSelector::ticketOptionByEventIdSelector($event_a_id), '1'); -$I->click(TicketSelector::ticketSelectionSubmitSelectorByEventId($event_a_id)); -$I->waitForText('successfully added'); -$I->click('.cart-results-go-back-button'); -$I->amOnUrl($event_c_link); -$I->see('Event RSM C'); -$I->selectOption(TicketSelector::ticketOptionByEventIdSelector($event_c_id), '1'); -$I->click(TicketSelector::ticketSelectionSubmitSelectorByEventId($event_c_id)); -$I->waitForText('successfully added'); -$I->click('.cart-results-register-button'); -$I->waitForText('Personal Information'); -$I->fillOutFirstNameFieldForAttendee('RSM Tester B'); -$I->fillOutLastNameFieldForAttendee('Guy'); -$I->fillOutEmailFieldForAttendee('rsm_testerb@example.org'); -$I->goToNextRegistrationStep(); -$I->waitForText('Congratulations', 15); - -$I->amGoingTo('Visit Messages Activity List Table and verify there are no Registration Multi-Status Messages for the registrations we just did'); -$I->loginAsAdmin(); -$I->amOnMessagesActivityListTablePage(); -$I->dontSee( - 'rsm_testerb@example.org', - MessagesAdmin::messagesActivityListTableCellSelectorFor( - 'to', - 'Registration Multi-status Summary', - MessagesAdmin::MESSAGE_STATUS_SENT, - '', - 'Primary Registrant' - ) -); -//there should still only be one admin multi-status summary thing. -$I->verifyMatchingCountofTextInMessageActivityListTableFor( - 1, - 'admin@example.com', - 'to', - 'Registration Multi-status Summary' -); - -//deactivate MER plugin so its not active for future tests -$I->ensurePluginDeactivated( - 'event-espresso-mer-multi-event-registration', - 'plugins deactivated' -); \ No newline at end of file diff --git a/acceptance_tests/tests/c-TestCustomMessageTemplateCept.php b/acceptance_tests/tests/c-TestCustomMessageTemplateCept.php deleted file mode 100644 index 53082b95ec3..00000000000 --- a/acceptance_tests/tests/c-TestCustomMessageTemplateCept.php +++ /dev/null @@ -1,188 +0,0 @@ -wantTo( - 'Test that when registrations for multiple events are completed, and those events share the same custom' - . 'template, that that custom template will be used.' -); - -//need the MER plugin active for this test (we'll deactivate it after). -$I->ensurePluginActive( - 'event-espresso-mer-multi-event-registration', - 'activated' -); - -$I->loginAsAdmin(); - -$I->amGoingTo('Create two custom registration approved templates'); -$I->amGoingTo('Create first custom registration approved template.'); -$I->createCustomMessageTemplateFromDefaultFor('Registration Approved', 'Email'); -$I->appendToWPEditorField('main', $custom_template_a_label); -$I->saveMessageTemplate(); -$I->waitForText('successfully updated'); -$I->switchContextTo('Registrant'); -$I->fillField('#title', $custom_template_a_label); -$I->appendToWPEditorField('main', $custom_template_a_label); -$I->saveMessageTemplate(); -$I->waitForText('successfully updated'); - -$I->amGoingTo('Create second custom registration approved template.'); -$I->createCustomMessageTemplateFromDefaultFor('Registration Approved', 'Email'); -$I->fillField('#title', $custom_template_b_label); -$I->appendToWPEditorField('main', $custom_template_b_label); -$I->saveMessageTemplate(); -$I->waitForText('successfully updated'); -$I->switchContextTo('Registrant'); -$I->appendToWPEditorField('main', $custom_template_b_label); -$I->saveMessageTemplate(); -$I->waitForText('successfully updated'); - -$I->amGoingTo('Create three events for testing with.'); -$I->amOnDefaultEventsListTablePage(); -$I->click(EventsAdmin::ADD_NEW_EVENT_BUTTON_SELECTOR); -$I->fillField(EventsAdmin::EVENT_EDITOR_TITLE_FIELD_SELECTOR, $event_one_label); -$I->selectCustomTemplateFor('Registration Approved', 'email', $custom_template_a_label); -$I->publishEvent(); -$event_one_link = $I->observeLinkUrlAt(EventsAdmin::EVENT_EDITOR_VIEW_LINK_AFTER_PUBLISH_SELECTOR); -$event_one_id = $I->observeValueFromInputAt(EventsAdmin::EVENT_EDITOR_EVT_ID_SELECTOR); - -$I->amOnDefaultEventsListTablePage(); -$I->click(EventsAdmin::ADD_NEW_EVENT_BUTTON_SELECTOR); -$I->fillField(EventsAdmin::EVENT_EDITOR_TITLE_FIELD_SELECTOR, $event_two_label); -$I->selectCustomTemplateFor('Registration Approved', 'email', $custom_template_a_label); -$I->publishEvent(); -$event_two_link = $I->observeLinkUrlAt(EventsAdmin::EVENT_EDITOR_VIEW_LINK_AFTER_PUBLISH_SELECTOR); -$event_two_id = $I->observeValueFromInputAt(EventsAdmin::EVENT_EDITOR_EVT_ID_SELECTOR); - -$I->amOnDefaultEventsListTablePage(); -$I->click(EventsAdmin::ADD_NEW_EVENT_BUTTON_SELECTOR); -$I->fillField(EventsAdmin::EVENT_EDITOR_TITLE_FIELD_SELECTOR, $event_three_label); -$I->selectCustomTemplateFor('Registration Approved', 'email', $custom_template_b_label); -$I->publishEvent(); -$event_three_link = $I->observeLinkUrlAt(EventsAdmin::EVENT_EDITOR_VIEW_LINK_AFTER_PUBLISH_SELECTOR); -$event_three_id = $I->observeValueFromInputAt(EventsAdmin::EVENT_EDITOR_EVT_ID_SELECTOR); - - -$test_registration_details = array( - 'fname' => 'CTGuy', - 'lname' => 'Dude', - 'email' => 'ctguy_dude@example.org' -); - -$I->amGoingTo('Register for Event One and Event Two and verify Custom Template A was used.'); -$I->logOut(); -$I->amOnUrl($event_one_link); -$I->selectOption(TicketSelector::ticketOptionByEventIdSelector($event_one_id), 1); -$I->click(TicketSelector::ticketSelectionSubmitSelectorByEventId($event_one_id)); -$I->waitForText('successfully added'); -$I->click('.cart-results-go-back-button'); -$I->amOnUrl($event_two_link); -$I->selectOption(TicketSelector::ticketOptionByEventIdSelector($event_two_id), 1); -$I->click(TicketSelector::ticketSelectionSubmitSelectorByEventId($event_two_id)); -$I->waitForText('successfully added'); -$I->click('.cart-results-register-button'); -$I->waitForText('Personal Information'); -$I->fillOutFirstNameFieldForAttendee($test_registration_details['fname']); -$I->fillOutLastNameFieldForAttendee($test_registration_details['lname']); -$I->fillOutEmailFieldForAttendee($test_registration_details['email']); -$I->goToNextRegistrationStep(); -$I->waitForText('Congratulations', 15); - -//go to list table and verify -$I->loginAsAdmin(); -$I->amOnMessagesActivityListTablePage(); -$I->viewMessageInMessagesListTableFor( - 'Registration Approved', - MessagesAdmin::MESSAGE_STATUS_SENT, - 'Email', - 'Registrant' -); -$I->seeTextInViewMessageModal($custom_template_a_label); -$I->dismissMessageModal(); -$I->deleteMessageInMessagesListTableFor( - 'Registration Approved', - MessagesAdmin::MESSAGE_STATUS_SENT, - 'Email', - 'Registrant' -); - -//verify admin context -$I->viewMessageInMessagesListTableFor( - 'Registration Approved' -); -$I->seeTextInViewMessageModal($custom_template_a_label); -$I->dismissMessageModal(); -$I->deleteMessageInMessagesListTableFor('Registration Approved'); - -$I->amGoingTo('Register for Event One and Event Three and verify that global template is used.'); -$I->logOut(); -$I->amOnUrl($event_one_link); -$I->selectOption(TicketSelector::ticketOptionByEventIdSelector($event_one_id), 1); -$I->click(TicketSelector::ticketSelectionSubmitSelectorByEventId($event_one_id)); -$I->waitForText('successfully added'); -$I->click('.cart-results-go-back-button'); -$I->amOnUrl($event_three_link); -$I->selectOption(TicketSelector::ticketOptionByEventIdSelector($event_three_id), 1); -$I->click(TicketSelector::ticketSelectionSubmitSelectorByEventId($event_three_id)); -$I->waitForText('successfully added'); -$I->click('.cart-results-register-button'); -$I->waitForText('Personal Information'); -$I->fillOutFirstNameFieldForAttendee($test_registration_details['fname']); -$I->fillOutLastNameFieldForAttendee($test_registration_details['lname']); -$I->fillOutEmailFieldForAttendee($test_registration_details['email']); -$I->goToNextRegistrationStep(); -$I->waitForText('Congratulations', 15); - -//go to list table and verify -$I->loginAsAdmin(); -$I->amOnMessagesActivityListTablePage(); -$I->viewMessageInMessagesListTableFor( - 'Registration Approved', - MessagesAdmin::MESSAGE_STATUS_SENT, - 'Email', - 'Registrant' -); -$I->waitForElementVisible(MessagesAdmin::MESSAGES_LIST_TABLE_VIEW_MESSAGE_DIALOG_CONTAINER_SELECTOR); -$I->dontSeeTextInViewMessageModal($custom_template_a_label); -$I->dontSeeTextInViewMessageModal($custom_template_b_label); -$I->dismissMessageModal(); -$I->deleteMessageInMessagesListTableFor( - 'Registration Approved', - MessagesAdmin::MESSAGE_STATUS_SENT, - 'Email', - 'Registrant' -); - -//verify admin context -$I->viewMessageInMessagesListTableFor( - 'Registration Approved' -); -$I->waitForElementVisible(MessagesAdmin::MESSAGES_LIST_TABLE_VIEW_MESSAGE_DIALOG_CONTAINER_SELECTOR); -$I->dontSee($custom_template_a_label); -$I->dontSee($custom_template_b_label); -$I->dismissMessageModal(); -$I->deleteMessageInMessagesListTableFor('Registration Approved'); - - - -//deactivate MER plugin so its not active for future tests -$I->ensurePluginDeactivated( - 'event-espresso-mer-multi-event-registration', - 'plugins deactivated' -); \ No newline at end of file diff --git a/acceptance_tests/tests/d-TestEventEditorCept.php b/acceptance_tests/tests/d-TestEventEditorCept.php deleted file mode 100644 index 702f51907ea..00000000000 --- a/acceptance_tests/tests/d-TestEventEditorCept.php +++ /dev/null @@ -1,41 +0,0 @@ -wantTo('Test various features/elements in the event editor.'); -$I->amGoingTo('Test ticket total calculations via js in the ticket editor.'); -$I->loginAsAdmin(); -$I->amOnDefaultEventsListTablePage(); -$I->click(EventsAdmin::ADD_NEW_EVENT_BUTTON_SELECTOR); -$I->fillField(EventsAdmin::eventEditorTicketPriceFieldSelector(), '32.50'); -$I->toggleAdvancedSettingsViewForTicketRow(); -$I->waitForElementVisible(EventsAdmin::eventEditorTicketAdvancedDetailsSubtotalSelector()); -$I->see('$32.50', EventsAdmin::eventEditorTicketAdvancedDetailsSubtotalSelector()); -$I->toggleTicketIsTaxableForTicketRow(); -$I->see('$4.88', EventsAdmin::eventEditorTicketTaxAmountDisplayForTaxIdAndTicketRowSelector()); -$I->see('$37.38', EventsAdmin::eventEditorTicketAdvancedDetailsTotalSelector()); -$I->saveEvent(); - -$I->amGoingTo('Test the same ticket total calculations via js in the ticket editor but with this format: 1.000,00'); -$I->amOnCountrySettingsAdminPage(); -$I->setCurrencyDecimalMarkTo(','); -$I->setCurrencyThousandsSeparatorTo('.'); -$I->saveCountrySettings(); -$I->amOnDefaultEventsListTablePage(); -$I->click(EventsAdmin::ADD_NEW_EVENT_BUTTON_SELECTOR); -$I->fillField(EventsAdmin::eventEditorTicketPriceFieldSelector(), '32,50'); -$I->toggleAdvancedSettingsViewForTicketRow(); -$I->waitForElementVisible(EventsAdmin::eventEditorTicketAdvancedDetailsSubtotalSelector()); -$I->see('$32,50', EventsAdmin::eventEditorTicketAdvancedDetailsSubtotalSelector()); -$I->toggleTicketIsTaxableForTicketRow(); -$I->see('$4,88', EventsAdmin::eventEditorTicketTaxAmountDisplayForTaxIdAndTicketRowSelector()); -$I->see('$37,38', EventsAdmin::eventEditorTicketAdvancedDetailsTotalSelector()); - -//restore country settings to original -$I->saveEvent(); -$I->amOnCountrySettingsAdminPage(); -$I->setCurrencyDecimalMarkTo('.'); -$I->setCurrencyThousandsSeparatorTo(','); -$I->saveCountrySettings(); \ No newline at end of file diff --git a/acceptance_tests/tests/e-TestContextActivationToggleCept.php b/acceptance_tests/tests/e-TestContextActivationToggleCept.php deleted file mode 100644 index 992c6d3808a..00000000000 --- a/acceptance_tests/tests/e-TestContextActivationToggleCept.php +++ /dev/null @@ -1,167 +0,0 @@ -wantTo( - 'Test that the context activation toggle for turning on or off specific contexts for message sending works as' - . ' expected' -); - -$I->loginAsAdmin(); - -$I->amGoingTo('Verify the toggle for toggling state on context is visible.'); -$I->amOnDefaultMessageTemplateListTablePage(); -$I->clickToEditMessageTemplateByMessageType('registration', 'admin'); -$I->see('The template for Event Admin Recipient is currently active.'); -$I->switchContextTo('Primary Registrant'); -$I->see('The template for Primary Registrant Recipient is currently active.'); - -$I->amGoingTo('Make sure the "To" field for Primary Registrant has content'); -$I->fillField(MessagesAdmin::messageTemplateToFieldSelector(), '[PRIMARY_REGISTRANT_EMAIL]'); -$I->saveMessageTemplate(); -//verify To Field has expected content after save. -$I->seeInField(MessagesAdmin::messageTemplateToFieldSelector(), '[PRIMARY_REGISTRANT_EMAIL]'); - -$I->amGoingTo('Disable the primary registrant context.'); -$I->toggleContextState('Primary Registrant Recipient', false); -//save and verify it stuck -$I->saveMessageTemplate(); -$I->see('The template for Primary Registrant Recipient is currently inactive.'); - -$I->amGoingTo( - 'Trigger Registration Approved Messages and verify primary registrant context is excluded from sent messages.' -); -$I->amOnDefaultEventsListTablePage(); -$I->click(EventsAdmin::ADD_NEW_EVENT_BUTTON_SELECTOR); -$I->fillField(EventsAdmin::EVENT_EDITOR_TITLE_FIELD_SELECTOR, $event_label); -$I->publishEvent(); -$event_link = $I->observeLinkUrlAt(EventsAdmin::EVENT_EDITOR_VIEW_LINK_AFTER_PUBLISH_SELECTOR); -$event_id = $I->observeValueFromInputAt(EventsAdmin::EVENT_EDITOR_EVT_ID_SELECTOR); -$test_registration_details = array( - 'fname' => 'ContextTestGuy', - 'lname' => 'ContextTestDude', - 'email' => 'contexttestguy@example.org', -); -$I->logOut(); -$I->amOnUrl($event_link); -$I->selectOption(TicketSelector::ticketOptionByEventIdSelector($event_id), 1); -$I->click(TicketSelector::ticketSelectionSubmitSelectorByEventId($event_id)); -$I->waitForText('Personal Information'); -$I->fillOutFirstNameFieldForAttendee($test_registration_details['fname']); -$I->fillOutLastNameFieldForAttendee($test_registration_details['lname']); -$I->fillOutEmailFieldForAttendee($test_registration_details['email']); -$I->goToNextRegistrationStep(); -$I->waitForText('Congratulations', 15); -//go to messages list table and verify -$I->loginAsAdmin(); -$I->amOnMessagesActivityListTablePage(); -//verify registrant context -$I->see( - $test_registration_details['email'], - MessagesAdmin::messagesActivityListTableCellSelectorFor( - 'to', - 'Registration Approved', - MessagesAdmin::MESSAGE_STATUS_SENT, - '', - 'Registrant' - ) -); -$I->deleteMessageInMessagesListTableFor( - 'Registration Approved', - MessagesAdmin::MESSAGE_STATUS_SENT, - 'Email', - 'Registrant' -); -//verify admin context -$I->see( - 'admin@example.com', - MessagesAdmin::messagesActivityListTableCellSelectorFor( - 'to', - 'Registration Approved', - MessagesAdmin::MESSAGE_STATUS_SENT - ) -); -$I->deleteMessageInMessagesListTableFor( - 'Registration Approved' -); -//verify primary registrant context is NOT present. -$I->dontSee( - $test_registration_details['email'], - MessagesAdmin::messagesActivityListTableCellSelectorFor( - 'to', - 'Registration Approved', - MessagesAdmin::MESSAGE_STATUS_SENT, - '', - 'Primary Registrant' - ) -); - -$I->amGoingTo( - 'Deactivate primary registrant context for Registration Approved Message Templates and restore the "To"' - . ' field to an empty string to verify the message does not send for that context.' -); -$I->amOnDefaultMessageTemplateListTablePage(); -$I->clickToEditMessageTemplateByMessageType('registration', 'primary_attendee'); -$I->toggleContextState('Primary Registrant Recipient', true); -$I->fillField(MessagesAdmin::messageTemplateToFieldSelector(), ''); -$I->saveMessageTemplate(); -$I->see('The template for Primary Registrant Recipient is currently active.'); -//repeat frontend registration and verify we get the same results with the empty "To" field. -$I->logOut(); -$I->amOnUrl($event_link); -$I->selectOption(TicketSelector::ticketOptionByEventIdSelector($event_id), 1); -$I->click(TicketSelector::ticketSelectionSubmitSelectorByEventId($event_id)); -$I->waitForText('Personal Information'); -$I->fillOutFirstNameFieldForAttendee($test_registration_details['fname']); -$I->fillOutLastNameFieldForAttendee($test_registration_details['lname']); -$I->fillOutEmailFieldForAttendee($test_registration_details['email']); -$I->goToNextRegistrationStep(); -$I->waitForText('Congratulations', 15); -//go to messages list table and verify -$I->loginAsAdmin(); -$I->amOnMessagesActivityListTablePage(); -//verify registrant context -$I->see( - $test_registration_details['email'], - MessagesAdmin::messagesActivityListTableCellSelectorFor( - 'to', - 'Registration Approved', - MessagesAdmin::MESSAGE_STATUS_SENT, - '', - 'Registrant' - ) -); -$I->deleteMessageInMessagesListTableFor( - 'Registration Approved', - MessagesAdmin::MESSAGE_STATUS_SENT, - 'Email', - 'Registrant' -); -//verify admin context -$I->see( - 'admin@example.com', - MessagesAdmin::messagesActivityListTableCellSelectorFor( - 'to', - 'Registration Approved', - MessagesAdmin::MESSAGE_STATUS_SENT - ) -); -$I->deleteMessageInMessagesListTableFor( - 'Registration Approved' -); -//verify primary registrant context is NOT present. -$I->dontSee( - $test_registration_details['email'], - MessagesAdmin::messagesActivityListTableCellSelectorFor( - 'to', - 'Registration Approved', - MessagesAdmin::MESSAGE_STATUS_SENT, - '', - 'Primary Registrant' - ) -); \ No newline at end of file diff --git a/assets/src/blocks/constants.js b/assets/src/blocks/constants.js deleted file mode 100644 index 4b54ad8de49..00000000000 --- a/assets/src/blocks/constants.js +++ /dev/null @@ -1 +0,0 @@ -export const CSS_CLASS_CORE_BLOCKS = 'ee-core-blocks event-espresso-blocks'; diff --git a/assets/src/blocks/event-attendees/edit.js b/assets/src/blocks/event-attendees/edit.js deleted file mode 100644 index a65e72509a9..00000000000 --- a/assets/src/blocks/event-attendees/edit.js +++ /dev/null @@ -1,550 +0,0 @@ -/** - * External dependencies - */ -import { InspectorControls } from '@wordpress/block-editor'; -import { Component, Fragment } from '@wordpress/element'; -import { - PanelBody, - Placeholder, - ToggleControl, - Spinner, - RangeControl, - SelectControl, -} from '@wordpress/components'; -import { withSelect } from '@wordpress/data'; -import { sprintf, _n, __ } from '@eventespresso/i18n'; -import { - EditorDatetimeSelect, - EditorEventSelect, - EditorStatusSelect, - EditorTicketSelect, - QueryLimit, - EventAttendeeList, -} from '@eventespresso/components'; -import { NotWithPostTypeCheck } from '@eventespresso/editor-hocs'; -import { - statusModel, - attendeeModel, - QUERY_ORDER_ASC, - QUERY_ORDER_DESC, - ALLOWED_ORDER_VALUES, -} from '@eventespresso/model'; -import PropTypes from 'prop-types'; -import { isEmpty } from 'lodash'; - -/** - * Internal dependencies - */ -import { CSS_CLASS_CORE_BLOCKS } from '../constants'; - -const defaultQueryData = { - showExpired: true, - limit: 50, -}; - -const isNewBlock = ( { eventId, datetimeId, ticketId } ) => eventId === 0 && - datetimeId === 0 && - ticketId === 0; - -const DEFAULT_ARRAY = []; - -let highestRequestedLimit = 200; - -/** - * EventAttendeesEditor Component - * - * This returns the component for the `edit` argument on the `EventAttendees` - * Block. - */ -export class EventAttendeesEditor extends Component { - static propTypes = { - attendees: PropTypes.array, - isLoading: PropTypes.bool, - attributes: PropTypes.shape( { - eventId: PropTypes.number, - datetimeId: PropTypes.number, - ticketId: PropTypes.number, - status: PropTypes.string, - showGravatar: PropTypes.bool, - displayOnArchives: PropTypes.bool, - limit: PropTypes.number, - orderBy: PropTypes.oneOf( [ - 'id', - 'lastNameOnly', - 'firstNameOnly', - 'firstThenLastName', - 'lastThenFirstName', - ] ), - order: PropTypes.oneOf( ALLOWED_ORDER_VALUES ), - avatarSize: PropTypes.number, - avatarClass: PropTypes.string, - } ), - }; - - static defaultProps = { - attendees: [], - isLoading: true, - attributes: { - eventId: 0, - datetimeId: 0, - ticketId: 0, - status: statusModel.REGISTRATION_STATUS_ID.APPROVED, - showGravatar: true, - displayOnArchives: false, - limit: 100, - orderBy: 'lastThenFirstName', - order: QUERY_ORDER_ASC, - avatarSize: 24, - avatarClass: 'contact', - }, - }; - - /** - * @param {Object} props - */ - constructor( props ) { - super( props ); - const { eventId, datetimeId } = this.props.attributes; - this.state = { - eventQueryData: { - ...defaultQueryData, - }, - datetimeQueryData: { - ...defaultQueryData, - forEventId: eventId, - }, - ticketQueryData: { - ...defaultQueryData, - forDatetimeId: datetimeId, - }, - statusQueryData: { - ...defaultQueryData, - statusType: statusModel.STATUS_TYPE_REGISTRATION, - }, - }; - } - - /** - * Set eventId on attributes - * @param {Object} eventId - */ - setEventId = ( eventId ) => { - const value = eventId !== null && eventId.value ? - parseInt( eventId.value, 10 ) : - 0; - this.props.setAttributes( - { - eventId: value, - datetimeId: 0, - ticketId: 0, - } - ); - this.setState( { - datetimeQueryData: { - ...this.state.datetimeQueryData, - forEventId: value, - }, - } ); - }; - - /** - * Set datetimeId on attributes - * @param {Object} datetimeId - */ - setDatetimeId = ( datetimeId ) => { - const value = datetimeId !== null && datetimeId.value ? - parseInt( datetimeId.value, 10 ) : - 0; - this.props.setAttributes( - { - datetimeId: value, - ticketId: 0, - } - ); - this.setState( { - ticketQueryData: { - ...this.state.ticketQueryData, - forDatetimeId: value, - }, - } ); - }; - - /** - * Set ticketId on attributes - * @param {Object} ticketId - */ - setTicketId = ( ticketId ) => { - const value = ticketId !== null && ticketId.value ? - parseInt( ticketId.value, 10 ) : - 0; - this.props.setAttributes( { ticketId: value } ); - }; - - /** - * Set status on attributes - * @param {Object} status - */ - setStatus = ( status ) => { - const value = status !== null && status.value ? - status.value : - statusModel.REGISTRATION_STATUS_ID.APPROVED; - this.props.setAttributes( { status: value } ); - }; - - /** - * Set limit for attendees to be shown in attributes. - * @param {number} limit - */ - setLimit = ( limit ) => { - this.props.setAttributes( { - limit: parseInt( limit, 10 ), - } ); - }; - - /** - * Set the orderBy attribute - * @param {string} orderBy - */ - setOrderBy = ( orderBy ) => { - this.props.setAttributes( { orderBy } ); - }; - - /** - * Set the order attribute - * @param {string} order - */ - setOrder = ( order ) => { - this.props.setAttributes( { order } ); - }; - - /** - * Set the size for the gravatar displayed. - * @param {number} size - */ - setAvatarSize = ( size ) => { - this.props.setAttributes( { - avatarSize: parseInt( size, 10 ), - } ); - }; - - /** - * Sets whether to show gravatar for attendees in attributes. - * @param {boolean} showGravatar - */ - toggleShowGravatar = ( showGravatar ) => { - this.props.setAttributes( { showGravatar } ); - }; - - /** - * Sets whether to show block on archive pages in attributes. - * @param {boolean} displayOnArchives - */ - toggleDisplayOnArchives = ( displayOnArchives ) => { - this.props.setAttributes( { displayOnArchives } ); - }; - - /** - * Retrieve the Attendees List component for the given attributes - * @return {Component} What to display for the attendee display. - */ - getAttendeesDisplay() { - const { isLoading, attendees } = this.props; - const { - showGravatar, - avatarSize, - avatarClass, - } = this.props.attributes; - - const avatarOptions = { - avatarWidth: avatarSize, - avatarHeight: avatarSize, - avatarClass, - }; - - if ( isLoading ) { - return ( - - - - ); - } - - if ( isNewBlock( this.props.attributes ) && - attendees === DEFAULT_ARRAY - ) { - return ( - - { __( - 'To get started, select what event you want to show attendees from in the block settings.', - 'event_espresso' - ) } - - ); - } - - if ( ! isLoading && isEmpty( attendees ) ) { - return ( - - { __( - 'There are no attendees for selected options.', - 'event_espresso' - ) } - - ); - } - return ; - } - - /** - * This receives the array of attendees and applies the limit to it so that - * only the set limit of attendees is returned from the beginning of the - * array. - * @param {Array} attendees - * @return {Array} A new array of attendees with the applied limit - */ - applyLimit( attendees ) { - if ( attendees.length <= this.props.attributes.limit ) { - return attendees; - } - return attendees.slice( 0, this.props.attributes.limit ); - } - - /** - * Returns inspector controls for the block. - * - * @param {Object} attributes - * @return {Component} The inspector controls component - */ - getInspectorControls( attributes ) { - const countAttendees = this.props.attendees.length || 0; - return ( - - - - { attributes.eventId !== 0 && - - } - { attributes.datetimeId !== 0 && - - } - - - - - - - - { attributes.showGravatar && - - } - - - - - - - ); - } - - render() { - return ( - - { this.getAttendeesDisplay() } - { this.getInspectorControls( this.props.attributes ) } - - ); - } -} - -export default withSelect( ( select, ownProps ) => { - const defaultProps = { ...EventAttendeesEditor.defaultProps.attributes }; - const { - eventId = defaultProps.eventId, - datetimeId = defaultProps.datetimeId, - ticketId = defaultProps.ticketId, - status = defaultProps.status, - orderBy = defaultProps.orderBy, - order = defaultProps.order, - limit = defaultProps.limit, - } = ownProps.attributes; - - // This ensures that we don't query unnecessarily since if the limit is - // lower than a query we've already done, then we already have cached data - // for this limit (and cache is still busted by any other query changes) - highestRequestedLimit = ! limit || - isNaN( limit ) || - limit <= highestRequestedLimit ? - highestRequestedLimit : - limit; - - const queryData = { - forEventId: eventId, - forDatetimeId: datetimeId, - forTicketId: ticketId, - forStatusId: status, - showGravatar: true, - defaultWhereConditions: 'full_this_minimum_others', - order, - orderBy, - limit: highestRequestedLimit, - }; - - const queryString = attendeeModel.getQueryString( queryData ); - const { - getAttendees, - isRequestingAttendees, - } = select( 'eventespresso/lists' ); - return { - ...EventAttendeesEditor.defaultProps, - ...ownProps, - attributes: { - ...EventAttendeesEditor.defaultProps.attributes, - ...ownProps.attributes, - }, - attendees: isNewBlock( { eventId, datetimeId, ticketId } ) ? - DEFAULT_ARRAY : - getAttendees( queryString ), - isLoading: isRequestingAttendees( queryString ), - }; -} )( EventAttendeesEditor ); diff --git a/assets/src/blocks/event-attendees/index.js b/assets/src/blocks/event-attendees/index.js deleted file mode 100644 index c8c08d6fafc..00000000000 --- a/assets/src/blocks/event-attendees/index.js +++ /dev/null @@ -1,92 +0,0 @@ -/** - * WordPress dependencies - */ -import { registerBlockType } from '@wordpress/blocks'; - -/** - * External dependencies - */ -import { __ } from '@eventespresso/i18n'; - -/** - * Internal dependencies - */ -import EventAttendeesEditor from './edit'; -import './style.css'; - -export const name = 'eventespresso/event-attendees'; - -export const settings = { - - title: __( 'Event Attendees', 'event_espresso' ), - - description: __( - 'Displays a list of people that have registered for the specified event', - 'event_espresso', - ), - - icon: 'groups', - - category: 'event-espresso', - - keywords: [ - __( 'event', 'event_espresso' ), - __( 'attendees', 'event_espresso' ), - __( 'list', 'event_espresso' ), - ], - - attributes: { - eventId: { - type: 'number', - default: 0, - }, - datetimeId: { - type: 'number', - default: 0, - }, - ticketId: { - type: 'number', - default: 0, - }, - status: { - type: 'string', - default: 'RAP', - }, - limit: { - type: 'number', - default: 100, - }, - order: { - type: 'string', - default: 'ASC', - }, - orderBy: { - type: 'string', - default: 'lastThenFirstName', - }, - showGravatar: { - type: 'boolean', - default: false, - }, - avatarClass: { - type: 'string', - default: 'contact', - }, - avatarSize: { - type: 'number', - default: 24, - }, - displayOnArchives: { - type: 'boolean', - default: false, - }, - }, - - edit: EventAttendeesEditor, - - save() { - return null; - }, -}; - -registerBlockType( name, settings ); diff --git a/assets/src/blocks/event-attendees/style.css b/assets/src/blocks/event-attendees/style.css deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/assets/src/blocks/event-attendees/test/__snapshots__/index.js.snap b/assets/src/blocks/event-attendees/test/__snapshots__/index.js.snap deleted file mode 100644 index 6de98593cdb..00000000000 --- a/assets/src/blocks/event-attendees/test/__snapshots__/index.js.snap +++ /dev/null @@ -1,388 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`EventAttendeesEditor Block block edit matches snapshot for no props 1`] = ` - - - - - - - - - - - - - - - - - - - - - - - -`; - -exports[`EventAttendeesEditor Block block edit matches snapshot with isLoading false and has attendees 1`] = ` - - - - - - - - - - - - - - - - - - - - - -`; - -exports[`EventAttendeesEditor Block block edit matches snapshot with isLoading false and no attendees 1`] = ` - - - There are no attendees for selected options. - - - - - - - - - - - - - - - - - - - - -`; diff --git a/assets/src/blocks/event-attendees/test/index.js b/assets/src/blocks/event-attendees/test/index.js deleted file mode 100644 index d31ac111136..00000000000 --- a/assets/src/blocks/event-attendees/test/index.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * External dependencies - */ -import { shallow } from 'enzyme'; - -/** - * Internal dependencies - */ -import { EventAttendeesEditor } from '../edit'; - -describe( 'EventAttendeesEditor Block', () => { - test( 'block edit matches snapshot for no props', () => { - const wrapper = shallow( ); - expect( wrapper ).toMatchSnapshot(); - } ); - test( 'block edit matches snapshot with isLoading false and ' + - 'no attendees', () => { - const wrapper = shallow( ); - expect( wrapper ).toMatchSnapshot(); - } ); - test( 'block edit matches snapshot with isLoading false ' + - 'and has attendees', () => { - const testProps = { - isLoading: false, - attendees: [ { ATT_ID: 10, ATT_fname: 'dude' } ], - }; - const wrapper = shallow( ); - expect( wrapper ).toMatchSnapshot(); - } ); -} ); diff --git a/assets/src/blocks/index-frontend.js b/assets/src/blocks/index-frontend.js deleted file mode 100644 index 5c489fde1a0..00000000000 --- a/assets/src/blocks/index-frontend.js +++ /dev/null @@ -1,3 +0,0 @@ -// So we get a frontend stylesheet built -import './event-attendees/style.css'; -import '../components/event-attendees/style.css'; diff --git a/assets/src/blocks/index.js b/assets/src/blocks/index.js deleted file mode 100644 index a83d0376eb0..00000000000 --- a/assets/src/blocks/index.js +++ /dev/null @@ -1 +0,0 @@ -import './event-attendees'; diff --git a/assets/src/components/event-attendees/attendee-list-item.js b/assets/src/components/event-attendees/attendee-list-item.js deleted file mode 100644 index c4a2b100f32..00000000000 --- a/assets/src/components/event-attendees/attendee-list-item.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * External imports - */ -import { isModelEntityOfModel } from '@eventespresso/validators'; -import warning from 'warning'; -import { Fragment } from '@wordpress/element'; - -/** - * Internal imports - */ -import { AvatarImage } from '../ui/image'; - -const AttendeeListItem = ( { - isLoading, - attendee, - showGravatar, - avatarOptions = {}, -} ) => { - function getAvatarUrl() { - const url = attendee.hasCalculatedField( 'userAvatar' ) ? - attendee.userAvatar : - ''; - return url === '' && avatarOptions.avatarUrl ? - avatarOptions.avatarUrl : - url; - } - - function getAttendeeName() { - return attendee.fname + ' ' + attendee.lname; - } - - function getAvatar() { - const url = getAvatarUrl(); - if ( ! isLoading && showGravatar && url === '' ) { - warning( - false, - 'showGravatar is true but there is no avatar url included ' + - 'with either the attendee entity or the avatarOptions prop' - ); - } - return showGravatar ? - : - null; - } - - if ( ! isModelEntityOfModel( attendee, 'attendee' ) ) { - warning( - false, - 'The EventAttendee component expects an attendee model entity.' - ); - return null; - } - - return ( - -
  • { getAvatar() }{ getAttendeeName() }
  • -
    - ); -}; -export default AttendeeListItem; diff --git a/assets/src/components/event-attendees/index.js b/assets/src/components/event-attendees/index.js deleted file mode 100644 index edb5f4d1252..00000000000 --- a/assets/src/components/event-attendees/index.js +++ /dev/null @@ -1,74 +0,0 @@ -/** - * External dependencies - */ -import { Component } from '@wordpress/element'; -import PropTypes from 'prop-types'; -import { isEmpty } from 'lodash'; -import classNames from 'classnames'; - -/** - * Internal Imports - */ -import AttendeeListItem from './attendee-list-item'; -import './style.css'; - -export default class EventAttendeeList extends Component { - static propTypes = { - isLoading: PropTypes.bool, - attendees: PropTypes.array, - showGravatar: PropTypes.bool, - containerCssClass: PropTypes.string, - containerId: PropTypes.string, - }; - - static defaultProps = { - attendees: [], - showGravatar: false, - containerCssClass: '', - containerId: 'event-attendees-list', - isLoading: false, - }; - - getAttendeeList() { - const { attendees, showGravatar, isLoading } = this.props; - if ( isEmpty( attendees ) ) { - return null; - } - const listItems = attendees.map( - ( attendee ) => { - if ( attendee.id ) { - return ; - } - return null; - } - ); - return ( -
      - { listItems } -
    - ); - } - - render() { - const { containerCssClass, containerId } = this.props; - return ( -
    - { this.getAttendeeList() } -
    - ); - } -} diff --git a/assets/src/components/event-attendees/style.css b/assets/src/components/event-attendees/style.css deleted file mode 100644 index 8a52d92a1fd..00000000000 --- a/assets/src/components/event-attendees/style.css +++ /dev/null @@ -1,17 +0,0 @@ -#ee-block-event-attendees.event-attendees ul { - list-style-type: none; -} - -#ee-block-event-attendees .contact-image-wrap-div { - display: inline-block; -} - -/** account for this current problem in WP 5.0 beta: https://core.trac.wordpress.org/ticket/45290 **/ -#ee-block-event-attendees p { - display: inline-block; -} - -#ee-block-event-attendees .contact-avatar-img { - margin: .25em 1em .25em 0; - vertical-align: middle; -} diff --git a/assets/src/components/form/index.js b/assets/src/components/form/index.js deleted file mode 100644 index 9f8ccaddf53..00000000000 --- a/assets/src/components/form/index.js +++ /dev/null @@ -1 +0,0 @@ -export * from './model'; diff --git a/assets/src/components/form/model/base/build-options.js b/assets/src/components/form/model/base/build-options.js deleted file mode 100644 index beecc8b6cda..00000000000 --- a/assets/src/components/form/model/base/build-options.js +++ /dev/null @@ -1,95 +0,0 @@ -/** - * External dependencies - */ -import { - isEmpty, - isFunction, - isUndefined, - reduce, - isArray, - isMap, -} from 'lodash'; -import warning from 'warning'; - -/** - * Receives an array|Object|Map of event entities and returns an array of simple - * objects that can be passed along to the options array used for a - * SelectControl component - * - * @param { Map|Object|Array } entities - * @param { Object } optionsEntityMap Object of key value pairs where values - * are the 'label:value' pairings used to populate the Select input. - * @param { string } mapSelection Determines which optionEntityMap pairing to - * use. - * @return { Array } Returns an array of simple objects formatted for any - * select control that receives its options in the format of an array of objects - * with label and value keys. - */ -const buildOptions = ( - entities, - optionsEntityMap, - mapSelection = 'default', -) => { - if ( isEmpty( entities ) ) { - return []; - } - entities = isMap( entities ) ? Array.from( entities.values() ) : entities; - if ( isEmpty( optionsEntityMap ) ) { - warning( - false, - 'A valid optionsEntityMap must be supplied ' + - 'in order to build options for a ModelSelect component', - optionsEntityMap, - ); - return []; - } - if ( isUndefined( optionsEntityMap[ mapSelection ] ) ) { - warning( - false, - 'A valid optionsEntityMap[ mapSelection ] must be supplied ' + - 'in order to build options for a ModelSelect component', - optionsEntityMap, - mapSelection, - ); - return []; - } - // if requested mapSelection exists then use that - let map = optionsEntityMap[ mapSelection ]; - - // if map is function then simply pass through entities to that function - if ( isFunction( map ) ) { - const options = map( entities ); - if ( isArray( options ) ) { - return options; - } - // set map to empty object because the function on it returned something - // other than an array - map = {}; - warning( - false, - 'The optionsEntityMap for ' + mapSelection + 'was a function but' + - ' it did not return an array of options. Make sure the function' + - ' returns an array of simple objects with label and value keys.', - ); - } - if ( isEmpty( map ) ) { - return []; - } - const reducerCallback = ( options, entity ) => { - const label = isFunction( map.label ) ? - map.label( entity ) : - entity[ map.label ]; - const value = isFunction( map.value ) ? - map.value( entity ) : - entity[ map.value ]; - if ( label && value ) { - options.push( { label, value } ); - } - return options; - }; - return ! isArray( entities ) ? - entities.reduce( reducerCallback, [] ) : - reduce( entities, reducerCallback, [] ); -}; - -export default buildOptions; diff --git a/assets/src/components/form/model/base/create-model-select.js b/assets/src/components/form/model/base/create-model-select.js deleted file mode 100644 index c73aea10a3a..00000000000 --- a/assets/src/components/form/model/base/create-model-select.js +++ /dev/null @@ -1,81 +0,0 @@ -/** - * External imports - */ -import { Component } from '@wordpress/element'; - -/** - * Internal imports - */ -import ModelSelect from './model-select'; -import { modelSelectName } from './utils'; -import PropTypes from 'prop-types'; - -const defaultPropTypes = { - selected: PropTypes.oneOfType( [ - PropTypes.number, - PropTypes.string, - ] ), - onSelect: PropTypes.func, - label: PropTypes.string, -}; - -/** - * Creates a Model Select component using the given arguments. - * - * @param {string} modelName - * @param {Object} defaultProps - * @param {Object} propTypes - * @return {ModelSelectComponent} A model select component. - */ -const createModelSelect = ( modelName, defaultProps = {}, propTypes = {} ) => { - class ModelSelectComponent extends Component { - /** - * @type {string} - */ - static modelName = modelName; - - /** - * @type {Object} - */ - static defaultProps = defaultProps; - - /** - * @type {Object} - */ - static propTypes = { - ...defaultPropTypes, - ...propTypes, - }; - - render() { - const { selected, onSelect } = this.props; - let { queryData } = this.props; - const selectOptions = { - selectConfiguration: { - defaultValue: selected, - onChange: onSelect, - ...this.props.selectConfiguration, - }, - }; - - if ( defaultProps.queryData && queryData ) { - queryData = { - ...defaultProps.queryData, - ...queryData, - }; - } - - const props = { - ...this.props, - ...selectOptions, - queryData, - modelName: this.constructor.modelName, - }; - return ; - } - } - ModelSelectComponent.displayName = modelSelectName( modelName ); - return ModelSelectComponent; -}; - -export default createModelSelect; diff --git a/assets/src/components/form/model/base/default-select-configuration.js b/assets/src/components/form/model/base/default-select-configuration.js deleted file mode 100644 index aafbf44e1c4..00000000000 --- a/assets/src/components/form/model/base/default-select-configuration.js +++ /dev/null @@ -1,111 +0,0 @@ -/** - * External imports - */ -import PropTypes from 'prop-types'; -import { __ } from '@eventespresso/i18n'; - -export const REACT_SELECT_TYPES = { - 'aria-describedby': PropTypes.string, - 'aria-label': PropTypes.string, - 'aria-labelledby': PropTypes.string, - autoFocus: PropTypes.bool, - backspaceRemovesValue: PropTypes.bool, - blurInputOnSelect: PropTypes.bool, - captureMenuScroll: PropTypes.bool, - className: PropTypes.string, - classNamePrefix: PropTypes.string, - closeMenuOnSelect: PropTypes.bool, - components: PropTypes.object, - controlShouldRenderValue: PropTypes.bool, - delimiter: PropTypes.string, - escapeClearsValue: PropTypes.bool, - filterOption: PropTypes.func, - formatGroupLabel: PropTypes.func, - formatOptionLabel: PropTypes.func, - getOptionLabel: PropTypes.func, - getOptionValue: PropTypes.func, - hideSelectedOptions: PropTypes.bool, - id: PropTypes.string, - inputValue: PropTypes.string, - inputId: PropTypes.string, - instanceId: PropTypes.oneOfType( [ - PropTypes.number, - PropTypes.string, - ] ), - isClearable: PropTypes.bool, - isDisabled: PropTypes.bool, - isLoading: PropTypes.bool, - isOptionDisabled: PropTypes.func, - isOptionSelected: PropTypes.func, - isMulti: PropTypes.bool, - isSearchable: PropTypes.bool, - loadingMessage: PropTypes.func, - minMenuHeight: PropTypes.number, - maxMenuHeight: PropTypes.number, - menuIsOpen: PropTypes.bool, - menuPlacement: PropTypes.oneOf( [ - 'auto', - 'bottom', - 'top', - ] ), - menuPosition: PropTypes.oneOf( [ - 'absolute', - 'fixed', - ] ), - menuPortalTarget: PropTypes.element, - menuShouldBlockScroll: PropTypes.bool, - menuShouldScrollIntoView: PropTypes.bool, - name: PropTypes.string, - noOptionsMessage: PropTypes.func, - onBlur: PropTypes.func, - onChange: PropTypes.func, - onFocus: PropTypes.func, - onInputChange: PropTypes.func, - onKeyDown: PropTypes.func, - onMenuOpen: PropTypes.func, - onMenuClose: PropTypes.func, - onMenuScrollToTop: PropTypes.func, - onMenuScrollToBottom: PropTypes.func, - openMenuOnFocus: PropTypes.bool, - openMenuOnClick: PropTypes.bool, - options: PropTypes.array, - pageSize: PropTypes.number, - placeholder: PropTypes.string, - screenReaderStatus: PropTypes.func, - styles: PropTypes.shape( { - clearIndicator: PropTypes.func, - container: PropTypes.func, - control: PropTypes.func, - dropdownIndicator: PropTypes.func, - group: PropTypes.func, - groupHeading: PropTypes.func, - indicatorsContainer: PropTypes.func, - indicatorSeparator: PropTypes.func, - input: PropTypes.func, - loadingIndicator: PropTypes.func, - loadingMessageCSS: PropTypes.func, - menu: PropTypes.func, - menuList: PropTypes.func, - menuPortal: PropTypes.func, - multiValue: PropTypes.func, - multiValueLabel: PropTypes.func, - multiValueRemove: PropTypes.func, - noOptionsMessageCSS: PropTypes.func, - option: PropTypes.func, - placeholder: PropTypes.func, - singleValue: PropTypes.func, - valueContainer: PropTypes.func, - } ), - tabIndex: PropTypes.string, - tabSelectsValue: PropTypes.bool, - value: PropTypes.oneOfType( [ - PropTypes.object, - PropTypes.array, - ] ), -}; - -export const REACT_SELECT_DEFAULTS = { - isClearable: true, - isLoading: true, - placeholder: __( 'Select...', 'event_espresso' ), -}; diff --git a/assets/src/components/form/model/base/model-select.js b/assets/src/components/form/model/base/model-select.js deleted file mode 100644 index eea1045501d..00000000000 --- a/assets/src/components/form/model/base/model-select.js +++ /dev/null @@ -1,263 +0,0 @@ -/** - * External imports - */ -import Select from 'react-select'; -import { Component, Fragment } from '@wordpress/element'; -import { isEmpty, uniqueId, find, isUndefined, isFunction, isMap } from 'lodash'; -import PropTypes from 'prop-types'; -import isShallowEqual from '@wordpress/is-shallow-equal'; - -/** - * WP dependencies - */ -import { withSelect } from '@wordpress/data'; - -/** - * Internal imports - */ -import buildOptions from './build-options'; -import { MODEL_NAMES } from '../../../../data/model/index'; -import { - REACT_SELECT_DEFAULTS, - REACT_SELECT_TYPES, -} from './default-select-configuration'; -import { - ALLOWED_ORDER_VALUES, - QUERY_ORDER_DESC, -} from '../../../../data/model/base'; - -/** - * ModelSelect component. - * This is a component that will generate a react-select input for a given - * model and its entities (provided via props). - * - * @see https://deploy-preview-2289--react-select.netlify.com/props#prop-types - * for options that can be passed through via the selectConfiguration prop. - * - * @param { Object } selectConfiguration An object containing options for the - * react-select component. - * @param { Array } modelEntities Array of model entities - * @param { string } modelName The name of the Model the entities - * belong to. - * @param { function } mapOptionsCallback This function will receive by default - * the modelEntities and optionsEntityMap, - * and is expected to return an array of options - * to be used for the react-select component. - * @param { Object } optionsEntityMap Object of key value pairs where values are the - * 'label:value' pairings used by `mapOptionsCallback` - * @param { string } mapSelection Determines which optionEntityMap pairing to use - */ -export class ModelSelect extends Component { - state = {}; - - static propTypes = { - selectConfiguration: PropTypes.shape( { - ...REACT_SELECT_TYPES, - } ), - modelEntities: PropTypes.array, - modelName: PropTypes.oneOf( MODEL_NAMES ).isRequired, - mapOptionsCallback: PropTypes.func, - optionsEntityMap: PropTypes.object, - mapSelection: PropTypes.string, - queryData: PropTypes.shape( { - limit: PropTypes.number, - orderBy: PropTypes.string, - order: PropTypes.oneOf( ALLOWED_ORDER_VALUES ), - } ), - getQueryString: PropTypes.func, - label: PropTypes.string, - }; - - static defaultProps = { - selectConfiguration: { - ...REACT_SELECT_DEFAULTS, - name: uniqueId( 'model-select-' ), - }, - modelEntities: [], - mapOptionsCallback: buildOptions, - mapSelection: 'default', - queryData: { - limit: 100, - order: QUERY_ORDER_DESC, - }, - label: '', - getQueryString: () => '', - }; - - constructor( props ) { - super( props ); - this.state = ModelSelect.setStateFromProps( props ); - } - - /** - * Sets the state from provided props - * @param {Object} props - * @return {{ - * isClearable, - * isLoading, - * placeholder, - * options: (*|Array), - * value: * - * }} - * Object to replace state. - */ - static setStateFromProps( props ) { - const { selectConfiguration } = props; - const options = ModelSelect.getOptions( props ); - const selectedValue = ModelSelect.getOptionObjectForValue( - selectConfiguration.defaultValue, options - ); - const updated = { - options, - value: selectedValue, - }; - - return { - ...REACT_SELECT_DEFAULTS, - ...selectConfiguration, - ...updated, - }; - } - - /** - * Sets up options for the select control from the incoming props. - * @param {Object} props - * @return {Array} Array of options for select control - */ - static getOptions( props ) { - const { - mapOptionsCallback, - modelEntities, - optionsEntityMap, - mapSelection, - } = props; - if ( isFunction( mapOptionsCallback ) && ! isEmpty( modelEntities ) ) { - return mapOptionsCallback( - modelEntities, - optionsEntityMap, - mapSelection - ); - } - return []; - } - - /** - * Given a value, returns the corresponding option object. - * @param {*} value - * @param {Array} options - * @return {Object|null} The option object for the given value or null. - */ - static getOptionObjectForValue( value, options ) { - if ( ! isEmpty( options ) ) { - const match = find( options, function( option ) { - return option.value === value; - } ); - return ! isUndefined( match ) ? - match : - null; - } - return null; - } - - /** - * Helper method for determining whether state should be updated. - * Criteria is whether the keys from the incoming entities are equivalent - * (equivalency means in same order as well) - * - * @param {Object} prevProps - * @param {Object} nextProps - * @return {boolean} True means state should be updated. - */ - static shouldUpdateState( prevProps, nextProps ) { - if ( prevProps === nextProps ) { - return false; - } - - const { selectConfiguration: prevConfiguration } = prevProps; - const { selectConfiguration: nextConfiguration } = nextProps; - - // if defaultValue has changed (selected value) then update state - if ( - prevConfiguration.defaultValue !== nextConfiguration.defaultValue - ) { - return true; - } - - if ( prevConfiguration.isLoading !== nextConfiguration.isLoading ) { - return true; - } - - // shallow compare of keys but only if we can - if ( - ! isMap( prevProps.modelEntities ) || - ! isMap( nextProps.modelEntities ) - ) { - return true; - } - - if ( - ! isShallowEqual( - Array.from( prevProps.modelEntities.keys() ), - Array.from( nextProps.modelEntities.keys() ) - ) - ) { - return true; - } - } - - componentDidMount() { - this.setState( - ModelSelect.setStateFromProps( this.props ) - ); - } - - componentDidUpdate( prevProps ) { - if ( ModelSelect.shouldUpdateState( prevProps, this.props ) ) { - this.setState( - ModelSelect.setStateFromProps( this.props ) - ); - } - } - - /** - * Returns the label for the select control - * - * @return {string} The label to use. - */ - getSelectLabel() { - const { label, selectConfiguration } = this.props; - return label ? - : - ''; - } - - render() { - return ( - - { this.getSelectLabel() } - - -``` - -And if there were validation errors performed, HTML for them would be automatically inserted directly into the form's HTML. - -So why should your code use the forms system instead of creating the HTML, javascript form-validation, server-side form-validation, and other related code yourself? Because this is a way of making your code more DRY ("don't repeat yourself", a coding principle that helps make your client code more easily-cheangeable), and once you get the hang of it, will be much quicker. - -That's the basics, now let's jump into how to customize your forms to make them behave and look just the way you need. - -### Input Types - -Event Espresso comes with many different built-in input types, like `EE_Email_Input` and `EE_Select_Input` you saw in `EE_Sample_Form`. They are contained in the event-espresso-core/core/libraries/form_sections/inputs. Each has a display strategy (how it looks), normalization strategy (what data type it represents), and validation strategy (what range of values it considers acceptable). - -| Input Class name | Displays as: | Normalizes to (represents): | Validates so long as the input is: | Comments | -| ---------------- | ------------ | --------------------------- | ---------------------------------- | -------- | -`EE_Admin_File_Uploader_Input` | a special WP file uploader, automatically including the needed CSS and JS | string | valid url | Should only be used from admin-pages -`EE_CVV_Input` | text input | string | integer | Also when the "sensitive data" is removed, clears out the value -`EE_Checkbox_Multi_Input` | checkbox | array of strings or array of integers | values in list of options provided | Options provided can be either strings or integers which affects the normalization and validation -`EE_Country_Select_Input` | text input | string | valid credit card | Automatically generates the list of options from entries in wp_esp_country database table -`EE_Currency_Input` | select (dropdown) | string | valid currency code | automatically generates options from entries in wp_esp_currency table -`EE_Email_Input` | email input | string | valid email address | -`EE_Fixed_Hidden_Input` | hidden input | string | N/A | User input is ignored -`EE_Month_Input` | select (dropdown) | string (January = "01", February = "02", etc) or integer (January = 1, February = 2, etc) | valid month number | constructor takes $leading_zero a boolean indicating whether values should be like "01" or 1 -`EE_Radio_Button_Input` | radio | string or integer | in list of options provided | options can be strings or integers which affects normalization and validation -`EE_Select_Input` | select (dropdown) | string or integer | in list of options provided | options can be array of strings or integers -`EE_Select_Reveal_Input` (EE4.8.41+) | select (dropdown) | string or integer | in list of options provided | same as `EE_Select_Input`, except related form sections are hidden or revealed by the selection. Eg if this input has 2 options "credit_card" and "echeck", and the input has sibling form sections BY THOSE SAME NAMES, then when "credit_card" is selected, the sibling "credit_card" form section will be revealed, and the "echeck" section will be hidden. That is, the values should be Relative Form Paths (see "Relative Form Paths" below), but are FROM THE INPUT's PARENT; in other words, they're form paths relative to this `EE_Select_Reveal_Input`, but automatically have `../` prepended onto them. -`EE_State_Select_Input` | select (dropdown) | integer (state ID) or string (state abbreviation or state name) | in list of options | Options can be an array a flat of array of strings like regular `EE_Select_Input`s, or an array of `EE_State`s, or null (which indicates to use all active states). For the latter two cases, you can use the input setting "value_field_name" to specify the name of the `EE_State` field to use for the HTML option tag's "value" attribute. -`EE_Submit_Input` | submit | string | none | -`EE_Text_Area_Input` | textarea | string | none | -`EE_Text_Input` | text | string | none | -`EE_Year_Input` | select (dropdown) | string | valid string representing a year | May optional show years in a two-digit (eg "14") or four-digit (eg "2014") format -`EE_Yes_No_Input` | select (dropdown) | boolean | none (besides verifying its a boolean) | - -### EE_Form_Section_Base - -All the other form section classes, and even form input classes, inherit from this base class. You can provide the following options in the $options_array in the constructor: - -| Option | Description | -| ------ | ----------- | -html_id | The "id" attribute of the HTML element that represents this form section (eg the div or input) -html_class | The value of the "class" attribute of the HTML element -html_style | The value of the "style" attribute of the HTML element -other_html_attributes | Any extra HTML attributes you may want to put on the HTML element representing the form section. (This should just be a string which will be put into the HTML element) - -### EE_Form_Section_Proper - -Representing a "normal" form section, with subsections and sub-inputs. It accepts all of EE_Form_Section_Base' inputs plus the following: - -| Option | Description | -| ------ | ----------- | -name | the name of the form section (will be used in the default html_name, html_id, label, etc). ONLY provide this if there is no parent form section. Otherwise, if its a sub-section of another form section, the name is specified by the subsection array key. See the example below -subsections | Array of EE_Form_Section_Base children that are the subsections of this section. Ie, an array of inputs and sub-form-sections. Array keys are the section names -layout_strategy | Sets the strategy for how the form section will be layed out when displaying it, a child of EE_Layout_Strategy_Base. This dictates what HTML will be used to open and close the form section, how the subsections will be rendered and what their spacers will be, and where the inputs, along with their labels and help text, will be placed. - -> **Important:** the topmost EE_Form_Section_Proper should be explicitly given a "name" in the constructor's arguments, otherwise its name will be derived from the classname (and if you have two forms with the name "EE_Form_Section_Proper" on the same page their input names will overlap and cause trouble). However, you should NOT set a "name" for sub-sections or inputs because it's given via the array key in the parent form section's subsections array. See below for the example. - -```php -//making a custom form that extends EE_Form_Section_Proper is a good practice -class EE_My_Form_Section extends EE_Form_Section_Proper { - function __construct( $options = array() ) { - $options[ 'subsections' ] = array_merge( array( - 'my_input' => EE_Text_Input() - ), $options[ 'subsections' ] ? $options[ 'subsections' ] : array() - parent::__construct( $options ); - } -} - -//it's best to make a class that extends EE_Form_Section_Proper -//because it's default name will be different from other forms -//and it can override parent methods if you want -$best_form = new EE_My_Form_Section( array( - 'name' => 'best_form', - 'subsections' => array( - 'input1' => new EE_Text_Input() - ) -)); - -//using EE_Form_Section_Proper is ok too, just make sure you provide a "name" -//option when it's not an sub-section -$ok_form = new EE_Form_Section_Proper( array( - 'name' => 'ok_form', - 'subsections' => array( - 'input1' => new EE_Text_Input(), - 'my_sub_form' => new EE_My_Form_Section() - ) -)); - -//when the form section you are using IS a sub-section, then DON'T provide a name -$very_bad_form = new EE_Form_Section_Proper( array( - //oups! forgot to provide a name. this is bad! compare to $ok_form - 'subsections' => array( - 'bad_named_twice' => new EE_My_Form_Section( array( - 'name' => 'unnecessary' //this sub-section shouldn't have a "name" option because the name is specified by "bad_named_twiced", - //the array key in the parent's subsections array. Compare to 'my_sub_form' in $ok_form - ), - ) -)); -``` - -### EE_Form_Input_Base - -Representing a piece of data we want to retrieve from the user in the form, and handles how we want to display that input. It accepts all of EE_Form_Section_Base' inputs plus the following: - -| Option | Description | -| ------ | ----------- | -default | normalized default/initial value (eg, if providing the default for a Yes_No_Input, you should provide TRUE or FALSE, not '1' or '0') -html_name | the value of the "name" attribute on the HTML input tag. Best left as the default -html_label_id | The value of the "id" attribute on the label tag -html_label_class | The value of the "class" attribute on the label tag -html_label_style | The value of the "style" attribute on the label tag -html_label_text | The text of the label tag for the input -html_label | Full HTML for the label on the input. Using this overrides all the other html_label_* options -html_help_text | Text explaining the input, usually placed in a tag nearby the input -html_help_class | The value of the "class" attribute on the tag containing the help text -html_help_style | The value of the "style" attribute on the tag containing the help text -required | Shortcut for adding the EE_Required_Validation strategy -display_strategy | Sets the display strategy for the input, should be a subclass of EE_Display_Strategy_Base -validation_strategies | An array of all the validation strategies on this input, children of EE_Validation_Strategy_Base -normalization_strategy | Sets the normalization strategy on this input, a child of EE_Normalization_Strategy_Base. Affects the type of the normalized_value (whether it's a string, a boolean, an int, a float, or an array of those things) -sensitive_date_removal_strategy | Sets the sensitive data removal strategy, child of EE_Sensitive_Data_Removal_Strategy. This affects how the data stored on the input is stored when you can clean_sensitive_data() on the input or the form -required_validation_error_message | The text to display near the input if it's required and NOT provided (in both the client-side and server-side validation) -validation_error_message | If the input is provided, but somehow fails validation, this is the message that will appear near the input -ignore_input | boolean. Set to `true` to have the input totally ignore whatever value the user submits server-side. This may be helpful for form inputs when they are to only be used in client-side Javascript like React, but should be totally ignored server-side - -> **Note:** some of the form inputs' first option is actually an array of options (eg EE_Checkbox_Input and EE_Radio_Button_Input), and the 2nd argument is the array of options. - -### EE_Form_Section_HTML - -HTML Form Sections are really just HTML that you want to accompany a form, but accepts no actual input. This can be handy to add a header to a form section, for example. - -You simply provide a string of HTML. - -### EE_Form_Section_HTML_From_Template - -This is the same as the EE_Form_SEction_HTML, but you instead provide a path to a template file where the HTML is contained, and an array of arguments to be made available to the template while rendering. - -### EE_Model_Form_Section - (in progress) - -A form section representing a single model object. Each field on the model will be mapped to a form input. In the future, model relations will also be mapped to a form input (or an entire subsection). This is still experimental. - -## Getting Validated, Normalized Data from your Form Sections - -Ok so you've created a form that displays nice, validates the users' data, normalizes it to the appropriate PHP types, now you want to do something with that data. What's the best way to get at it? - -### Distinction between raw_value and normalized_value - -Each form input contains two "values": - -* the raw value, the exact string or array the user provided in the form submission. This data is generally UNSAFE for usage in your code, espcially for anything getting saved to the database. The only reason you might want to use this data is to re-display it to the user in the form, saying that it was somehow didn't pass validation. It can be retrieve using `EE_Form_Input_Base::raw_value()` and `EE_Form_Input_Base::raw_value_in_form()`(escapes quotes so this can be echoed in an HTML element attribute) -* the normalized value, which is derived from the raw form input but has been validated and normalized according to the normalization strategy of the input. This can be retrieved using `EE_Form_Input_Base::normalized_value()`, or `EE_Form_Section_Proper::input_values()` and `EE_Form_Section_Proper::input_pretty_values()` (individual inputs can change the "pretty" version of the normalized value, but it's normally the same as the normalized value) - -For example, let's say you have an `EE_Yes_No_Input` input in your form like so: - -```php -$form = new EE_Form_Section_Proper( array( - 'name' => 'Darth Vaders Decision', - 'subsections' => array( - 'destroy_alderan' => new EE_Yes_No_Input() - ) -); -``` - -When that form is submitted, and someone selects "Yes", the `raw_value()` would be the string "1", and the `normalized_value()` would be the PHP boolean TRUE. - -Another example: let's say you have an `EE_Text_Input` input in your form, which you set the normalization strategy to be `EE_Int_Normalization` like so: - -```php -$form = new EE_Form_Section_Proper( array( - 'name' => 'alderan_casulaty_count_form', - 'subsections' => array( - 'count' => new EE_Text_Input( array( - 'normalization_strategy' => new EE_Int_Normalization() - ) - ) -); -``` - -Now let's say a Rebel Scum is filling this form out, they might disabled javascript so the client-side validation won't work, and they might submit a value of "0; DELETE * FROM wp_posts WHERE 1=1;" instead of a proper number (an SQL injection attack). The `raw_value()` of that input is exactly what they provided: "0; DELETE * FROM wp_posts WHERE 1=1;" and if used in a MySQL query and not escaped, may drop all the posts in your database! See why using the `raw_value()` is a bad idea? However, the `normalized_value()` will simply be NULL because that string couldn't be converted into an integer. - -So why do we even keep the `raw_value()`? Because when we check to see if the form is valid (by calling `$form->receive_form_submission( $_POST ); if( $form->is_valid() ) { ... }`) and we see that it isn't, it's nice to have the raw value the user submitted so we can display it back to them and say "Please provide integers only". - -## Form Section Usage of Strategies - -In the form sections and inputs, many of the classes share some functionality which is hard to achieve with class inheritance. Eg, there could be an `EE_Radio_Button_Input` and an `EE_Text_Input` whose values should both be integers, but there could be other `EE_Radio_Button_Input`s and other `EE_Text_Input`s whose values should be simple strings. In order to avoid repeating the same code in multiple places, instead each `EE_Form_Input_Base` child has a normalization strategy to indicate how the form input's data should be normalized into a PHP variable, and a few other strategies - -### Display Strategies - -Each input has a single display strategy which dictates how your input will appear on the page. They are contained in core/libraries/form_sections/strategies/display - -| Class Name | Description | -| ---------- | ----------- | -`EE_Admin_File_Uploader_Display_Strategy` | Displays a file upload input which should be used from Wordpress admin pages. The user can either manually enter a URL of a file into the input, or click a button to bring up Wordpress' media uploader. -`EE_Checkbox_Display_Strategy` | Should only be used by inputs extending EE_Form_Input_With_Options_Base. Shows all the options as checkboxes. -`EE_Hidden_Display_Strategy` | Inputs will be of the type "hidden" and won't take up space in the form -`EE_Radio_Button_Display_Strategy` | Should only be used with inputs extending EE_Form_Input_With_Options_Base. Shows all options as radio buttons -`EE_Select_Display_Strategy` | Should only be used with inputs extending EE_Form_Input_With_Options_Base. Shows a "select" input with each option being a nested "option" tag -`EE_Select_Multiple_Display_Strategy` | Should only be used with inputs extending EE_Form_Input_With_Options_Base. Shows a "Select multiple" input with each option being a nested "option" tag. -`EE_Submit_Input_Display_Strategy` | Displays an input of type "submit" -`EE_Text_Area_Display_Strategy` | Displays a "textarea" tag -`EE_Text_Input_Display_Strategy` | By default shows an input of type "text". However, you can provide either the strings "password" or "email" to its constructor to change its type accordingly - -### Normalization Strategies - -Each input has a single normalization strategy which dictates what PHP datatype will represent the submitted data (eg, a string, a float, an integer, an array, etc). They are contained in core/libraries/form_sections/strategies/normalization - -| Class Name | Description | -| ---------- | ----------- | -`EE_All_Caps_Normalization` | Makes sure the string is all capital letters -`EE_Boolean_Normalization` | Makes sure the value is either a php boolean `true` or `false` -`EE_Credit_Card_Normalization` | Make sure the value is a string and valid credit card number (it automatically removes whitespace from the user's input) -`EE_Float_Normalization` | Makes sure the user's input is a valid number including decimal places (including negatives) -`EE_Int_Normalization` | Makes sure the user's input is a valid whole number (including negatives) -`EE_Many_Values_Normalization` | Makes sure the result is an array. Its constructor takes an argument to indicate which other normalization strategy should be used on each of the array's elements -`EE_Slug_Normalization` | Makes sure the input is a string which can be a valid URL slug -`EE_Text_Normalization` | Just makes sure the input is a string (as opposed to an array) -`EE_Null_Normalization` | Ignores user input by replacing whatever value was received to just be `null`. Used when you don't want the input to be used server-side at all. - -### Validation Strategies - -Each input can have zero or more validation strategies which dictate what data is considered valid for the input (both client-side and server-side). They are contained in core/libraries/form_sections/strategies/validation - -| Class Name | Description | -| ---------- | ----------- | -`EE_Conditionally_Required_Validation_Strategy` (EE4.8.41+) | Same as `EE_Required_Validation_Strategy`, except the associated input is only required when provided the requirement conditions array is met. The requirement conditions array's top-level key a relative form path (see "Relative Form Paths" below), its value is an array. This 2nd level array has two items: the first is the operator (for now only '=' is accepted), and the 2nd argument is the the value the field should be in order to make the field required. Eg `array( '../payment_type' => array( '=', 'credit_card' )` means this field is required, provided the sibling input "payment_type" has the value "credit_card". -`EE_Credit_Card_Validation_Strategy` | Validates that the value is a valid credit card number -`EE_Email_Validation_Strategy` | Validates that the value is a valid email address -`EE_Enum_Validation_Strategy` | Validates that the value is one of the list of options provided to the strategy -`EE_Float_Validation_Strategy` | Validates that the value is a valid float/decimal number -`EE_Int_Validation_Strategy` | Validates that the input is a valid whole number -`EE_Many_Valued_Validation_Strategy` | Validates the value is an array. Its constructor accepts another validation strategy as an argument, indicating how to validate each element of the array -`EE_Required_Validation_Strategy` | Validates that the value isn't NULL -`EE_Simple_HTML_Validation_Strategy` | Validates that the input only contains "simple" HTML tags (only works server-side; there is currently no client-side validation for this strategy) -`EE_Text_Validation_Strategy` | Validates that the value is a simple string (ie not an array) -`EE_URL_Validation_Strategy` | Validates that the input is a valid URL. Server-side it also verifies that the URL isn't broken (ie, that we receive an HTTP 200 response when a request is sent to that URL) - -### Sensitive Data Removal Strategies - -Each input can have a sensitive data removal strategy. This strategy is optionally invoked by calling `clean_sensitive_data` on the form section or input to clean sensitive user data out of the form in case you want to store the actual form results somewhere (eg, masking credit cards numbers). They are contained in core/libraries/form_sections/strategies/sensitive_data_removal - -| Class Name | Description | -| ---------- | ----------- | -`EE_All_Sensitive_Data_Removal` | Removes the entire normalized and raw value from the input -`EE_CCV_Sensitive_Data` | Masks the entire value with Xs (eg replaces "123" with "XXX") -`EE_Credit_Card_Sensitive_Data_Removal` | Masks the entire credit card number except the last 4 digits -`EE_No_Sensitive_Data_Removal` | Leaves the normalized value as-is (default) - -### Layout Strategies - -ONLY for EE_Form_Section_Proper. This strategy dictates how to display the form section and layout its subsections. For each of the form's sub-inputs, dictates where to put the input's label, the input itself, its help text and error messages etc. These are contained in core/libraries/form_sections/strategies/layout - -| Class Name | Description | -| ---------- | ----------- | -`EE_Two_Column_Layout` | Lays the form out in two columns: the first having the input labels, the 2nd for the actual input, help text, and errors. -`EE_Admin_Two_Column_Layout` | Same as EE_Two_Column_Layout except it adds Wordpress-specific classes to make the form layout in the normal "Wordpressy" way -`EE_Div_Per_Section_Layout` | Lays the form out so that each input is in its own div tag (placing labels just above the inputs) -`EE_FIeldset_Section_Layout` | Same as EE_Div_Per_Section_Layout, except opens the form section with a fieldset and legend tags. -`EE_Template_Layout` | Uses a specific template files to layout the form. Please read the strategy's comments for documentation - -## Custom Form Layouts - -If you need a more custom form layout than what's provided by the default layout strategies, you have several options: - -* Use `EE_Template_Layout_Strategy`so the form's layout can be reused elsewhere -* Layout the form manually by using the form's - -## Form-wide Validation - -So far the form inputs' validation strategies do a pretty good job of validating users' input in forms. But what if you want form validation that depends on multiple inputs? Eg, question A is only required if checkbox B is checked? That is form-wide validation and is handled server-side quite easily in this next example. - -Basically, you need to make a child class of `EE_Form_Section_Proper` and override the `_validate()` method, by using `add_validation_error` and providing an `EE_Validation_Error` if there is a validation problem. - -```php -class My_Custom_Validation_Form extends EE_Form_Section_Proper { - function __construct( $options = array() ) { - $options[ 'subsections' ] = array_merge( array( - 'is_storm_trooper' => new EE_Yes_No_Input(), - 'passphrase' => new EE_Password_Input() - ), $options[ 'subsections' ] ? $options[ 'subsections' ] : array() - ); - } - /** - * Overrides parent's _validate() method to check - */ - protected function _validate() { - if( $this->get_input_value( 'is_storm_trooper'' ) && - $this->get_input_value( 'passphrase' ) === NULL ) { - $this->add_validation_error( new EE_Validation_Error( __( 'If you\'re a storm trooper, proivide a passphrase! Blast \'em!', 'event_espresso'), 'blast_em', $this ) ); - } - parent::_validate(); - } - - //enqueue a javascript file to handle client-side validation - public function wp_enqueu_scripts() { - parent::wp_enqueue_scripts(); - wp_enqueue_script( 'my_form_validation', 'path_to_my_js_file', array( 'jquery-validate', 'ee_form_section_validation', TRUE ); - } -} -``` - -If a validation error is added to the form, it will be considered invalid and `is_valid()` will return FALSE. Also when re-displaying the form, the form-wide validation error should appear automatically at the top of the form. - -Note that this also enqueues a javascript file which could take care of performing the same logic client-side. - -##Relative Form Paths (EE4.8.41+) -`EE_Select_Reveal_Input` and `EE_Conditionally_Required_Validation_Strategy` both use "relative form paths" to refer to other inputs in a form. These are modeled after filesystem paths. Pretend each formsection or form input is a directory in a filesystem. How would you change from the current directory, eg "/home/user/me/a" to "/home/user/me/b"? You'd type `cd ../b` right? Likewise, if you have a form with two sub-inputs, "a" and "b", and you want to refer to "b" from "a", you would you "../b". -That is, "../" means to look to the parent, and anything after that refers to a child form section. -For example, let's say we have a form that's structured like this - -``` -grantparent_form_section --parent_form_section ---child_input ---sibling_input --aunt_form_section ---cousin_input -``` - -That is, `grandparent_form_section` has two children: `parent_form_section` and `aunt_form_section`; `parent_form_section` has two child inputs: `child_input` and `sibling_input`; and `aunt_form_section` has a single child: `cousin_input`. -Here are some example relateive form paths, using this form structure: - -* From `parent_form_section` to `grandparent_form_section`: `../` (up a level) -* From `parent_form_section` to `aunt_form_setion`: `../aunt_form_section` (up a level, down to "aunt_form_section") -* From `parent_form_section` to `cousin_input`: `../aunt_form_section/cousin_input` (up a level, down to "aunt_form_section", then down to "cousin_input") -* From `parent_form_section` to `child_input`: `child_input` (down to "child_input") -* From `parent_form_section` to itself: '../parent_form_section` (up a level, down to "parent_form_section") -* From `child_input` to `sibling_input`: `../sibling_input` (up a level, down to "sibling_input") -* From 'child_input` to `parent_form_section`: `../` (up a level) -* From `child_input` to `grandparent_form_section`: `../../` (up two levels) -* From `child_input` to `cousin_input`: `../../aunt_form_section/cousin_input` (up two levels, then down to "aunt_form_section", then down to "cousin_input") -* From `grandparent_form_section` to `child_input`: `parent_form_section/child_input` (down to "parent_form_section", then down to "child_input") diff --git a/docs/K--Capability-System/README.md b/docs/K--Capability-System/README.md deleted file mode 100644 index 55ae4d6f5d3..00000000000 --- a/docs/K--Capability-System/README.md +++ /dev/null @@ -1,5 +0,0 @@ -This contains documents related to the EE4 capability system: - -## Table of Contents - -- [EE Capability System Overview](ee-capability-system-overview.md) \ No newline at end of file diff --git a/docs/K--Capability-System/ee-capability-system-overview.md b/docs/K--Capability-System/ee-capability-system-overview.md deleted file mode 100644 index ebbbe3cf432..00000000000 --- a/docs/K--Capability-System/ee-capability-system-overview.md +++ /dev/null @@ -1,102 +0,0 @@ -# EE4 Capability System Overview - -Beginning with version 4.5.0, Event Espresso has introduced a number of WordPress capabilities for restricting access to various actions and views in the users dashboard. WordPress developers familiar with the [WordPress Roles and Capabilities](http://codex.wordpress.org/Roles_and_Capabilities) system know that it provides a really powerful system for user management. - -Here's some important things to know about this new system as introduced in core: - -## No UI for user management - -The system is entirely hidden to the average user as there is no ui for user management and for the average user updating to 4.5.0 there will be no change in behaviour because all the new capabilities have been added to the core WP administrator role by default. - -We decided to take this approach because there are a plethora of Capability and User management WordPress plugins out there that can be used with our system to create roles and mix and match capabilities. At some point in the future we may create our own specific Event Espresso Roles plugin, but for now the need is met by just providing granular capabilities on EE admin pages. - -## Over 100+ granular capabilities added - -Yeah, that's a lot! There are more added in 4.6.0 with the introduction of payment methods as well. A number of capabilities follow the capability mapping system WordPress provides for not only restricting access to general views but also restricting access based on whether a user "owns" the item being viewed or not (i.e. Event Authors only being able to edit their own events, or a user being able to edit only their own custom message templates). - -> We've prepared documentation on all the capabilities and what they affect via a google spreadsheet. [Click Here for Access](https://docs.google.com/spreadsheet/ccc?key=0Al0RhqTD8pDfdEhtcFhLdW9rTFdPOWtrODh3d1QyN1E&usp=sharing"> (then press back in your browser and return to this page, and then Return to Event Espresso to view your transaction) - - - - \ No newline at end of file diff --git a/tests/mocks/addons/new-payment-method/payment_methods/New_Payment_Method_Offsite/templates/new_payment_method_offsite_intro.template.php b/tests/mocks/addons/new-payment-method/payment_methods/New_Payment_Method_Offsite/templates/new_payment_method_offsite_intro.template.php deleted file mode 100644 index e09f680c848..00000000000 --- a/tests/mocks/addons/new-payment-method/payment_methods/New_Payment_Method_Offsite/templates/new_payment_method_offsite_intro.template.php +++ /dev/null @@ -1,7 +0,0 @@ -log( $billing_info, $payment ); - switch( $billing_info[ 'status' ] ){ - case 'Approved': - $payment->set_status( $this->_pay_model->approved_status() ); - $payment->set_gateway_response( "Payment accepted"); - break; - case 'Pending': - $payment->set_status( $this->_pay_model->pending_status() ); - $payment->set_gateway_response("The payment is in progress. Another message will be sent when payment is approved."); - break; - case 'Declined': - $payment->set_status( $this->_pay_model->declined_status() ); - $payment->set_gateway_response("The payment has been declined."); - break; - case 'Failed': - $payment->set_status( $this->_pay_model->failed_status() ); - $payment->set_gateway_response("The payment failed for technical reasons or expired."); - } - return $payment; - } -} - -// End of file EEG_New_Payment_Method_Onsite.php \ No newline at end of file diff --git a/tests/mocks/addons/new-payment-method/payment_methods/New_Payment_Method_Onsite/EE_PMT_New_Payment_Method_Onsite.pm.php b/tests/mocks/addons/new-payment-method/payment_methods/New_Payment_Method_Onsite/EE_PMT_New_Payment_Method_Onsite.pm.php deleted file mode 100644 index c3be8fd7eab..00000000000 --- a/tests/mocks/addons/new-payment-method/payment_methods/New_Payment_Method_Onsite/EE_PMT_New_Payment_Method_Onsite.pm.php +++ /dev/null @@ -1,98 +0,0 @@ -file_folder().'EEG_New_Payment_Method_Onsite.gateway.php'); - $this->_gateway = new EEG_New_Payment_Method_Onsite(); - $this->_pretty_name = __("New Payment Method Onsite", 'event_espresso'); - $this->_requires_https = true; - parent::__construct($pm_instance); - } - - /** - * Adds the help tab - * @see EE_PMT_Base::help_tabs_config() - * @return array - */ - public function help_tabs_config(){ - return array( - $this->get_help_tab_name() => array( - 'title' => __('New Payment Method Onsite Settings', 'event_espresso'), - 'filename' => 'new_payment_method_onsite' - ), - ); - } - - /** - * @param \EE_Transaction $transaction - * @return \EE_Billing_Attendee_Info_Form - */ - public function generate_new_billing_form( EE_Transaction $transaction = null ) { - $form = new EE_Billing_Attendee_Info_Form( $this->_pm_instance, array( - 'name' => 'New_Payment_Method_Onsite_Form', - 'subsections' => array( - //this will become the payments status when processing payments on this mock object - 'status' => new EE_Select_Input( - array( - 'Approved' => 'Approved', - 'Pending' => 'Pending', - 'Declined' => 'Declined', - 'Failed' => 'Failed' - ), - array( 'html_help_text' => __( 'What the payment status will be set to', 'event_espresso' ) ) - ), - 'credit_card' => new EE_Credit_Card_Input( array( - 'required' => false, - 'html_label_text' => __( 'Credit Card', 'event_espresso' ), - ) ), - 'exp_month' => new EE_Credit_Card_Month_Input( true, array( - 'required' => false, - 'html_label_text' => __( 'Expiry Month', 'event_espresso' ) - ) ), - 'exp_year' => new EE_Credit_Card_Year_Input( array( - 'required' => false, - 'html_label_text' => __( 'Expiry Year', 'event_espresso' ), - ) ), - 'cvv' => new EE_CVV_Input( array( - 'required' => false, - 'html_label_text' => __( 'CVV', 'event_espresso' ) - ) ), - ) - ) ); - return $form; - } - - /** - * Gets the form for all the settings related to this payment method type - * @return EE_Payment_Method_Form - */ - public function generate_new_settings_form() { - $form = new EE_Payment_Method_Form(array( - 'extra_meta_inputs'=>array( - 'login_id'=>new EE_Text_Input(array( - 'html_label_text'=> sprintf(__("Login ID %s", "event_espresso"), $this->get_help_tab_link() ) - ))))); - return $form; - } -} -// End of file EE_PMT_Onsite.php \ No newline at end of file diff --git a/tests/mocks/addons/new-payment-method/payment_methods/New_Payment_Method_Onsite/help_tabs/index.php b/tests/mocks/addons/new-payment-method/payment_methods/New_Payment_Method_Onsite/help_tabs/index.php deleted file mode 100644 index 0dc63376116..00000000000 --- a/tests/mocks/addons/new-payment-method/payment_methods/New_Payment_Method_Onsite/help_tabs/index.php +++ /dev/null @@ -1,2 +0,0 @@ -

    -

    - -

    -

    - -

    -

    -
      -
    • -
      - -
    • -
    • -
      - -
    • -
    • -
      - -
    • -
    \ No newline at end of file diff --git a/tests/mocks/addons/new-payment-method/payment_methods/New_Payment_Method_Onsite/index.php b/tests/mocks/addons/new-payment-method/payment_methods/New_Payment_Method_Onsite/index.php deleted file mode 100644 index 0dc63376116..00000000000 --- a/tests/mocks/addons/new-payment-method/payment_methods/New_Payment_Method_Onsite/index.php +++ /dev/null @@ -1,2 +0,0 @@ - - - Event Espresso Addon rules for PHP_CodeSniffer - - ./ - - - - - - - - - - eea-new-payment-method.php - - - - *\.class_ext.php - *\.model_ext.php - - diff --git a/tests/mocks/addons/new-payment-method/scripts/espresso_new_payment_method.js b/tests/mocks/addons/new-payment-method/scripts/espresso_new_payment_method.js deleted file mode 100644 index 890f3380a9b..00000000000 --- a/tests/mocks/addons/new-payment-method/scripts/espresso_new_payment_method.js +++ /dev/null @@ -1,3 +0,0 @@ -jQuery(document).ready(function($) { - -}); \ No newline at end of file diff --git a/tests/mocks/addons/new-payment-method/scripts/index.php b/tests/mocks/addons/new-payment-method/scripts/index.php deleted file mode 100644 index 0dc63376116..00000000000 --- a/tests/mocks/addons/new-payment-method/scripts/index.php +++ /dev/null @@ -1,2 +0,0 @@ - - - - ./testcases/ - - - diff --git a/tests/mocks/addons/new-payment-method/tests/testcases/espresso_addon_skeleton.php b/tests/mocks/addons/new-payment-method/tests/testcases/espresso_addon_skeleton.php deleted file mode 100644 index 46be715a82a..00000000000 --- a/tests/mocks/addons/new-payment-method/tests/testcases/espresso_addon_skeleton.php +++ /dev/null @@ -1,29 +0,0 @@ -assertEquals( has_action('AHEE__EE_System__load_espresso_addons', 'load_espresso_new_payment_method'), 10 ); - $this->assertTrue( class_exists( 'EE_New_Payment_Method' ) ); - } -} diff --git a/tests/mocks/admin/EE_Admin_Mocks.php b/tests/mocks/admin/EE_Admin_Mocks.php deleted file mode 100644 index 9d9348410b0..00000000000 --- a/tests/mocks/admin/EE_Admin_Mocks.php +++ /dev/null @@ -1,208 +0,0 @@ -load_core('Admin_Page'); -EE_Registry::instance()->load_core('Admin_Hooks'); -EE_Registry::instance()->load_core('Admin_Page_Init'); - -/** - * Mocks an invalid hooks class - * - * @since 4.3.0 - */ -class dummy_not_exist_Hooks extends EE_Admin_Hooks { - protected function _set_hooks_properties() { - $this->_name = NULL; - } - - public function verify_page_object() { - return $this->_page_object; - } -} - - - -/** - * Mocks a valid hooks class - * - * @since 4.3.0 - */ -class mock_valid_admin_page_Admin_Mock_Valid_Hooks extends EE_Admin_Hooks { - - public $extended_properties = FALSE; - public $route_callback = FALSE; - public $redirect_action_early_callback = FALSE; - public $redirect_action_callback = FALSE; - public $redirect_filter_callback = FALSE; - public $default_admin_callback = FALSE; - public $FHEE_list_table_views_route_callback = FALSE; - public $FHEE_list_table_views_page_callback = FALSE; - public $FHEE_list_table_views_global_callback = FALSE; - public $modify_metaboxes_callback = FALSE; - public $ajax_test = FALSE; - - protected function _set_hooks_properties() { - $this->_name = 'admin_mock_valid'; - $this->_init_func = array( - 'default' => 'init_callback_test' - ); - $this->_ajax_func = array( - 'ajax_test' => 'ajax_test_callback' - ); - $this->_metaboxes = array( - 0 => array( - 'page_route' => array('default'), - 'func' => 'test_metabox', - 'label' => __('Test Metabox', 'event_espresso'), - 'priority' => 'high', - 'context' => 'normal' - ) - ); - $this->_scripts_styles = array( - 'registers' => array( - 'test-css' => array( - 'url' => 'test.css', - 'type' => 'css' - ), - 'test-js' => array( - 'url' => 'test.js', - 'depends' => array('jquery') - ) - ), - 'deregisters' => array( - 'event-editor-css' => array('type' => 'css' ) - ), - 'enqueues' => array( - 'test-css' => array( 'default' ), - 'test-js' => array( 'default' ) - ), - 'localize' => array( - 'test-js' => array( - 'TEST_ITEM' => 'this is a test' ) - ) - ); - } - - public function test_metabox() { - return true; - } - - protected function _extend_properties() { - $this->extended_properties = TRUE; - } - - - public function verify_adminpage_obj() { - return $this->_adminpage_obj; - } - - public function verify_page_object() { - return $this->_page_object; - } - - public function verify_current_route() { - return $this->_current_route; - } - - - public function verify_extend() { - return $this->_extend; - } - - public function init_callback_test() { - return true; - } - - public function default_callback() { - $this->route_callback = TRUE; - } - - public function _redirect_action_early_default() { - $this->redirect_action_early_callback = TRUE; - } - - public function _redirect_action_default() { - $this->redirect_action_callback = TRUE; - } - - public function _redirect_filter_default() { - $this->redirect_filter_callback = TRUE; - } - - - public function default_admin_footer() { - $this->default_admin_callback = TRUE; - } - - public function default_FHEE_list_table_views_mock_valid_admin_page_default() { - $this->FHEE_list_table_views_route_callback = TRUE; - } - - public function default_FHEE_list_table_views_mock_valid_admin_page() { - $this->FHEE_list_table_views_page_callback = TRUE; - } - - public function default_FHEE_list_table_views() { - $this->FHEE_list_table_views_global_callback = TRUE; - } - - public function default_AHEE__EE_Admin_Page___display_admin_page__modify_metaboxes() { - $this->modify_metaboxes_callback = TRUE; - } - - public function ajax_test_callback() { - $this->ajax_test = TRUE; - } - - - /** - * Method for setting protected properties for testing - * - * @since 4.3.0 - * - * @param string $property The name of the property to set - * @param mixed $value The value to give the property - */ - public function set_property( $property = '', $value = NULL ) { - $this->{$property} = $value; - } - - - - /** - * Method for getting protected properties for testing - * - * @since 4.3.0 - * - * @param string $property The name of the property to get.] - * @return mixed - */ - public function get_property( $property = '' ) { - return $this->{$property}; - } - - - /** - * wrapper for calling protected/private methods. - * - * @since 4.3.0 - * - * @param string $method the protected method - * to call - * @return mixed - */ - public function call_method( $method ) { - return $this->{$method}(); - } -} diff --git a/tests/mocks/admin/admin_mock_valid/Admin_Mock_Valid_Admin_Page.core.php b/tests/mocks/admin/admin_mock_valid/Admin_Mock_Valid_Admin_Page.core.php deleted file mode 100644 index 765fe0a94a1..00000000000 --- a/tests/mocks/admin/admin_mock_valid/Admin_Mock_Valid_Admin_Page.core.php +++ /dev/null @@ -1,58 +0,0 @@ -page_slug = 'mock_valid_admin_page'; - $this->page_label = __('Mock Valid Admin Page'); - $this->_admin_base_url = admin_url('admin.php?page=mock_valid_admin_page'); - $this->_admin_base_path = dirname( __FILE__ ); - } - - protected function _define_page_props() { - $this->_admin_page_title = $this->page_label; - $this->_labels = array( - 'label' => __('Some Label') - ); - } - - - protected function _set_page_routes() { - $this->_page_routes = array( - 'default' => 'default_route_callback' - ); - } - - - - protected function _set_page_config() { - $this->_page_config = array( - 'nav' => array( - 'label' => __('Mock Valid Admin Page'), - 'order' => 10 - ) - ); - } - - - public function default_route_callback() { - return true; - } - - protected function _ajax_hooks(){} - protected function _add_screen_options() {} - protected function _add_feature_pointers() {} - public function load_scripts_styles() {} - public function admin_init() {} - public function admin_notices() {} - public function admin_footer_scripts() {} -} diff --git a/tests/mocks/admin/events/Events_Admin_Page_Mock.php b/tests/mocks/admin/events/Events_Admin_Page_Mock.php deleted file mode 100644 index ab2eda891a2..00000000000 --- a/tests/mocks/admin/events/Events_Admin_Page_Mock.php +++ /dev/null @@ -1,51 +0,0 @@ -_default_tickets_update( $evtobj, $data ); - } - - - - - /** - * Mock for the _delete_event method that will handle setting up things for testing event deletes via the admin page. - * @param $EVT_ID_to_delete - */ - public function delete_event( $EVT_ID_to_delete ) { - //set request data for event - $this->_req_data['EVT_ID'] = $EVT_ID_to_delete; - $this->_delete_event( false ); - } - -} //end class Events_Admin_Page_Mock diff --git a/tests/mocks/admin/messages/Messages_Admin_Page_Mock.php b/tests/mocks/admin/messages/Messages_Admin_Page_Mock.php deleted file mode 100644 index d0752895b84..00000000000 --- a/tests/mocks/admin/messages/Messages_Admin_Page_Mock.php +++ /dev/null @@ -1,61 +0,0 @@ -_activate_messenger( $messenger_name ); - } - - - public function activate_message_type_for_messenger( $messenger_name, $message_type_name ) { - return $this->_activate_message_type_for_messenger( $messenger_name, $message_type_name ); - } - - - public function deactivate_messenger( $messenger_name ) { - return $this->_deactivate_messenger( $messenger_name ); - } - - - public function deactivate_message_type_for_messenger( $messenger_name, $message_type_name ) { - return $this->_deactivate_message_type_for_messenger( $messenger_name, $message_type_name ); - } - -} //end class Registrations_Admin_Page_Mock \ No newline at end of file diff --git a/tests/mocks/admin/pricing/espresso_events_Pricing_Hooks_Mock.php b/tests/mocks/admin/pricing/espresso_events_Pricing_Hooks_Mock.php deleted file mode 100644 index 88cce7498bd..00000000000 --- a/tests/mocks/admin/pricing/espresso_events_Pricing_Hooks_Mock.php +++ /dev/null @@ -1,52 +0,0 @@ -_date_format_strings = $format_strings; - } - - - - - - public function update_dtts( $evt_obj, $data ) { - return $this->_update_datetimes( $evt_obj, $data ); - } - - - - public function update_tkts( $evtobj, $saved_dtts, $data ) { - return $this->_update_tickets( $evtobj, $saved_dtts, $data ); - } - - -} //end espresso_events_Pricing_Hooks_mock diff --git a/tests/mocks/admin/registrations/EE_Registrations_List_Table_Mock.php b/tests/mocks/admin/registrations/EE_Registrations_List_Table_Mock.php deleted file mode 100644 index 2626d3a3e41..00000000000 --- a/tests/mocks/admin/registrations/EE_Registrations_List_Table_Mock.php +++ /dev/null @@ -1,38 +0,0 @@ -_total_registrations_this_month(); - } - - public function total_registrations_today() { - return $this->_total_registrations_today(); - } -} diff --git a/tests/mocks/admin/registrations/Registrations_Admin_Page_Mock.php b/tests/mocks/admin/registrations/Registrations_Admin_Page_Mock.php deleted file mode 100644 index f676f4f4469..00000000000 --- a/tests/mocks/admin/registrations/Registrations_Admin_Page_Mock.php +++ /dev/null @@ -1,86 +0,0 @@ -_req_data = array_merge($_POST, $_REQUEST); - return $this->_set_registration_status_from_request($status, $notify); - } - - - /** - * @param array $request - * @param int $per_page - * @param bool $count - * @return array - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @since 4.10.2.p - */ - public function get_registration_query_parameters( - $request = array(), - $per_page = 10, - $count = false - ) { - return $this->_get_registration_query_parameters($request, $per_page, $count); - } -} diff --git a/tests/mocks/admin/transactions/Transactions_Admin_Page_Mock.php b/tests/mocks/admin/transactions/Transactions_Admin_Page_Mock.php deleted file mode 100644 index 57e8c5cb10a..00000000000 --- a/tests/mocks/admin/transactions/Transactions_Admin_Page_Mock.php +++ /dev/null @@ -1,184 +0,0 @@ -_req_data += $request_data; - } - - - - /** - * create_payment_from_request_data - * - * @param array $request_data - * @return \EE_Payment - */ - public function create_payment_from_request_data( $request_data ) { - return $this->_create_payment_from_request_data($request_data); - } - - - - /** - * _process_transaction_payments - * - * @param \EE_Transaction $transaction - * @return array - */ - public function process_transaction_payments( EE_Transaction $transaction ) { - return $this->_process_transaction_payments( $transaction ); - } - - - - /** - * _get_REG_IDs_to_apply_payment_to - * - * returns a list of registration IDs that the payment will apply to - * - * @param \EE_Payment $payment - * @return array - */ - public function get_REG_IDs_to_apply_payment_to( EE_Payment $payment ) { - return $this->_get_REG_IDs_to_apply_payment_to( $payment ); - } - - - - /** - * _get_existing_reg_payment_REG_IDs - * - * returns a list of registration IDs that the payment is currently related to - * as recorded in the database - * - * @param \EE_Payment $payment - * @return array - */ - public function get_existing_reg_payment_REG_IDs( EE_Payment $payment ) { - return $this->_get_existing_reg_payment_REG_IDs( $payment ); - } - - - - /** - * _remove_existing_registration_payments - * - * this calculates the difference between existing relations - * to the supplied payment and the new list registration IDs, - * removes any related registrations that no longer apply, - * and then updates the registration paid fields - * - * @param \EE_Payment $payment - * @param int $PAY_ID - * @return bool; - */ - public function remove_existing_registration_payments( EE_Payment $payment, $PAY_ID = 0 ) { - return $this->_remove_existing_registration_payments( $payment, $PAY_ID ); - } - - - - /** - * _update_registration_payments - * - * this applies the payments to the selected registrations - * but only if they have not already been paid for - * - * @param EE_Transaction $transaction - * @param \EE_Payment $payment - * @param array $REG_IDs - * @return void - */ - public function update_registration_payments( EE_Transaction $transaction, EE_Payment $payment, $REG_IDs = array() ) { - $this->_update_registration_payments( $transaction, $payment, $REG_IDs ); - } - - - - /** - * _process_registration_status_change - * - * This processes requested registration status changes for all the registrations - * on a given transaction and (optionally) sends out notifications for the changes. - * - * @param EE_Transaction $transaction - * @param array $REG_IDs - * @return bool - */ - public function process_registration_status_change( EE_Transaction $transaction, $REG_IDs = array() ) { - return $this->_process_registration_status_change( $transaction, $REG_IDs ); - } - - - - /** - * _build_payment_json_response - * - * @access public - * @param \EE_Payment $payment - * @param array $REG_IDs - * @param bool | null $delete_txn_reg_status_change - * @return array - */ - public function build_payment_json_response( EE_Payment $payment, $REG_IDs = array(), $delete_txn_reg_status_change = null ) { - return $this->_build_payment_json_response( $payment, $REG_IDs, $delete_txn_reg_status_change ); - } - - - - /** - * _registration_payment_data_array - * adds info for 'owing' and 'paid' for each registration to the json response - * - * @param array $REG_IDs - * @return array - */ - public function registration_payment_data_array( $REG_IDs ) { - return $this->_registration_payment_data_array( $REG_IDs ); - } - - - -} //end class Registrations_Admin_Page_Mock diff --git a/tests/mocks/core/EE_Base_Class_Repository_Mock.php b/tests/mocks/core/EE_Base_Class_Repository_Mock.php deleted file mode 100644 index a1bf2a0b83f..00000000000 --- a/tests/mocks/core/EE_Base_Class_Repository_Mock.php +++ /dev/null @@ -1,28 +0,0 @@ -interface = 'EE_Ticket'; - parent::__construct(); - } - - -} -// End of file EE_Base_Class_Repository_Mock.php -// Location: /tests/mocks/core//EE_Base_Class_Repository_Mock.php \ No newline at end of file diff --git a/tests/mocks/core/EE_Class_For_Testing_Loading.core.php b/tests/mocks/core/EE_Class_For_Testing_Loading.core.php deleted file mode 100644 index 0d48bb6d23b..00000000000 --- a/tests/mocks/core/EE_Class_For_Testing_Loading.core.php +++ /dev/null @@ -1,24 +0,0 @@ -interface = 'EE_Ticket'; - } - -} -// End of file EE_Object_Collection_Mock.php -// Location: /tests/mocks/EE_Object_Collection_Mock.php \ No newline at end of file diff --git a/tests/mocks/core/EE_Object_Repository_Mock.php b/tests/mocks/core/EE_Object_Repository_Mock.php deleted file mode 100644 index bdb3767c7c4..00000000000 --- a/tests/mocks/core/EE_Object_Repository_Mock.php +++ /dev/null @@ -1,26 +0,0 @@ -interface = 'EE_Ticket'; - $this->persist_method = 'save'; - } - - -} -// End of file EE_Object_Repository_Mock.php -// Location: /tests/mocks/EE_Object_Repository_Mock.php \ No newline at end of file diff --git a/tests/mocks/core/EE_Registry_Mock.core.php b/tests/mocks/core/EE_Registry_Mock.core.php deleted file mode 100644 index 9c9399ad868..00000000000 --- a/tests/mocks/core/EE_Registry_Mock.core.php +++ /dev/null @@ -1,235 +0,0 @@ -_load($file_paths, $class_prefix, $class_name, $type, $arguments, $from_db, $cache, $load_only); - } - - - /** - * @access public - * @param string $class_name - * @param string $class_prefix - * @return null|object - */ - public function get_cached_class($class_name, $class_prefix = '', $arguments = array()) - { - return $this->_get_cached_class($class_name, $class_prefix, $arguments); - } - - - /** - * @access public - * @param string $class_name - * @param string $type - * @param array $file_paths - * @return string - */ - public function resolve_path($class_name, $type = '', $file_paths = array()) - { - return $this->_resolve_path($class_name, $type, $file_paths); - } - - - /** - * @access public - * @param string $path - * @param string $class_name - * @param string $type - * @param array $file_paths - * @return void - * @throws ReflectionException - * @throws EE_Error - */ - public function require_file($path, $class_name, $type = '', $file_paths = array()) - { - $this->_require_file($path, $class_name, $type, $file_paths); - } - - - /** - * @access public - * @param string $class_name - * @param array $arguments - * @param string $type - * @param bool $from_db - * @return null | object - * @throws ReflectionException - * @throws InvalidArgumentException - * @throws InvalidInterfaceException - * @throws InvalidDataTypeException - * @throws EE_Error - */ - public function create_object($class_name, $arguments = array(), $type = 'core', $from_db = false) - { - //echo "\n create_object"; - //echo "\n $class_name"; - //echo "\n resolve_dependencies: "; - //var_dump( $resolve_dependencies ); - return $this->_create_object($class_name, $arguments, $type, $from_db); - } - - - /** - * @access public - * @param object $class_obj - * @param string $class_name - * @param string $class_prefix - * @param bool $from_db - * @return void - */ - public function set_cached_class($class_obj, $class_name, $class_prefix = '', $from_db = false) - { - $this->_set_cached_class($class_obj, $class_name, $class_prefix, $from_db); - } - - - /** - * @access public - * @param array $array - * @return bool - */ - public function array_is_numerically_and_sequentially_indexed(array $array) - { - return $this->_array_is_numerically_and_sequentially_indexed($array); - } - - - /** - * @access public - * @param string $class_name - * @return bool - */ - public function dependency_map_has($class_name = '') - { - return $this->_dependency_map->has($class_name); - } - - - /** - * @access public - * @param string $class_name - * @param string $dependency - * @return bool - */ - public function has_dependency_for_class($class_name = '', $dependency = '') - { - return $this->_dependency_map->has_dependency_for_class($class_name, $dependency); - } - - - /** - * @access public - * @param string $class_name - * @param string $dependency - * @return bool - */ - public function loading_strategy_for_class_dependency($class_name = '', $dependency = '') - { - return $this->_dependency_map->loading_strategy_for_class_dependency($class_name, $dependency); - } - - - /** - * @access public - * @param string $class_name - * @return bool - */ - public function dependency_map_class_loader($class_name = '') - { - return $this->_dependency_map->class_loader($class_name); - } -} - - - -// End of file EE_Registry_Mock.core.php -// Location: /tests/mocks/core/EE_Registry_Mock.core.php diff --git a/tests/mocks/core/EE_Session_Mock.core.php b/tests/mocks/core/EE_Session_Mock.core.php deleted file mode 100644 index 84c88882c1f..00000000000 --- a/tests/mocks/core/EE_Session_Mock.core.php +++ /dev/null @@ -1,256 +0,0 @@ -cache_storage = $cache_storage; - $this->request = $request; - $this->encryption = $encryption; - } - - - public function lifespan() { - return 60 * MINUTE_IN_SECONDS; - } - - - - /** - * @return EE_Encryption - */ - public function encryption() { - return $this->encryption; - } - - - /** - * @param null $key - * @param bool $reset_cache - * @return array - */ - public function get_session_data($key = null, $reset_cache = false) - { - if ($reset_cache) { - $this->clear_session(); - } - if (! empty($key)) { - return isset($this->session_data[ $key ]) ? $this->session_data[ $key ] : null; - } - return $this->session_data; - } - - - /** - * set session data - * - * @access public - * @param array $data - * @return TRUE on success, FALSE on fail - */ - public function set_session_data($data) - { - foreach ($data as $key => $value) { - $this->session_data[ $key ] = $value; - } - return true; - } - - - public function clear_session($class = '', $function = '') - { - $this->session_data = array(); - } - - - /** - * @param \EE_Cart $cart - * @return bool - */ - public function set_cart(EE_Cart $cart) - { - $this->session_data['cart'] = $cart; - return true; - } - - - /** - * reset_cart - */ - public function reset_cart() - { - $this->session_data['cart'] = null; - } - - - /** - * @return \EE_Cart - */ - public function cart() - { - return isset($this->session_data['cart']) && $this->session_data['cart'] instanceof EE_Cart - ? $this->session_data['cart'] - : null; - } - - - /** - * @param \EE_Checkout $checkout - * @return bool - */ - public function set_checkout(EE_Checkout $checkout) - { - $this->session_data['checkout'] = $checkout; - return true; - } - - - /** - * reset_checkout - */ - public function reset_checkout() - { - $this->session_data['checkout'] = null; - } - - - /** - * @return \EE_Checkout - */ - public function checkout() - { - return isset($this->session_data['checkout']) && $this->session_data['checkout'] instanceof EE_Checkout - ? $this->session_data['checkout'] - : null; - } - - - /** - * @param \EE_Transaction $transaction - * @return bool - * @throws EE_Error - */ - public function set_transaction(EE_Transaction $transaction) - { - // first remove the session from the transaction before we save the transaction in the session - $transaction->set_txn_session_data(null); - $this->session_data['transaction'] = $transaction; - return true; - } - - - /** - * reset_transaction - */ - public function reset_transaction() - { - $this->session_data['transaction'] = null; - } - - - /** - * @return \EE_Transaction - */ - public function transaction() - { - return isset($this->session_data['transaction']) - && $this->session_data['transaction'] instanceof EE_Transaction - ? $this->session_data['transaction'] - : null; - } -} -// End of file EE_Session_Mock.core.php -// Location: /tests/mocks/core/EE_Session_Mock.core.php diff --git a/tests/mocks/core/Psr4AutoloaderMock.php b/tests/mocks/core/Psr4AutoloaderMock.php deleted file mode 100644 index 286a1f66dc1..00000000000 --- a/tests/mocks/core/Psr4AutoloaderMock.php +++ /dev/null @@ -1,24 +0,0 @@ -files = $files; - } - - - - protected function requireFile( $file ) { - return in_array( $file, $this->files ); - } - -} -// End of file Psr4AutoloaderMock.php -// Location: /tests/mocks/core/Psr4AutoloaderMock.php \ No newline at end of file diff --git a/tests/mocks/core/data_migration_scripts/EE_DMS_Core_1_0_0.dms.php b/tests/mocks/core/data_migration_scripts/EE_DMS_Core_1_0_0.dms.php deleted file mode 100644 index 3caf05bb8de..00000000000 --- a/tests/mocks/core/data_migration_scripts/EE_DMS_Core_1_0_0.dms.php +++ /dev/null @@ -1,41 +0,0 @@ - '3.1.26' ){ -// echo "$version_string can be migrated fro"; - return true; - }elseif( ! $version_string ){ -// echo "no version string provided: $version_string"; - //no version string provided... this must be pre 4.1 - //because since 4.1 we're - return false;//changed mind. dont want people thinking they should migrate yet because they cant - }else{ -// echo "$version_string doesnt apply"; - return false; - } - } - - public function schema_changes_after_migration() { - - } - - public function schema_changes_before_migration() { - - } -} - -// End of file EE_4_1_0_Mock.dms.php \ No newline at end of file diff --git a/tests/mocks/core/data_migration_scripts/EE_DMS_Core_5_0_0.dms.php b/tests/mocks/core/data_migration_scripts/EE_DMS_Core_5_0_0.dms.php deleted file mode 100644 index a04c1d08e52..00000000000 --- a/tests/mocks/core/data_migration_scripts/EE_DMS_Core_5_0_0.dms.php +++ /dev/null @@ -1,44 +0,0 @@ - '4.0.0' ){ -// echo "$version_string can be migrated fro"; - return true; - }elseif( ! $version_string ){ -// echo "no version string provided: $version_string"; - //no version string provided... this must be pre 4.1 - //because since 4.1 we're - return false;//changed mind. dont want people thinking they should migrate yet because they cant - }else{ -// echo "$version_string doesnt apply"; - return false; - } - } - - public function schema_changes_after_migration() { - - } - - public function schema_changes_before_migration() { - - } -} - -// End of file EE_4_1_0_Mock.dms.php \ No newline at end of file diff --git a/tests/mocks/core/db_class_extensions/EEE_Mock_Attendee.class_ext.php b/tests/mocks/core/db_class_extensions/EEE_Mock_Attendee.class_ext.php deleted file mode 100644 index 86af8e5a013..00000000000 --- a/tests/mocks/core/db_class_extensions/EEE_Mock_Attendee.class_ext.php +++ /dev/null @@ -1,34 +0,0 @@ -_model_name_extended = 'Attendee'; - parent::__construct(); - } - - /** - * Samples function that can be called on any EE_Attendee when this class extension - * is registered - * @param type $txn_id - * @return boolean - */ - function ext_foobar( $txn_id = FALSE ){ - return TRUE; - } -} - -// End of file EEE_Mock_Attendee.php \ No newline at end of file diff --git a/tests/mocks/core/db_classes/EE_Mock.class.php b/tests/mocks/core/db_classes/EE_Mock.class.php deleted file mode 100644 index 6ef45ee05a7..00000000000 --- a/tests/mocks/core/db_classes/EE_Mock.class.php +++ /dev/null @@ -1,50 +0,0 @@ -_fields[$field_name]) - ? $this->_fields[$field_name] - : null; - } -} diff --git a/tests/mocks/core/db_model_extensions/EEME_Mock_Attendee.model_ext.php b/tests/mocks/core/db_model_extensions/EEME_Mock_Attendee.model_ext.php deleted file mode 100644 index a31d584dbd0..00000000000 --- a/tests/mocks/core/db_model_extensions/EEME_Mock_Attendee.model_ext.php +++ /dev/null @@ -1,34 +0,0 @@ -_model_name_extended = 'Attendee'; - $this->_extra_tables = array( - 'Mock_Attendee_Meta' => new EE_Secondary_Table('esp_mock_attendee_meta', 'MATTM_ID', 'ATT_ID' ) - ); - $this->_extra_fields = array('Mock_Attendee_Meta'=>array( - 'MATTM_ID'=> new EE_DB_Only_Int_Field('MATTM_ID', __('Mock Attendee Meta Row ID','event_espresso'), false), - 'MATT_ID_fk'=>new EE_DB_Only_Int_Field('ATT_ID', __("Foreign Key to Attendee in Post Table", "event_espresso"), false), - 'ATT_foobar'=>new EE_Foreign_Key_Int_Field('ATT_foobar', __("Foobar", 'event_espresso'), true,0,'Transaction'))); - $this->_extra_relations = array('Transaction'=>new EE_Belongs_To_Relation()); - parent::__construct(); - } - function ext_foobar( $arg1 = FALSE ){ - return $this->_->get_all(array(array('Transaction.TXN_ID'=>$arg1))); - } -} - -// End of file EEME_Mock_Attendee.model_ext.php \ No newline at end of file diff --git a/tests/mocks/core/db_models/EEM_Mock.model.php b/tests/mocks/core/db_models/EEM_Mock.model.php deleted file mode 100644 index 3c01ade75b2..00000000000 --- a/tests/mocks/core/db_models/EEM_Mock.model.php +++ /dev/null @@ -1,39 +0,0 @@ -_tables = array( - 'Mock' => new EE_Primary_Table('esp_mock', 'MCK_ID'), - ); - $this->_fields = array( - 'Mock' => array( - 'MCK_ID' => new EE_Primary_Key_Int_Field('MCK_ID', "Mock Object ID"), - 'MCK_value' => new EE_Plain_Text_Field('MCK_value', 'Mock Object Value', true), - 'MCK_datetime' => new EE_DateTime_Field('MCK_datetime', 'Mock Datetime', false, EE_Datetime_Field::now) - ), - ); - parent::__construct($timezone); - } -} \ No newline at end of file diff --git a/tests/mocks/core/db_models/fields/EE_Datetime_Field_Mock.php b/tests/mocks/core/db_models/fields/EE_Datetime_Field_Mock.php deleted file mode 100644 index 99986bcb0c7..00000000000 --- a/tests/mocks/core/db_models/fields/EE_Datetime_Field_Mock.php +++ /dev/null @@ -1,48 +0,0 @@ -{$field}; - } - - - public function set_nullable() { - $this->_nullable = true; - } - - - public function prepare_for_display( $DateTime, $schema = false ) { - return $this->_prepare_for_display( $DateTime, $schema ); - } - - - - public function get_date_object( $date_string ) { - return parent::_get_date_object( $date_string ); - } - - - -} diff --git a/tests/mocks/core/domain/DomainMock.php b/tests/mocks/core/domain/DomainMock.php deleted file mode 100644 index 3dd7fcd3c1c..00000000000 --- a/tests/mocks/core/domain/DomainMock.php +++ /dev/null @@ -1,56 +0,0 @@ -results[] = filter_var($result, FILTER_VALIDATE_BOOLEAN); - } - - - /** - * returns true if current request matches specification - * - * @since 4.9.71.p - * @return boolean - */ - public function isMatchingRoute() - { - foreach ($this->specifications as $index => $specification) { - if (! isset($this->results[ $index ])) { - return false; - } - if ($specification->isMatchingRoute() !== $this->results[ $index ]) { - return false; - } - } - return true; - } -} \ No newline at end of file diff --git a/tests/mocks/core/domain/entities/route_match/RouteMatchSpecificationDecoratorMock.php b/tests/mocks/core/domain/entities/route_match/RouteMatchSpecificationDecoratorMock.php deleted file mode 100644 index 9edb6455132..00000000000 --- a/tests/mocks/core/domain/entities/route_match/RouteMatchSpecificationDecoratorMock.php +++ /dev/null @@ -1,36 +0,0 @@ -specification; - } - - /** - * returns true if current request matches specification - * - * @since 4.9.71.p - * @return boolean - */ - public function isMatchingRoute() - { - return $this->specification->isMatchingRoute(); - } -} \ No newline at end of file diff --git a/tests/mocks/core/domain/entities/route_match/RouteMatchSpecificationMock.php b/tests/mocks/core/domain/entities/route_match/RouteMatchSpecificationMock.php deleted file mode 100644 index 3be9f752e4f..00000000000 --- a/tests/mocks/core/domain/entities/route_match/RouteMatchSpecificationMock.php +++ /dev/null @@ -1,70 +0,0 @@ -param = $param; - } - - /** - * @param mixed $value - */ - public function setValue($value) - { - $this->value = $value; - } - - /** - * @return RequestInterface - */ - public function getRequest() - { - return $this->request; - } - - /** - * @return mixed - */ - public function getParam() - { - return $this->param; - } - - /** - * @return mixed - */ - public function getValue() - { - return $this->value; - } - - /** - * returns true if current request matches specification - * - * @since 4.9.71.p - * @return boolean - */ - public function isMatchingRoute() - { - return $this->request->getRequestParam($this->param) === $this->value; - } -} \ No newline at end of file diff --git a/tests/mocks/core/domain/services/admin/registrations/list_table/QueryBuilderMock.php b/tests/mocks/core/domain/services/admin/registrations/list_table/QueryBuilderMock.php deleted file mode 100644 index fdf1af71993..00000000000 --- a/tests/mocks/core/domain/services/admin/registrations/list_table/QueryBuilderMock.php +++ /dev/null @@ -1,154 +0,0 @@ -where_params; - } - - /** - * @return string - */ - public function getView() - { - return $this->view; - } - - /** - * Sets up the where conditions for the registrations query. - * - * @return array - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - */ - public function getWhereClause() - { - return parent::getWhereClause(); - } - - - /** - * This will add ATT_ID to the provided $this->where_clause array for EE model query parameters. - */ - public function addAttendeeIdToWhereConditions() - { - parent::addAttendeeIdToWhereConditions(); - } - - - /** - * This will add EVT_ID to the provided $this->where_clause array for EE model query parameters. - */ - public function addEventIdToWhereConditions() - { - parent::addEventIdToWhereConditions(); - } - - - /** - * Adds category ID if it exists in the request to the where conditions for the registrations query. - */ - public function addCategoryIdToWhereConditions() - { - parent::addCategoryIdToWhereConditions(); - } - - - /** - * Adds the datetime ID if it exists in the request to the where conditions for the registrations query. - */ - public function addDatetimeIdToWhereConditions() - { - parent::addDatetimeIdToWhereConditions(); - } - - - /** - * Adds the ticket ID if it exists in the request to the where conditions for the registrations query. - */ - public function AddTicketIdToWhereConditions() - { - parent::AddTicketIdToWhereConditions(); - } - - - /** - * Adds the correct registration status to the where conditions for the registrations query. - * If filtering by registration status, then we show registrations matching that status. - * If not filtering by specified status, then we show all registrations excluding incomplete registrations - * UNLESS viewing trashed registrations. - */ - public function addRegistrationStatusToWhereConditions() - { - parent::addRegistrationStatusToWhereConditions(); - } - - - /** - * Adds any provided date restraints to the where conditions for the registrations query. - * - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - */ - public function addDateToWhereConditions() - { - parent::addDateToWhereConditions(); - } - - - /** - * Adds any provided search restraints to the where conditions for the registrations query - */ - public function addSearchToWhereConditions() - { - parent::addSearchToWhereConditions(); - } - - - /** - * Sets up the orderby for the registrations query. - * - * @return array - */ - public function getOrderbyClause() - { - return parent::getOrderbyClause(); - } - - - /** - * Sets up the limit for the registrations query. - * - * @param $per_page - * @return array - */ - public function getLimitClause($per_page) - { - return parent::getLimitClause($per_page); - } -} \ No newline at end of file diff --git a/tests/mocks/core/domain/services/capabilities/CapCheckMock.php b/tests/mocks/core/domain/services/capabilities/CapCheckMock.php deleted file mode 100644 index 403f8b6cf8a..00000000000 --- a/tests/mocks/core/domain/services/capabilities/CapCheckMock.php +++ /dev/null @@ -1,64 +0,0 @@ -capability; - } - - - - /** - * @return string - */ - public function context() - { - return $this->context; - } - - - - /** - * @return int|string - */ - public function ID() - { - return $this->ID; - } -} diff --git a/tests/mocks/core/domain/services/capabilities/CapabilitiesCheckerMock.php b/tests/mocks/core/domain/services/capabilities/CapabilitiesCheckerMock.php deleted file mode 100644 index 27fbb2db0d1..00000000000 --- a/tests/mocks/core/domain/services/capabilities/CapabilitiesCheckerMock.php +++ /dev/null @@ -1,63 +0,0 @@ -cap_check_passes) { - throw new InsufficientPermissionsException($cap_check->context()); - } - return true; - } - - - - /** - * @param string $capability - the capability to be checked, like: 'ee_edit_registrations' - * @param string $context - what the user is attempting to do, like: 'Edit Registration' - * @param int $ID - (optional) ID for item where current_user_can is being called from - * @return bool - * @throws InsufficientPermissionsException - * @throws InvalidClassException - */ - public function process($capability, $context, $ID = 0) - { - return $this->processCapCheck(new CapCheckMock()); - } -} -// End of file CapabilitiesCheckerMock.php -// Location: EventEspresso\tests\mocks\core\domain\services\capabilities/CapabilitiesCheckerMock.php \ No newline at end of file diff --git a/tests/mocks/core/domain/services/contexts/RequestTypeContextFactoryMock.php b/tests/mocks/core/domain/services/contexts/RequestTypeContextFactoryMock.php deleted file mode 100644 index 2242acfa63d..00000000000 --- a/tests/mocks/core/domain/services/contexts/RequestTypeContextFactoryMock.php +++ /dev/null @@ -1,28 +0,0 @@ -_is_conditional_shortcode($shortcode); - } -} \ No newline at end of file diff --git a/tests/mocks/core/libraries/batch/JobHandlers/DatetimeOffsetFixMock.php b/tests/mocks/core/libraries/batch/JobHandlers/DatetimeOffsetFixMock.php deleted file mode 100644 index 9cc3401c7d2..00000000000 --- a/tests/mocks/core/libraries/batch/JobHandlers/DatetimeOffsetFixMock.php +++ /dev/null @@ -1,26 +0,0 @@ -_ready_queue; - } -} \ No newline at end of file diff --git a/tests/mocks/core/libraries/messages/validators/EE_Messages_Validator_Mock.php b/tests/mocks/core/libraries/messages/validators/EE_Messages_Validator_Mock.php deleted file mode 100644 index d3a03d77aa9..00000000000 --- a/tests/mocks/core/libraries/messages/validators/EE_Messages_Validator_Mock.php +++ /dev/null @@ -1,41 +0,0 @@ - 'something', - * '[ANOTHER_SHORTCODE]' => 'something else' - * ) - * - * @return string|bool If there are invalid shortcodes then a string of those shortcodes are - * returned. Otherwise false is returned. - */ - public function invalid_shortcodes( $value, $valid_shortcodes ) { - return $this->_invalid_shortcodes( $value, $valid_shortcodes ); - } - - - protected function _modify_validator() {} -} diff --git a/tests/mocks/core/libraries/shortcodes/EE_Shortcodes_Mock.php b/tests/mocks/core/libraries/shortcodes/EE_Shortcodes_Mock.php deleted file mode 100644 index 48b6f4f5ac6..00000000000 --- a/tests/mocks/core/libraries/shortcodes/EE_Shortcodes_Mock.php +++ /dev/null @@ -1,87 +0,0 @@ -label = 'Shortcodes Mock Parser'; - $this->description = 'Shortcodes Mock Description'; - $this->_shortcodes = array( - '[MOCK_A]' => 'MOCK A shortcode', - '[MOCK_B]' => 'MOCK B shortcode' - ); - } - - - /** - * This method will give parsing instructions for each shortcode defined in the _shortcodes array. Child methods - * will have to take care of handling. - * - * @access protected - * @param string $shortcode the shortcode to be parsed. - * @param mixed (object|array) $data incoming data for the parser. The data could be either an object or - * array because there are some shortcodes that might be replaced by - * prepared data that has multiple items in a list (i.e. list of attendees - * in an event and we're showing fname/lname for each attendee). In this - * case data will be in an array. Otherwise the data shoudl be in a - * properly formatted object. The EEH_Parse_Shortcodes.helper.php describes - * the data object we're expecting. - * @return string parsed shortcode - */ - protected function _parser($shortcode) - { - switch($shortcode) { - case '[MOCK_A]': - return 'parsed MOCK_A'; - break; - case '[MOCK_B]': - return 'parsed MOCK_B'; - break; - default: - return ''; - } - } - - - /** - * Note this is overriding the parent parser class so don't use this mock to test - * Any actual parser setup/verification. It's only used to directly test the _parser method in here. - * - * @param string $shortcode - * @param array $data Make sure you send in `template` and `data` as keys on this if you want them tested. - * @param array $extra_data Make sure you send in `messenger`, `message_type`, and `message` as keys on this if you - * want them tested. - * @return string - */ - public function parser($shortcode, $data = array(), $extra_data = array()) - { - $this->_data = $data; //make sure you send in template on this if you want to test template parsing - $this->_extra_data = $extra_data; - $this->_set_messages_properties(); - return $this->_parser($shortcode); - } - - - /** - * Use to test parent protected method. - * @param string $shortcode - * @param string $closing_tag - * @param bool $show - * @return string - */ - public function mutate_conditional_block_in_template($shortcode, $show = true) - { - return parent::_mutate_conditional_block_in_template( - $shortcode, - $show - ); - } -} \ No newline at end of file diff --git a/tests/mocks/core/services/EE_Injector_Tester_With_Array_Session_Int_Constructor_Params.class.php b/tests/mocks/core/services/EE_Injector_Tester_With_Array_Session_Int_Constructor_Params.class.php deleted file mode 100644 index 512265776ff..00000000000 --- a/tests/mocks/core/services/EE_Injector_Tester_With_Array_Session_Int_Constructor_Params.class.php +++ /dev/null @@ -1,71 +0,0 @@ -array_property = $some_array; - $this->session_property = $session; - $this->integer_property = $some_int; - } - - - - /** - * @return array - */ - public function array_property() { - return $this->array_property; - } - - - - /** - * @return \EE_Session_Mock - */ - public function session_property() { - return $this->session_property; - } - - - - /** - * @return int - */ - public function integer_property() { - return $this->integer_property; - } - - - -} -// End of file EE_Injector_Tester_With_Array_Session_Int_Constructor_Params.class.php -// Location: tests/mocks/core/services/EE_Injector_Tester_With_Array_Session_Int_Constructor_Params.class.php \ No newline at end of file diff --git a/tests/mocks/core/services/assets/I18nRegistryMock.php b/tests/mocks/core/services/assets/I18nRegistryMock.php deleted file mode 100644 index ccbc9d98efc..00000000000 --- a/tests/mocks/core/services/assets/I18nRegistryMock.php +++ /dev/null @@ -1,36 +0,0 @@ -incrementCallToMethod(__METHOD__); - parent::registerInlineScript($handle, $translations, $domain); - } - - - private function incrementCallToMethod($method_name) - { - if (! isset($this->track_calls_to_method[ $method_name ])) { - $this->track_calls_to_method[ $method_name ] = 0; - } - $this->track_calls_to_method[ $method_name ]++; - } - - - public function getCountOfMethodCalled($method_name) - { - return isset($this->track_calls_to_method[ $method_name ]) - ? $this->track_calls_to_method[ $method_name ] - : 0; - } -} \ No newline at end of file diff --git a/tests/mocks/core/services/cache/CacheStorageMock.php b/tests/mocks/core/services/cache/CacheStorageMock.php deleted file mode 100644 index d5e888a2237..00000000000 --- a/tests/mocks/core/services/cache/CacheStorageMock.php +++ /dev/null @@ -1,93 +0,0 @@ -storage[$key] = new stdClass(); - $this->storage[$key]->data = $data; - $this->storage[$key]->expiration = $expiration; - return true; - } - - - /** - * retrieves cache data - * should automatically trigger early cache refresh for standard cache items - * in order to avoid cache stampedes on busy sites. - * For non-standard cache items like PHP Session data where early refreshing is not wanted, - * the $standard_cache parameter should be set to false when retrieving data - * - * @param string $key [required] - * @param bool $standard_cache - * @return mixed - */ - public function get($key, $standard_cache = true) - { - return $this->storage[$key]->expiration > time() - ? $this->storage[$key]->data - : null; - } - - - /** - * delete a single cached item - * - * @param string $key [required] full or partial cache key to be deleted - */ - public function delete($key) - { - unset($this->storage[$key]); - } - - - /** - * delete multiple cached items - * - * @param array $keys [required] array of full or partial cache keys to be deleted - * @param bool $force_delete [optional] if true, then will not check incoming keys against those being tracked - * and proceed directly to deleting those entries from the cache storage - */ - public function deleteMany(array $keys, $force_delete = false) - { - foreach ($keys as $key) { - $this->delete($key); - } - } - - -} -// Location: CacheStorageMock.php diff --git a/tests/mocks/core/services/cache/PostRelatedCacheManagerMock.php b/tests/mocks/core/services/cache/PostRelatedCacheManagerMock.php deleted file mode 100644 index 8a206597add..00000000000 --- a/tests/mocks/core/services/cache/PostRelatedCacheManagerMock.php +++ /dev/null @@ -1,40 +0,0 @@ -command_handler; - } - - - - /** - * @param \EventEspresso\core\services\commands\CommandInterface $command - * @return mixed - */ - public function execute($command) - { - return $this->results; - } - -} -// End of file CommandBusMock.php -// Location: EventEspresso\tests\mocks\core\services\commands/CommandBusMock.php \ No newline at end of file diff --git a/tests/mocks/core/services/commands/CommandHandlerManagerMock.php b/tests/mocks/core/services/commands/CommandHandlerManagerMock.php deleted file mode 100644 index 95a6bde21ba..00000000000 --- a/tests/mocks/core/services/commands/CommandHandlerManagerMock.php +++ /dev/null @@ -1,58 +0,0 @@ -command_handler[$fqcn_for_command] = $command_handler; - } - - - - /** - * @param CommandInterface $command - * @param CommandBusInterface $command_bus - * @return mixed - */ - public function getCommandHandler(CommandInterface $command, CommandBusInterface $command_bus = null) - { - $command_name = get_class($command); - $handler = $this->command_handler[$command_name]; - if ($handler instanceof CompositeCommandHandler) { - $handler->setCommandBus($command_bus); - } - return $handler; - } -} -// End of file CommandHandlerManagerMock.php -// Location: EventEspresso\core\services\commands/CommandHandlerManagerMock.php \ No newline at end of file diff --git a/tests/mocks/core/services/commands/MockCommand.php b/tests/mocks/core/services/commands/MockCommand.php deleted file mode 100644 index b4e4b22b206..00000000000 --- a/tests/mocks/core/services/commands/MockCommand.php +++ /dev/null @@ -1,25 +0,0 @@ -results; - } - - - /** - * @param CommandInterface $command - * @return $this|CommandHandlerInterface - * @throws InvalidEntityException - * @since 4.9.80.p - */ - public function verify(CommandInterface $command) - { - if (! $command instanceof $this->expected) { - throw new InvalidEntityException($command, $this->expected); - } - return $this; - } -} -// End of file MockCommandHandler.php -// Location: testcases/tests/testcases/core/services/commands/MockCommandHandler.php diff --git a/tests/mocks/core/services/commands/MockCompositeCommand.php b/tests/mocks/core/services/commands/MockCompositeCommand.php deleted file mode 100644 index 5f85ab64a3b..00000000000 --- a/tests/mocks/core/services/commands/MockCompositeCommand.php +++ /dev/null @@ -1,26 +0,0 @@ -results; - } -} -// End of file MockCompositeCommandHandler.php -// Location: EventEspresso\tests\mocks\core\services\commands/MockCompositeCommandHandler.php \ No newline at end of file diff --git a/tests/mocks/core/services/commands/MockTwoCommand.php b/tests/mocks/core/services/commands/MockTwoCommand.php deleted file mode 100644 index b4e4b22b206..00000000000 --- a/tests/mocks/core/services/commands/MockTwoCommand.php +++ /dev/null @@ -1,25 +0,0 @@ -beans = $beans; - } - - - - /** - * @return string - */ - public function getBeans() - { - return $this->beans; - } - -} -// End of file Coffee.php -// Location: /Coffee.php \ No newline at end of file diff --git a/tests/mocks/core/services/container/HonduranBean.php b/tests/mocks/core/services/container/HonduranBean.php deleted file mode 100644 index 1b9bc026595..00000000000 --- a/tests/mocks/core/services/container/HonduranBean.php +++ /dev/null @@ -1,31 +0,0 @@ -identifier(); - } - - - /** - * @return array - */ - public function getAcceptableValues() - { - return $this->acceptableValues(); - } - - - /** - * @return Closure - */ - public function getEvaluationCallback() - { - return $this->evaluationCallback(); - } - -} -// Location: ContextCheckerMock.php diff --git a/tests/mocks/core/services/dependencies/DependencyResolverMock.php b/tests/mocks/core/services/dependencies/DependencyResolverMock.php deleted file mode 100644 index 1761b2d1963..00000000000 --- a/tests/mocks/core/services/dependencies/DependencyResolverMock.php +++ /dev/null @@ -1,45 +0,0 @@ -aliases; - } - - /** - * @return array - */ - public function getNamespaceRoots() - { - return $this->namespace_roots; - } - - /** - * Used to configure and/or setup any aliases or namespace roots required by the DependencyResolver - * - * @since 4.9.71.p - * @throws InvalidAliasException - */ - public function initialize() - { - // do nothing as we will configure everything within our tests - } -} \ No newline at end of file diff --git a/tests/mocks/core/services/dependencies/composites/Oof.php b/tests/mocks/core/services/dependencies/composites/Oof.php deleted file mode 100644 index 697ab70872e..00000000000 --- a/tests/mocks/core/services/dependencies/composites/Oof.php +++ /dev/null @@ -1,18 +0,0 @@ -key = 'oof'; - } -} diff --git a/tests/mocks/core/services/dependencies/composites/OofOuchOwie.php b/tests/mocks/core/services/dependencies/composites/OofOuchOwie.php deleted file mode 100644 index ac6bfc277cb..00000000000 --- a/tests/mocks/core/services/dependencies/composites/OofOuchOwie.php +++ /dev/null @@ -1,45 +0,0 @@ -setKey(); - $this->request = $request; - } - - abstract public function setKey(); - - /** - * @since 4.9.71.p - * @return string - */ - public function oofOuchOwie() - { - return $this->request->getRequestParam($this->key); - } -} diff --git a/tests/mocks/core/services/dependencies/composites/OofOuchOwieDecorator.php b/tests/mocks/core/services/dependencies/composites/OofOuchOwieDecorator.php deleted file mode 100644 index b779b327423..00000000000 --- a/tests/mocks/core/services/dependencies/composites/OofOuchOwieDecorator.php +++ /dev/null @@ -1,39 +0,0 @@ -oofOuchOwie = $oofOuchOwie; - parent::__construct($request); - } - - /** - * @since 4.9.71.p - * @return string - */ - public function oofOuchOwie() - { - return $this->oofOuchOwie->oofOuchOwie() . $this->request->getRequestParam($this->key); - } -} \ No newline at end of file diff --git a/tests/mocks/core/services/dependencies/composites/OofOuchOwieInterface.php b/tests/mocks/core/services/dependencies/composites/OofOuchOwieInterface.php deleted file mode 100644 index 4210b9ac9d0..00000000000 --- a/tests/mocks/core/services/dependencies/composites/OofOuchOwieInterface.php +++ /dev/null @@ -1,19 +0,0 @@ -key = 'ouch'; - } -} diff --git a/tests/mocks/core/services/dependencies/composites/Owie.php b/tests/mocks/core/services/dependencies/composites/Owie.php deleted file mode 100644 index f48cb495ead..00000000000 --- a/tests/mocks/core/services/dependencies/composites/Owie.php +++ /dev/null @@ -1,18 +0,0 @@ -key = 'owie'; - } -} diff --git a/tests/mocks/core/services/loaders/CachingLoaderMock.php b/tests/mocks/core/services/loaders/CachingLoaderMock.php deleted file mode 100644 index ebef8fe4503..00000000000 --- a/tests/mocks/core/services/loaders/CachingLoaderMock.php +++ /dev/null @@ -1,35 +0,0 @@ -cache; - } - - - -} -// End of file CachingLoaderMock.php -// Location: EventEspresso\tests\mocks\core\services\loaders/CachingLoaderMock.php \ No newline at end of file diff --git a/tests/mocks/core/services/loaders/ClassToLoad.php b/tests/mocks/core/services/loaders/ClassToLoad.php deleted file mode 100644 index c721dcc6a76..00000000000 --- a/tests/mocks/core/services/loaders/ClassToLoad.php +++ /dev/null @@ -1,47 +0,0 @@ -args = $args; - } - - - /** - * @return array - */ - public function args() - { - return $this->args; - } - - - public function sameInstance(ClassToLoad $other_class) - { - return $other_class === $this; - } -} diff --git a/tests/mocks/core/services/loaders/NewClassToLoad.php b/tests/mocks/core/services/loaders/NewClassToLoad.php deleted file mode 100644 index 7f91f546679..00000000000 --- a/tests/mocks/core/services/loaders/NewClassToLoad.php +++ /dev/null @@ -1,19 +0,0 @@ -processRequestStack($request, $response); - } -} diff --git a/tests/mocks/core/services/request/ObiWanKenobiWare.php b/tests/mocks/core/services/request/ObiWanKenobiWare.php deleted file mode 100644 index 3961cf60ab8..00000000000 --- a/tests/mocks/core/services/request/ObiWanKenobiWare.php +++ /dev/null @@ -1,16 +0,0 @@ -processRequestStack($request, $response); - } -} diff --git a/tests/mocks/core/services/request/RequestMock.php b/tests/mocks/core/services/request/RequestMock.php deleted file mode 100644 index 8e3850998f3..00000000000 --- a/tests/mocks/core/services/request/RequestMock.php +++ /dev/null @@ -1,227 +0,0 @@ -get = $get; - $this->post = $post; - $this->cookie = $cookie; - $this->server = $server; - $this->files = $files; - $this->request = array_merge($this->get, $this->post); - $this->ip_address = $this->visitorIp($ip_address); - parent::__construct($get, $post, $cookie, $server); - } - - - /** - * @param string $key - * @param string $value - * @param bool $override_ee - * @return void - */ - public function setRequestParam($key, $value, $override_ee = false) - { - $this->request[ $key ] = $value; - } - - - /** - * returns the value for a request param if the given key exists - * - * @param string $key - * @param null $default - * @return mixed - */ - public function getRequestParam($key, $default = null) - { - return isset($this->request[ $key ]) ? $this->request[ $key ] : $default; - } - - - /** - * check if param exists - * - * @param string $key - * @return bool - */ - public function requestParamIsSet($key) - { - return isset($this->request[ $key ]); - } - - - /** - * check if a request parameter exists whose key that matches the supplied wildcard pattern - * and return the value for the first match found - * wildcards can be either of the following: - * ? to represent a single character of any type - * * to represent one or more characters of any type - * - * @param string $pattern - * @param null|mixed $default - * @return false|int - */ - public function getMatch($pattern, $default = null) - { - // replace wildcard chars with regex chars - $pattern = str_replace( - array("\*", "\?"), - array('.*', '.'), - preg_quote($pattern, '/') - ); - foreach ($this->request as $key => $request_param) { - if (preg_match('/^' . $pattern . '$/is', $key)) { - return $request_param; - } - } - return null; - } - - - /** - * check if a request parameter exists whose key matches the supplied wildcard pattern - * wildcards can be either of the following: - * ? to represent a single character of any type - * * to represent one or more characters of any type - * returns true if a match is found or false if not - * - * @param string $pattern - * @return false|int - */ - public function matches($pattern) - { - return $this->getMatch($pattern) !== null; - } - - - /** - * remove param - * - * @param string $key - * @param bool $unset_from_global_too - */ - public function unSetRequestParam($key, $unset_from_global_too = false) - { - unset($this->request[ $key ]); - } - - - /** - * @param string $visitor_ip - * @return string - */ - public function visitorIp($visitor_ip = '0.0.0.0') - { - return $visitor_ip; - } - - - /** - * @param bool $relativeToWpRoot - * @return string - */ - public function requestUri($relativeToWpRoot = false) - { - return isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : ''; - } - - - /** - * @param string $user_agent - */ - public function setUserAgent($user_agent = '') - { - $this->user_agent = $user_agent; - } - - -} \ No newline at end of file diff --git a/tests/mocks/core/services/request/RequestStackBuilderMock.php b/tests/mocks/core/services/request/RequestStackBuilderMock.php deleted file mode 100644 index 17e570c8688..00000000000 --- a/tests/mocks/core/services/request/RequestStackBuilderMock.php +++ /dev/null @@ -1,30 +0,0 @@ -int = (int) $int_value; - } - - - public function intValue() - { - return $this->int; - } -} \ No newline at end of file diff --git a/tests/mocks/modules/EED_Single_Page_Checkout_Mock.php b/tests/mocks/modules/EED_Single_Page_Checkout_Mock.php deleted file mode 100644 index a0165b6b542..00000000000 --- a/tests/mocks/modules/EED_Single_Page_Checkout_Mock.php +++ /dev/null @@ -1,18 +0,0 @@ -_is_reg_checkout(); - } -} \ No newline at end of file diff --git a/tests/mocks/modules/EED_Ticket_Sales_Monitor_Mock.php b/tests/mocks/modules/EED_Ticket_Sales_Monitor_Mock.php deleted file mode 100644 index 48e04013383..00000000000 --- a/tests/mocks/modules/EED_Ticket_Sales_Monitor_Mock.php +++ /dev/null @@ -1,29 +0,0 @@ -_pay_model->get_payment_by_txn_id_chq_nmbr($update_info[ 'gateway_txn_id' ] ); - if($payment instanceof EEI_Payment && isset( $update_info[ 'status' ] ) ){ - if( $update_info[ 'status' ] == $this->_pay_model->approved_status() ){ - $payment->set_status( $this->_pay_model->approved_status() ); - }elseif( $update_info[ 'status' ] == $this->_pay_model->pending_status() ){ - $payment->set_status( $this->_pay_model->pending_status() ); - }else{ - $payment->set_status( $this->_pay_model->failed_status() ); - } - } - return $payment; - } - - - - /** - * - * @param EEI_Payment $payment - * @param array $billing_info - * @param string $return_url - * @param string $notify_url - * @param string $cancel_url - * @return \EE_Payment|\EEI_Payment - */ - public function set_redirection_info( $payment, $billing_info = array(), $return_url = NULL, $notify_url = NULL, $cancel_url = NULL ) { - global $auto_made_thing_seed; - $payment->set_redirect_url('http://google.com'); - $payment->set_txn_id_chq_nmbr( $auto_made_thing_seed++ ); - return $payment; - } -} - -// End of file EEG_Mock_Onsite.php \ No newline at end of file diff --git a/tests/mocks/payment_methods/Mock_Offsite/EE_PMT_Mock_Offsite.pm.php b/tests/mocks/payment_methods/Mock_Offsite/EE_PMT_Mock_Offsite.pm.php deleted file mode 100644 index 570aa7f5286..00000000000 --- a/tests/mocks/payment_methods/Mock_Offsite/EE_PMT_Mock_Offsite.pm.php +++ /dev/null @@ -1,59 +0,0 @@ -file_folder().'EEG_Mock_Offsite.gateway.php'); - $this->_gateway = new EEG_Mock_Offsite(); - $this->_pretty_name = __("Mock Offsite", 'event_espresso'); - parent::__construct($pm_instance); - } - - /** - * Creates the billing form for this payment method type - * @param \EE_Transaction $transaction - * @return NULL - */ - public function generate_new_billing_form( EE_Transaction $transaction = NULL ) { - return NULL; - } - - /** - * Gets the form for all the settings related to this payment method type - * @return EE_Payment_Method_Form - */ - public function generate_new_settings_form() { - $form = new EE_Payment_Method_Form(array( - 'extra_meta_inputs'=>array( - 'login_id'=>new EE_Text_Input(array( - 'html_label_text'=> sprintf(__("Login ID %s", "event_espresso"), EEH_Template::get_help_tab_link(self::help_tab_link)) - ))))); - return $form; - } - - - -} - -// End of file EE_PMT_Onsite.php \ No newline at end of file diff --git a/tests/mocks/payment_methods/Mock_Onsite/EEG_Mock_Onsite.gateway.php b/tests/mocks/payment_methods/Mock_Onsite/EEG_Mock_Onsite.gateway.php deleted file mode 100644 index 47631264031..00000000000 --- a/tests/mocks/payment_methods/Mock_Onsite/EEG_Mock_Onsite.gateway.php +++ /dev/null @@ -1,33 +0,0 @@ -log( $billing_info, $payment ); - $payment->set_status( $billing_info[ 'status' ] ); - return $payment; - } -} - -// End of file EEG_Mock_Onsite.php \ No newline at end of file diff --git a/tests/mocks/payment_methods/Mock_Onsite/EE_PMT_Mock_Onsite.pm.php b/tests/mocks/payment_methods/Mock_Onsite/EE_PMT_Mock_Onsite.pm.php deleted file mode 100644 index 41dfcee8cde..00000000000 --- a/tests/mocks/payment_methods/Mock_Onsite/EE_PMT_Mock_Onsite.pm.php +++ /dev/null @@ -1,69 +0,0 @@ -file_folder().'EEG_Mock_Onsite.gateway.php'); - $this->_gateway = new EEG_Mock_Onsite(); - $this->_pretty_name = __("Mock Onsite", 'event_espresso'); - parent::__construct($pm_instance); - } - - /** - * @param \EE_Transaction $transaction - * @return \EE_Billing_Attendee_Info_Form - */ - public function generate_new_billing_form( EE_Transaction $transaction = NULL ) { - $form = new EE_Billing_Attendee_Info_Form($this->_pm_instance,array( - 'name'=>'Mock_Onsite_Form', - 'subsections'=>array( - 'status' => new EE_Text_Input(),//this will become the payments status when processing payments on this mock object - 'credit_card'=>new EE_Credit_Card_Input(array( - 'required'=>false - )), - 'exp_month'=>new EE_Month_Input(true, array( - 'required'=>false - )), - 'exp_year'=>new EE_Year_Input(), - 'cvv'=>new EE_CVV_Input(), - ) - )); - return $form; - } - - /** - * Gets the form for all the settings related to this payment method type - * @return EE_Payment_Method_Form - */ - public function generate_new_settings_form() { - $form = new EE_Payment_Method_Form(array( - 'extra_meta_inputs'=>array( - 'login_id'=>new EE_Text_Input(array( - 'html_label_text'=> sprintf(__("Login ID %s", "event_espresso"), EEH_Template::get_help_tab_link(self::help_tab_link)) - ))))); - return $form; - } -} - -// End of file EE_PMT_Onsite.php \ No newline at end of file diff --git a/tests/phpunit.xml b/tests/phpunit.xml deleted file mode 100644 index 5075f1232a7..00000000000 --- a/tests/phpunit.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - - ../ - - ../acceptance_tests - ../assets - ../bin - ../config - ../docs - ../eslint - ../languages - ../node_modules - ../scripts - ../public - ../tests - ../vendor - ../wp-assets - - - - - - ./testcases/ - - - - - ignore - live - big_rest_tests - - - - - - - - 2000 - - - - - - - - - diff --git a/tests/testcases/admin_pages/events/Events_Admin_Page_Test.php b/tests/testcases/admin_pages/events/Events_Admin_Page_Test.php deleted file mode 100644 index e0f1feead05..00000000000 --- a/tests/testcases/admin_pages/events/Events_Admin_Page_Test.php +++ /dev/null @@ -1,61 +0,0 @@ -delayedAdminPageMocks( 'events' ); - } - - - - protected function _load_requirements( $timezone = 'America/Vancouver' ) { - $this->_admin_page = new Events_Admin_Page_Mock(); - $this->_event = $this->factory->event->create(); - $this->_event->set_timezone( $timezone ); - $this->_event->save(); - $this->_set_default_dates( $timezone ); - } - - - - - /** - * Tests the _delete_event method via the mock - * @see https://events.codebasehq.com/projects/event-espresso/tickets/9699 - * @group 9699 - */ - public function test_delete_event() { - $this->_load_requirements(); - //let's delete the event - $this->_admin_page->delete_event( $this->_event->ID() ); - - //assert it got deleted! - $this->assertEmpty( EEM_Event::instance()->get_one_by_ID( $this->_event->ID() ) ); - } -} \ No newline at end of file diff --git a/tests/testcases/admin_pages/events_decaf/Events_Admin_Page_Decaf_Test.php b/tests/testcases/admin_pages/events_decaf/Events_Admin_Page_Decaf_Test.php deleted file mode 100644 index 7f998f95d65..00000000000 --- a/tests/testcases/admin_pages/events_decaf/Events_Admin_Page_Decaf_Test.php +++ /dev/null @@ -1,227 +0,0 @@ -delayedAdminPageMocks( 'decaf_events' ); - } - - - /** - * loader for setting the $_admin_page_property - * - * @param string $timezone Timezone string to initialize the times in. - * @since 4.6 - */ - protected function _load_requirements( $timezone = 'America/Vancouver' ) { - $this->_admin_page = new Events_Admin_Page_Mock(); - $this->_event = $this->factory->event->create(); - $this->_event->set_timezone( $timezone ); - $this->_event->save(); - $this->_set_default_dates( $timezone ); - } - - - - - /** - * tests the decaf datetime and tickets update method for Events Admin Page. - * - *@since 4.6 - */ - public function test_default_tickets_update() { - //first test is just with default data - $this->_load_requirements(); - $this->_testing_updates( "Tests with Default Data\n" ); - - //next test is with empty TKT_start and TKT_end dates. - $replacement['edit_tickets']['1']['TKT_start_date'] = null; - $replacement['edit_tickets']['1']['TKT_end_date'] = null; - - //override _default_dates because we expect something different. - $this->_default_dates = array(); - $this->_load_requirements(); - $this->_default_dates['TKT_start'] = new DateTime( 'now', new DateTimeZone( 'America/Vancouver' ) ); - - /** - * TKT_start is set in the decaf ticket saves without seconds, so we need to set the seconds to zero as well for comparison. - */ - $this->_default_dates['TKT_start']->setTime( $this->_default_dates['TKT_start']->format( 'H' ), $this->_default_dates['TKT_start']->format( 'i' ), 0 ); - /** - * tkt end date is the same as start date because here's the code execution in Events_Admin_page::default_tickets_update: - * 1. If no TKT_end_date, then set to DTT_EVT_start. - * 2. However, this means that DTT_EVT_start (because its static) will always be earlier than what the value for TKT_start_date is. - * 3. So later the code changes TKT_end_date to be the SAME as TKT_start_date and then sets it forward by a day. So that's what our expected value will be. - */ - $this->_default_dates['TKT_end'] = clone $this->_default_dates['TKT_start']; - $this->_default_dates['TKT_end'] = $this->_default_dates['TKT_end']->add( new DateInterval( 'P1D' ) ); - $this->_testing_updates( "Tests with unset tkt start and end date\n", $replacement ); - - } - - - - - /** - * This is a common looped to test saves of ticket and datetime data. - * - * @param string $context_for_error_messages Used this to add context to any failed tests so - * you can easily verify what triggered it. - * @param array $data_to_replace An array of replacements for the default data. - * Use null to indicate you want the key unset. - * @since 4.6 - */ - protected function _testing_updates( $context_for_error_messages, $data_to_replace = array() ) { - $formats_to_test = $this->date_formats_to_test(); - - $saved_dtts_for_tickets = $formats_for_compare = $saved_tkts = array(); - - /** - * Note: Keep in mind, decaf does NOT provide the ability to choose the format that the dates are - * displayed in for the event editor. So when we test comparing formats, it is important to set the - * format on the objects before retrieval. Also important is that only the 'Y-m-d h:i a' format is used - * on the decaf editor form. So we make sure the all the dates going in for the data are in the same format. - */ - - foreach( $formats_to_test['date'] as $date_format ) { - foreach( $formats_to_test['time'] as $time_format ) { - $full_format = $date_format . ' ' . $time_format; - $decaf_date_format = 'Y-m-d h:i a'; - $data = $this->_get_save_data( $decaf_date_format ); - - //is there any data to unset/replace? - if ( ! empty( $data_to_replace ) ) { - //any data to unset? - foreach( $data_to_replace as $top_level => $second_level ) { - if ( is_array( $second_level ) ) { - foreach ( $second_level as $third_level => $fourth_level ) - if ( is_array( $fourth_level ) ) { - foreach ( $fourth_level as $fifth_level => $sixth_level ) { - if ( is_null( $sixth_level ) ) { - unset( $data_to_replace[$top_level][$third_level][$fifth_level] ); - unset( $data[$top_level][$third_level][$fifth_level] ); - - } - } - } else if ( is_null( $fourth_level ) ) { - unset( $data_to_replace[$top_level][$third_level] ); - unset( $data[$top_level][$third_level] ); - } - } else { - if ( is_null( $second_level ) ) { - unset( $data_to_replace[$top_level] ); - unset( $data[$top_level] ); - } - } - } - //moige - $data = array_merge( $data, $data_to_replace ); - } - - - - $saved_data = $this->_admin_page->default_tickets_update( $this->_event, $data ); - $dtt = $saved_data[0]; - $tkts = $saved_data[1]; - - //verify datetime. - $this->assertInstanceof( 'EE_Datetime', $dtt ); - //verify start and date - $this->assertEquals( $dtt->start_date_and_time( $date_format, $time_format ), $this->_default_dates['DTT_start']->format( $full_format ), $context_for_error_messages . sprintf( 'Start Date Format Tested: %s', $full_format ) ); - $this->assertEquals( $dtt->end_date_and_time( $date_format, $time_format ), $this->_default_dates['DTT_end']->format( $full_format ), $context_for_error_messages . sprintf( 'End Date Format Tested: %s', $full_format ) ); - - $saved_dtts_for_tickets[$full_format] = $dtt; - $formats_for_compare[$dtt->ID()] = array( $date_format, $time_format ); - - //verify tkts - foreach ( $tkts as $tkt ) { - $this->assertInstanceof( 'EE_Ticket', $tkt, $context_for_error_messages . sprintf( 'Format: %s', $full_format ) ); - - //verify start and date - //Note: currently this test sometimes fails depending on the timing of when it happens and how fast - // the server is. Whenever I've seen this fail its been off by 1 minute and that's because when the - // default dates for testing were created, they likely happened at the second turnover. - $this->assertDateWithinOneMinute( $tkt->start_date( $date_format, $time_format ), $this->_default_dates['TKT_start']->format( $full_format ), $full_format, $context_for_error_messages . sprintf( 'Start Ticket DateFormat Tested: %s', $full_format ) ); - $this->assertDateWithinOneMinute( $tkt->end_date( $date_format, $time_format ), $this->_default_dates['TKT_end']->format( $full_format ), $full_format, $context_for_error_messages . sprintf( 'End Ticket Date Format Tested: %s', $full_format ) ); - - $saved_tkts[$full_format] = $tkt; - } - } - } - - - //now let's verify these items were saved corectly in the db. - /*$new_tkts = $new_dtts = array(); - foreach ( $tkt as $format => $tkt ) { - $new_tkts[$format] = EEM_Ticket::instance()->refresh_entity_map_from_db( $tkt->ID() ); - } - - foreach ( $saved_dtts_for_tickets[$full_format] as $format => $dtt ) { - $new_dtts[$format] = EEM_Datetime::instance()->refresh_entity_map_from_db( $dtt->ID() ); - }/**/ - - $new_event = EEM_Event::instance()->refresh_entity_map_from_db( $this->_event->ID() ); - $new_event->set_timezone( 'America/Vancouver' ); - - $evt_dtts = $new_event->datetimes_ordered(); - - //now let's do comparisons. - foreach( $evt_dtts as $edtt ) { - $formats = $formats_for_compare[$edtt->ID()]; - $format = $formats[0] . ' ' . $formats[1]; - $this->assertEquals( $edtt->start_date_and_time( $formats[0], $formats[1] ), $this->_default_dates['DTT_start']->format( $format), $context_for_error_messages . sprintf( 'DB DTT/Default DTT Start Date Format Checked: %s', $format ) ); - $this->assertEquals( $edtt->end_date_and_time( $formats[0], $formats[1] ), $this->_default_dates['DTT_end']->format( $format ), $context_for_error_messages . sprintf( 'DB DTT/Default DTT End Date Format Checked: %s', $format ) ); - $this->assertEquals( $edtt->start_date_and_time( $formats[0], $formats[1] ), $saved_dtts_for_tickets[$format]->start_date_and_time( $formats[0], $formats[1] ), $context_for_error_messages . sprintf( 'DB DTT/Orig DTT Start Date Format Checked: %s', $format ) ); - $this->assertEquals( $edtt->end_date_and_time( $formats[0], $formats[1] ), $saved_dtts_for_tickets[$format]->end_date_and_time( $formats[0], $formats[1] ), $context_for_error_messages . sprintf( 'DB DTT/Orig DTT End Date Format Checked: %s', $format ) ); - - //get related ticket on this $edtt - $evt_tkt = $edtt->get_first_related( 'Ticket' ); - $this->assertDateWithinOneMinute( $evt_tkt->start_date( $formats[0], $formats[1] ), $this->_default_dates['TKT_start']->format( $format ), $format, $context_for_error_messages . sprintf( 'DB TKT/Default TKT Start Date Format Checked: %s', $format ) ); - $this->assertDateWithinOneMinute( $evt_tkt->end_date( $formats[0], $formats[1] ), $this->_default_dates['TKT_end']->format( $format ), $format, $context_for_error_messages . sprintf( 'DB TKT/Default TKT End Date Format Checked: %s', $format ) ); - $this->assertDateWithinOneMinute( $evt_tkt->start_date( $formats[0], $formats[1] ), $saved_tkts[$format]->start_date( $formats[0], $formats[1] ), $format, $context_for_error_messages . sprintf( 'DB TKT/Orig TKT Start Date Format Checked: %s', $format ) ); - $this->assertDateWithinOneMinute( $evt_tkt->end_date( $formats[0], $formats[1] ), $saved_tkts[$format]->end_date( $formats[0], $formats[1] ), $format, $context_for_error_messages . sprintf( 'DB TKT/Orig TKT End Date Format Checked: %s', $format ) ); - } - } - - - - - -} -// end class Events_Admin_Page_Decaf -// Location: testcases/admin_pages/events_decaf/Events_Admin_Page_Decaf_Test.php diff --git a/tests/testcases/admin_pages/messages/Messages_Admin_Page_Test.php b/tests/testcases/admin_pages/messages/Messages_Admin_Page_Test.php deleted file mode 100644 index 5a1d65d60d3..00000000000 --- a/tests/testcases/admin_pages/messages/Messages_Admin_Page_Test.php +++ /dev/null @@ -1,79 +0,0 @@ -delayedAdminPageMocks( 'messages' ); - $this->_load_requirements(); - } - - - - protected function _load_requirements() { - $this->_MessagesAdminPage = new Messages_Admin_Page_Mock(); - $this->_MessageResourceManager = EE_Registry::instance()->load_lib( 'Message_Resource_Manager' ); - } - - - /** - * This is testing that the active messenger settings option in the db does not get corrupted when activating a messenger. - * @group 9330 - */ - public function test_activate_messenger_with_invalid_messenger() { - $original_active_messenger_settings = $this->_MessageResourceManager->get_active_messengers_option( true ); - - //activate a dummy messenger - $activated = $this->_MessagesAdminPage->activate_messenger( 'dummy_messenger' ); - $this->assertFalse( $activated ); - - //verify that the new active_messenger_settings is the same as the original so no corruption. - $updated_active_messenger_settings = $this->_MessageResourceManager->get_active_messengers_option( true ); - $this->assertEquals( $original_active_messenger_settings, $updated_active_messenger_settings ); - //lets just reset notices because we don't care about them for this test. This prevents a fail from automatically firing. - EE_Error::reset_notices(); - } - - - - - /** - * This is testing that the active messenger settings option in the db does not get corrupted when activating a messenger. - * @group 9330 - */ - public function test_deactivate_messenger_with_valid_messenger() { - $original_active_messenger_settings = $this->_MessageResourceManager->get_active_messengers_option( true ); - $this->assertTrue( isset( $original_active_messenger_settings['html'] ) ); - //unset manually the html messenger from this array so we'll have our expected array. - unset( $original_active_messenger_settings['html'] ); - - //deactivate an actual messenger - $deactivated = $this->_MessagesAdminPage->deactivate_messenger( 'html' ); - - $this->assertTrue( $deactivated ); - $updated_active_messenger_settings = $this->_MessageResourceManager->get_active_messengers_option( true ); - - $this->assertEquals( $original_active_messenger_settings, $updated_active_messenger_settings ); - //lets just reset notices because we don't care about them for this test. This prevents a fail from automatically firing. - EE_Error::reset_notices(); - } -} \ No newline at end of file diff --git a/tests/testcases/admin_pages/pricing/espresso_events_Pricing_Hooks_Test.php b/tests/testcases/admin_pages/pricing/espresso_events_Pricing_Hooks_Test.php deleted file mode 100644 index c86965dca03..00000000000 --- a/tests/testcases/admin_pages/pricing/espresso_events_Pricing_Hooks_Test.php +++ /dev/null @@ -1,191 +0,0 @@ -loadAdminMocks(); - } - - - - /** - * loads the pricing mock object for tests - * - * @param string $timezone Timezone string to initialize the times in. - * @throws EE_Error - * @since 4.6 - */ - protected function _load_pricing_mock($timezone = 'America/Vancouver') - { - $this->_pricingMock = new espresso_events_Pricing_Hooks_Mock(); - $this->_event = $this->factory->event->create(); - $this->_event->set_timezone($timezone); - $this->_event->save(); - $this->_set_default_dates($timezone); - } - - - - /** - * Contains tests for the update_dtts method and update_tkts method. - * - * @since 4.6 - */ - public function test_update_dtts_and_update_tkts() - { - $this->_load_pricing_mock(); - $formats_to_test = $this->date_formats_to_test(); - $saved_dtts_for_tickets = $formats_for_compare = $saved_tkts = array(); - //test each date and time format combination for creating datetime objects - foreach ($formats_to_test['date'] as $date_format) { - foreach ($formats_to_test['time'] as $time_format) { - $full_format = $date_format . ' ' . $time_format; - $this->_pricingMock->set_date_format_strings(array('date' => $date_format, 'time' => $time_format)); - $data = $this->_get_save_data($full_format); - $dtts = $this->_pricingMock->update_dtts($this->_event, $data); - foreach ($dtts as $dtt) { - $this->assertInstanceOf('EE_Datetime', $dtt); - /** @var EE_Datetime $dtt */ - //verify start and date - $this->assertEquals( - $dtt->start_date_and_time(), - $this->_default_dates['DTT_start']->format($full_format), - sprintf('Start Date Format Tested: %s', $full_format) - ); - $this->assertEquals( - $dtt->end_date_and_time(), - $this->_default_dates['DTT_end']->format($full_format), - sprintf('End Date Format Tested: %s', $full_format) - ); - $saved_dtts_for_tickets[$full_format] = $dtt; - $formats_for_compare[$dtt->ID()] = array($date_format, $time_format); - } - } - } - //test each date and time format combination for creating ticket objects - foreach ($formats_to_test['date'] as $date_format) { - foreach ($formats_to_test['time'] as $time_format) { - $full_format = $date_format . ' ' . $time_format; - $this->_pricingMock->set_date_format_strings(array('date' => $date_format, 'time' => $time_format)); - $data = $this->_get_save_data($full_format); - $dtt_for_ticket['1'] = $saved_dtts_for_tickets[$full_format]; - $tkts = $this->_pricingMock->update_tkts($this->_event, $dtt_for_ticket, $data); - foreach ($tkts as $tkt) { - $this->assertInstanceOf('EE_Ticket', $tkt, sprintf('Format: %s', $full_format)); - //verify start and date - $this->assertEquals( - $tkt->start_date(), - $this->_default_dates['TKT_start']->format($full_format), - sprintf('Start Ticket DateFormat Tested: %s', $full_format) - ); - $this->assertEquals( - $tkt->end_date(), - $this->_default_dates['TKT_end']->format($full_format), - sprintf('End Ticket Date Format Tested: %s', $full_format) - ); - $saved_tkts[$full_format] = $tkt; - } - } - } - //now let's verify these items were saved correctly in the db. - /*$new_tkts = $new_dtts = array(); - foreach ( $tkt as $format => $tkt ) { - $new_tkts[$format] = EEM_Ticket::instance()->refresh_entity_map_from_db( $tkt->ID() ); - } - - foreach ( $saved_dtts_for_tickets[$full_format] as $format => $dtt ) { - $new_dtts[$format] = EEM_Datetime::instance()->refresh_entity_map_from_db( $dtt->ID() ); - }/**/ - /** @var EE_Event $new_event */ - $new_event = EEM_Event::instance()->refresh_entity_map_from_db($this->_event->ID()); - $new_event->set_timezone('America/Vancouver'); - $evt_dtts = $new_event->datetimes_ordered(); - //now let's do comparisons. - foreach ($evt_dtts as $edtt) { - if(!$edtt instanceof EE_Datetime) { - continue; - } - $formats = $formats_for_compare[$edtt->ID()]; - $format = $formats[0] . ' ' . $formats[1]; - $this->assertEquals( - $edtt->start_date_and_time($formats[0], $formats[1]), - $this->_default_dates['DTT_start']->format($format), - sprintf('DB DTT/Default DTT Start Date Format Checked: %s', $format) - ); - $this->assertEquals( - $edtt->end_date_and_time($formats[0], $formats[1]), - $this->_default_dates['DTT_end']->format($format), - sprintf('DB DTT/Default DTT End Date Format Checked: %s', $format) - ); - $this->assertEquals( - $edtt->start_date_and_time($formats[0], $formats[1]), - $saved_dtts_for_tickets[$format]->start_date_and_time(), - sprintf('DB DTT/Orig DTT Start Date Format Checked: %s', $format) - ); - $this->assertEquals( - $edtt->end_date_and_time($formats[0], $formats[1]), - $saved_dtts_for_tickets[$format]->end_date_and_time(), - sprintf('DB DTT/Orig DTT End Date Format Checked: %s', $format) - ); - //get related ticket on this $edtt - $evt_tkt = $edtt->get_first_related('Ticket'); - $this->assertEquals( - $evt_tkt->start_date($formats[0], $formats[1]), - $this->_default_dates['TKT_start']->format($format), - sprintf('DB TKT/Default TKT Start Date Format Checked: %s', $format) - ); - $this->assertEquals( - $evt_tkt->end_date($formats[0], $formats[1]), - $this->_default_dates['TKT_end']->format($format), - sprintf('DB TKT/Default TKT End Date Format Checked: %s', $format) - ); - $this->assertEquals( - $evt_tkt->start_date($formats[0], $formats[1]), - $saved_tkts[$format]->start_date($formats[0], $formats[1]), - sprintf('DB TKT/Orig TKT Start Date Format Checked: %s', $format) - ); - $this->assertEquals( - $evt_tkt->end_date($formats[0], $formats[1]), - $saved_tkts[$format]->end_date($formats[0], $formats[1]), - sprintf('DB TKT/Orig TKT End Date Format Checked: %s', $format) - ); - } - } - - -} -//end class espresso_events_Pricing_Hooks_Test -// Location: tests/testcases/admin_pages/pricing/espresso_events_Pricing_Hooks_Test.php diff --git a/tests/testcases/admin_pages/registrations/EE_Registrations_List_Table_Test.php b/tests/testcases/admin_pages/registrations/EE_Registrations_List_Table_Test.php deleted file mode 100644 index 8798c0198f6..00000000000 --- a/tests/testcases/admin_pages/registrations/EE_Registrations_List_Table_Test.php +++ /dev/null @@ -1,105 +0,0 @@ -loadAdminMocks(); - } - - - - - public function _load_mock() { - $this->_mock = new EE_Registrations_List_Table_Mock(''); - } - - - - - - /** - * @since 4.6.0 - */ - public function test_total_registrations_this_month() { - $this->_load_mock(); - //baseline dates - $now = new DateTime( 'now' ); - - //let's setup some registrations to test. Setting status as not approved to avoid the incomplete exclusion on the method tested. - $registrations = $this->factory->registration->create_many( 4, array( 'STS_ID' => EEM_Registration::status_id_not_approved ) ); - - $this->assertEquals( 4, count( $registrations ) ); - - //let's modify the first registration so it happened two months ago. Note, the reason why I am doing this - //instead of one month is because if today's date is March 31st, March 30th, or March 29th. There is - //wierd PHP behaviour where subtracting one month will result in a date remaining in March. - //@see http://php.net/manual/en/datetime.sub.php#example-2469 - $first_registration = reset( $registrations ); - $first_registration->set( 'REG_date', $now->sub( new DateInterval('P2M') )->format('U') ); - $first_registration->save(); - - //modify the last registration so it happens next month. - $last_registration = end( $registrations ); - $last_registration->set( 'REG_date', $now->add( new DateInterval('P3M') )-> format( 'U' ) ); - - $last_registration->save(); - - //now let's test the method. - $this->assertEquals(2, $this->_mock->total_registrations_this_month() ); - - - } - - - - /** - * @since 4.6.x - */ - public function test_total_registrations_today() { - $this->_load_mock(); - //baseline dates - $now = new DateTime( 'now' ); - $nowEST = new DateTime( 'now', new DateTimeZone( 'America/Toronto' ) ); - - //let's setup some registrations to test. Setting status as not approved to avoid the incomplete exclusion on the method tested. - $registrations = $this->factory->registration->create_many( 4, array( 'STS_ID' => EEM_Registration::status_id_not_approved ) ); - - $this->assertEquals( 4, count( $registrations ) ); - - //let's modify the first registration so it happened last month. - $first_registration = reset( $registrations ); - $first_registration->set( 'REG_date', $now->sub( new DateInterval('P1M') )->format('U') ); - $first_registration->save(); - - //modify the last registration so it happens next month. - $last_registration = end( $registrations ); - $last_registration->set( 'REG_date', $now->add( new DateInterval('P2M') )-> format( 'U' ) ); - $last_registration->save(); - - //now let's test the method. - $this->assertEquals(2, $this->_mock->total_registrations_today() ); - } - -} //end class EE_Registrations_List_Table_Test diff --git a/tests/testcases/admin_pages/registrations/Registrations_Admin_Page_Test.php b/tests/testcases/admin_pages/registrations/Registrations_Admin_Page_Test.php deleted file mode 100644 index 4d99ea5e672..00000000000 --- a/tests/testcases/admin_pages/registrations/Registrations_Admin_Page_Test.php +++ /dev/null @@ -1,698 +0,0 @@ -original_timezone_string = get_option('timezone_string'); - //set timezone of site to 'America/Vancouver' for tests. - update_option('timezone_string', 'America/Vancouver'); - $this->Vancouver_TZ = new DateTimeZone('America/Vancouver'); - $this->UTC_TZ = new DateTimeZone('UTC'); - - $this->delayedAdminPageMocks('registrations'); - //need to set a user with registration privileges for default queries in the admin. - $user = $this->factory->user->create_and_get(); - $user->add_role('administrator'); - wp_set_current_user( $user->ID ); - $this->request = LoaderFactory::getLoader()->getShared( - 'EventEspresso\core\services\request\RequestInterface' - ); - } - - - public function tearDown() - { - //restore timezone to original setting - update_option('timezone_string', $this->original_timezone_string); - parent::tearDown(); - } - - - /** - * loader for setting the $_admin_page_property - * - * @since 4.6 - */ - protected function _load_requirements() - { - $this->_admin_page = new Registrations_Admin_Page_Mock(); - } - - - /** - * This is a utility method for this test suite to generate a url to use with the _GOTO method for testing - * functionality. - * - * @param array $extra_query_params - * @return string - */ - protected function _get_reg_admin_url( $extra_query_params = array() ) { - return add_query_arg( - array_merge( - array( 'page' => 'espresso_registrations' ), - $extra_query_params - ), - admin_url() - ); - } - - - /** - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @throws RuntimeException - * @throws EntityNotFoundException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws \PHPUnit\Framework\Exception - * @throws Exception - * @since 4.6.x - * -- testing today queries - * -- testing this month queries - * -- testing month range queries. - */ - public function test_get_registrations() - { - // to view how dates are added or subtracted, uncomment the following - /*foreach( array( '01', '15', '31' ) as $day ) { - echo "\n\n\n ADD DATES"; - $date = "2015-01-{$day}"; - $now = DateTime::createFromFormat( 'Y-m-d', $date ); - echo "\n\n starting : " . $now->format( 'M d, Y' ); - for ( $x = 1; $x <= 12; $x++ ) { - echo "\n\n now : " . $now->format( 'M d, Y' ); - $prev_month = $this->_get_date_one_month_ago( $now ); - echo "\n prev: " . $prev_month->format( 'M d, Y' ); - $next_month = $this->_get_date_one_month_from_now( $now ); - echo "\n next: " . $next_month->format( 'M d, Y' ); - $year = (int)$now->format( 'Y' ); - $month = (int)$now->format( 'n' ); - $month++; - $days_in_month = (int)$next_month->format( 't' ); - $now_day = $day > $days_in_month ? $days_in_month : $day; - $now = DateTime::createFromFormat( 'Y-m-d', "{$year}-{$month}-{$now_day}" ); - - } - echo "\n\n\n SUBTRACT DATES"; - $now = DateTime::createFromFormat( 'Y-m-d', $date ); - echo "\n\n starting : " . $now->format( 'M d, Y' ); - for ( $x = 12; $x > 0; $x-- ) { - echo "\n\n now : " . $now->format( 'M d, Y' ); - $prev_month = $this->_get_date_one_month_ago( $now ); - echo "\n prev: " . $prev_month->format( 'M d, Y' ); - $next_month = $this->_get_date_one_month_from_now( $now ); - echo "\n next: " . $next_month->format( 'M d, Y' ); - $year = (int)$now->format( 'Y' ); - $month = (int)$now->format( 'n' ); - $month++; - $days_in_month = (int)$next_month->format( 't' ); - $now_day = $day > $days_in_month ? $days_in_month : $day; - $now = DateTime::createFromFormat( 'Y-m-d', "{$year}-{$month}-{$now_day}" ); - } - }*/ - // baseline DateTime objects - $now = new DateTime('now', $this->Vancouver_TZ); - $prev_month = $this->_get_date_one_month_ago($now); - $next_month = $this->_get_date_one_month_from_now($now); - // echo "\n\n now : " . $now->format( 'M j, Y g:i a' ); - // echo "\n prev: " . $prev_month->format( 'M j, Y g:i a' ); - // echo "\n next: " . $next_month->format( 'M j, Y g:i a' ); - - //let's setup some registrations to test. - // first create a txn - /** @var EE_Transaction $transaction */ - $transaction = $this->factory->transaction->create(); - $registrations = $this->factory->registration->create_many(4, array('TXN_ID' => $transaction->ID())); - $this->assertCount( - 4, - $registrations, - 'there should be 4 registrations in total, not ' . count($registrations) - . "\nHere are the registrations: " . $this->reg_debug($registrations, true) - ); - - //create an event and add to the registrations - $event = $this->factory->event->create(array('EVT_wp_user' => get_current_user_id())); - if ($event instanceof EE_Event) { - foreach ($registrations as $registration) { - if ($registration instanceof EE_Registration) { - $registration->_add_relation_to($transaction, 'Transaction'); - $registration->_add_relation_to($event, 'Event'); - $registration->set('STS_ID', EEM_Registration::status_id_pending_payment); - $registration->save(); - } - } - } - // let's modify the first registration so it happened one months ago, - $first_registration = reset($registrations); - $first_registration->set('REG_date', $prev_month->format('U')); - $first_registration->save(); - // modify the last registration so it happens next month. - $last_registration = end($registrations); - $last_registration->set('REG_date', $next_month->format('U')); - $last_registration->save(); - // $this->reg_debug( $registrations ); - //let's test queries for today - $this->go_to( - $this->_get_reg_admin_url(array('status'=>'today')) - ); - $this->_load_requirements(); - $registrations = $this->_admin_page->get_registrations(); - $this->request->unSetRequestParams(['page', 'status']); - // echo "\n\n " . __LINE__ . ") " . __METHOD__ . "() STATUS: " . $_GET['status']; - // $this->reg_debug( $registrations ); - $this->assertCount( - 2, - $registrations, - 'there should be 2 registrations for today, not ' . count($registrations) - . "\nHere are the registrations: " . $this->reg_debug($registrations, true) - ); - //test queries for this month - $this->go_to( - $this->_get_reg_admin_url(array('status'=>'month')) - ); - $this->_load_requirements(); - $registrations = $this->_admin_page->get_registrations(); - $this->request->unSetRequestParams(['page', 'status']); - // echo "\n\n " . __LINE__ . ") " . __METHOD__ . "() STATUS: " . $_GET['status']; - // $this->reg_debug( $registrations ); - $this->assertCount( - 2, - $registrations, - 'there should be 2 registrations for this month, not ' . count($registrations) - . "\nHere are the registrations: " . $this->reg_debug($registrations, true) - ); - // test queries for month range using last month - $this->go_to( - $this->_get_reg_admin_url(array('month_range' => $prev_month->format('F Y'))) - ); - $this->_load_requirements(); - $this->_admin_page->get_registrations(); - $registrations = $this->_admin_page->get_registrations(); - // echo "\n\n " . __LINE__ . ") " . __METHOD__ . "() MONTH_RANGE: " . $_GET[ 'month_range' ]; - // $this->reg_debug( $registrations ); - $this->assertCount( - 1, - $registrations, - 'there should be 1 registration for ' . $_GET['month_range'] . ', not ' . count($registrations) - . "\nHere are the registrations: " . $this->reg_debug($registrations, true) - ); - $this->request->unSetRequestParams(['page', 'month_range']); - } - - - /** - * @param EE_Registration[] $registrations - * @param bool $return - * @return string - */ - public function reg_debug($registrations, $return = false) - { - $result = "\n\n " . __LINE__ . ') ' . __METHOD__ . '()'; - $result .= "\n registration count: " . count($registrations); - foreach ($registrations as $registration) { - if ($registration instanceof EE_Registration) { - $result .= "\n registration date: " . $registration->date(); - } - } - if ($return) { - return $result; - } - echo $result; - return ''; - } - - - /** - * @since 4.8.10.rc.10 - * @group integration - * @throws DomainException - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @throws RuntimeException - * @throws EntityNotFoundException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws AssertionFailedError - * @throws \PHPUnit\Framework\Exception - */ - public function test__set_registration_status_from_request_for_single_registration() - { - //first setup a registration - /** @var EE_Registration $testing_registration */ - $testing_registration = $this->factory->registration->create( - array('STS_ID' => EEM_Registration::status_id_pending_payment) - ); - // and a txn - $testing_registration->_add_relation_to($this->factory->transaction->create(), 'Transaction'); - $_REQUEST['_REG_ID'] = $testing_registration->ID(); - $this->_load_requirements(); - $success = $this->_admin_page->set_registration_status_from_request(EEM_Registration::status_id_not_approved); - $this->assertArrayHasKey('success', $success); - $this->assertTrue($success['success']); - $this->assertArrayHasKey('REG_ID', $success); - $this->assertArrayContains($testing_registration->ID(), $success['REG_ID']); - - //verify registration got changed to not approved. - /** @var EE_Registration $actual_registration */ - $actual_registration = EEM_Registration::reset()->instance()->get_one_by_ID($testing_registration->ID()); - $this->assertEquals(EEM_Registration::status_id_not_approved, $actual_registration->status_ID()); - } - - - /** - * @since 4.8.10.rc.10 - * @group integration - * @throws DomainException - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @throws RuntimeException - * @throws EntityNotFoundException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws AssertionFailedError - * @throws \PHPUnit\Framework\Exception - */ - public function test__set_registration_status_from_request_for_multiple_registrations() - { - /** @var EE_Transaction $txn */ - $txn = $this->factory->transaction->create(); - /** @var EE_Line_Item $tli */ - $tli = EEH_Line_Item::create_total_line_item($txn); - $tli->save(); - /** @var EE_Ticket $tkt */ - $tkt = $this->factory->ticket_chained->create(); - EEH_Line_Item::add_ticket_purchase($tli, $tkt); - //basically the same as the prior test except here we're testing multiple registrations. - /** @var EE_Registration $registration_a */ - $registration_a = $this->factory->registration->create( - array( - 'STS_ID' => EEM_Registration::status_id_cancelled, - 'TXN_ID' => $txn->ID(), - 'TKT_ID' => $tkt->ID(), - ) - ); - $registration_a->save(); - /** @var EE_Registration $registration_b */ - $registration_b = $this->factory->registration->create( - array( - 'STS_ID' => EEM_Registration::status_id_pending_payment, - 'TXN_ID' => $txn->ID(), - 'TKT_ID' => $tkt->ID(), - ) - ); - $registration_b->save(); - /** @var EE_Registration $registration_c */ - $registration_c = $this->factory->registration->create( - array( - 'STS_ID' => EEM_Registration::status_id_not_approved, - 'TXN_ID' => $txn->ID(), - 'TKT_ID' => $tkt->ID(), - ) - ); - $registration_c->save(); - - $expected_ids = array($registration_a->ID(), $registration_b->ID(), $registration_c->ID()); - $_REQUEST['_REG_ID'] = $expected_ids; - $this->_load_requirements(); - $success = $this->_admin_page->set_registration_status_from_request(EEM_Registration::status_id_not_approved); - $this->assertArrayHasKey('success', $success); - $this->assertTrue($success['success']); - $this->assertArrayHasKey('REG_ID', $success); - $this->assertCount(3, $success['REG_ID']); - $this->assertEquals($expected_ids, $success['REG_ID']); - - //verify registrations got changed to approved (or stayed there). - $registrations = EEM_Registration::reset()->instance()->get_all( - array(array('STS_ID' => EEM_Registration::status_id_not_approved)) - ); - $this->assertCount(3, $registrations); - $this->assertEquals($expected_ids, array_keys($registrations)); - } - - - /** - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws \PHPUnit\Framework\Exception - * @since 4.10.2.p - */ - public function test_add_event_id_to_where_conditions() - { - $this->go_to( - $this->_get_reg_admin_url(array('event_id' => 42)) - ); - $this->_load_requirements(); - $where = $this->_admin_page->get_registration_query_parameters($this->_admin_page->get_request_data()); - $this->assertCount(2, $where[0]); - $this->assertArrayHasKey('EVT_ID', $where[0]); - $this->assertEquals(42, $where[0]['EVT_ID']); - $this->request->unSetRequestParam('event_id', true); - } - - - /** - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws \PHPUnit\Framework\Exception - * @since 4.10.2.p - */ - public function test_add_category_id_to_where_conditions() - { - $this->go_to( - $this->_get_reg_admin_url(array('EVT_CAT' => 42)) - ); - $this->_load_requirements(); - $where = $this->_admin_page->get_registration_query_parameters($this->_admin_page->get_request_data()); - $this->assertCount(2, $where[0]); - $this->assertArrayHasKey('Event.Term_Taxonomy.term_id', $where[0]); - $this->assertEquals(42, $where[0]['Event.Term_Taxonomy.term_id']); - $this->request->unSetRequestParam('EVT_CAT', true); - } - - - /** - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws \PHPUnit\Framework\Exception - * @since 4.10.2.p - */ - public function test_add_datetime_id_to_where_conditions() - { - $this->go_to( - $this->_get_reg_admin_url(array('datetime_id' => 42)) - ); - $this->_load_requirements(); - $where = $this->_admin_page->get_registration_query_parameters($this->_admin_page->get_request_data()); - $this->assertCount(2, $where[0]); - $this->assertArrayHasKey('Ticket.Datetime.DTT_ID', $where[0]); - $this->assertEquals(42, $where[0]['Ticket.Datetime.DTT_ID']); - $this->request->unSetRequestParam('datetime_id', true); - } - - - /** - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws AssertionFailedError - * @throws \PHPUnit\Framework\Exception - * @since 4.10.2.p - */ - public function test_add_registration_status_to_where_conditions_no_status_not_trash_view() - { - $this->_load_requirements(); - $where = $this->_admin_page->get_registration_query_parameters($this->_admin_page->get_request_data()); - $this->assertCount(1, $where[0]); - $this->assertArrayHasKey('STS_ID', $where[0]); - $this->assertInternalType('array',$where[0]['STS_ID']); - $this->assertArrayContains('!=', $where[0]['STS_ID']); - $this->assertArrayContains(EEM_Registration::status_id_incomplete, $where[0]['STS_ID']); - } - - - /** - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @since 4.10.2.p - */ - public function test_add_registration_status_to_where_conditions_no_status_trash_view(){ - $this->_load_requirements(); - $req = $this->_admin_page->get_request_data(); - $req['status'] = 'trash'; - $where = $this->_admin_page->get_registration_query_parameters($req); - $this->assertEquals(array( 'REG_deleted' => true ), $where[0]); - $this->request->unSetRequestParam('status', true); - } - - - /** - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws \PHPUnit\Framework\Exception - * @since 4.10.2.p - */ - public function test_add_registration_status_to_where_conditions_with_status_and_incomplete_view() - { - $this->go_to( - $this->_get_reg_admin_url(array('_reg_status'=>EEM_Registration::status_id_approved)) - ); - $this->_load_requirements(); - $req = $this->_admin_page->get_request_data(); - $req['status'] = 'incomplete'; - $where = $this->_admin_page->get_registration_query_parameters($req); - $this->assertCount(1, $where[0]); - $this->assertArrayHasKey('STS_ID', $where[0]); - $this->assertEquals(EEM_Registration::status_id_approved, $where[0]['STS_ID']); - $this->request->unSetRequestParams(['_reg_status', 'status'], true); - } - - - /** - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws \PHPUnit\Framework\Exception - * @since 4.10.2.p - */ - public function test_add_registration_status_to_where_conditions_no_status_and_incomplete_view() - { - $this->_load_requirements(); - $req = $this->_admin_page->get_request_data(); - $req['status'] = 'incomplete'; - $where = $this->_admin_page->get_registration_query_parameters($req); - $this->assertCount(1, $where[0]); - $this->assertArrayHasKey('STS_ID', $where[0]); - $this->assertEquals(EEM_Registration::status_id_incomplete, $where[0]['STS_ID']); - $this->request->unSetRequestParam('status', true); - } - - - /** - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws \PHPUnit\Framework\Exception - * @since 4.10.2.p - */ - public function test_add_registration_status_to_where_conditions_with_status() - { - $this->go_to( - $this->_get_reg_admin_url(array('_reg_status'=>EEM_Registration::status_id_approved)) - ); - $this->_load_requirements(); - $where = $this->_admin_page->get_registration_query_parameters($this->_admin_page->get_request_data()); - $this->assertCount(1, $where[0]); - $this->assertArrayHasKey('STS_ID',$where[0]); - $this->assertEquals(EEM_Registration::status_id_approved,$where[0]['STS_ID']); - $this->request->unSetRequestParam('_reg_status', true); - } - - - /** - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws \PHPUnit\Framework\Exception - * @since 4.10.2.p - */ - public function test_add_date_to_where_conditions_for_this_month() - { - $this->_load_requirements(); - $current_year_and_month = date('Y-m', current_time('timestamp')); - $days_this_month = date('t', current_time('timestamp')); - $expected_start_date = date_create_from_format( - 'Y-m-d H:i:s', - $current_year_and_month . '-01 00:00:00', - $this->Vancouver_TZ - )->setTimezone($this->UTC_TZ); - $expected_end_date = date_create_from_format( - 'Y-m-d H:i:s', - $current_year_and_month . '-' . $days_this_month . ' 23:59:59', - $this->Vancouver_TZ - )->setTimezone($this->UTC_TZ); - $req = $this->_admin_page->get_request_data(); - $req['status'] = 'month'; - $where = $this->_admin_page->get_registration_query_parameters($req); - $this->request->unSetRequestParam('status', true); - $this->assertCount(2,$where[0]); - $this->assertArrayHasKey('REG_date',$where[0]); - $this->assertCount(2,$where[0]['REG_date']); - $this->assertContains('BETWEEN',$where[0]['REG_date']); - $this->assertInstanceOf('Datetime',$where[0]['REG_date'][1][0]); - $this->assertInstanceOf('Datetime',$where[0]['REG_date'][1][1]); - /** @var EventEspresso\core\domain\entities\DbSafeDateTime $actual_start_date */ - /** @var EventEspresso\core\domain\entities\DbSafeDateTime $actual_end_date */ - list($actual_start_date, $actual_end_date) = $where[0]['REG_date'][1]; - $this->assertEquals( - $expected_start_date->format('Y-m-d H:i'), - $actual_start_date->format('Y-m-d H:i'), - 'start dates do not match' - ); - $this->assertEquals( - $expected_end_date->format('Y-m-d H:i'), - $actual_end_date->format('Y-m-d H:i'), - 'end dates do not match' - ); - } - - - /** - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws AssertionFailedError - * @throws \PHPUnit\Framework\Exception - * @since 4.10.2.p - */ - public function test_add_search_to_where_conditions() - { - $this->go_to( - $this->_get_reg_admin_url(array('s'=>'gogogo')) - ); - $this->_load_requirements(); - $where = $this->_admin_page->get_registration_query_parameters( - $this->_admin_page->get_request_data() - ); - $this->assertCount(2,$where[0]); - $this->assertArrayHasKey('OR*search_conditions',$where[0]); - $this->assertArrayHasKey('Event.EVT_name',$where[0]['OR*search_conditions']); - $this->assertInternalType('array', $where[0]['OR*search_conditions']['Event.EVT_name']); - $this->assertEquals('%gogogo%',$where[0]['OR*search_conditions']['Event.EVT_name'][1]); - $this->request->unSetRequestParam('s', true); - } - - - /** - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws AssertionFailedError - * @throws \PHPUnit\Framework\Exception - * @since 4.10.2.p - */ - public function test_get_orderby_for_registrations_query_none_specified() - { - $this->_load_requirements(); - $query_params = $this->_admin_page->get_registration_query_parameters( - $this->_admin_page->get_request_data() - ); - $this->assertArrayHasKey('order_by', $query_params); - $orderby = $query_params['order_by']; - $this->assertCount(2,$orderby); - $this->assertInternalType('array', $orderby); - $this->assertArrayHasKey('REG_date', $orderby); - $this->assertEquals('DESC', $orderby['REG_date']); - } - - - /** - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws AssertionFailedError - * @throws \PHPUnit\Framework\Exception - * @since 4.10.2.p - */ - public function test_get_orderby_for_registrations_query_specified_orderby_and_order() - { - $this->go_to( - $this->_get_reg_admin_url(array('orderby' => '_Reg_status', 'order' => 'ASC')) - ); - $this->_load_requirements(); - $query_params = $this->_admin_page->get_registration_query_parameters( - $this->_admin_page->get_request_data() - ); - $this->assertArrayHasKey('order_by', $query_params); - $orderby = $query_params['order_by']; - $this->assertCount(2,$orderby); - $this->assertInternalType('array', $orderby); - $this->assertArrayHasKey('STS_ID',$orderby); - $this->assertEquals('ASC',$orderby['STS_ID']); - $this->assertArrayHasKey('REG_ID',$orderby); - $this->assertEquals('ASC',$orderby['REG_ID']); - $this->request->unSetRequestParams(['orderby', 'order'], true); - } -} -//end Registrations_Admin_Page_Test -// Location: /tests/testcases/admin_pages/registrations/Registrations_Admin_Page_Test.php diff --git a/tests/testcases/admin_pages/registrations/form_sections/EERegistrationCustomQuestionsFormTest.php b/tests/testcases/admin_pages/registrations/form_sections/EERegistrationCustomQuestionsFormTest.php deleted file mode 100644 index f0a02a588ca..00000000000 --- a/tests/testcases/admin_pages/registrations/form_sections/EERegistrationCustomQuestionsFormTest.php +++ /dev/null @@ -1,192 +0,0 @@ -delayedAdminPageMocks('registrations'); - - } - - /** - * loader for setting the $_admin_page_property - * - * @since 4.6 - */ - protected function loadRequirements() - { - $this->_admin_page = new Registrations_Admin_Page_Mock(); - require_once(REG_ADMIN . 'form_sections/EE_Registration_Custom_Questions_Form.form.php'); - } - - /** - * Tests build_form_from_registration. We have a primary reg, and primary regs should answer the personal info - * question group, but no custom questions for that question group. - * @since 4.10.0.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @throws RuntimeException - * @throws \EventEspresso\core\exceptions\EntityNotFoundException - * @throws \EventEspresso\core\exceptions\InvalidDataTypeException - * @throws \EventEspresso\core\exceptions\InvalidInterfaceException - */ - public function testBuildFormFromRegistrationForPrimaryRegistrationNoCustomQuestions() - { - $this->loadRequirements(); - $reg = $this->factory->registration_chained->create_object( - [ - 'REG_count' => 1, - ] - ); - $e = $reg->event(); - $e->add_question_group(1, true); - $form = new EE_Registration_Custom_Questions_Form($reg); - $subsections = $form->subsections(); - // Assert only the first question group in there - $this->assertEquals(0, count($subsections)); - } - - /** - * Tests build_form_from_registration. We have a primary reg, who should answer the personal info question group - * and it has a custom question in it. - * @since 4.10.0.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @throws RuntimeException - * @throws \EventEspresso\core\exceptions\EntityNotFoundException - * @throws \EventEspresso\core\exceptions\InvalidDataTypeException - * @throws \EventEspresso\core\exceptions\InvalidInterfaceException - */ - public function testBuildFormFromRegistrationForPrimaryRegistrationWithCustomQuestions() - { - $this->loadRequirements(); - $qg1 = EEM_Question_Group::instance()->get_one_by_ID(EEM_Question_Group::system_personal); - $customq = $this->new_model_obj_with_dependencies('Question', ['QST_system' => '']); - $qg1->_add_relation_to($customq, 'Question'); - $reg = $this->factory->registration_chained->create_object( - [ - 'REG_count' => 1, - ] - ); - $e = $reg->event(); - $e->add_question_group(1, true); - $form = new EE_Registration_Custom_Questions_Form($reg); - $subsections = $form->subsections(); - // Assert only the first question group in there - $this->assertArrayHasKey(1, $subsections); - $this->assertEquals(1, count($subsections)); - } - - /** - * Tests build_form_from_registration. We have an additional reg, but only primary attendees should answer - * the personal info question group (which has a custom question in it). - * @since 4.10.0.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @throws RuntimeException - * @throws \EventEspresso\core\exceptions\EntityNotFoundException - * @throws \EventEspresso\core\exceptions\InvalidDataTypeException - * @throws \EventEspresso\core\exceptions\InvalidInterfaceException - */ - public function testBuildFormFromRegistrationForAdditionalRegistrationWrongContext() - { - $this->loadRequirements(); - $qg1 = EEM_Question_Group::instance()->get_one_by_ID(EEM_Question_Group::system_personal); - $customq = $this->new_model_obj_with_dependencies('Question', ['QST_system' => '']); - $qg1->_add_relation_to($customq, 'Question'); - $reg = $this->factory->registration_chained->create_object( - [ - 'REG_count' => 2, - 'REG_group_size' => 2, - ] - ); - $e = $reg->event(); - // Note that we're adding the question group for PRIMARY attendees, whereas this attendee is an additional one. - $e->add_question_group(1, true); - $form = new EE_Registration_Custom_Questions_Form($reg); - $subsections = $form->subsections(); - // Assert this additional attendee wasn't asked to answer a question group only for primary attendees. - $this->assertEquals(0, count($subsections)); - } - - /** - * Tests build_form_from_registration. We have an additional reg, but only primary attendees should answer - * the personal info question group (which has a custom question in it). - * @since 4.10.0.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @throws RuntimeException - * @throws \EventEspresso\core\exceptions\EntityNotFoundException - * @throws \EventEspresso\core\exceptions\InvalidDataTypeException - * @throws \EventEspresso\core\exceptions\InvalidInterfaceException - */ - public function testBuildFormFromRegistrationForAdditionalRegistrationNoCustomQuestions() - { - $this->loadRequirements(); - $reg = $this->factory->registration_chained->create_object( - [ - 'REG_count' => 2, - 'REG_group_size' => 2, - ] - ); - $e = $reg->event(); - // Note that we're adding the question group for additional attendees, of which our reg is one. - $e->add_question_group(1, false); - $form = new EE_Registration_Custom_Questions_Form($reg); - $subsections = $form->subsections(); - // No custom questions for additional attendees. - $this->assertEquals(0, count($subsections)); - } - - /** - * Tests build_form_from_registration. We have an additional reg, who should answer the personal info question group - * and it has a custom question in it. - * @since 4.10.0.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @throws RuntimeException - * @throws \EventEspresso\core\exceptions\EntityNotFoundException - * @throws \EventEspresso\core\exceptions\InvalidDataTypeException - * @throws \EventEspresso\core\exceptions\InvalidInterfaceException - */ - public function testBuildFormFromRegistrationForAdditionalRegistration() - { - $this->loadRequirements(); - $qg1 = EEM_Question_Group::instance()->get_one_by_ID(EEM_Question_Group::system_personal); - $customq = $this->new_model_obj_with_dependencies('Question', ['QST_system' => '']); - $qg1->_add_relation_to($customq, 'Question'); - $reg = $this->factory->registration_chained->create_object( - [ - 'REG_count' => 2, - 'REG_group_size' => 2, - ] - ); - $e = $reg->event(); - // Note that we are adding a question group for additional attendees, of which this registration is one. - $e->add_question_group(1, false); - $form = new EE_Registration_Custom_Questions_Form($reg); - $subsections = $form->subsections(); - // Assert only the first question group in there - $this->assertEquals(1, count($subsections)); - $this->assertArrayHasKey(1, $subsections); - } - -} -// End of file EERegistrationCustomQuestionsFormTest.php -// Location: ${NAMESPACE}/EERegistrationCustomQuestionsFormTest.php diff --git a/tests/testcases/admin_pages/transactions/Transactions_Admin_Page_Test.php b/tests/testcases/admin_pages/transactions/Transactions_Admin_Page_Test.php deleted file mode 100644 index 255a35dfea3..00000000000 --- a/tests/testcases/admin_pages/transactions/Transactions_Admin_Page_Test.php +++ /dev/null @@ -1,760 +0,0 @@ -delayedAdminPageMocks('transactions'); - } - - - /** - * _generate_transaction_and_registrations - * - * @since 4.8 - * @param float $txn_total - * @param int $reg_count - * @return \EE_Transaction - */ - protected function _generate_transaction_and_registrations($txn_total = 10.00, $reg_count = 0) - { - /** @type EE_Transaction $transaction */ - $transaction = $this->new_model_obj_with_dependencies( - 'Transaction', - array( - 'STS_ID' => EEM_Transaction::incomplete_status_code, - 'TXN_total' => $txn_total, - 'TXN_paid' => 0, - ) - ); - if ($reg_count) { - $registrations = $this->factory->registration->create_many( - $reg_count, - array( - 'STS_ID' => EEM_Registration::status_id_pending_payment, - 'REG_final_price' => $txn_total / $reg_count, - ) - ); - foreach ($registrations as $registration) { - if ($registration instanceof EE_Registration) { - $transaction->_add_relation_to($registration, 'Registration'); - $registration->save(); - } - } - } - $transaction->save(); - return $transaction; - } - - - /** - * _get_registrations_from_transaction - * - * @since 4.8 - * @param \EE_Transaction $transaction - * @param int $reg_count - * @return \EE_Registration[] - */ - protected function _get_x_number_of_registrations_from_transaction(EE_Transaction $transaction, $reg_count = 0) - { - $registrations = $transaction->registrations(); - return array_slice($registrations, 0, $reg_count, true); - } - - - /** - * _payment_method - * - * @since 4.8 - * @return EE_Payment_Method - */ - protected function _payment_method() - { - if ($this->_payment_method === null) { - switch (rand(1, 3)) { - case 1 : - $type = 'Mock_Onsite'; - break; - case 2 : - $type = 'Mock_Offsite'; - break; - case 3 : - default : - $type = 'Mock_Offline'; - break; - } - $this->_payment_method = $this->new_model_obj_with_dependencies( - 'Payment_Method', - array( - 'PMD_type' => $type, - ) - ); - } - return $this->_payment_method; - } - - - /** - * _generate_payment_details_array - * - * @since 4.8 - * @param EE_Transaction $transaction - * @param float $amount - * @param int $PAY_ID - * @param bool $refund - * @return array - */ - protected function _generate_details_array_for_payment_or_refund( - EE_Transaction $transaction, - $amount = 10.00, - $PAY_ID = null, - $refund = false - ) { - return array( - 'type' => $refund !== true ? 1 : -1, - 'PAY_ID' => $PAY_ID, - 'TXN_ID' => $transaction->ID(), - 'PMD_ID' => $this->_payment_method()->ID(), - 'STS_ID' => EEM_Payment::status_id_approved, - 'PAY_source' => EEM_Payment_Method::scope_admin, - 'PAY_details' => array(), - 'PAY_amount' => $amount, - 'PAY_timestamp' => time() - 86400, - 'PAY_po_number' => rand(100, 1000), - 'PAY_extra_accntng' => rand(100, 1000), - 'PAY_txn_id_chq_nmbr' => rand(100, 1000), - 'PAY_gateway_response' => 'You are a true champion!', - ); - } - - - /** - * test_create_new_payment_or_refund_from_request_data - * used for tests that just need an EE_Payment object - * - * @since 4.8 - * @param array $payment_details - * @return EE_Payment - */ - protected function _generate_payment($payment_details) - { - // make sure refunds have a negative amount - $payment_details['PAY_amount'] = $payment_details['type'] < 0 ? $payment_details['PAY_amount'] * -1 : $payment_details['PAY_amount']; - // then remove 'type' from the payment details since it's not an EEM_Payment field - unset($payment_details['type']); - return EE_Payment::new_instance($payment_details, '', array('Y-m-d', 'H:i a')); - } - - - /** - * test_create_new_payment_or_refund_from_request_data - * used for tests that need payment details passed via $_REQUEST data - * - * @since 4.8 - * @param EE_Transaction $transaction - * @return array - */ - protected function _generate_request_data_for_new_payment_or_refund(EE_Transaction $transaction) - { - $payment_details = $this->_generate_details_array_for_payment_or_refund($transaction); - $request_data['txn_admin_payment'] = array( - 'type' => $payment_details['type'], - 'TXN_ID' => $payment_details['TXN_ID'], - 'PAY_ID' => $payment_details['PAY_ID'], - 'PMD_ID' => $payment_details['PMD_ID'], - 'status' => $payment_details['STS_ID'], - 'date' => $payment_details['PAY_timestamp'], - 'amount' => $payment_details['PAY_amount'], - 'po_number' => $payment_details['PAY_po_number'], - 'accounting' => $payment_details['PAY_extra_accntng'], - 'txn_id_chq_nmbr' => $payment_details['PAY_txn_id_chq_nmbr'], - ); - $this->_admin_page->set_request_data($request_data); - return $request_data; - } - - - /** - * _setup_standard_transaction_and_payment - * uses the above methods to create a transaction with related registrations, and a payment - * - * @since 4.8 - * @param float $txn_total - * @param int $reg_count - * @param float $payment_amount - */ - protected function _setup_standard_transaction_and_payment( - $txn_total = 10.00, - $reg_count = 0, - $payment_amount = 10.00 - ) { - $this->_transaction = $this->_generate_transaction_and_registrations($txn_total, $reg_count); - $this->_payment = $this->_generate_payment( - $this->_generate_details_array_for_payment_or_refund($this->_transaction, $payment_amount) - ); - } - - - /** - * _apply_payment_to_registrations - * - * @since 4.8 - * @param \EE_Registration[] $registrations - */ - protected function _apply_payment_to_registrations($registrations) - { - //echo "\n\n " . __METHOD__ . "() \n"; - // reset reg_payment_REG_IDs - $this->_admin_page->set_existing_reg_payment_REG_IDs(); - $available_payment = $this->_payment->amount(); - foreach ($registrations as $registration) { - if ($registration instanceof EE_Registration) { - if ($available_payment > 0) { - $owing = $registration->final_price() - $registration->paid(); - if ($owing > 0) { - // don't allow payment amount to exceed the available payment amount, OR the amount owing - $payment_amount = min($available_payment, $owing); - // update $available_payment_amount - $available_payment = $available_payment - $payment_amount; - //calculate and set new REG_paid - $registration->set_paid($registration->paid() + $payment_amount); - //$registration->set_paid( $available_payment ); - $registration->_add_relation_to($this->_payment, 'Payment', - array('RPY_amount' => $this->_payment->amount())); - $registration->save(); - } - } - } - } - /** @type EE_Payment $payment */ - $payment = EEM_Payment::instance()->get_one_by_ID($this->_payment->ID()); - $registration_payments = $payment->registration_payments(); - $this->assertNotEmpty($registration_payments); - } - - - - //public function test_apply_payments_or_refunds() {} - - - /** - * test_create_new_payment_or_refund_from_request_data - * - * @since 4.8 - * @group 8620 - */ - public function test_create_new_payment_or_refund_from_request_data() - { - $this->_admin_page = new Transactions_Admin_Page_Mock(); - //echo "\n\n " . __METHOD__ . "() \n"; - $transaction = $this->_generate_transaction_and_registrations(); - $request_data = $this->_generate_request_data_for_new_payment_or_refund($transaction); - $payment = $this->_admin_page->create_payment_from_request_data($request_data['txn_admin_payment']); - $this->assertInstanceOf('EE_Payment', $payment); - } - - - /** - * test_get_REG_IDs_to_apply_payment_to_for_specific_registrations_and_new_payment - * - * @since 4.8 - * @group 8620 - */ - public function test_get_REG_IDs_to_apply_payment_to_for_specific_registrations_and_new_payment() - { - $this->_admin_page = new Transactions_Admin_Page_Mock(); - //echo "\n\n " . __METHOD__ . "() \n"; - $this->_setup_standard_transaction_and_payment(40.00, 4, 10.00); - // get 2 out of the four registrations - $registrations = $this->_get_x_number_of_registrations_from_transaction($this->_transaction, 2); - // pass those REG IDs via the $_REQUEST data - $this->_admin_page->set_request_data( - array( - 'txn_admin_payment' => array( - 'registrations' => array_keys($registrations), - ), - ) - ); - $REG_IDs = $this->_admin_page->get_REG_IDs_to_apply_payment_to($this->_payment); - foreach ($registrations as $registration) { - if ($registration instanceof EE_Registration) { - $this->assertContains($registration->ID(), $REG_IDs); - } - } - } - - - /** - * test_get_REG_IDs_to_apply_payment_to_for_all_registrations_and_new_payment - * - * @since 4.8 - * @group 8620 - */ - public function test_get_REG_IDs_to_apply_payment_to_for_all_registrations_and_new_payment() - { - $this->_admin_page = new Transactions_Admin_Page_Mock(); - //echo "\n\n " . __METHOD__ . "() \n"; - $this->_setup_standard_transaction_and_payment(40.00, 4, 10.00); - $REG_IDs = $this->_admin_page->get_REG_IDs_to_apply_payment_to($this->_payment); - foreach ($this->_transaction->registrations() as $registration) { - if ($registration instanceof EE_Registration) { - $this->assertContains($registration->ID(), $REG_IDs); - } - } - } - - - /** - * test_get_existing_reg_payment_REG_IDs - * - * @since 4.8 - * @group 8620 - */ - public function test_get_existing_reg_payment_REG_IDs() - { - $this->_admin_page = new Transactions_Admin_Page_Mock(); - //echo "\n\n " . __METHOD__ . "() \n"; - $this->_setup_standard_transaction_and_payment(40.00, 4, 15.00); - // get 2 out of the four registrations - $registrations = $this->_get_x_number_of_registrations_from_transaction($this->_transaction, 2); - $this->_apply_payment_to_registrations($registrations); - $REG_IDs = $this->_admin_page->get_existing_reg_payment_REG_IDs($this->_payment); - $registrations = $this->_transaction->registrations(); - // $15 payment should have applied $10 to first reg and $5 to second reg - $this->assertContains(reset($registrations)->ID(), $REG_IDs); - $this->assertContains(next($registrations)->ID(), $REG_IDs); - // and nothing to the last two registrations - $this->assertNotContains(next($registrations)->ID(), $REG_IDs); - $this->assertNotContains(next($registrations)->ID(), $REG_IDs); - } - - - /** - * test_remove_existing_registration_payments - * - * @since 4.8 - * @group 8620 - */ - public function test_remove_existing_registration_payments() - { - $this->_admin_page = new Transactions_Admin_Page_Mock(); - //echo "\n\n " . __METHOD__ . "() \n"; - $this->_setup_standard_transaction_and_payment(40.00, 4, 10.00); - $registrations = $this->_get_x_number_of_registrations_from_transaction($this->_transaction, 2); - $this->_apply_payment_to_registrations($registrations); - $removed = $this->_admin_page->remove_existing_registration_payments($this->_payment, $this->_payment->ID()); - $this->assertTrue($removed); - // update payment from db - /** @type EE_Payment $payment */ - $payment = EEM_Payment::instance()->get_one_by_ID($this->_payment->ID()); - $registration_payments = $payment->registration_payments(); - $this->assertEmpty($registration_payments); - - } - - - /** - * test_update_registration_payments - * - * @since 4.8 - * @group 8620 - */ - public function test_update_registration_payments_one_reg_paid_in_full() - { - $this->_admin_page = new Transactions_Admin_Page_Mock(); - $this->_setup_standard_transaction_and_payment(40.00, 4, 10.00); - $this->_admin_page->set_existing_reg_payment_REG_IDs(); - $registrations = $this->_get_x_number_of_registrations_from_transaction($this->_transaction, 2); - $this->_admin_page->update_registration_payments($this->_transaction, $this->_payment, - array_keys($registrations)); - $registrations = $this->_transaction->registrations(); - $this->assertEquals(10.00, reset($registrations)->paid()); - $this->assertEquals(0, next($registrations)->paid()); - $this->assertEquals(0, next($registrations)->paid()); - $this->assertEquals(0, next($registrations)->paid()); - } - - - /** - * test_update_registration_payments - * - * @since 4.8 - * @group 8620 - */ - public function test_update_registration_payments_one_reg_paid_in_full_one_partial() - { - $this->_admin_page = new Transactions_Admin_Page_Mock(); - $this->_setup_standard_transaction_and_payment(40.00, 4, 15.00); - $this->_admin_page->set_existing_reg_payment_REG_IDs(); - $registrations = $this->_get_x_number_of_registrations_from_transaction($this->_transaction, 2); - $this->_admin_page->update_registration_payments($this->_transaction, $this->_payment, - array_keys($registrations)); - // now get ALL registrations - $registrations = $this->_transaction->registrations(); - $this->assertEquals(10.00, reset($registrations)->paid()); - $this->assertEquals(5.00, next($registrations)->paid()); - $this->assertEquals(0, next($registrations)->paid()); - $this->assertEquals(0, next($registrations)->paid()); - } - - - /** - * test_update_registration_payments - * - * @since 4.8 - * @group 8620 - */ - public function test_update_registration_payments_last_reg_paid_in_full() - { - $this->_admin_page = new Transactions_Admin_Page_Mock(); - $this->_setup_standard_transaction_and_payment(40.00, 4, 10.00); - $this->_admin_page->set_existing_reg_payment_REG_IDs(); - $registrations = $this->_transaction->registrations(); - $this->_admin_page->update_registration_payments($this->_transaction, $this->_payment, - array(end($registrations)->ID())); - // ref - //$registrations = $this->_transaction->registrations(); - $this->assertEquals(0, reset($registrations)->paid()); - $this->assertEquals(0, next($registrations)->paid()); - $this->assertEquals(0, next($registrations)->paid()); - $this->assertEquals(10.00, next($registrations)->paid()); - } - - - /** - * test_update_registration_payments - * - * @since 4.8 - * @group 8620 - */ - public function test_update_registration_payments_all_paid_in_full() - { - $this->_admin_page = new Transactions_Admin_Page_Mock(); - $this->_setup_standard_transaction_and_payment(40.00, 4, 40.00); - $this->_admin_page->set_existing_reg_payment_REG_IDs(); - $registrations = $this->_transaction->registrations(); - $this->_admin_page->update_registration_payments($this->_transaction, $this->_payment, - array_keys($registrations)); - $this->assertEquals(10.00, reset($registrations)->paid()); - $this->assertEquals(10.00, next($registrations)->paid()); - $this->assertEquals(10.00, next($registrations)->paid()); - $this->assertEquals(10.00, next($registrations)->paid()); - } - - - /** - * test_update_registration_payments - * - * @since 4.8 - * @group 8620 - */ - public function test_update_registration_payments_two_payments() - { - $this->_admin_page = new Transactions_Admin_Page_Mock(); - $this->_setup_standard_transaction_and_payment(40.00, 4, 10.00); - $this->_admin_page->set_existing_reg_payment_REG_IDs(); - $registrations = $this->_transaction->registrations(); - $reg_IDs = array_keys($registrations); - $this->_admin_page->update_registration_payments($this->_transaction, $this->_payment, $reg_IDs); - $this->assertEquals(10.00, reset($registrations)->paid()); - $this->assertEquals(0, next($registrations)->paid()); - $this->assertEquals(0, next($registrations)->paid()); - $this->assertEquals(0, next($registrations)->paid()); - // second payment - $this->_payment = $this->_generate_payment( - $this->_generate_details_array_for_payment_or_refund($this->_transaction, 15.00) - ); - // reset reg IDs - $this->_admin_page->set_existing_reg_payment_REG_IDs(); - $this->_admin_page->update_registration_payments($this->_transaction, $this->_payment, $reg_IDs); - $this->assertEquals(10.00, reset($registrations)->paid()); - $this->assertEquals(10.00, next($registrations)->paid()); - $this->assertEquals(5.00, next($registrations)->paid()); - $this->assertEquals(0, next($registrations)->paid()); - } - - - /** - * test_update_registration_payments - * - * @since 4.8 - * @group 8620 - */ - public function test_update_registration_payments_three_payments_all_paid() - { - $this->_admin_page = new Transactions_Admin_Page_Mock(); - $this->_setup_standard_transaction_and_payment(40.00, 4, 10.00); - $this->_admin_page->set_existing_reg_payment_REG_IDs(); - $registrations = $this->_transaction->registrations(); - $reg_IDs = array_keys($registrations); - $this->_admin_page->update_registration_payments($this->_transaction, $this->_payment, $reg_IDs); - $this->assertEquals(10.00, reset($registrations)->paid()); - $this->assertEquals(0, next($registrations)->paid()); - $this->assertEquals(0, next($registrations)->paid()); - $this->assertEquals(0, next($registrations)->paid()); - // second payment - $this->_payment = $this->_generate_payment( - $this->_generate_details_array_for_payment_or_refund($this->_transaction, 15.00) - ); - // reset reg IDs - $this->_admin_page->set_existing_reg_payment_REG_IDs(); - $this->_admin_page->update_registration_payments($this->_transaction, $this->_payment, $reg_IDs); - $this->assertEquals(10.00, reset($registrations)->paid()); - $this->assertEquals(10.00, next($registrations)->paid()); - $this->assertEquals(5.00, next($registrations)->paid()); - $this->assertEquals(0, next($registrations)->paid()); - // third and final payment - $this->_payment = $this->_generate_payment( - $this->_generate_details_array_for_payment_or_refund($this->_transaction, 15.00) - ); - // reset reg IDs - $this->_admin_page->set_existing_reg_payment_REG_IDs(); - $this->_admin_page->update_registration_payments($this->_transaction, $this->_payment, $reg_IDs); - $this->assertEquals(10.00, reset($registrations)->paid()); - $this->assertEquals(10.00, next($registrations)->paid()); - $this->assertEquals(10.00, next($registrations)->paid()); - $this->assertEquals(10.00, next($registrations)->paid()); - } - - - /** - * test_process_registration_status_change_set_all_registrations_approved - * - * @since 4.8 - * @group 8620 - */ - public function test_process_registration_status_change_set_all_registrations_approved() - { - $this->_admin_page = new Transactions_Admin_Page_Mock(); - // first we need to setup an admin with EE caps - global $current_user; - $current_user = $this->wp_admin_with_ee_caps(); - $this->_setup_standard_transaction_and_payment(40.00, 4, 40.00); - $this->_admin_page->set_existing_reg_payment_REG_IDs(); - // going to need the registration to have an EE_Ticket for this test - $ticket = $this->new_ticket( - array( - 'ticket_price' => 10.00, - 'ticket_taxable' => false, - ) - ); - $registrations = $this->_transaction->registrations(); - foreach ($registrations as $registration) { - if ($registration instanceof EE_Registration) { - $registration->_add_relation_to($ticket, 'Ticket'); - $registration->_add_relation_to($ticket->get_related_event(), 'Event'); - $registration->save(); - $this->assertEquals(EEM_Registration::status_id_pending_payment, $registration->status_ID()); - } - } - // set $_REQUEST data - $this->_admin_page->set_request_data( - array( - 'txn_reg_status_change' => array( - 'reg_status' => EEM_Registration::status_id_approved, - ), - ) - ); - $status_updates = $this->_admin_page->process_registration_status_change($this->_transaction, - array_keys($registrations)); - $this->assertTrue($status_updates); - foreach ($registrations as $registration) { - if ($registration instanceof EE_Registration) { - $this->assertEquals(EEM_Registration::status_id_approved, $registration->status_ID()); - } - } - } - - - /** - * test_process_registration_status_change_set_two_registrations_approved - * - * @since 4.8 - * @group 8620 - */ - public function test_process_registration_status_change_set_two_registrations_approved() - { - $this->_admin_page = new Transactions_Admin_Page_Mock(); - // first we need to setup an admin with EE caps - global $current_user; - $current_user = $this->wp_admin_with_ee_caps(); - $this->_setup_standard_transaction_and_payment(40.00, 4, 20.00); - $reg_IDs = array_keys($this->_transaction->registrations()); - $registrations = $this->_get_x_number_of_registrations_from_transaction($this->_transaction, 2); - $this->_apply_payment_to_registrations($registrations); - //$this->_admin_page->set_existing_reg_payment_REG_IDs(); - // going to need the registration to have an EE_Ticket for this test - $ticket = $this->new_ticket( - array( - 'ticket_price' => 10.00, - 'ticket_taxable' => false, - ) - ); - //$registrations = $this->_transaction->registrations(); - foreach ($registrations as $registration) { - if ($registration instanceof EE_Registration) { - $registration->_add_relation_to($ticket, 'Ticket'); - $registration->_add_relation_to($ticket->get_related_event(), 'Event'); - $registration->save(); - $this->assertEquals(EEM_Registration::status_id_pending_payment, $registration->status_ID()); - } - } - // set $_REQUEST data - $this->_admin_page->set_request_data( - array( - 'txn_reg_status_change' => array( - 'reg_status' => EEM_Registration::status_id_approved, - ), - ) - ); - $status_updates = $this->_admin_page->process_registration_status_change($this->_transaction, - array_keys($registrations)); - $this->assertTrue($status_updates); - // re-query for ALL of the registrations - $registrations = $this->_transaction->registrations(array(array('REG_ID' => array('IN', $reg_IDs)))); - $this->assertEquals(EEM_Registration::status_id_approved, reset($registrations)->status_ID()); - $this->assertEquals(EEM_Registration::status_id_approved, next($registrations)->status_ID()); - $this->assertEquals(EEM_Registration::status_id_pending_payment, next($registrations)->status_ID()); - $this->assertEquals(EEM_Registration::status_id_pending_payment, next($registrations)->status_ID()); - } - - - /** - * test_build_payment_json_response_for_payment - * - * @since 4.8 - * @group 8620 - */ - public function test_build_payment_json_response_for_payment() - { - $this->_admin_page = new Transactions_Admin_Page_Mock(); - $this->_setup_standard_transaction_and_payment(40.00, 4, 15.00); - // need to make sure relation is set between payment and payment method - $this->_payment->_add_relation_to($this->_payment_method(), 'Payment_Method'); - $registrations = $this->_get_x_number_of_registrations_from_transaction($this->_transaction, 1); - $this->_apply_payment_to_registrations($registrations); - $json_response_data = $this->_admin_page->build_payment_json_response($this->_payment); - $pay_status = EEM_Payment::instance()->status_array(true); - $this->assertEquals(15.00, $json_response_data['amount']); - // total paid is still zero, because we haven't actually updated the TXN with the payment info - $this->assertEquals(0, $json_response_data['total_paid']); - $this->assertEquals(EEM_Transaction::incomplete_status_code, $json_response_data['txn_status']); - $this->assertEquals(EEM_Payment::status_id_approved, $json_response_data['pay_status']); - $this->assertEquals(EEM_Payment::status_id_approved, $json_response_data['STS_ID']); - $this->assertEquals($pay_status[EEM_Payment::status_id_approved], $json_response_data['status']); - $this->assertEquals($this->_payment->ID(), $json_response_data['PAY_ID']); - $this->assertEquals($this->_payment->timestamp('Y-m-d', 'h:i a'), $json_response_data['date']); - $this->assertEquals(strtoupper($this->_payment->source()), $json_response_data['method']); - $this->assertEquals($this->_payment_method()->ID(), $json_response_data['PM_ID']); - $this->assertEquals($this->_payment_method()->admin_name(), $json_response_data['gateway']); - $this->assertEquals($this->_payment->gateway_response(), $json_response_data['gateway_response']); - $this->assertEquals($this->_payment->txn_id_chq_nmbr(), $json_response_data['txn_id_chq_nmbr']); - $this->assertEquals($this->_payment->po_number(), $json_response_data['po_number']); - $this->assertEquals($this->_payment->extra_accntng(), $json_response_data['extra_accntng']); - $this->assertEquals($this->_payment->extra_accntng(), $json_response_data['extra_accntng']); - // will validate $json_response_data[ 'registrations' ] in test_registration_payment_data_array() - } - - - /** - * test_build_payment_json_response_for_deleted_payment - * - * @since 4.8 - * @group 8620 - */ - public function test_build_payment_json_response_for_deleted_payment() - { - $this->_admin_page = new Transactions_Admin_Page_Mock(); - $this->_setup_standard_transaction_and_payment(40.00, 4, 15.00); - // need to make sure relation is set between payment and payment method - $this->_payment->_add_relation_to($this->_payment_method(), 'Payment_Method'); - $registrations = $this->_get_x_number_of_registrations_from_transaction($this->_transaction, 1); - $this->_apply_payment_to_registrations($registrations); - $json_response_data = $this->_admin_page->build_payment_json_response($this->_payment, array(), true); - $this->assertEquals($this->_payment->ID(), $json_response_data['PAY_ID']); - $this->assertEquals(15.00, $json_response_data['amount']); - // total paid is still zero, because we haven't actually updated the TXN with the payment info - $this->assertEquals(0, $json_response_data['total_paid']); - $this->assertEquals(EEM_Transaction::incomplete_status_code, $json_response_data['txn_status']); - $this->assertEquals(EEM_Payment::status_id_approved, $json_response_data['pay_status']); - $this->assertTrue($json_response_data['delete_txn_reg_status_change']); - // will validate $json_response_data[ 'registrations' ] in test_registration_payment_data_array() - } - - - /** - * test_registration_payment_data_array - * - * @since 4.8 - * @group 8620 - */ - public function test_registration_payment_data_array() - { - $this->_admin_page = new Transactions_Admin_Page_Mock(); - $this->_setup_standard_transaction_and_payment(40.00, 4, 25.00); - $registrations = $this->_transaction->registrations(); - $this->_apply_payment_to_registrations($registrations); - $registration_payment_data_array = $this->_admin_page->registration_payment_data_array(array_keys($registrations)); - // format the payment values - $ten_dollars = EEH_Template::format_currency(10.00); - $five_dollars = EEH_Template::format_currency(5.00); - $no_dollars = EEH_Template::format_currency(0.00); - // reg # 1 paid $10, owes 0 - $registration_payment_data = reset($registration_payment_data_array); - $this->assertEquals($ten_dollars, $registration_payment_data['paid']); - $this->assertEquals($no_dollars, $registration_payment_data['owing']); - // reg # 2 paid $10, owes 0 - $registration_payment_data = next($registration_payment_data_array); - $this->assertEquals($ten_dollars, $registration_payment_data['paid']); - $this->assertEquals($no_dollars, $registration_payment_data['owing']); - // reg # 3 paid $5, owes $5 - $registration_payment_data = next($registration_payment_data_array); - $this->assertEquals($five_dollars, $registration_payment_data['paid']); - $this->assertEquals($five_dollars, $registration_payment_data['owing']); - // reg # 4 paid $0, owes $10 - $registration_payment_data = next($registration_payment_data_array); - $this->assertEquals($no_dollars, $registration_payment_data['paid']); - $this->assertEquals($ten_dollars, $registration_payment_data['owing']); - } - - -} -// End of file Transactions_Admin_Page_Test.php -// Location: /tests/testcases/admin_pages/transactions/Transactions_Admin_Page_Test.php \ No newline at end of file diff --git a/tests/testcases/core/EE_Addon_Test.php b/tests/testcases/core/EE_Addon_Test.php deleted file mode 100644 index 9397c554491..00000000000 --- a/tests/testcases/core/EE_Addon_Test.php +++ /dev/null @@ -1,131 +0,0 @@ -_main_file_path = EE_TESTS_DIR . 'mocks/addons/eea-new-addon/eea-new-addon.php'; - require_once $this->_main_file_path; - //loading that file adds a hook, but we want to control when it hooks in - remove_action( 'AHEE__EE_System__load_espresso_addons', 'load_espresso_new_addon' ); - $this->_table_analysis = new \EventEspresso\core\services\database\TableAnalysis(); - $this->_table_manager = new \EventEspresso\core\services\database\TableManager( $this->_table_analysis ); - parent::__construct($name, $data, $dataName); - } - public function setUp(){ - parent::setUp(); - //let's just make a generic addon, but not bother registering it - $loader = EventEspresso\core\services\loaders\LoaderFactory::getLoader(); - require_once dirname($this->_main_file_path) . '/EE_New_Addon.class.php'; - $this->_addon = $loader->getShared( - 'EE_New_Addon', - array( - $loader->getShared('EE_Dependency_Map'), - null, - 'EE_Registry::create(addon)' => true - ) - ); - $this->_addon->set_name( 'New_Addon' ); - $this->_addon->set_main_plugin_file( $this->_main_file_path ); - $this->_addon->set_version( '1.0.0' ); - $this->_addon->set_min_core_version( '4.0.0' ); - add_filter( 'FHEE__EEH_Activation__create_table__short_circuit', array( $this, 'dont_short_circuit_new_addon_table' ), 20, 3 ); - } - - public function tearDown(){ - //drop all the temporary tables we created during this test, because each subsequent test expects them to be gone - $this->_table_manager->dropTables( $this->_temp_tables_added_by_addon ); - parent::tearDown(); - } - - - - /** - * OK's the creation of the esp_new_addon table, because this hooks in AFTER EE_UNitTestCase's callback on this same hook - * - * @param bool $short_circuit - * @param string $table_name - * @param string $create_sql - * @return boolean - */ - public function dont_short_circuit_new_addon_table( $short_circuit = false, $table_name = '', $create_sql = '' ){ - if ( - in_array( $table_name, $this->_temp_tables_added_by_addon ) - ) { -// echo "\r\n\r\nDONT short circuit $sql"; - //it's not altering. it's ok to allow this - return false; - }else{ -// echo "3\r\n\r\n short circuit:$sql"; - return $short_circuit; - } - } - - public function test_update_list_of_installed_versions(){ - $initial_activation_history = $this->_addon->get_activation_history(); - $this->assertEmpty( $initial_activation_history ); - $now_string = substr( date( 'Y-m-d H:i:s', time() ), 0, -1); - //now update the list - $this->_addon->update_list_of_installed_versions( $initial_activation_history, '2.0.0' ); - //now let's try adding more to it - $this->_addon->update_list_of_installed_versions( $initial_activation_history, '3.0.0' ); - $new_activation_history = $this->_addon->get_activation_history(); - $version_number = key($new_activation_history); - $times_installed = array_shift($new_activation_history); - $this->assertEquals('2.0.0',$version_number); - $this->assertTrue( is_array( $times_installed ) ); - $time_first_installed = array_shift( $times_installed ); - $this->assertEquals( $now_string, substr( $time_first_installed, 0, -1) ); - - $second_version_number = key($new_activation_history); - $times_second_v_installed = array_shift($new_activation_history); - $this->assertEquals('3.0.0',$second_version_number); - $this->assertTrue( is_array( $times_second_v_installed ) ); - $time_second_v_first_installed = array_shift( $times_second_v_installed ); - $this->assertEquals($now_string, substr( $time_second_v_first_installed, 0, -1) ); - } - - public function test_get_main_plugin_file(){ - $this->assertEquals($this->_main_file_path,$this->_addon->get_main_plugin_file() ); - } - - public function test_get_main_plugin_file_basename(){ - $this->assertEquals(plugin_basename($this->_main_file_path ), $this->_addon->get_main_plugin_file_basename() ); - } - public function test_get_main_plugin_file_dirname(){ - $this->assertEquals( dirname($this->_main_file_path ), $this->_addon->get_main_plugin_file_dirname() ); - } - - - -} - -// End of file EE_Addon_Test.php diff --git a/tests/testcases/core/EE_Base_Class_Repository_Test.php b/tests/testcases/core/EE_Base_Class_Repository_Test.php deleted file mode 100644 index 4683a0730a5..00000000000 --- a/tests/testcases/core/EE_Base_Class_Repository_Test.php +++ /dev/null @@ -1,127 +0,0 @@ -repository = new EE_Base_Class_Repository_Mock(); - } - - public function test_save() { - $ticket_1 = $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_price' => '5' ), false ); - $this->repository->add( $ticket_1 ); - $this->assertEquals( $ticket_1->ID(), 0 ); - $saved = false; - $this->repository->rewind(); - while ( $this->repository->valid() ) { - if ( $this->repository->current() === $ticket_1 ) { - $saved = $this->repository->save(); - $this->assertNotEquals( $this->repository->current()->ID(), 0 ); - $this->assertEquals( $this->repository->current()->ID(), $ticket_1->ID() ); - break; - } - $this->repository->next(); - } - $this->assertNotEquals( $saved, false ); - } - - public function test_save_all() { - $ticket_1 = $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_price' => '5' ), false ); - $ticket_2 = $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_price' => '6' ), false ); - $this->repository->add( $ticket_1 ); - $this->repository->add( $ticket_2 ); - $this->assertEquals( count( $this->repository ), 2 ); - $this->assertEquals( $ticket_1->ID(), 0 ); - $this->assertEquals( $ticket_2->ID(), 0 ); - $saved = $this->repository->save_all(); - $this->assertEquals( $saved, true ); - $this->assertNotEquals( $ticket_1->ID(), 0 ); - $this->assertNotEquals( $ticket_2->ID(), 0 ); - } - - public function test_delete() { - $ticket_1 = $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_price' => '5' ), false ); - $this->repository->add( $ticket_1 ); - $this->assertTrue( $this->repository->has( $ticket_1 ) ); - $this->repository->rewind(); - while ( $this->repository->valid() ) { - if ( $this->repository->current() === $ticket_1 ) { - $this->repository->save(); - $this->assertEquals( $this->repository->current()->ID(), $ticket_1->ID() ); - break; - } - $this->repository->next(); - } - $ticket_1_ID = $ticket_1->ID(); - $this->assertNotEquals( $ticket_1_ID, 0 ); - // now test that we can delete the ticket and remove it from the repo - $this->repository->rewind(); - while ( $this->repository->valid() ) { - if ( $this->repository->current() === $ticket_1 ) { - $deleted = $this->repository->delete(); - $this->assertTrue( $deleted ); - break; - } - $this->repository->next(); - } - $this->assertFalse( $this->repository->has( $ticket_1 ) ); - $this->assertEquals( count( $this->repository ), 0 ); - // because tickets are soft deletable - $ticket1_from_db = EEM_Ticket::instance()->get_one_by_ID( $ticket_1_ID ); - $this->assertTrue( $ticket1_from_db->deleted() ); - } - - - - - public function test_delete_all() { - $ticket_1 = $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_price' => '5' ), false ); - $ticket_2 = $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_price' => '6' ), false ); - $this->repository->add( $ticket_1 ); - $this->repository->add( $ticket_2 ); - $this->assertTrue( $this->repository->has( $ticket_1 ) ); - $this->assertTrue( $this->repository->has( $ticket_2 ) ); - $this->assertEquals( count( $this->repository ), 2 ); - $this->assertEquals( $ticket_1->ID(), 0 ); - $this->assertEquals( $ticket_2->ID(), 0 ); - $saved = $this->repository->save_all(); - $this->assertEquals( $saved, true ); - $ticket_1_ID = $ticket_1->ID(); - $ticket_2_ID = $ticket_2->ID(); - $this->assertNotEquals( $ticket_1_ID, 0 ); - $this->assertNotEquals( $ticket_2_ID, 0 ); - // now test that we can delete the tickets and remove them from the repo - $deleted = $this->repository->delete_all(); - $this->assertTrue( $deleted ); - $this->assertFalse( $this->repository->has( $ticket_1 ) ); - $this->assertFalse( $this->repository->has( $ticket_2 ) ); - // and the total count - $this->assertEquals( count( $this->repository ), 0 ); - // because tickets are soft deletable - $ticket1_from_db = EEM_Ticket::instance()->get_one_by_ID( $ticket_1_ID ); - $this->assertTrue( $ticket1_from_db->deleted() ); - $ticket2_from_db = EEM_Ticket::instance()->get_one_by_ID( $ticket_2_ID ); - $this->assertTrue( $ticket2_from_db->deleted() ); - } - - - -} -// End of file EE_Base_Class_Repository_Test.php -// Location: /tests/testcases/core/EE_Base_Class_Repository_Test.php \ No newline at end of file diff --git a/tests/testcases/core/EE_Capabilities_Test.php b/tests/testcases/core/EE_Capabilities_Test.php deleted file mode 100644 index fc8afb921fb..00000000000 --- a/tests/testcases/core/EE_Capabilities_Test.php +++ /dev/null @@ -1,340 +0,0 @@ -CAPS = EE_Registry::instance()->CAP; - } - - - - /** - * test the get_ee_capabilities method on EE_Capabilities class. - * - * @since 4.5.0 - */ - public function test_get_ee_capabilities() - { - //test getting admin capabilities (default) - $admin_capabilities = $this->CAPS->get_ee_capabilities(); - $this->assertFalse(isset($admin_capabilities[self::ADMINISTRATOR_ROLE])); - $this->assertTrue(is_array($admin_capabilities) && isset($admin_capabilities[0])); - $first_cap = $admin_capabilities[0]; - $this->assertEquals('ee_read_ee', $first_cap); - - //test getting all capabilities - $all_caps = $this->CAPS->get_ee_capabilities(''); - $this->assertArrayHasKey(self::ADMINISTRATOR_ROLE, $all_caps); - - //test getting invalid capability - $caps = $this->CAPS->get_ee_capabilities('no_exist'); - $this->assertEmpty($caps); - } - - - - public function test_add_new_capabilities_via_filtering_init_caps() - { - global $wp_roles; - //check the current user is an admin - $user = $this->factory->user->create_and_get(); - $this->assertInstanceOf('WP_User', $user); - $this->assertFalse($this->CAPS->user_can($user, 'ee_new_cap', 'test')); - - //ok now add another cap, and re-init stuff and verify it got added correctly - //add a new cap - add_filter('FHEE__EE_Capabilities__init_caps_map__caps', array($this, 'add_new_caps')); - // but we'll need to set the reset flag to true if we want to do things this way - $this->CAPS->init_caps(true); - //check it got added - $this->assertArrayContains('ee_new_cap', $this->CAPS->get_ee_capabilities(self::ADMINISTRATOR_ROLE)); - $user->add_role(self::ADMINISTRATOR_ROLE); - $this->assertTrue($this->CAPS->user_can($user, 'ee_new_cap', 'test')); - //then check newly-created users get that new role - //refresh the roles' caps and the user object - $wp_roles = new WP_Roles(); - $user_refreshed = get_user_by('id', $user->ID); - $this->assertTrue($this->CAPS->user_can($user_refreshed, 'ee_new_cap', 'test')); - } - - public function add_new_caps($existing_caps) - { - $existing_caps[self::ADMINISTRATOR_ROLE][] = 'ee_new_cap'; - return $existing_caps; - } - - - - public function testAddCaps() - { - $this->CAPS->init_caps(true); - global $wp_roles; - //check the current user is an admin - $user = $this->factory->user->create_and_get(); - $this->assertInstanceOf('WP_User', $user); - $this->assertFalse($this->CAPS->user_can($user, 'ee_new_cap', 'test')); - // ok now add a new cap, but this time using addCaps - $this->CAPS->addCaps(array(self::ADMINISTRATOR_ROLE => array('ee_new_cap'))); - //check it got added - $this->assertArrayContains('ee_new_cap', $this->CAPS->get_ee_capabilities(self::ADMINISTRATOR_ROLE)); - $user->add_role(self::ADMINISTRATOR_ROLE); - $this->assertTrue($this->CAPS->user_can($user, 'ee_new_cap', 'test')); - //then check newly-created users get that new role - //refresh the roles' caps and the user object - $wp_roles = new WP_Roles(); - $user_refreshed = get_user_by('id', $user->ID); - $this->assertTrue($this->CAPS->user_can($user_refreshed, 'ee_new_cap', 'test')); - } - - - - public function test_add_cap_to_role() - { - $this->CAPS->init_caps(true); - global $wp_roles; - //check the current user is an admin - $user = $this->factory->user->create_and_get(); - $this->assertInstanceOf('WP_User', $user); - $this->assertFalse($this->CAPS->user_can($user, 'ee_new_cap', 'test')); - // ok now add a new cap, but this time using addCaps - $this->CAPS->add_cap_to_role(self::ADMINISTRATOR_ROLE, 'ee_new_cap'); - //check it got added - $this->assertArrayContains('ee_new_cap', $this->CAPS->get_ee_capabilities(self::ADMINISTRATOR_ROLE)); - $user->add_role(self::ADMINISTRATOR_ROLE); - $this->assertTrue($this->CAPS->user_can($user, 'ee_new_cap', 'test')); - //then check newly-created users get that new role - //refresh the roles' caps and the user object - $wp_roles = new WP_Roles(); - $user_refreshed = get_user_by('id', $user->ID); - $this->assertTrue($this->CAPS->user_can($user_refreshed, 'ee_new_cap', 'test')); - } - - - - /** - * @since 4.5.0 - */ - public function test_current_user_can_and_user_can() - { - global $current_user; - //setup our user and set as current user. - $user = $this->factory->user->create_and_get(); - $this->assertInstanceOf('WP_User', $user); - $user->add_role(self::ADMINISTRATOR_ROLE); - $current_user = $user; - - //check what should be a valid cap - $this->assertTrue($this->CAPS->current_user_can('ee_read_ee', 'tests')); - $this->assertTrue($this->CAPS->user_can($user, 'ee_read_ee', 'tests')); - - //check what should be an invalid cap - $this->assertFalse($this->CAPS->current_user_can('invalid_cap', 'tests')); - $this->assertFalse($this->CAPS->user_can($user, 'invalid_cap', 'tests')); - - //test context filter - function test_custom_filter($cap, $id) - { - if ($cap == 'ee_read_ee') { - return 'need_this_instead'; - } - - return $cap; - } - - add_filter('FHEE__EE_Capabilities__current_user_can__cap__tests', 'test_custom_filter', 10, 2); - add_filter('FHEE__EE_Capabilities__user_can__cap__tests', 'test_custom_filter', 10, 2); - - $this->assertFalse($this->CAPS->current_user_can('ee_read_ee', 'tests')); - $this->assertFalse($this->CAPS->user_can($user, 'ee_read_ee', 'tests')); - - //test global filter - function test_global_filter($filtered_cap, $context, $cap, $id) - { - if ($cap == 'ee_read_ee' && $context == 'tests') { - return 'ee_read_ee'; //override what was set by custom filter - } - - return $cap; - } - - add_filter('FHEE__EE_Capabilities__current_user_can__cap', 'test_global_filter', 10, 4); - add_filter('FHEE__EE_Capabilities__user_can__cap', 'test_global_filter', 10, 4); - - $this->assertTrue($this->CAPS->current_user_can('ee_read_ee', 'tests')); - $this->assertTrue($this->CAPS->user_can($user, 'ee_read_ee', 'tests')); - } - - - - public function testRemoveCaps() - { - $this->CAPS->init_caps(true); - /** @var WP_Role $administrator_role */ - $administrator_role = get_role(self::ADMINISTRATOR_ROLE); - $this->assertInstanceOf('WP_Role', $administrator_role); - // verify two ways that cap exists - $this->assertTrue(isset($administrator_role->capabilities['ee_manage_gateways'])); - $this->assertTrue($administrator_role->has_cap('ee_manage_gateways')); - // for whatever reason, this site wants to have all gateways - // under control of someone other than the standard administrator - // so they want to remove the 'ee_manage_gateways' cap from the above administrator role - $this->CAPS->removeCaps(array(self::ADMINISTRATOR_ROLE => array('ee_manage_gateways'))); - $user = $this->setupAdminUserAndTestCapDoesNOtExist('ee_manage_gateways'); - $this->assertFalse( - $this->CAPS->user_can($user, 'ee_manage_gateways', 'test'), - 'The admin user should NOT have the "ee_manage_gateways" capability because it was removed!' - ); - } - - - - public function test_remove_cap_from_role() - { - $this->CAPS->init_caps(true); - /** @var WP_Role $administrator_role */ - $administrator_role = get_role(self::ADMINISTRATOR_ROLE); - $this->assertInstanceOf('WP_Role', $administrator_role); - // verify that cap exists - $this->assertTrue($administrator_role->has_cap('ee_manage_gateways')); - // for whatever reason, this site wants to have all gateways - // under control of someone other than the standard administrator - // so they want to remove the 'ee_manage_gateways' cap from the above administrator role - $this->CAPS->remove_cap_from_role(self::ADMINISTRATOR_ROLE, 'ee_manage_gateways'); - $user = $this->setupAdminUserAndTestCapDoesNOtExist('ee_manage_gateways'); - $this->assertFalse( - $this->CAPS->user_can($user, 'ee_manage_gateways', 'test'), - 'The admin user should NOT have the "ee_manage_gateways" capability because it was removed!' - ); - } - - - - private function setupAdminUserAndTestCapDoesNOtExist($cap_to_test = '') - { - /** @var WP_User $user */ - $user = $this->factory->user->create_and_get(); - $this->assertInstanceOf('WP_User', $user); - // verify they don't have the $cap_to_test YET... - $this->assertFalse( - $this->CAPS->user_can($user, $cap_to_test, 'test'), - 'The admin user should NOT have the "'. $cap_to_test .'" capability YET!' - ); - // first remove the existing default role - $user->remove_role(self::SUBSCRIBER_ROLE); - // verify that no other roles exist that could be granting caps - $this->assertEmpty($user->roles); - // now make this user an administrator - $user->add_role(self::ADMINISTRATOR_ROLE); - $this->assertEquals(self::ADMINISTRATOR_ROLE, reset($user->roles)); - return $user; - } - - - public function testPaymentMethodCaps() - { - // we're going to fake the activation of the Mock_Onsite payment method - // which should bestow the following capability to administrators - $mock_onsite_capability = 'ee_payment_method_mock_onsite'; - // but first we need to fake being in the admin - $this->go_to(admin_url()); - // first let's verify that admins do not currently have this cap - /** @var WP_Role $administrator_role */ - $administrator_role = get_role(self::ADMINISTRATOR_ROLE); - $this->assertInstanceOf('WP_Role', $administrator_role); - // verify two ways that cap does not exist YET... - $this->assertFalse(isset($administrator_role->capabilities[$mock_onsite_capability])); - $this->assertFalse($administrator_role->has_cap($mock_onsite_capability)); - // now create an admin user - $user = $this->setupAdminUserAndTestCapDoesNOtExist($mock_onsite_capability); - // and fake activation of the Mock Onsite Payment Method - $this->_pretend_addon_hook_time(); - EE_Register_Payment_Method::register( - 'onsite', - array( - 'payment_method_paths' => array( - EE_TESTS_DIR . 'mocks/payment_methods/Mock_Onsite', - ), - ) - ); - // to complete the fake PM registration, we need to reset the EE_Payment_Method_Manager - // which will take care of injecting all Payment Method caps into the default cap map - // normally we wouldn't do this because the PM would get registered before the caps get initialized - EE_Payment_Method_Manager::reset(); - // and confirm that the admin role now has that cap - $this->assertTrue( - $administrator_role->has_cap($mock_onsite_capability), - 'The admin user should have the "' . $mock_onsite_capability . '" capability!' - ); - // but it appears caps are only added when the role is assigned - // (that's really clever WordPress what's the point of having roles then?) - // turns out we can call the protected _init_caps() method, to reset the caps - $this->refreshRolesForUser($user); - // then verify the user also has the cap - $this->assertTrue( - $this->CAPS->user_can($user, $mock_onsite_capability, 'test'), - 'The admin user should have the "' . $mock_onsite_capability . '" capability!' - ); - // now deactivate the Mock Onsite PM - EE_Register_Payment_Method::deregister('onsite'); - //deregister will just set the hook to run on `AHEE__EE_System__core_loaded_and_ready` so we need to call that - //hook - do_action('AHEE__EE_System__core_loaded_and_ready'); - // and confirm that the admin role now has lost that cap - $this->assertFalse( - $administrator_role->has_cap($mock_onsite_capability), - 'The admin user should NOT have the "' . $mock_onsite_capability . '" capability!' - ); - $this->refreshRolesForUser($user); - // then verify the user also has also lost the cap - $this->assertFalse( - $this->CAPS->user_can($user, $mock_onsite_capability, 'test'), - 'The admin user should have the "' . $mock_onsite_capability . '" capability!' - ); - } - - - - public function testAddNewRoleWhenAddingCap() - { - $this->CAPS->init_caps(true); - $jedi_master = 'ee_jedi_master'; - /** @var WP_Role $jedi_master_role */ - $jedi_master_role = get_role($jedi_master); - $this->assertNull($jedi_master_role); - $this->CAPS->add_cap_to_role($jedi_master, 'ee_use_the_force'); - /** @var WP_Role $jedi_master_role */ - $jedi_master_role = get_role($jedi_master); - $this->assertInstanceOf('WP_Role', $jedi_master_role); - } -} -// end EE_Capabilities_Test class -// Location: testcases/core/EE_Capabilities_Test.php diff --git a/tests/testcases/core/EE_Cart_Test.php b/tests/testcases/core/EE_Cart_Test.php deleted file mode 100644 index c122fa81fb3..00000000000 --- a/tests/testcases/core/EE_Cart_Test.php +++ /dev/null @@ -1,200 +0,0 @@ -_session = LoaderFactory::getLoader()->getShared('EE_Session_Mock'); - EE_Cart::reset( null, $this->_session ); - } - - public function test_get_cart_from_txn(){ - $transaction = $this->new_typical_transaction(); - $grand_total_line_item = $transaction->total_line_item(); - $cart = EE_Cart::reset( null, $this->_session ); - $this->assertNotEquals( $cart->get_grand_total()->ID(), $grand_total_line_item->ID() ); - $cart = EE_Cart::get_cart_from_txn( $transaction, $this->_session ); - $this->assertEquals( $cart->get_grand_total()->ID(), $grand_total_line_item->ID() ); - } - - public function test_get_tickets(){ - $transaction = $this->new_typical_transaction(); - $plain_line_items = EEM_Line_Item::instance()->get_all_of_type_for_transaction( EEM_Line_Item::type_line_item, $transaction ); - $cart = EE_Cart::get_cart_from_txn( $transaction, $this->_session ); - $this->assertNotEmpty( $cart->get_tickets() ); - $this->assertEEModelObjectsEquals( $plain_line_items, $cart->get_tickets() ); - } - - public function test_all_ticket_quantity_count(){ - $transaction = $this->new_typical_transaction(); - EEM_Line_Item::instance()->get_all_of_type_for_transaction( EEM_Line_Item::type_line_item, $transaction ); - $cart = EE_Cart::get_cart_from_txn( $transaction, $this->_session ); - $this->assertEquals( 1, $cart->all_ticket_quantity_count() ); - } - - public function test_get_taxes(){ - $transaction = $this->new_typical_transaction(); - $taxes = EEM_Line_Item::instance()->get_all_of_type_for_transaction( EEM_Line_Item::type_tax, $transaction ); - $cart = EE_Cart::get_cart_from_txn( $transaction, $this->_session ); - $this->assertEEModelObjectsEquals( $taxes, $cart->get_taxes() ); - } - public function test_get_grand_total(){ - $transaction = $this->new_typical_transaction(); - $cart = EE_Cart::get_cart_from_txn( $transaction, $this->_session ); - $this->assertEEModelObjectsEquals( $transaction->total_line_item(), $cart->get_grand_total() ); - } - public function test_add_ticket_to_cart(){ - //let's make an interesting ticket, with multiple datetimes, multiple prices etc - $quantity_purchased = 4; - /** @type EE_Ticket $ticket */ - $ticket = $this->new_model_obj_with_dependencies('Ticket', array( 'TKT_price' => '16.5', 'TKT_taxable' => FALSE ) ); - $base_price_type = EEM_Price_Type::instance()->get_one( array( array('PRT_name' => 'Base Price' ) ) ); - $dollar_surcharge_price_type = EEM_Price_Type::instance()->get_one( array( array( 'PRT_name' => 'Dollar Surcharge' ) ) ); - $percent_surcharge_price_type = EEM_Price_Type::instance()->get_one( array( array( 'PRT_name' => 'Percent Surcharge' ) ) ); - $this->assertInstanceOf( 'EE_Price_Type', $base_price_type ); - $this->assertInstanceOf( 'EE_Price_Type', $dollar_surcharge_price_type ); - $this->assertInstanceOf( 'EE_Price_Type', $percent_surcharge_price_type ); - /** @type EE_Price $base_price */ - $base_price = $this->new_model_obj_with_dependencies( 'Price', array( 'PRC_amount' => 10, 'PRT_ID' => $base_price_type->ID() ) ); - /** @type EE_Price $dollar_surcharge */ - $dollar_surcharge = $this->new_model_obj_with_dependencies( 'Price', array( 'PRC_amount' => 5, 'PRT_ID' => $dollar_surcharge_price_type->ID() ) ); - /** @type EE_Price $percent_surcharge */ - $percent_surcharge = $this->new_model_obj_with_dependencies( 'Price', array( 'PRC_amount' => 10, 'PRT_ID' => $percent_surcharge_price_type->ID() ) ); - $ticket->_add_relation_to( $base_price, 'Price' ); - $ticket->_add_relation_to( $dollar_surcharge, 'Price' ); - $ticket->_add_relation_to( $percent_surcharge, 'Price' ); - $this->assertArrayContains( $base_price, $ticket->prices() ); - $this->assertArrayContains( $dollar_surcharge, $ticket->prices() ); - $this->assertArrayContains( $percent_surcharge, $ticket->prices() ); - $event = $this->new_model_obj_with_dependencies( 'Event' ); - $ddt1 = $this->new_model_obj_with_dependencies( 'Datetime', array( 'EVT_ID'=> $event->ID() ) ); - $ddt2 = $this->new_model_obj_with_dependencies( 'Datetime', array( 'EVT_ID'=> $event->ID() ) ); - $ticket->_add_relation_to( $ddt1, 'Datetime' ); - $ticket->_add_relation_to( $ddt2, 'Datetime' ); - $this->assertArrayContains( $ddt1, $ticket->datetimes() ); - $this->assertArrayContains( $ddt2, $ticket->datetimes() ); - // reset cart - $cart = EE_Cart::reset( null, $this->_session ); - $cart->add_ticket_to_cart( $ticket, $quantity_purchased ); - $total_line_item = $cart->get_grand_total(); - $subtotals = $total_line_item->children(); - $this->assertNotEmpty( $subtotals ); - $items_purchased = $total_line_item->get_items(); - $this->assertEquals(1, count( $items_purchased ) ); - $item_purchased = array_shift( $items_purchased ); - $this->assertEquals( $ticket->name(), $item_purchased->name() ); - $this->assertEquals( $item_purchased->total(), $total_line_item->total() ); - $sub_line_items = $item_purchased->children(); - $this->assertEquals( count( $ticket->prices() ), count( $sub_line_items ) ); - //the first one should be the base price - $base_price_sli = array_shift( $sub_line_items ); - $this->assertEquals( $base_price->amount() * 4, $base_price_sli->total() ); - $dollar_surcharge_sli = array_shift( $sub_line_items ); - $this->assertEquals( $dollar_surcharge->amount() * 4, $dollar_surcharge_sli->total( - ) ); - $percent_surcharge_sli = array_shift( $sub_line_items ); - $this->assertEquals( $percent_surcharge->amount(), $percent_surcharge_sli->percent() ); - $this->assertEquals( ($base_price->amount() + $dollar_surcharge->amount() )* $percent_surcharge->amount() / 100 * $quantity_purchased, $percent_surcharge_sli->total() ); - $this->assertEquals($ticket->price() * $quantity_purchased, $cart->get_cart_grand_total() ); - - } - - public function test_get_cart_total_before_tax(){ - $transaction = $this->new_typical_transaction(); - $cart = EE_Cart::get_cart_from_txn( $transaction, $this->_session ); - $this->assertEquals( 10, $cart->get_cart_total_before_tax() ); - } - - public function test_get_applied_taxes(){ - $transaction = $this->new_typical_transaction(); - $cart = EE_Cart::get_cart_from_txn( $transaction, $this->_session ); - $this->assertEquals( 1.5, $cart->get_applied_taxes() ); - } - - public function test_get_cart_grand_total(){ - $transaction = $this->new_typical_transaction(); - $cart = EE_Cart::get_cart_from_txn( $transaction, $this->_session ); - $this->assertEquals( 11.5, $cart->get_cart_grand_total() ); - } - - public function test_delete_items(){ - //known to fail - $ticket_types = 4; - $transaction = $this->new_typical_transaction( array( 'ticket_types' => $ticket_types ) ); - /** @type EE_Line_Item $latest_line_item */ - $latest_line_item = EEM_Line_Item::instance()->get_one( array( - array( 'LIN_type' => EEM_Line_Item::type_line_item ), - 'order_by' => array( 'LIN_ID'=>'DESC' ) ) ); - $cart = EE_Cart::get_cart_from_txn( $transaction, $this->_session ); - - $removals = $cart->delete_items( array( $latest_line_item->code() ) ); - //should remove the ticket line item and its sub-line-item for the price - $this->assertEquals( 2, $removals ); - $this->assertEquals( $ticket_types - 1, $cart->all_ticket_quantity_count() ); - $cart_items = $cart->get_tickets(); - $this->assertArrayDoesNotContain( $latest_line_item, $cart_items ); - } - - public function test_empty_cart(){ - $transaction = $this->new_typical_transaction(); - $cart = EE_Cart::get_cart_from_txn( $transaction, $this->_session ); - $this->assertEEModelObjectsEquals( $transaction->total_line_item(), $cart->get_grand_total() ); - - $cart->empty_cart(); - $this->assertNotEquals( $transaction->total_line_item(), $cart->get_grand_total() ); - } - - public function test_set_grand_total_line_item(){ - $t1 = $this->new_typical_transaction(); - $t1_line_item = $t1->total_line_item(); - $t2 = $this->new_typical_transaction( array( 'ticket_types' => 2) ); - $cart = EE_Cart::get_cart_from_txn( $t2, $this->_session ); - $this->assertNotEquals( $t1_line_item, $cart->get_grand_total() ); - EE_Cart::instance( null, $this->_session )->set_grand_total_line_item( $t1_line_item ); - $this->assertEEModelObjectsEquals( $t1_line_item, $cart->get_grand_total() ); - } - - public function test_save_cart(){ - $t2 = $this->new_typical_transaction( array( 'ticket_types' => 2) ); - $cart = EE_Cart::get_cart_from_txn( $t2, $this->_session ); - $this->_session->reset_data( array( 'cart' ) ); - $this->assertNotEquals( $this->_session->get_session_data( 'cart' ), $cart ); - - $cart->save_cart(); - - $this->assertEquals( $this->_session->get_session_data( 'cart' ), $cart ); - } - - - -} -// End of file EE_Cart_Test.php -// Location: /tests/testcases/core/EE_Cart_Test.php diff --git a/tests/testcases/core/EE_Data_Migration_Manager_Test.php b/tests/testcases/core/EE_Data_Migration_Manager_Test.php deleted file mode 100644 index 0ad74fd707d..00000000000 --- a/tests/testcases/core/EE_Data_Migration_Manager_Test.php +++ /dev/null @@ -1,246 +0,0 @@ -get_all_data_migration_scripts_available(); - $this->assertArrayHasKey('EE_DMS_Core_4_1_0', $dms_classpaths); - $this->assertArrayHasKey('EE_DMS_Core_1_0_0',$dms_classpaths); - $this->assertArrayHasKey('EE_DMS_Core_4_2_0', $dms_classpaths); - $this->assertArrayHasKey('EE_DMS_Core_4_3_0', $dms_classpaths); -} - public function test_ensure_current_database_state_is_set(){ - $this->_pretend_current_code_state_is_at(espresso_version()); - $this->_pretend_current_db_state_is_at(); - $db_state = EE_Data_Migration_Manager::instance()->ensure_current_database_state_is_set(); - $this->assertArrayHasKey('Core',$db_state); - $this->assertEquals(espresso_version(), $db_state['Core']); - } - public function test_check_for_applicable_data_migration_scripts(){ - add_filter('FHEE__EE_Data_Migration_Manager__get_data_migration_script_folders',array($this,'add_mock_dms')); - $this->_pretend_current_db_state_is_at('3.1.37.7'); - $dmss = EE_Data_Migration_Manager::reset()->check_for_applicable_data_migration_scripts(); - //check it contains the DMSs that apply, and that they're ordered correctly - $this->assertInstanceOf( 'EE_DMS_Core_1_0_0', array_shift($dmss)); - $this->assertInstanceOf( 'EE_DMS_Core_4_1_0', array_shift($dmss)); - //pretend we already ran one DMS - $dms_done = EE_Registry::instance()->load_dms( 'Core_4_1_0' ); - $dms_done->set_completed(); - $this->_pretend_ran_dms($dms_done); - $dmss = EE_Data_Migration_Manager::instance()->check_for_applicable_data_migration_scripts(); - $this->assertArrayNotHasKey('EE_DMS_Core_4_1_0',$dmss); - $this->assertArrayHasKey('EE_DMS_Core_1_0_0',$dmss); - - //now pretend we're elsewhere in the migration where 4.2 should be ran - $this->_pretend_current_db_state_is_at('4.1.1'); - $dmss = EE_Data_Migration_Manager::instance()->check_for_applicable_data_migration_scripts(); - $this->assertArrayHasKey('EE_DMS_Core_4_2_0',$dmss); - - } - public function test_parse_dms_classname(){ - $details = EE_Data_Migration_Manager::instance()->parse_dms_classname("EE_DMS_Funky_4_8_12"); - $this->assertEquals("Funky",$details['slug']); - $this->assertEquals(4,$details['major_version']); - $this->assertEquals(8,$details['minor_version']); - $this->assertEquals(12,$details['micro_version']); - } - public function test_get_data_migrations_ran(){ - //make sure all DMSs are autoloaded - EE_Data_Migration_Manager::instance()->get_all_data_migration_scripts_available(); - $dms1 = EE_Registry::instance()->load_dms( 'Core_4_1_0' ); - $dms1->set_completed(); - $this->_pretend_ran_dms($dms1); - $dms_ran = EE_Data_Migration_Manager::instance()->get_data_migrations_ran(); - $this->assertArrayHasKey('Core', $dms_ran); - $this->assertArrayhasKey('4.1.0',$dms_ran['Core']); - } - public function test_get_most_up_to_date_dms(){ - EE_Data_Migration_Manager::reset(); - $dms_classname = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms(); - //yes, this test will need to be updated everytime we add a new core DMS - $this->assertEquals('EE_DMS_Core_4_10_0',$dms_classname); - } - - /** - * @group 7120 - */ - public function test_reattempt(){ - $dms41 = EE_Registry::instance()->load_dms( 'Core_4_1_0' ); - $dms41->set_completed(); - $dms42 = EE_Registry::instance()->load_dms( 'Core_4_2_0' ); - $dms42->set_broken(); - $this->_pretend_ran_dms($dms41); - $this->_pretend_ran_dms($dms42); - $last_ran_script = EE_Data_Migration_Manager::reset()->get_last_ran_script(); - $this->assertEquals($dms42,$last_ran_script); - $this->assertTrue( $last_ran_script->is_broken() ); - EE_Data_Migration_Manager::instance()->reattempt(); - $this->assertFalse( $last_ran_script->is_broken() ); - - - } - - public function test_get_last_ran_script(){ - $dms41 = EE_Registry::instance()->load_dms( 'Core_4_1_0' ); - $dms41->set_completed(); - $dms42 = EE_Registry::instance()->load_dms( 'Core_4_2_0' ); - $this->_pretend_ran_dms($dms41); - $this->_pretend_ran_dms($dms42); - $last_ran_script = EE_Data_Migration_Manager::reset()->get_last_ran_script(); - $this->assertEquals($dms42,$last_ran_script); - - //now if it's borked, we still should have found dms42 - $dms42->set_broken(); - $this->_pretend_ran_dms($dms42); - $last_ran_script = EE_Data_Migration_Manager::reset()->get_last_ran_script(); - $this->assertEquals($dms42,$last_ran_script); - - //all DMSs are complete, so we shouldn't find a current one - $dms42->set_completed(); - $this->_pretend_ran_dms($dms42); - $last_ran_script = EE_Data_Migration_Manager::reset()->get_last_ran_script(); - $this->assertNull($last_ran_script); - - //now what we're ok with finding a complete dms (we're not searching - //for a currently-executing one) - $last_ran_script = EE_Data_Migration_Manager::reset()->get_last_ran_script(TRUE); - $this->assertEquals($dms42,$last_ran_script); - } - - - - private function _pretend_ran_dms(EE_Data_Migration_Script_Base $dms_class){ - $details = EE_Data_Migration_Manager::instance()->parse_dms_classname(get_class($dms_class)); - $plugin_slug_for_use_in_option_name = $details['slug']."."; - $version_string = $details['major_version'].".".$details['minor_version'].".".$details['micro_version']; - update_option(EE_Data_Migration_Manager::data_migration_script_option_prefix.$plugin_slug_for_use_in_option_name.$version_string,$dms_class->properties_as_array()); - } - private function _pretend_current_code_state_is_at($code_version = NULL){ - if($code_version){ - $code_version_array = array($code_version => current_time('timestamp') - 1000); - update_option('espresso_db_update',$code_version_array); - }else{ - delete_option('espresso_db_update'); - } - } - private function _pretend_current_db_state_is_at($core_version = NULL){ - if( $core_version ){ - $current_db_state = array('Core'=>$core_version); - update_option(EE_Data_Migration_Manager::current_database_state,$current_db_state); - }else{ - delete_option(EE_Data_Migration_Manager::current_database_state); - } - } - private function _add_mock_dms(){ - add_filter('FHEE__EE_Data_Migration_Manager__get_data_migration_script_folders',array($this,'add_mock_dms')); - EE_Data_Migration_Manager::reset(); - } - private function _remove_mock_dms(){ - remove_filter('FHEE__EE_Data_Migration_Manager__get_data_migration_script_folders',array($this,'add_mock_dms')); - } - public function add_mock_dms($dms_folders){ - $dms_folders[] = EE_TESTS_DIR . 'mocks/core/data_migration_scripts'; - return $dms_folders; - } - public function test_script_migrates_to_version(){ - $migrates_to = EE_Data_Migration_Manager::instance()->script_migrates_to_version('EE_DMS_Core_6_4_3'); - $this->assertEquals( 'Core', $migrates_to[ 'slug' ] ); - $this->assertEquals( '6.4.3', $migrates_to[ 'version' ] ); - } - - public function test_get_migration_ran(){ - $dms41 = EE_Registry::instance()->load_dms( 'Core_4_1_0' ); - $this->_pretend_ran_dms( $dms41 ); - $dms_found = EE_Data_Migration_Manager::reset()->get_migration_ran( '4.1.0', 'Core' ); - $this->assertEquals( $dms41->migrates_to_version(), $dms_found->migrates_to_version() ); - $dms_not_found = EE_Data_Migration_Manager::instance()->get_migration_ran( '4.2.0', 'Core' ); - $this->assertNull( $dms_not_found ); - } - - public function test_migration_has_run(){ - $dms41 = EE_Registry::instance()->load_dms( 'Core_4_1_0' ); - $this->_pretend_ran_dms( $dms41 ); - $this->assertTrue( EE_Data_Migration_Manager::reset()->migration_has_ran( '4.1.0', 'Core' ) ); - $this->assertFalse( EE_Data_Migration_Manager::instance()->migration_has_ran( '4.2.0', 'Core' ) ); - } - - /** - * @group 6910 - */ - public function test_enqueue_db_initialization_for(){ - EE_Data_Migration_Manager::reset()->enqueue_db_initialization_for( 'Core' ); - EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for( 'Mock' ); - $this->assertEquals( array( 'Core', 'Mock' ), EE_Data_Migration_Manager::instance()->get_db_initialization_queue() ); - } - - /** - * @group 6910 - */ - public function test_get_db_initialization_queue(){ - update_option( EE_Data_Migration_Manager::db_init_queue_option_name, array( 'MockA', 'MockB' ) ); - $this->assertEquals( array( 'MockA', 'MockB' ), EE_Data_Migration_Manager::instance()->get_db_initialization_queue() ); - } - - /** - * @group 8328 - */ - public function test_database_needs_updating_to__exact_matches(){ - EE_Data_Migration_Manager::instance()->update_current_database_state_to( array( 'slug' => 'Core', 'version' => '4.9.0' ) ); - $this->assertFalse( EE_Data_Migration_Manager::instance()->database_needs_updating_to( array( 'slug' => 'Core', 'version' => '4.9.0' ) ) ); - } - - /** - * @group 8328 - */ - public function test_database_needs_updating_to__first_3_version_parts_matches(){ - EE_Data_Migration_Manager::instance()->update_current_database_state_to( array( 'slug' => 'Core', 'version' => '4.9.0.dev.123' ) ); - $this->assertFalse( EE_Data_Migration_Manager::instance()->database_needs_updating_to( array( 'slug' => 'Core', 'version' => '4.9.0.beta.432' ) ) ); - } - /** - * @group 8328 - */ - public function test_database_needs_updating_to__current_version_is_greater(){ - EE_Data_Migration_Manager::instance()->update_current_database_state_to( array( 'slug' => 'Core', 'version' => '4.9.0.dev.123' ) ); - $this->assertTrue( EE_Data_Migration_Manager::instance()->database_needs_updating_to( array( 'slug' => 'Core', 'version' => '4.9.3.dev.123' ) ) ); - } - - /** - * @group 8328 - */ - public function test_database_needs_updating_to__current_version_is_lower(){ - EE_Data_Migration_Manager::instance()->update_current_database_state_to( array( 'slug' => 'Core', 'version' => '4.9.0' ) ); - $this->assertFalse( EE_Data_Migration_Manager::instance()->database_needs_updating_to( array( 'slug' => 'Core', 'version' => '4.4.0.p' ) ) ); - } -} - -// End of file EE_Data_Migration_Manager_Test.php diff --git a/tests/testcases/core/EE_Data_Migration_Script_Base_Test.php b/tests/testcases/core/EE_Data_Migration_Script_Base_Test.php deleted file mode 100644 index 8adb09b100a..00000000000 --- a/tests/testcases/core/EE_Data_Migration_Script_Base_Test.php +++ /dev/null @@ -1,53 +0,0 @@ -load_dms( 'EE_DMS_Core_4_1_0' ); - for( $i = 0; $i < 60; $i++ ){ - $dms->add_error( 'error ' . $i ); - } - //count should be 51 because once we get to 50, it should stop adding them - $this->assertEquals( 51, count( $dms->get_errors() ) ); - $dms->add_error( 'force', TRUE ); - //count should be (50 / 2) + 2 (because we should have wiped the first half, then added two - $this->assertEquals( 27, count( $dms->get_errors() ) ); - //and check that the first one should be... error 25 because - $errors = $dms->get_errors(); - $first_error = array_shift( $errors ); - $this->assertEquals( 'error 25', $first_error ); - } -} - -// End of file EE_Data_Migration_Script_Base.php diff --git a/tests/testcases/core/EE_Dependency_Map_Test.php b/tests/testcases/core/EE_Dependency_Map_Test.php deleted file mode 100644 index 68c1d9b9f83..00000000000 --- a/tests/testcases/core/EE_Dependency_Map_Test.php +++ /dev/null @@ -1,222 +0,0 @@ -_dependency_map = EE_Dependency_Map::instance(); - } - - - public function tearDown() { - $this->_dependency_map->reset(); - parent::tearDown(); - } - - - /** - * @since 4.9.62.p - * @throws PHPUnit_Framework_AssertionFailedError - */ - public function test_core_dependencies() { - $this->validate_core_dependency_map( $this->_dependency_map->dependency_map() ); - } - - - - /** - * @param $dependencies_or_load - * @param string $classname - * @throws PHPUnit_Framework_AssertionFailedError - */ - public function validate_core_dependency_map( $dependencies_or_load, $classname = '' ) { - if ( is_array( $dependencies_or_load ) ) { - foreach ( $dependencies_or_load as $class_name => $dependency ) { - if ( $dependency !== null ) { - $this->validate_core_dependency_map( $dependency, $class_name ); - } - } - } else { - $classname = $this->_dependency_map->getFqnForAlias($classname); - // verify that a valid class constant has been set for the value - $this->assertEquals( - EE_Dependency_Map::load_new_object || EE_Dependency_Map::load_from_cache, - $dependencies_or_load, - sprintf( 'The %s class has an invalid value in the EE_Dependency_Map.', $classname ) - ); - // if class is not using PSR-4 compatible namespacing - if (strpos($classname,'\\') === false) { - // verify that a loader exists for the class - $loader = $this->_dependency_map->class_loader($classname); - $this->assertNotEmpty( - $loader, - sprintf('A class loader should be set for "%s" but appears to be missing.', $classname) - ); - } - } - } - - - /** - * @since 4.9.62.p - * @throws \PHPUnit\Framework\AssertionFailedError - * @throws \PHPUnit\Framework\Exception - */ - public function test_core_class_loaders() { - $skip = array( - 'EE_Admin' => 'messes with other unit tests', - 'EE_Session' => 'session doesn\'t load during unit tests', - 'EE_Messages_Template_Defaults' => 'Closure has required arguments', - 'EE_CPT_Default_Strategy' => 'has required arguments', - 'EE_CPT_Attendee_Strategy' => 'has required arguments', - 'EE_CPT_Event_Strategy' => 'has required arguments', - 'EE_CPT_Venue_Strategy' => 'has required arguments', - ); - //loop through and verify the class loader can successfully load the class it is set for - foreach ( $this->_dependency_map->class_loaders() as $class => $loader ) { - if ( isset( $skip[ $class ] ) || strpos( $class, 'Command' ) !== false ) { - continue; - } - $dependency = $loader instanceof Closure ? $loader() : EE_Registry::instance()->$loader( $class ); - // helpers are simply loaded and do not return an instance - if ( $loader === 'load_helper' ) { - $this->assertTrue( $dependency ); - } else { - $this->assertInstanceOf( - $class, - $dependency, - sprintf( - 'The "%1$s" class has "%2$s" set as its loader, but instead of an object, we received "%3$s"', - $class, - $loader instanceof Closure ? print_r( $loader, true ) : $loader, - print_r( $dependency, true ) - ) - ); - } - } - } - - - /** - * @since 4.9.62.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @throws \EventEspresso\core\exceptions\InvalidDataTypeException - * @throws \EventEspresso\core\exceptions\InvalidInterfaceException - * @throws \PHPUnit\Framework\Exception - */ - public function test_core_class_loader_for_EE_Messages_Template_Defaults() { - /** @type EE_Message_Resource_Manager $Message_Resource_Manager */ - $Message_Resource_Manager = EE_Registry::instance()->load_lib( 'Message_Resource_Manager' ); - $loader = $this->_dependency_map->class_loader('EE_Messages_Template_Defaults'); - $this->assertInstanceOf( 'Closure', $loader ); - $Messages_Template_Defaults = $loader( - array( - $Message_Resource_Manager->valid_messenger( 'html' ), - $Message_Resource_Manager->valid_message_type( 'invoice' ) - ) - ); - $this->assertInstanceOf( 'EE_Messages_Template_Defaults', $Messages_Template_Defaults ); - } - - - /** - * @since 4.9.62.p - * @throws DomainException - * @throws \PHPUnit\Framework\AssertionFailedError - */ - public function test_register_class_loader() { - EE_Dependency_Map::register_class_loader( 'Dummy_Class', 'load_lib' ); - $actual_class_loader = $this->_dependency_map->class_loader( 'Dummy_Class' ); - $this->assertNotEmpty( $actual_class_loader ); - $this->assertEquals( 'load_lib', $actual_class_loader ); - - $this->setExpectedException( - 'DomainException', - esc_html__('"dummy_loader" is not a valid loader method on EE_Registry.', 'event_espresso') - ); - EE_Dependency_Map::register_class_loader( 'Dummy_Class', 'dummy_loader' ); - } - - - /** - * @since 4.9.62.p - * @throws \PHPUnit\Framework\AssertionFailedError - */ - public function test_register_dependency() { - //test a successful registration. - $registered = EE_Dependency_Map::register_dependencies( 'Dummy_Class', array( 'EE_Something', 'EE_Something_Else' ) ); - $this->assertTrue( $registered ); - $actual_dependency_map = $this->_dependency_map->dependency_map(); - $this->assertTrue( isset( $actual_dependency_map['Dummy_Class'] ) ); - $this->assertEquals( array( 'EE_Something', 'EE_Something_Else' ), $actual_dependency_map['Dummy_Class'] ); - - //test a unsuccessful registration (cannot override an existing dependency. - $registered = EE_Dependency_Map::register_dependencies( 'Dummy_Class', array() ); - $this->assertFalse( $registered ); - } - - - /** - * can't easily extend EE_Dep_Map so - * just going to test all three methods together - * - * @throws \PHPUnit\Framework\AssertionFailedError - * @throws \PHPUnit\Framework\AssertionFailedError - */ - public function test_add_has_get_alias() - { - $interface = 'Dummy_Interface'; - $class_name = 'Dummy_Class'; - $this->assertFalse($this->_dependency_map->isAlias($interface)); - $this->_dependency_map->add_alias($class_name, $interface); - $this->assertTrue($this->_dependency_map->isAlias($interface)); - $this->assertEquals( - $class_name, - $this->_dependency_map->getFqnForAlias($interface) - ); - } - - - /** - * can't easily extend EE_Dep_Map so - * just going to test all three methods together - * - * @throws \PHPUnit\Framework\AssertionFailedError - * @throws \PHPUnit\Framework\AssertionFailedError - */ - public function test_add_has_get_alias_for_class() - { - $interface = 'Dummy_Interface_2'; - $class_name = 'Dummy_Class_2'; - $for_class = 'Other_Class'; - $this->assertFalse($this->_dependency_map->isAlias($interface, $for_class)); - $this->_dependency_map->add_alias($class_name, $interface, $for_class); - $this->assertTrue($this->_dependency_map->isAlias($interface, $for_class)); - $this->assertEquals( - $class_name, - $this->_dependency_map->getFqnForAlias($interface, $for_class) - ); - } - - - -} -// Location: tests/testcases/core/EE_Dependency_Map_Test.php diff --git a/tests/testcases/core/EE_Encryption_Test.php b/tests/testcases/core/EE_Encryption_Test.php deleted file mode 100644 index 19b71bfefa4..00000000000 --- a/tests/testcases/core/EE_Encryption_Test.php +++ /dev/null @@ -1,350 +0,0 @@ -encryption = EE_Encryption_Mock::instance(); - } - - - - /** - * @param int $length - * @return string - */ - private function generateRandomString($length = 10) - { - $characters = '0123456789 abcd efg hijk lmnop qrs tuv wxyz ABCD EFG HIJK LMNOP QRS TUV WXYZ'; - $charactersLength = strlen($characters); - $randomString = ''; - for ($i = 0; $i < $length; $i++) { - $randomString .= $characters[mt_rand(0, $charactersLength - 1)]; - } - return $randomString; - } - - - - /** - * @return string - */ - private function generatePropertyOrKeyName() - { - $property = str_replace(' ', '', $this->generateRandomString(mt_rand(5, 10))); - if(empty($property)) { - return $this->generatePropertyOrKeyName(); - } - return $property; - } - - - - /** - * @return string - */ - private function getString() - { - return 'LPT: Change all of your passwords to "incorrect" so that your computer just tells you when you forget!'; - } - - - - /** - * @return array - */ - private function getArrayData() - { - $array = array(); - $array_size = mt_rand(5, 10); - for ($x = 0; $x <= $array_size; $x++) { - $key = mt_rand(0, 1) - ? $this->generatePropertyOrKeyName() - : count($array); - $array[$key] = $this->generateRandomString(mt_rand(10, 50)); - } - return $array; - } - - - - /** - * @return stdClass - */ - private function getObjectData() - { - $object = new stdClass(); - $array_size = mt_rand(5, 10); - for ($x = 0; $x <= $array_size; $x++) { - $property = $this->generatePropertyOrKeyName(); - $object->{$property} = $this->generateRandomString(mt_rand(10, 50)); - } - return $object; - } - - - /** - * @param string $encrypt - * @param string $decrypt - * @param $data - * @param string $cipher_method - */ - private function runEncryptionTest($encrypt, $decrypt, $data, $cipher_method = '') - { - if($cipher_method !== '') { - $this->assertEquals( - $data, - unserialize( - $this->encryption->{$decrypt}( - $this->encryption->{$encrypt}( - serialize($data), - $cipher_method - ), - $cipher_method - ) - ) - ); - } else { - $this->assertEquals( - $data, - unserialize( - $this->encryption->{$decrypt}( - $this->encryption->{$encrypt}( - serialize($data) - ) - ) - ) - ); - } - } - - - - /** - * @return void - */ - public function testGetEncryptionKey() - { - $key = $this->encryption->get_encryption_key(); - $this->assertEquals( - get_option(EE_Encryption::ENCRYPTION_OPTION_KEY, ''), - $key - ); - } - - - /** - * @requires function openssl_encrypt - * @return void - * @throws RuntimeException - */ - public function testOpensslEncryption() - { - // with strings - $this->assertEquals( - $this->getString(), - $this->encryption->openssl_decrypt( - $this->encryption->openssl_encrypt( - $this->getString() - ) - ) - ); - // with arrays - $this->runEncryptionTest( - 'openssl_encrypt', - 'openssl_decrypt', - $this->getArrayData() - ); - // with objects - $this->runEncryptionTest( - 'openssl_encrypt', - 'openssl_decrypt', - $this->getObjectData() - ); - } - - - /** - * @requires function openssl_encrypt - * @return void - * @throws RuntimeException - */ - public function testOpensslEncryptionWithCipherMethods() - { - $cipher_methods = openssl_get_cipher_methods(); - foreach ($cipher_methods as $cipher_method) { - // only use ciphers that produce a vector - if(openssl_cipher_iv_length($cipher_method) !== false){ - // with strings - $this->assertEquals( - $this->getString(), - $this->encryption->openssl_decrypt( - $this->encryption->openssl_encrypt( - $this->getString(), - $cipher_method - ), - $cipher_method - ) - ); - // with arrays - $this->runEncryptionTest( - 'openssl_encrypt', - 'openssl_decrypt', - $this->getArrayData(), - $cipher_method - ); - // with objects - $this->runEncryptionTest( - 'openssl_encrypt', - 'openssl_decrypt', - $this->getObjectData(), - $cipher_method - ); - } - } - } - - - - /** - * @requires function mcrypt_encrypt - * @return void - * @throws RuntimeException - */ - public function testMcryptEncryption() - { - if (PHP_VERSION_ID >= 70100) { - $this->markTestSkipped( - 'The mcrypt extension is deprecated in PHP version 7.1 and therefore can not be tested.' - ); - } - $this->assertEquals( - $this->getString(), - $this->encryption->m_decrypt( - $this->encryption->m_encrypt( - $this->getString() - ) - ) - ); - $this->runEncryptionTest( - 'm_encrypt', - 'm_decrypt', - $this->getArrayData() - ); - $this->runEncryptionTest( - 'm_encrypt', - 'm_decrypt', - $this->getObjectData() - ); - } - - - - /** - * @return void - * @throws RuntimeException - */ - public function testAcmeEncryption() - { - $this->assertEquals( - $this->getString(), - $this->encryption->acme_decrypt( - $this->encryption->acme_encrypt( - $this->getString() - ) - ) - ); - $this->runEncryptionTest( - 'acme_encrypt', - 'acme_decrypt', - $this->getArrayData() - ); - $this->runEncryptionTest( - 'acme_encrypt', - 'acme_decrypt', - $this->getObjectData() - ); - } - - - /** - * @return void - * @throws RuntimeException - */ - public function testBase64StringEncoding() - { - $this->assertEquals( - $this->getString(), - $this->encryption->base64_string_decode( - $this->encryption->base64_string_encode( - $this->getString() - ) - ) - ); - } - - - /** - * @return void - * @throws RuntimeException - */ - public function testBase64UrlEncoding() - { - $url = 'http://eventespresso.com'; - $this->assertEquals( - $url, - $this->encryption->base64_url_decode( - $this->encryption->base64_url_encode($url) - ) - ); - } - - - /** - * @throws PHPUnit_Framework_AssertionFailedError - * @throws \PHPUnit\Framework\AssertionFailedError - * @throws \PHPUnit\Framework\AssertionFailedError - */ - public function testValidBase64() - { - $this->assertTrue( - $this->encryption->valid_base_64( - $this->encryption->base64_string_encode( - $this->getString() - ) - ) - ); - $this->assertFalse( - $this->encryption->valid_base_64( - $this->getString() - ) - ); - } - - -} -// testcases/core/EE_Encryption_Test.php diff --git a/tests/testcases/core/EE_Maintenance_Mode_Test.php b/tests/testcases/core/EE_Maintenance_Mode_Test.php deleted file mode 100644 index 940e36d0318..00000000000 --- a/tests/testcases/core/EE_Maintenance_Mode_Test.php +++ /dev/null @@ -1,100 +0,0 @@ -assertEquals( EE_Maintenance_Mode::level_0_not_in_maintenance, EE_Maintenance_Mode::instance()->level() ); - - //the DB is up-to-date, so we shouldn't be put into mm - EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old(); - $this->assertEquals( EE_Maintenance_Mode::level_0_not_in_maintenance, EE_Maintenance_Mode::instance()->level() ); - } - - public function test_set_mm_if_bd_old__remove_mm(){ - //now pretend the DB got borked somehow and we're in mm2 when we shouldn't be. this should fix it - EE_Maintenance_Mode::instance()->set_maintenance_level( EE_Maintenance_Mode::level_2_complete_maintenance ); - $this->assertEquals( EE_Maintenance_Mode::level_2_complete_maintenance, EE_Maintenance_Mode::instance()->level() ); - EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old(); - $this->assertEquals( EE_Maintenance_Mode::level_0_not_in_maintenance, EE_Maintenance_Mode::instance()->level() ); - } - public function test_set_mm_if_db_old__success(){ - $this->assertEquals( EE_Maintenance_Mode::level_0_not_in_maintenance, EE_Maintenance_Mode::instance()->level() ); - //we pretend teh DB state is out-of-date, so we should be put into mm - $this->_pretend_current_db_state_is_at('3.1.37.7'); - EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old(); - $this->assertEquals( EE_Maintenance_Mode::level_2_complete_maintenance, EE_Maintenance_Mode::instance()->level() ); - } - public function test_set_mm_if_db_old__in_mm1(){ - //put the site into mm1 and verify it doesn't get swapped to mm0 when we call set_mm_if_db_old - $this->assertEquals( EE_Maintenance_Mode::level_0_not_in_maintenance, EE_Maintenance_Mode::instance()->real_level() ); - EE_Maintenance_Mode::instance()->set_maintenance_level( EE_Maintenance_Mode::level_1_frontend_only_maintenance ); - $this->assertEquals( EE_Maintenance_Mode::level_1_frontend_only_maintenance, EE_Maintenance_Mode::instance()->real_level() ); - EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old(); - $this->assertEquals( EE_Maintenance_Mode::level_1_frontend_only_maintenance, EE_Maintenance_Mode::instance()->real_level() ); - } - - public function test_set_maintenance_level(){ - $this->assertEquals( EE_Maintenance_Mode::level_0_not_in_maintenance, EE_Maintenance_Mode::instance()->real_level() ); - EE_Maintenance_Mode::instance()->set_maintenance_level( EE_Maintenance_Mode::level_1_frontend_only_maintenance ); - $this->assertEquals( EE_Maintenance_Mode::level_1_frontend_only_maintenance, EE_Maintenance_Mode::instance()->real_level() ); - EE_Maintenance_Mode::instance()->set_maintenance_level( EE_Maintenance_Mode::level_2_complete_maintenance ); - $this->assertEquals( EE_Maintenance_Mode::level_2_complete_maintenance, EE_Maintenance_Mode::instance()->real_level() ); - } - /** - * tests that EE_Maintenance_Mode::level() correctly pretend a site is - * NOT in maintenance mode for admin users only on frontend and ajax requests - * @global type $current_user - */ - public function test_maintenance_level(){ - global $current_user; - $this->assertFalse( is_admin() ); - $this->assertFalse( current_user_can( 'administrator' ) ); - EE_Maintenance_Mode::instance()->set_maintenance_level( EE_Maintenance_Mode::level_1_frontend_only_maintenance ); - $this->assertEquals( EE_Maintenance_Mode::level_1_frontend_only_maintenance, EE_Maintenance_Mode::instance()->level() ); - //now make the current user an admin, and maintenance mode shoudl be detected as 0 - - $current_user = $this->factory->user->create_and_get( array( 'role' => 'administrator' ) ); - $this->assertEquals( EE_Maintenance_Mode::level_0_not_in_maintenance, EE_Maintenance_Mode::instance()->level() ); - - } - public function test_zz(){ - $this->assertFalse( current_user_can( 'administrator' ) ); - } - /** - * @see EE_Migration_Manager_Test::_pretend_current_db_state_is_at which this was - * copied from. If it's used again, we should put this function into EE_UnitTestCase - * @param type $core_version - */ - private function _pretend_current_db_state_is_at($core_version = NULL){ - if( $core_version ){ - $current_db_state = array('Core'=>$core_version); - update_option(EE_Data_Migration_Manager::current_database_state,$current_db_state); - }else{ - delete_option(EE_Data_Migration_Manager::current_database_state); - } - } - - /** - * the DMS manager maintains a bit of state in order to be more efficient, which we want to lose between tests - */ - public function setUp(){ - parent::setUp(); - EE_Data_Migration_Manager::reset(); - } -} - -// End of file EE_Maintenance_Mode_Test.php \ No newline at end of file diff --git a/tests/testcases/core/EE_Object_Collection_Test.php b/tests/testcases/core/EE_Object_Collection_Test.php deleted file mode 100644 index 89b2b847575..00000000000 --- a/tests/testcases/core/EE_Object_Collection_Test.php +++ /dev/null @@ -1,107 +0,0 @@ -collection = new EE_Object_Collection_Mock(); - } - - public function test_add() { - // add ticket 1 - $ticket_1 = $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_price' => '5' ) ); - $this->assertCount( 0, $this->collection ); - $this->collection->add( $ticket_1 ); - $this->assertCount( 1, $this->collection ); - $this->assertContains( $ticket_1, $this->collection ); - // add ticket 2 - $ticket_2 = $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_price' => '6' ) ); - $this->collection->add( $ticket_2 ); - $this->assertCount( 2, $this->collection ); - $this->assertContains( $ticket_2, $this->collection ); - } - - public function test_set_info() { - // add ticket 1 - $ticket_1 = $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_price' => '5' ) ); - $this->collection->add( $ticket_1 ); - $this->collection->set_info( $ticket_1, 'ticket_1' ); - $this->assertEquals( $this->collection[ $ticket_1 ], 'ticket_1' ); - } - - public function test_get_by_info() { - $ticket_1 = $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_price' => '5' ) ); - $this->collection->add( $ticket_1, 'ticket_1' ); - $T1 = $this->collection->get_by_info( 'ticket_1' ); - $this->assertEquals( $ticket_1, $T1 ); - } - - public function test_has() { - $ticket_1 = $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_price' => '5' ) ); - $this->collection->add( $ticket_1 ); - $exists = $this->collection->has( $ticket_1 ); - $this->assertEquals( $exists, true ); - } - - public function test_remove() { - // add ticket 1 - $ticket_1 = $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_price' => '5' ) ); - $this->collection->add( $ticket_1 ); - // add ticket 2 - $ticket_2 = $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_price' => '6' ) ); - $this->collection->add( $ticket_2 ); - $this->assertCount( 2, $this->collection ); - // remove ticket 1 - $this->collection->remove( $ticket_1 ); - $this->assertNotContains( $ticket_1, $this->collection ); - $this->assertCount( 1, $this->collection ); - // remove ticket 2 - $this->collection->remove( $ticket_2 ); - $this->assertNotContains( $ticket_2, $this->collection ); - $this->assertCount( 0, $this->collection ); - } - - public function test_set_current() { - $ticket_1 = $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_name' => 'ticket-1', 'TKT_price' => '5' ) ); - $ticket_2 = $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_name' => 'ticket-2', 'TKT_price' => '6' ) ); - $ticket_3 = $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_name' => 'ticket-3', 'TKT_price' => '7' ) ); - $this->collection->add( $ticket_1 ); - $this->collection->add( $ticket_2 ); - $this->collection->add( $ticket_3 ); - $this->collection->rewind(); - $this->collection->set_current( $ticket_3 ); - $this->assertEquals( $this->collection->current()->name(), 'ticket-3' ); - } - - public function test_set_current_by_info() { - $ticket_1 = $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_name' => 'ticket-1', 'TKT_price' => '5' ) ); - $ticket_2 = $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_name' => 'ticket-2', 'TKT_price' => '6' ) ); - $ticket_3 = $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_name' => 'ticket-3', 'TKT_price' => '7' ) ); - $this->collection->add( $ticket_1 ); - $this->collection->add( $ticket_2 ); - $this->collection->add( $ticket_3 ); - $this->collection->set_info( $ticket_3, '7-dollar-ticket' ); - $this->collection->rewind(); - $this->collection->set_current_by_info( '7-dollar-ticket' ); - $this->assertEquals( $this->collection->current()->name(), 'ticket-3' ); - } - -} -// End of file EE_Object_Collection_Test.php -// Location: /tests/testcases/core/EE_Object_Collection_Test.php \ No newline at end of file diff --git a/tests/testcases/core/EE_Object_Repository_Test.php b/tests/testcases/core/EE_Object_Repository_Test.php deleted file mode 100644 index f36c9576879..00000000000 --- a/tests/testcases/core/EE_Object_Repository_Test.php +++ /dev/null @@ -1,69 +0,0 @@ -repository = new EE_Object_Repository_Mock(); - } - - public function test_persist() { - $ticket_1 = $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_price' => '5' ), false ); - $this->repository->add( $ticket_1 ); - $this->assertTrue( $this->repository->has( $ticket_1 ) ); - $this->assertEquals( $ticket_1->ID(), 0 ); - $this->assertEquals( count( $this->repository ), 1 ); - $saved = false; - $this->repository->rewind(); - while ( $this->repository->valid() ) { - if ( $this->repository->current() === $ticket_1 ) { - $saved = $this->repository->persist(); - $this->assertNotEquals( $this->repository->current()->ID(), 0 ); - $this->assertEquals( $this->repository->current()->ID(), $ticket_1->ID() ); - break; - } - $this->repository->next(); - } - $this->assertNotEquals( $saved, false ); - } - - - - - public function test_persist_all() { - $ticket_1 = $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_price' => '5' ), false ); - $ticket_2 = $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_price' => '6' ), false ); - $this->repository->add( $ticket_1 ); - $this->repository->add( $ticket_2 ); - $this->assertTrue( $this->repository->has( $ticket_1 ) ); - $this->assertTrue( $this->repository->has( $ticket_2 ) ); - $this->assertEquals( count( $this->repository ), 2 ); - $this->assertEquals( $ticket_1->ID(), 0 ); - $this->assertEquals( $ticket_2->ID(), 0 ); - $saved = $this->repository->persist_all(); - $this->assertEquals( $saved, true ); - $this->assertNotEquals( $ticket_1->ID(), 0 ); - $this->assertNotEquals( $ticket_2->ID(), 0 ); - } - - - -} -// End of file EE_Object_Repository_Test.php -// Location: /tests/testcases/core/EE_Object_Repository_Test.php \ No newline at end of file diff --git a/tests/testcases/core/EE_Payment_Processor_Test.php b/tests/testcases/core/EE_Payment_Processor_Test.php deleted file mode 100644 index d94bde5feac..00000000000 --- a/tests/testcases/core/EE_Payment_Processor_Test.php +++ /dev/null @@ -1,548 +0,0 @@ -_pretend_addon_hook_time(); - EE_Register_Payment_Method::register( - 'onsite', - array( - 'payment_method_paths' => array( - EE_TESTS_DIR . 'mocks/payment_methods/Mock_Onsite', - ), - ) - ); - EE_Register_Payment_Method::register( - 'offsite', - array( - 'payment_method_paths' => array( - EE_TESTS_DIR . 'mocks/payment_methods/Mock_Offsite', - ), - ) - ); - EE_Payment_Method_Manager::instance()->reset(); - //remove all actions that have been added by messages because we aren't testing them here. - remove_all_actions( 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful' ); - remove_all_actions( 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__no_payment_made' ); - remove_all_actions( 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__not_successful' ); - remove_all_actions( 'AHEE__EE_Payment_Processor__update_txn_based_on_payment' ); - } - - - - public function tearDown() { - EE_Register_Payment_Method::deregister( 'onsite' ); - EE_Register_Payment_Method::deregister( 'offsite' ); - parent::tearDown(); - } - - - - /** - * Creates a transaction with all valid data (ie, it's for an event that has - * datetimes and tickets etc) - * - * @return EE_Transaction - * @throws \EE_Error - */ - protected function _new_typical_transaction() { - /** @type EE_Transaction $transaction */ - $transaction = $this->new_model_obj_with_dependencies( 'Transaction', array( 'TXN_total' => 10.00 ) ); - $ticket = $this->get_ticket_mock(); - $user = $this->get_wp_user_mock( 'administrator' ); - $event = $this->get_event_mock( $user ); - $registration = $this->get_registration_mock( $transaction, $ticket, $event, 10.00 ); - $transaction->_add_relation_to( $registration, 'Registration' ); - /** @type EE_Datetime $dtt */ - $dtt = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $event->ID(), - 'DTT_EVT_start' => current_time( 'timestamp' ) + 60 * 60, - 'DTT_EVT_end' => current_time( 'timestamp' ) + 5 * 60 * 60, - ) - ); - $dtt->_add_relation_to( $ticket, 'Ticket' ); - $transaction->set_reg_steps( - array( - 'attendee_information' => true, - 'payment_options' => true, - 'finalize_registration' => current_time( 'timestamp' ), - ) - ); - return $transaction; - } - - - - /** - * @param string $role - * @return \WP_User - */ - public function get_wp_user_mock( $role = 'administrator' ) { - /** @type WP_User $user */ - $user = $this->factory->user->create_and_get(); - $user->add_role( $role ); - return $user; - } - - - - /** - * @param float $TKT_price - * @return \EE_Ticket - * @throws \EE_Error - */ - public function get_ticket_mock( $TKT_price = 10.00 ) { - return $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_price' => $TKT_price ) ); - } - - - - /** - * @param \WP_User $EVT_wp_user - * @return \EE_Event - * @throws \EE_Error - */ - public function get_event_mock( WP_User $EVT_wp_user = null ) { - return $this->new_model_obj_with_dependencies( 'Event', array( 'EVT_wp_user' => $EVT_wp_user->ID ) ); - } - - - - /** - * @param \EE_Transaction $transaction - * @param \EE_Ticket $ticket - * @param \EE_Event $event - * @param float $REG_final_price - * @return \EE_Registration - * @throws \EE_Error - */ - public function get_registration_mock( - EE_Transaction $transaction, - EE_Ticket $ticket, - EE_Event $event, - $REG_final_price = 10.00 - ) { - return $this->new_model_obj_with_dependencies( - 'Registration', - array( - 'TXN_ID' => $transaction->ID(), - 'TKT_ID' => $ticket->ID(), - 'EVT_ID' => $event->ID(), - 'REG_final_price' => $REG_final_price, - 'REG_count' => EEM_Registration::PRIMARY_REGISTRANT_COUNT, - ) - ); - } - - - - /** - * Gets the actual payment status in the database (useful for verifying a payment has actually been updated) - * - * @global WPDB $wpdb - * @param EE_Payment $payment - * @return string - * @throws \EE_Error - */ - protected function _get_payment_status_in_db( EE_Payment $payment ) { - global $wpdb; - $esp_payment = $payment->get_model()->table(); - return $wpdb->get_var( $wpdb->prepare( "SELECT STS_ID FROM $esp_payment WHERE PAY_ID = %d", $payment->ID() ) ); - } - - - - /** - * @group 7753 - * @throws \EE_Error - */ - public function test_process_payment__onsite__success() { - //setup all the $_REQUEST globals etc because messages require them - $this->go_to( 'http://localhost/' ); - /** @type EE_Payment_Method $pm */ - $pm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Mock_Onsite' ) ); - $transaction = $this->_new_typical_transaction(); - $billing_form = $pm->type_obj()->billing_form( $transaction ); - $billing_form->receive_form_submission( - array( - 'status' => EEM_Payment::status_id_approved, - 'credit_card' => '4111 1111 1111 1111', - 'exp_month' => '12', - 'exp_year' => '2032', - 'cvv' => '123', - ) - ); - global $wp_actions; - $successful_payment_actions = EEH_Array::is_set( - $wp_actions, - 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful', - 0 - ); - $payment_actions = EEH_Array::is_set( - $wp_actions, - 'AHEE__EE_Payment_Processor__update_txn_based_on_payment', - 0 - ); - add_action( - 'AHEE__EE_Payment_Processor__update_txn_based_on_payment', - array( $this, 'assert_payment_message_trigger_for_success' ), - 10, - 2 - ); - /** @type EE_Payment_Processor $payment_processor */ - $payment_processor = EE_Registry::instance()->load_core( 'Payment_Processor' ); - $payment = $payment_processor->process_payment( - $pm, - $transaction, - null, - $billing_form, - 'success', - 'CART', - true, - true - ); - $this->assertInstanceOf( 'EE_Payment', $payment ); - //verify it's already been saved - $this->assertNotEquals( 0, $payment->ID() ); - $this->assertEquals( EEM_Payment::status_id_approved, $payment->status() ); - $this->assertEquals( EEM_Payment::status_id_approved, $this->_get_payment_status_in_db( $payment ) ); - $this->assertEquals( - $successful_payment_actions + 1, - $wp_actions['AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful'] - ); - $this->assertEquals( - $payment_actions + 1, - $wp_actions['AHEE__EE_Payment_Processor__update_txn_based_on_payment'] - ); - } - - - - /** - * Asserts that the payment's status is approved when the hook is called - * - * @param EE_Payment $transaction - * @param EE_Payment $payment - */ - public function assert_payment_message_trigger_for_success( $transaction, $payment ) { - $this->assertEquals( EEM_Payment::status_id_approved, $payment->get( 'STS_ID' ) ); - } - - - - public function test_update_txn_based_on_payment() { - //create a txn, and an UNSAVED payment. then call this. - /** @type EE_Transaction $txn */ - $txn = $this->new_model_obj_with_dependencies( - 'Transaction', - array( - 'STS_ID' => EEM_Transaction::incomplete_status_code, - 'TXN_total' => 10.00, - ) - ); - $ticket = $this->get_ticket_mock(); - $user = $this->get_wp_user_mock( 'administrator' ); - $event = $this->get_event_mock( $user ); - $registration = $this->get_registration_mock( $txn, $ticket, $event, 10.00 ); - $txn->_add_relation_to( $registration, 'Registration' ); - /** @type EE_Payment $payment */ - $payment = $this->new_model_obj_with_dependencies( - 'Payment', - array( - 'TXN_ID' => $txn->ID(), - 'STS_ID' => EEM_Payment::status_id_approved, - 'PAY_amount' => 10.00, - ), - false - ); - // simulate payment save performed in EE_PMT_Base::process_payment() - $payment->save(); - //$this->new_model_obj_with_dependencies( 'Registration', array( 'TXN_ID' => $txn->ID(), 'REG_count' => 1 ) ); - $this->assertEquals( EEM_Payment::status_id_approved, $payment->status() ); - /** @type EE_Payment_Processor $payment_processor */ - $payment_processor = EE_Registry::instance()->load_core( 'Payment_Processor' ); - $payment_processor->update_txn_based_on_payment( $txn, $payment ); - //the payment should have been saved, and the txn appropriately updated - $this->assertEquals( EEM_Payment::status_id_approved, $payment->status() ); - $this->assertEquals( $payment, $txn->last_payment() ); - $this->assertEquals( 10.00, $payment->amount() ); - $this->assertEquals( $txn->ID(), $payment->get( 'TXN_ID' ) ); - /** @type EE_Transaction_Payments $transaction_payments */ - $transaction_payments = EE_Registry::instance()->load_class( 'Transaction_Payments' ); - $this->assertEquals( - 10.00, - $transaction_payments->recalculate_total_payments_for_transaction( - $txn, - EEM_Payment::status_id_approved - ) - ); - $this->assertEquals( 10.00, $txn->paid() ); - $this->assertEquals( EEM_Transaction::complete_status_code, $txn->status_ID() ); - } - - - - public function test_update_txn_based_on_payment__offline() { - //create a txn, and an UNSAVED payment. then call this. - /** @type EE_Transaction $txn */ - $txn = $this->new_model_obj_with_dependencies( - 'Transaction', - array( - 'STS_ID' => EEM_Transaction::incomplete_status_code, - 'TXN_total' => 10, - ) - ); - /** @type EE_Payment $payment */ - $payment = $this->new_model_obj_with_dependencies( - 'Payment', - array( - 'TXN_ID' => $txn->ID(), - 'STS_ID' => EEM_Payment::status_id_pending, - 'PAY_amount' => 0, - ), - false - ); - //because this is from an OFFLINE gateway, the payment shouldn't be saved - $this->assertEquals( EEM_Payment::status_id_pending, $payment->status() ); - /** @type EE_Payment_Processor $payment_processor */ - $payment_processor = EE_Registry::instance()->load_core( 'Payment_Processor' ); - $payment_processor->update_txn_based_on_payment( $txn, $payment ); - //the payment should have NOT been saved, and the txn appropriately updated - $this->assertEquals( EEM_Payment::status_id_pending, $payment->status() ); - $this->assertEquals( 0, $payment->ID() ); - $this->assertEquals( null, $txn->last_payment() ); - $this->assertEquals( 0, $payment->amount() ); - $this->assertEquals( $txn->ID(), $payment->get( 'TXN_ID' ) ); - /** @type EE_Transaction_Payments $transaction_payments */ - $transaction_payments = EE_Registry::instance()->load_class( 'Transaction_Payments' ); - $this->assertEquals( - 0, - $transaction_payments->recalculate_total_payments_for_transaction( - $txn, - EEM_Payment::status_id_approved - ) - ); - $this->assertEquals( 0, $txn->paid() ); - $this->assertEquals( EEM_Transaction::incomplete_status_code, $txn->status_ID() ); - } - - - - public function test_process_payment__onsite__declined() { - /** @type EE_Payment_Method $pm */ - $pm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Mock_Onsite' ) ); - $transaction = $this->_new_typical_transaction(); - $billing_form = $pm->type_obj()->billing_form( $transaction ); - $billing_form->receive_form_submission( - array( - 'status' => EEM_Payment::status_id_declined, - 'credit_card' => '4111 1111 1111 1111', - 'exp_month' => '12', - 'exp_year' => '2032', - 'cvv' => '123', - ) - ); - global $wp_actions; - $successful_payment_actions = EEH_Array::is_set( - $wp_actions, - 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful', - 0 - ); - /** @type EE_Payment_Processor $payment_processor */ - $payment_processor = EE_Registry::instance()->load_core( 'Payment_Processor' ); - $payment = $payment_processor->process_payment( - $pm, - $transaction, - null, - $billing_form, - 'success', - 'CART', - true, - true - ); - $this->assertInstanceOf( 'EE_Payment', $payment ); - //verify it's already been saved - $this->assertNotEquals( 0, $payment->ID() ); - $this->assertEquals( EEM_Payment::status_id_declined, $payment->status() ); - $this->assertEquals( EEM_Payment::status_id_declined, $this->_get_payment_status_in_db( $payment ) ); - $this->assertEquals( - $successful_payment_actions, - EEH_Array::is_set( - $wp_actions, - 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful', - 0 - ) - ); - } - - - - /** - * @throws \EE_Error - * @throws \Exception - */ - public function test_process_payment__offsite__declined_then_approved() { - global $wp_actions; - /** @type EE_Payment_Processor $payment_processor */ - $payment_processor = EE_Registry::instance()->load_core( 'Payment_Processor' ); - /** @type EE_Payment_Method $pm */ - $pm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Mock_Offsite' ) ); - $transaction = $this->_new_typical_transaction(); - $successful_payment_actions = EEH_Array::is_set( - $wp_actions, - 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful', - 0 - ); - $payment = $payment_processor->process_payment( $pm, $transaction, null, null, 'success', 'CART', true, true ); - $this->assertInstanceOf( 'EE_Payment', $payment ); - //verify it's already been saved - $this->assertNotEquals( 0, $payment->ID() ); - //assert that the payment still has its default status - $this->assertEquals( - EEM_Payment::instance()->field_settings_for( 'STS_ID' )->get_default_value(), - $payment->status() - ); - $this->assertEquals( - EEM_Payment::instance()->field_settings_for( 'STS_ID' )->get_default_value(), - $this->_get_payment_status_in_db( $payment ) - ); - //assert that the we haven't notified of successful payment JUST yet... - $this->assertEquals( - $successful_payment_actions, - EEH_Array::is_set( - $wp_actions, - 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful', - 0 - ) - ); - //PENDING IPN - $payment = $payment_processor->process_ipn( - array( 'status' => EEM_Payment::status_id_pending, 'gateway_txn_id' => $payment->txn_id_chq_nmbr() ), - $transaction, - $pm - ); - $this->assertEquals( EEM_Payment::status_id_pending, $payment->status() ); - $this->assertEquals( EEM_Payment::status_id_pending, $this->_get_payment_status_in_db( $payment ) ); - //and the payment-approved action should have NOT been triggered - $this->assertEquals( - $successful_payment_actions, - EEH_Array::is_set( - $wp_actions, - 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful', - 0 - ) - ); - //APPROVED IPN - $payment = $payment_processor->process_ipn( - array( 'status' => EEM_Payment::status_id_approved, 'gateway_txn_id' => $payment->txn_id_chq_nmbr() ), - $transaction, - $pm - ); - //payment should be what the gateway set it to be, which was approved - $this->assertEquals( EEM_Payment::status_id_approved, $payment->status() ); - $this->assertEquals( EEM_Payment::status_id_approved, $this->_get_payment_status_in_db( $payment ) ); - //and the payment-approved action should have been triggered - $this->assertEquals( - $successful_payment_actions + 1, - EEH_Array::is_set( - $wp_actions, - 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful', - 0 - ) - ); - //DUPLICATE SUCCESS IPN - //for this, we need to reset payment model so we fetch a NEW payment object, instead of reusing the old - //and because the payment method caches a payment method type which caches a gateway which caches the payment model, - //we also need to reset the payment method - EEM_Payment::reset(); - $pm = EEM_Payment_Method::reset()->get_one_by_ID( $pm->ID() ); - $payment = $payment_processor->process_ipn( - array( 'status' => EEM_Payment::status_id_approved, 'gateway_txn_id' => $payment->txn_id_chq_nmbr() ), - $transaction, - $pm - ); - //payment should be what the gateway set it to be, which was failed - $this->assertEquals( EEM_Payment::status_id_approved, $payment->status() ); - //and the payment-approved action should have NOT been triggered this time because it's a duplicate - $this->assertEquals( - $successful_payment_actions + 1, - EEH_Array::is_set( - $wp_actions, - 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful', - 0 - ) - ); - } - - - - public function test_process_payment__offline() { - /** @type EE_Payment_Method $pm */ - $pm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Admin_Only' ) ); - $transaction = $this->_new_typical_transaction(); - global $wp_actions; - $successful_payment_actions = EEH_Array::is_set( - $wp_actions, - 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__no_payment_made', - 0 - ); - /** @type EE_Payment_Processor $payment_processor */ - $payment_processor = EE_Registry::instance()->load_core( 'Payment_Processor' ); - $payment = $payment_processor->process_payment( $pm, $transaction, null, null, 'success', 'CART', true, true ); - // offline payments are not saved... because no payment ever actually happened - $this->assertEquals( 0, $payment->ID() ); - $this->assertEquals( EEM_Transaction::incomplete_status_code, $transaction->status_ID() ); - $this->assertEquals( - $successful_payment_actions + 1, - $wp_actions['AHEE__EE_Payment_Processor__update_txn_based_on_payment__no_payment_made'] - ); - } - - - - /** - * @group 7201 - * @throws \EE_Error - * @throws \Exception - */ - public function test_process_ipn() { - /** @type EE_Payment_Method $pm */ - $pm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Mock_Offsite' ) ); - $this->assertInstanceOf( 'EE_PMT_Mock_Offsite', $pm->type_obj() ); - $this->assertInstanceOf( 'EEG_Mock_Offsite', $pm->type_obj()->get_gateway() ); - $txn = $this->new_typical_transaction(); - //we don't want to bother sending messages. We're not wanting ot test that right now - remove_all_filters( 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful' ); - $payment = EE_Payment_Processor::instance()->process_payment( $pm, $txn ); - $fake_req_data = array( - 'gateway_txn_id' => $payment->txn_id_chq_nmbr(), - 'status' => EEM_Payment::status_id_approved, - ); - $this->assertNotEmpty( $payment->ID() ); - $payment = EE_Payment_Processor::instance()->process_ipn( $fake_req_data, $txn, $pm->slug() ); - $this->assertInstanceOf( 'EE_Payment', $payment ); - $this->assertEquals( EEM_Payment::status_id_approved, $payment->STS_ID() ); - $this->assertEquals( EEM_Payment::status_id_approved, $this->_get_payment_status_in_db( $payment ) ); - } - - - -} -// End of file EE_Payment_Processor_Test.php -// Location: tests/testcases/core/EE_Payment_Processor_Test.php diff --git a/tests/testcases/core/EE_Payment_Processor_With_Messages_Test.php b/tests/testcases/core/EE_Payment_Processor_With_Messages_Test.php deleted file mode 100644 index dd9510986a9..00000000000 --- a/tests/testcases/core/EE_Payment_Processor_With_Messages_Test.php +++ /dev/null @@ -1,54 +0,0 @@ -_pretend_addon_hook_time(); - EE_Register_Payment_Method::register('onsite', array( - 'payment_method_paths'=>array( - EE_TESTS_DIR . 'mocks/payment_methods/Mock_Onsite' - ) - )); - EE_Register_Payment_Method::register('offsite',array( - 'payment_method_paths' => array( - EE_TESTS_DIR . 'mocks/payment_methods/Mock_Offsite' - ) - )); - EE_Payment_Method_Manager::instance()->reset(); - - //unlike EE_Payment_Processor_With_Messages, this is integration testing - //and so we want to leave messages hooks in-place - - } - public function tearDown(){ - EE_Register_Payment_Method::deregister( 'onsite' ); - EE_Register_Payment_Method::deregister( 'offsite' ); - parent::tearDown(); - } -} - -// End of file EE_Payment_Processor_Test.php diff --git a/tests/testcases/core/EE_Registry_Test.php b/tests/testcases/core/EE_Registry_Test.php deleted file mode 100644 index 38f204eccdb..00000000000 --- a/tests/testcases/core/EE_Registry_Test.php +++ /dev/null @@ -1,778 +0,0 @@ - EE_Dependency_Map::load_from_cache, - 'EE_Encryption' => EE_Dependency_Map::load_from_cache - ) - ); - EE_Dependency_Map::register_dependencies( - 'EE_Injector_Tester_With_Array_Session_Int_Constructor_Params', - array( 'EE_Session_Mock' => EE_Dependency_Map::load_from_cache ) - ); - EE_Dependency_Map::register_class_loader( 'EE_Session_Mock' ); - EE_Dependency_Map::register_class_loader( 'EE_Injector_Tester_With_Array_Session_Int_Constructor_Params' ); - require_once EE_TESTS_DIR . 'mocks/core/EE_Registry_Mock.core.php'; - $loader = LoaderFactory::getLoader(); - EE_Registry_Mock::instance( - EE_Dependency_Map::instance(), - $loader->getShared('EventEspresso\core\services\container\Mirror'), - $loader->getShared('EventEspresso\core\services\loaders\ClassInterfaceCache'), - $loader->getShared('EventEspresso\core\services\loaders\ObjectIdentifier') - ); - EE_Registry_Mock::instance()->initialize(); - parent::setUp(); - } - - - - /** - * @param array $class_abbreviations - * @return array - */ - public function unit_test_registry_class_abbreviations( $class_abbreviations = array() ) { - $class_abbreviations[ 'EE_Session_Mock' ] = 'SSN'; - return $class_abbreviations; - } - - - - /** - * @param array $core_paths - * @return array - */ - public function unit_test_registry_core_paths( $core_paths = array() ) { - $core_paths[] = EE_TESTS_DIR . 'mocks/core/'; - return $core_paths; - } - - - - - /** - * this tests that objects cached using the EE_Registry class abbreviations can be retrieved - * - * @group 8284 - * @author Brent Christensen - */ - public function test_get_cached_class_abbreviations() { - // verify that EE_Network_Config has not already been loaded - $cached_class = EE_Registry_Mock::instance()->get_cached_class( 'EE_Network_Config' ); - $this->assertEquals( null, $cached_class ); - // create a stdClass object will use to mock the EE_Network_Config class - $orig_class = new stdClass(); - $orig_class->name = 'EE_Network_Config'; - // and manually cache it at EE_Registry_Mock::instance()->NET_CFG - EE_Registry_Mock::instance()->NET_CFG = $orig_class; - // now attempt to retrieve it - $cached_class = EE_Registry_Mock::instance()->get_cached_class( 'EE_Network_Config' ); - $this->assertEquals( $orig_class->name, $cached_class->name ); - // remove what we added - EE_Registry_Mock::instance()->NET_CFG = null; - } - - - - /** - * this tests that objects cached directly as EE_Registry_Mock properties can be retrieved - * - * @group 8284 - * @author Brent Christensen - */ - public function test_get_cached_class_property() { - // verify that "Some_Class" has not already been loaded - $cached_class = EE_Registry_Mock::instance()->get_cached_class( 'Some_Class' ); - $this->assertEquals( null, $cached_class ); - // create a stdClass object will use to mock the class - $orig_class = new stdClass(); - $orig_class->name = 'Some_Class'; - // and manually cache it at EE_Registry_Mock::instance()->Some_Class - EE_Registry_Mock::instance()->Some_Class = $orig_class; - // now attempt to retrieve it - $cached_class = EE_Registry_Mock::instance()->get_cached_class( 'Some_Class' ); - $this->assertEquals( $orig_class->name, $cached_class->name ); - } - - - - /** - * this tests that objects cached on EE_Registry->LIB can be retrieved - * - * @group 8284 - * @author Brent Christensen - */ - public function test_get_cached_class_library() { - // verify that "Library_Class" has not already been loaded - $cached_class = EE_Registry_Mock::instance()->get_cached_class( 'Library_Class' ); - $this->assertEquals( null, $cached_class ); - // create a stdClass object will use to mock the class - $orig_class = new stdClass(); - $orig_class->name = 'Library_Class'; - // and manually cache it at EE_Registry_Mock::instance()->Some_Class - EE_Registry_Mock::instance()->LIB->Library_Class = $orig_class; - // now attempt to retrieve it - $cached_class = EE_Registry_Mock::instance()->get_cached_class( 'Library_Class' ); - $this->assertEquals( $orig_class->name, $cached_class->name ); - } - - - - /** - * this tests that objects cached on EE_Registry->addons can be retrieved - * - * @group 8284 - * @author Brent Christensen - */ - public function test_get_cached_class_addon() { - // verify that "Addon_Class" has not already been loaded - $cached_class = EE_Registry_Mock::instance()->get_cached_class( 'Addon_Class', 'addon' ); - $this->assertEquals( null, $cached_class ); - // create a stdClass object will use to mock the class - $orig_class = new stdClass(); - $orig_class->name = 'Addon_Class'; - // and manually cache it at EE_Registry_Mock::instance()->addons->Addon_Class - EE_Registry_Mock::instance()->addons->Addon_Class = $orig_class; - // now attempt to retrieve it - $cached_class = EE_Registry_Mock::instance()->get_cached_class( 'Addon_Class', 'addon' ); - $this->assertEquals( $orig_class->name, $cached_class->name ); - } - - - /** - * This tests that the _file_loaded_for_class property is retrieved/utilized properly when load_only flag is set to - * true on the EE_Registry instance. - * @author Darren Ethier - */ - public function test__load_with_load_only_flag() { - // now do a object load request for EE_Answer - $class_loaded = EE_Registry_Mock::instance()->load_class( 'EE_Answer' ); - $this->assertInstanceOf( 'EE_Answer', $class_loaded ); - // now verify that with the $load_only flag set to true, that boolean true is returned - $file_loaded = EE_Registry_Mock::instance()->load( - array( EE_CLASSES ), - 'EE_', - 'EE_Answer', - 'class', - array(), - false, - true, - true // LOAD ONLY FLAG SET TO TRUE - ); - $this->assertTrue( $file_loaded ); - - } - - - /** - * Same as previous test except we do a load only call first. The second call should return the cached object - * and NOT true. - * @author Darren Ethier - * @group 9326 - */ - public function test__load_with_load_only_flag_set_true_on_first_load() { - //do load only - $loaded = EE_Registry_Mock::instance()->load_class( - 'EE_Answer', - array(), - false, - true, - true //load only set to true. - ); - - //should return true - $this->assertTrue( $loaded ); - //should be able to access the class now - $this->assertTrue( class_exists( 'EE_Answer', false ) ); - - //now try to grab an instance of EE_Answer - $class_instance = EE_Registry_Mock::instance()->load_class( 'EE_Answer' ); - $this->assertInstanceOf( 'EE_Answer', $class_instance ); - } - - - - - /** - * this tests that paths to EE class files can be resolved correctly - * - * @group 8284 - * @author Brent Christensen - */ - public function test_resolve_path(){ - // try to find the path to the EE_Session class - $this->assertEquals( - // expected - str_replace( array( '\\', '/' ), '/', EE_CORE . 'EE_Session.core.php' ), - // actual - EE_Registry_Mock::instance()->resolve_path( - 'EE_Session', - 'core', - array( - EE_CORE, - EE_ADMIN, - EE_CPTS, - EE_CORE . 'data_migration_scripts/' - ) - ) - ); - } - - - - - /** - * this tests that EE class files can be loaded correctly - * - * @group 8284 - * @author Brent Christensen - */ - public function test_require_file(){ - // first verify that EE_Class_For_Testing_Loading is not already loaded - // (made sure to set the class_exists() autoload param to false) - $this->assertEquals( false, class_exists( 'EE_Class_For_Testing_Loading', false ) ); - // let's attempt to load the EE_Cart - EE_Registry_Mock::instance()->require_file( - EE_MOCKS_DIR . 'core/EE_Class_For_Testing_Loading.core.php', - 'EE_Class_For_Testing_Loading', - 'core', - array( - EE_CORE, - EE_ADMIN, - EE_CORE . 'data_migration_scripts/', - EE_MOCKS_DIR, - EE_MOCKS_DIR . 'core/', - ) - ); - $this->assertEquals( true, class_exists( 'EE_Class_For_Testing_Loading', false ) ); - } - - - - - /** - * this tests that abstract EE class files are loaded but not instantiated - * - * @group 8284 - * @author Brent Christensen - */ - public function test_create_object_abstract(){ - // let's attempt to load the abstract EE_Addon class file - require_once( EE_CORE . 'EE_Addon.core.php' ); - $this->assertEquals( true, class_exists( 'EE_Addon' ) ); - // now attempt instantiation - $class_object = EE_Registry_Mock::instance()->create_object( 'EE_Addon' ); - // abstract classes only return true to denote that they have been loaded - $this->assertEquals( true, $class_object ); - } - - - - - /** - * this tests that EE model object classes can be instantiated correctly - * - * @group 8284 - * @author Brent Christensen - */ - public function test_create_object_new_instance_from_db() { - // let's attempt to load an instantiate an EE_Question object with ID=1 - require_once( EE_CLASSES . 'EE_Question.class.php' ); - $this->assertEquals( true, class_exists( 'EE_Question' ) ); - // now attempt instantiation - $class_object = EE_Registry_Mock::instance()->create_object( - 'EE_Question', - array( array( 'QST_ID' => 1 ) ), - 'class', - true // FROM DB FLAG SET TO TRUE - ); - $this->assertEquals( true, $class_object instanceof EE_Question ); - $this->assertEquals( 1, $class_object->ID() ); - } - - - - /** - * this tests that EE model object classes can be instantiated correctly - * - * @group 8284 - * @author Brent Christensen - */ - public function test_create_object_new_instance() { - // let's attempt to load an instantiate an EE_Question object with ID=1 - // despite the fact that we just loaded the file in a previous test, - // let's just double check that the class exists - require_once( EE_CLASSES . 'EE_Question.class.php' ); - $this->assertEquals( true, class_exists( 'EE_Question' ) ); - // now attempt instantiation - $class_object = EE_Registry_Mock::instance()->create_object( - 'EE_Question', - array(), - 'class' - ); - $this->assertEquals( true, $class_object instanceof EE_Question ); - $this->assertEquals( 0, $class_object->ID() ); - } - - - - /** - * this tests that EE class files can be instantiated correctly - * - * @group 8284 - * @author Brent Christensen - */ - public function test_create_object_isInstantiable(){ - // let's attempt to load the EE_Module_Request_Router class file - require_once( EE_CORE . 'EE_Module_Request_Router.core.php' ); - $this->assertEquals( true, class_exists( 'EE_Module_Request_Router' ) ); - // now attempt instantiation - $class_object = EE_Registry_Mock::instance()->create_object( 'EE_Module_Request_Router' ); - $this->assertEquals( true, $class_object instanceof EE_Module_Request_Router ); - } - - - - /** - * this tests that EE singleton classes can be instantiated correctly - * - * @group 8284 - * @author Brent Christensen - */ - public function test_create_object_singleton(){ - // let's attempt to load the EE_Capabilities class file - require_once(EE_CORE . 'EE_Capabilities.core.php' ); - $this->assertEquals( true, class_exists( 'EE_Capabilities' ) ); - // now attempt instantiation - $class_object = EE_Registry_Mock::instance()->create_object( 'EE_Capabilities' ); - $this->assertEquals( true, $class_object instanceof EE_Capabilities ); - } - - - - /** - * this tests that EE classes with core dependencies can be instantiated correctly - * - * @group 8284 - * @author Brent Christensen - */ - public function test_create_object_and_resolve_dependencies(){ - // let's attempt to load the EE_Front_Controller class file - require_once( EE_CORE . 'EE_Front_Controller.core.php' ); - $this->assertEquals( true, class_exists( 'EE_Front_Controller' ) ); - // now attempt instantiation knowing that the EE_Front_Controller class - // injects the EE_Module_Request_Router class in the constructor - /** @type EE_Front_Controller $class_object */ - $class_object = EE_Registry_Mock::instance()->create_object( 'EE_Front_Controller' ); - $this->assertInstanceOf( 'EE_Front_Controller', $class_object ); - //echo "\n Request_Handler: \n"; - //var_dump( $class_object->Request_Handler() ); - //echo "\n Module_Request_Router: \n"; - //var_dump( $class_object->Module_Request_Router() ); - $this->assertInstanceOf( 'EE_Request_Handler', $class_object->Request_Handler() ); - $this->assertInstanceOf( 'EE_Module_Request_Router', $class_object->Module_Request_Router() ); - } - - - - /** - * this tests that objects cached using the EE_Registry class abbreviations can be retrieved - * - * @group 8284 - * @author Brent Christensen - */ - public function test_set_cached_class_abbreviations() { - // create a stdClass object we'll use for a mock - $orig_class = new stdClass(); - $orig_class->name = 'If_This_Is_An_Abbreviated_Class_Name_Then_Why_Is_It_So_Long'; - // cache it at EE_Registry_Mock::instance()->NET_CFG - EE_Registry_Mock::instance()->set_cached_class( $orig_class, 'EE_Network_Config' ); - // now attempt to retrieve it - $cached_class = EE_Registry_Mock::instance()->NET_CFG; - $this->assertEquals( $orig_class, $cached_class ); - } - - - - /** - * this tests that objects cached directly as EE_Registry_Mock properties can be retrieved - * - * @group 8284 - * @author Brent Christensen - */ - public function test_set_cached_class_property() { - // create a stdClass object we'll use for a mock - $orig_class = new stdClass(); - $orig_class->name = 'Some_Class'; - // cache it at EE_Registry_Mock::instance()->CAP - EE_Registry_Mock::instance()->set_cached_class( $orig_class, 'Some_Class' ); - // now attempt to retrieve it - $cached_class = EE_Registry_Mock::instance()->Some_Class; - $this->assertEquals( $orig_class, $cached_class ); - } - - - - /** - * this tests that objects cached on EE_Registry->LIB can be retrieved - * - * @group 8284 - * @author Brent Christensen - */ - public function test_set_cached_class_library() { - // create a stdClass object we'll use for a mock - $orig_class = new stdClass(); - $orig_class->name = 'Library_Class'; - // cache it at EE_Registry_Mock::instance()->CAP - EE_Registry_Mock::instance()->set_cached_class( $orig_class, 'Library_Class' ); - // now attempt to retrieve it - $cached_class = EE_Registry_Mock::instance()->LIB->Library_Class; - $this->assertEquals( $orig_class, $cached_class ); - } - - - - /** - * this tests that objects cached on EE_Registry->addons can be retrieved - * - * @group 8284 - * @author Brent Christensen - */ - public function test_set_cached_class_addon() { - // create a stdClass object we'll use for a mock - $orig_class = new stdClass(); - $orig_class->name = 'Addon_Class'; - // cache it at EE_Registry_Mock::instance()->CAP - EE_Registry_Mock::instance()->set_cached_class( $orig_class, 'Addon_Class', 'addon' ); - // now attempt to retrieve it - $cached_class = EE_Registry_Mock::instance()->addons->Addon_Class; - $this->assertEquals( $orig_class, $cached_class ); - } - - - /** - * Checks to ensure that when we reset the registry with reset models to true, that the models are actually reset. - * @group 10109 - */ - public function test_reset_with_reset_models() { - $testing_model = EE_Registry_Mock::instance()->load_model( 'Event' ); - - //put something in the entity map - $e = $this->new_model_obj_with_dependencies( 'Event' ); - $this->assertNotNull( $testing_model->get_from_entity_map( $e->ID() ) ); - - //now let's do the full Registry reset including resetting the models. - EE_Registry_Mock::instance()->reset( false, true, true ); - - //after the reset, the entity map on the model SHOULD be empty. - $this->assertNull( EEM_Registration::instance()->get_from_entity_map( $e->ID() ) ); - $this->assertNull( $testing_model->get_from_entity_map( $e->ID() ) ); - } - - - - /** - * checks model resets happen properly: the model instance should NOT change - * (in case code anywhere has a direct reference to it) but its properties - * should be reset to their original settings - * @group 10107 - * @author Mike Nelson - */ - public function test_reset_model(){ - $model_a = EE_Registry_Mock::instance()->load_model('Event'); - $model_a2 = EE_Registry_Mock::instance()->load_model('Event'); - $model_a3 = EEM_Event::instance(); - //and put something in its entity map - $e = $this->new_model_obj_with_dependencies( 'Event' ); - $this->assertNotNull( $model_a->get_from_entity_map( $e->ID() ) ); - $this->assertEquals($model_a, $model_a2); - $this->assertEquals($model_a2, $model_a3); - //let's set a differnet WP timezone. When the model is reset, it - //should automatically use this new timezone - $new_timezone_string = 'America/Detroit'; - update_option( 'timezone_string', $new_timezone_string ); - $model_b1 = EEM_Event::reset(); - $this->assertEquals( $model_a, $model_b1); - $model_b2 = EE_Registry_Mock::instance()->reset_model('Event'); - $this->assertEquals( $model_a, $model_b2); - //verify the model now has the new wp timezone - $this->assertEquals( $new_timezone_string, $model_b1->get_timezone() ); - //and that the model's entity map has been reset - $this->assertNull( $model_b1->get_from_entity_map( $e->ID() ) ); - } - - - - /** - * test_array_is_numerically_and_sequentially_indexed - * - * @author Brent Christensen - */ - public function test_array_is_numerically_and_sequentially_indexed() { - // empty arrays should return true - $this->assertTrue( - EE_Registry_Mock::instance()->array_is_numerically_and_sequentially_indexed( array() ) - ); - // should also be fine - $this->assertTrue( - EE_Registry_Mock::instance()->array_is_numerically_and_sequentially_indexed( - array( array() ) - ) - ); - // beauty eh? - $this->assertTrue( - EE_Registry_Mock::instance()->array_is_numerically_and_sequentially_indexed( - array( 'a', 'b', 'c' ) - ) - ); - // numeric "string" keys will get typecast as integers - $this->assertTrue( - EE_Registry_Mock::instance()->array_is_numerically_and_sequentially_indexed( - array( "0" => 'a', "1" => 'b', "2" => 'c' ) - ) - ); - // arrays that are not zero-indexed should return false - $this->assertFalse( - EE_Registry_Mock::instance()->array_is_numerically_and_sequentially_indexed( - array( 1 => 'a', 2 => 'b', 3 => 'c' ) - ) - ); - // out of order - $this->assertFalse( - EE_Registry_Mock::instance()->array_is_numerically_and_sequentially_indexed( - array( "1" => 'a', "0" => 'b', "2" => 'c' ) - ) - ); - // oh come on now!!! Not even close ! - $this->assertFalse( - EE_Registry_Mock::instance()->array_is_numerically_and_sequentially_indexed( - array( "a" => 'a', "b" => 'b', "c" => 'c' ) - ) - ); - } - - - /** - * checks that type hinted classes in constructors are properly instantiated and passed - * without negatively affecting other constructor parameters - * - * @author Brent Christensen - */ - public function test_dependency_injection() { - // either need to set an autoloader for any dependency classes or just pre-load them - EE_Registry_Mock::instance()->load_core('EE_Session_Mock'); - add_filter( - 'FHEE__EE_Registry__load_service__service_paths', - function() { - return array( - EE_TESTS_DIR . 'mocks/core/services/' - ); - } - ); - // test EE_Injector_Tester_With_Array_Session_Int_Constructor_Params - // with NO passed arguments - /** @type EE_Injector_Tester_With_Array_Session_Int_Constructor_Params $class */ - $class = EE_Registry_Mock::instance()->load_service( - 'EE_Injector_Tester_With_Array_Session_Int_Constructor_Params' - ); - $this->assertEquals( array(), $class->array_property() ); - $this->assertInstanceOf( 'EE_Session_Mock', $class->session_property() ); - $this->assertEquals( 0, $class->integer_property() ); - // reset - EE_Registry_Mock::instance()->LIB->EE_Injector_Tester_With_Array_Session_Int_Constructor_Params = null; - // test EE_Injector_Tester_With_Array_Session_Int_Constructor_Params - // with numerically indexed array passed as argument 1 - $numerically_indexed_array = array( - 0 => 'zero', - 1 => 'one', - 2 => 'two', - 3 => 'three', - ); - /** @type EE_Injector_Tester_With_Array_Session_Int_Constructor_Params $class */ - $class = EE_Registry_Mock::instance()->load_service( - 'EE_Injector_Tester_With_Array_Session_Int_Constructor_Params', - array( $numerically_indexed_array ) - ); - $this->assertEquals( $numerically_indexed_array, $class->array_property() ); - $this->assertInstanceOf( 'EE_Session_Mock', $class->session_property() ); - $this->assertEquals( 0, $class->integer_property() ); - // reset - EE_Registry_Mock::instance()->LIB->EE_Injector_Tester_With_Array_Session_Int_Constructor_Params = null; - // test EE_Injector_Tester_With_Array_Session_Int_Constructor_Params - // with string indexed array passed as argument 1 - // and the integer 2 passed as argument 3 - $string_indexed_array = array( - 'zero' => 0, - 'one' => 1, - 'two' => 2, - 'three' => 3, - ); - /** @type EE_Injector_Tester_With_Array_Session_Int_Constructor_Params $class */ - $class = EE_Registry_Mock::instance()->load_service( - 'EE_Injector_Tester_With_Array_Session_Int_Constructor_Params', - array( $string_indexed_array, null, 2 ) - ); - $this->assertEquals( $string_indexed_array, $class->array_property() ); - $this->assertInstanceOf( 'EE_Session_Mock', $class->session_property() ); - $this->assertEquals( 2, $class->integer_property() ); - } - - - /** - * This test verifies that if a dependency map entry has more than one type of class listed as dependencies and they - * are both set as `load_new_object`, then they are actually two distinct objects when the parent object - * is instantiated. - * - * For this test we'll use EE_Messages_Generator because it expects two distinct EE_Message_Queue objects sent into its - * constructor via the dependency map. - * - * @group 9325 - * @author Darren Ethier - */ - public function test_multiple_duplicate_class_different_instance_on_construct_using_dependency_map() { - //first register our mock in the dependency map - $dependencies = array( - 'EE_Messages_Queue' => EE_Dependency_Map::load_new_object, - 'EE_Messages_Data_Handler_Collection' => EE_Dependency_Map::load_new_object, - 'EE_Message_Template_Group_Collection' => EE_Dependency_Map::load_new_object, - 'EEH_Parse_Shortcodes' => EE_Dependency_Map::load_from_cache, - ); - $registered = EE_Dependency_Map::register_dependencies( 'EE_Messages_Generator_Mock', $dependencies ); - $this->assertTrue( $registered ); - - $mock_paths[] = EE_TESTS_DIR . 'mocks/core/libraries/messages'; - - //load the mock generator - /** @var EE_Messages_Generator_Mock $generator */ - $generator = EE_Registry_Mock::instance()->load( $mock_paths, 'EE_', 'Messages_Generator_Mock', '' ); - - //verify both queues are distinct - $this->assertNotEquals( - spl_object_hash( $generator->generation_queue() ), - spl_object_hash( $generator->ready_queue() ) - ); - } - - - - /** - * This test verifies that any new dependencies registered - * on EE_Dependency_Map are immediately visible to EE_Registry. - * It may seem wrong because it appears to be testing methods that actually exist on EE_Dependency_Map, - * but they are all methods that are called via the \EE_Registry::$_dependency_map property. - * So this test is just verifying that EE_Registry and EE_Dependency_Map are in sync. - * - * Uses EE_Registry_Mock::dependency_map_has(), - * EE_Registry_Mock::has_dependency_for_class(), - * and EE_Registry_Mock::loading_strategy_for_class_dependency(), - * which all call methods via the EE_Dependency_Map property on EE_Registry - * - * @author Brent Christensen - */ - public function test_registry_can_see_newly_registered_dependencies() { - // first verify that dependency doesn't already exist - $this->assertFalse( - EE_Registry_Mock::instance()->dependency_map_has( 'Some_New_Class_Name' ) - ); - // then register it - EE_Dependency_Map::register_dependencies( - 'Some_New_Class_Name', - array( 'DependencyOne' => EE_Dependency_Map::load_new_object ) - ); - // and verify that it's now available - $this->assertTrue( - EE_Registry_Mock::instance()->dependency_map_has( 'Some_New_Class_Name' ) - ); - // verify loading strategy - $this->assertEquals( - EE_Dependency_Map::load_new_object, - EE_Registry_Mock::instance()->loading_strategy_for_class_dependency( 'Some_New_Class_Name', 'DependencyOne' ) - ); - } - - - - /** - * This test verifies that any new class loaders registered - * on EE_Dependency_Map are immediately visible to EE_Registry. - * It may seem wrong because it appears to be testing methods that actually exist on EE_Dependency_Map, - * but they are all methods that are called via the \EE_Registry::$_dependency_map property. - * So this test is just verifying that EE_Registry and EE_Dependency_Map are in sync. - * - * Uses EE_Registry_Mock::loading_strategy_for_class_dependency() - * which calls EE_Dependency_Map::loading_strategy_for_class_dependency() via the property on EE_Registry - * - * @author Brent Christensen - */ - public function test_registry_can_see_newly_registered_class_loaders() { - // first verify that class loader doesn't already exist - $this->assertEmpty( - EE_Registry_Mock::instance()->dependency_map_class_loader( 'DependencyOne' ) - ); - // then register it - EE_Dependency_Map::register_class_loader( 'DependencyOne', 'load_core' ); - // and verify that it's now available - $this->assertEquals( - 'load_core', - EE_Registry_Mock::instance()->dependency_map_class_loader( 'DependencyOne' ) - ); - } - - - /** - * Corresponds to https://github.com/eventespresso/eventsmart.com-website/issues/36 - * where fetching an add-on that isn't yet registered causes an error - */ - public function testGetAddonThatDoesntExist() - { - EE_Registry_Mock::instance()->getAddon('foobar'); - $this->assertTrue(true); - } - - - /** - * Corresponds to https://github.com/eventespresso/eventsmart.com-website/issues/36 - * where fetching an add-on that isn't yet registered causes an error - */ - public function testremoveAddonThatDoesntExist() - { - EE_Registry_Mock::instance()->removeAddon('foobar'); - $this->assertTrue(true); - } - -} -// End of file EE_Registry_Test.php -// Location: /tests/testcases/core/EE_Registry_Test.php diff --git a/tests/testcases/core/EE_System_Test.php b/tests/testcases/core/EE_System_Test.php deleted file mode 100644 index 348edb2350c..00000000000 --- a/tests/testcases/core/EE_System_Test.php +++ /dev/null @@ -1,383 +0,0 @@ -_original_espresso_db_update = get_option('espresso_db_update'); - $this->_original_db_state = get_option( EE_Data_Migration_Manager::current_database_state ); - EE_System::reset(); - } - public function test_detect_request_type(){ - - $this->_pretend_espresso_db_update_is(array( - espresso_version() => array(current_time('mysql')) - )); - $request_type = EE_System::reset()->detect_req_type(); - $this->assertEquals(EE_System::req_type_normal,$request_type); - //check that it detects an upgrade - $this->_pretend_espresso_db_update_is(array( - $this->_add_to_version(espresso_version(), '0.-1.0.0.0') => array(current_time('mysql')) - )); - $request_type = EE_System::reset()->detect_req_type(); - $this->assertEquals(EE_System::req_type_upgrade,$request_type); - //check that it detects activation - $this->_pretend_espresso_db_update_is(NULL); - $request_type = EE_System::reset()->detect_req_type(); - $this->assertEquals(EE_System::req_type_new_activation,$request_type); - //check that it detects downgrade, even though we don't really care atm -// EE_System::reset(); -// $this->_pretend_espresso_db_upgrade_is(array( -// $this->_add_to_version(espresso_version(), '0.1.0.0.0') => array(current_time('mysql')) -// )); -// $request_type = EE_System::instance()->detect_req_type(); -// $this->assertEquals(EE_System::req_type_downgrade,$request_type); - //lastly, check that we detect reactivations - update_option('ee_espresso_activation',true); - $this->_pretend_espresso_db_update_is(array( - espresso_version() => array(current_time('mysql')) - )); - $request_type = EE_System::reset()->detect_req_type(); - $this->assertEquals(EE_System::req_type_reactivation,$request_type); - } - /** - * just tests the EE_System_Test::_add_to_version private method to make sure it's working - * (because other tests depend on it) - */ - function test_add_to_version(){ - $version = '4.3.2.alpha.001'; - $version_to_add = '1.0.-1.1.1'; - $new_version = $this->_add_to_version($version, $version_to_add); - $this->assertEquals('5.3.1.alpha.002',$new_version); - } - /** - * check things turn out as expected for NORMAL REQUEST - */ - function test_detect_activation_or_upgrade__normal(){ - delete_option( 'ee_espresso_activation' ); - $pretend_activation_history = array( - espresso_version() => array(current_time('mysql')) - ); - $this->_pretend_espresso_db_update_is($pretend_activation_history); - $current_activation_history_before = get_option('espresso_db_update'); - $this->assertEquals(1,count($current_activation_history_before[espresso_version()])); - EE_System::instance()->detect_if_activation_or_upgrade(); - $current_activation_history_after = get_option('espresso_db_update'); - //this should have just added to the number of times this same verison was activated - $this->assertEquals(EE_System::req_type_normal,EE_System::instance()->detect_req_type()); - $this->assertArrayHasKey( espresso_version(), $current_activation_history_after ); - $this->assertTimeIsAbout(current_time( 'timestamp' ), $current_activation_history_after[ espresso_version() ][ 0 ] ); - - } - /** - * new activation - */ - function test_detect_activation_or_upgrade__new_install() { - $this->_pretend_espresso_db_update_is(NULL); - //pretend the activation indicator option was set (because it's really unusual - //for a plugin to be activated without having WP call its activation hook) - update_option('ee_espresso_activation',TRUE); - remove_action('AHEE__EE_System__perform_activations_upgrades_and_migrations',array(EE_System::instance(),'initialize_db_if_no_migrations_required')); - $this->assertWPOptionDoesNotExist('espresso_db_update'); - EE_System::reset()->detect_if_activation_or_upgrade(); - $current_activation_history = get_option('espresso_db_update'); - //check we've added this to the version history - //and that the hook for adding tables n stuff was added - $this->assertArrayHasKey( espresso_version(), $current_activation_history ); - $this->assertTimeIsAbout(current_time( 'timestamp' ), $current_activation_history[ espresso_version() ][ 0 ] ); - has_action('AHEE__EE_System__perform_activations_upgrades_and_migrations',array(EE_System::instance(),'initialize_db_if_no_migrations_required')); - //and the activation indicator option shoudl have been removed - $this->assertWPOptionDoesNotExist('ee_espresso_activation'); - } - - /** - * tests EE_SYstem_Test::assertTimeIsAbout - */ - public function test_assertTimeIsAbout(){ - //these tests should fail - try{ - $this->assertTimeIsAbout(current_time( 'timestamp' ), current_time( 'timestamp' ) + 6, 5 ); - }catch( PHPUnit_Framework_ExpectationFailedException $e ){ - $this->assertTrue( TRUE ); - } - try{ - $this->assertTimeIsAbout(current_time( 'timestamp' ), current_time( 'timestamp' ) - 6, 5 ); - }catch( PHPUnit_Framework_ExpectationFailedException $e ){ - $this->assertTrue( TRUE ); - } - $this->assertTimeIsAbout( current_time( 'timestamp' ), current_time( 'timestamp' ) + 4, 5 ); - $this->assertTimeIsAbout( current_time( 'timestamp' ), current_time( 'timestamp' ) - 3, 5 ); - } - - /** - * Asserts that there is at most $precision time difference between $expected_time and - * $actual_time, in either direction - * @param string|int $expected_time mysql or unix timestamp - * @param string|int $actual_time mysql or unix timestamp - * @param int $precision allowed number of seconds of time idfference without failing - */ - protected function assertTimeIsAbout($expected_time, $actual_time, $precision = 5) { - if( ! is_int( $expected_time ) ){ - $expected_time = strtotime( $expected_time ); - } - if( ! is_int( $actual_time ) ){ - $actual_time = strtotime( $actual_time ); - } - $this->assertLessThanOrEqual($precision, abs( $actual_time - $expected_time ) ); - } - /** - * tests we can detect an upgrade when the plugin is deactivated, then a new version of the plugin - * is uploaded, and then activated (ie, the plugin's activation hook was fired) - */ - function test_detect_activation_or_upgrade__upgrade_upon_activation(){ - $pretend_previous_version = $this->_add_to_version(espresso_version(),'0.-1.0.0.0'); - $this->_pretend_espresso_db_update_is(array( - $pretend_previous_version => array(current_time('mysql')) - )); - //pretend the activation indicator option was set (because it's really unusual - //for a plugin to be activated without having WP call its activation hook) - update_option('ee_espresso_activation',TRUE); - - EE_System::reset()->detect_if_activation_or_upgrade(); - $current_activation_history = get_option('espresso_db_update'); - $this->assertEquals(EE_System::req_type_upgrade,EE_System::instance()->detect_req_type()); - $this->assertArrayHasKey( $pretend_previous_version, $current_activation_history ); - $this->assertTimeIsAbout(current_time( 'timestamp' ), $current_activation_history[ $pretend_previous_version ][ 0 ] ); - $this->assertArrayHasKey( espresso_version(), $current_activation_history ); - $this->assertTimeIsAbout(current_time( 'timestamp' ), $current_activation_history[ espresso_version() ][ 0 ] ); - - $this->assertWPOptionDoesNotExist('ee_espresso_activation'); - } - /** - * tests we can detect an upgrade when the plugin files were automatically - * updated (ie, the plugins' activation hook wasn't called) - */ - function test_detect_activation_or_upgrade__upgrade_upon_normal_request(){ - $pretend_previous_version = $this->_add_to_version(espresso_version(),'0.-1.0.0.0'); - $this->_pretend_espresso_db_update_is(array( - $pretend_previous_version => array(current_time('mysql')) - )); - - $this->assertEquals(EE_System::req_type_upgrade,EE_System::reset()->detect_req_type()); - $current_activation_history = get_option('espresso_db_update'); - $this->assertArrayHasKey( $pretend_previous_version, $current_activation_history ); - $this->assertTimeIsAbout(current_time( 'timestamp' ), $current_activation_history[ $pretend_previous_version ][ 0 ] ); - $this->assertArrayHasKey( espresso_version(), $current_activation_history ); - $this->assertTimeIsAbout(current_time( 'timestamp' ), $current_activation_history[ espresso_version() ][ 0 ] ); - $this->assertWPOptionDoesNotExist('ee_espresso_activation'); - } - function test_detect_activation_or_upgrade__reactivation(){ - $this->_pretend_espresso_db_update_is(array( - espresso_version() => array(current_time('mysql')) - )); - update_option('ee_espresso_activation',true); - - $this->assertEquals(EE_System::req_type_reactivation,EE_System::reset()->detect_req_type()); - $current_activation_history = get_option('espresso_db_update'); -// $this->assertEquals(array(espresso_version() =>array(current_time('mysql'),current_time('mysql'))),$current_activation_history); - $this->assertArrayHasKey( espresso_version(), $current_activation_history ); - $this->assertTimeIsAbout(current_time( 'timestamp' ), $current_activation_history[ espresso_version() ][ 0 ] ); - $this->assertTimeIsAbout(current_time( 'timestamp' ), $current_activation_history[ espresso_version() ][ 1 ] ); - $this->assertWPOptionDoesNotExist('ee_espresso_activation'); - } - function test_detect_activation_or_upgrade__downgrade_upon_normal_request(){ - $pretend_previous_version = $this->_add_to_version(espresso_version(),'0.1.0.0.0'); - $this->_pretend_espresso_db_update_is(array( - $pretend_previous_version => array(current_time('mysql')) - )); - $this->assertEquals(EE_System::req_type_downgrade,EE_System::reset()->detect_req_type()); - $current_activation_history = get_option('espresso_db_update'); - $this->assertArrayHasKey( $pretend_previous_version, $current_activation_history ); - $this->assertTimeIsAbout(current_time( 'timestamp' ), $current_activation_history[ $pretend_previous_version ][ 0 ] ); - $this->assertArrayHasKey( espresso_version(), $current_activation_history ); - $this->assertTimeIsAbout(current_time( 'timestamp' ), $current_activation_history[ espresso_version() ][ 0 ] ); - $this->assertWPOptionDoesNotExist('ee_espresso_activation'); - } - /** - * tests that we're detecting request types correctly on normal requests (ie, NOT an activation request) - * A new install would only occur on a non-activation request because the site was previously in maintenance mode - * - */ - function test_detect_req_type_given_activation_history__on_normal_requests(){ - $activation_history = array(); - - //detect brand new activation BUT we're in maintenance mode, so it will be basically ignored - EE_Maintenance_Mode::instance()->set_maintenance_level( EE_Maintenance_Mode::level_2_complete_maintenance ); - $this->assertEquals( EE_System::req_type_new_activation, EE_System::detect_req_type_given_activation_history($activation_history, '', '1.0.0.dev.000' ) ); - EE_Maintenance_Mode::instance()->set_maintenance_level( EE_Maintenance_Mode::level_0_not_in_maintenance ); - - //detect brand new activation - $this->assertEquals( EE_System::req_type_new_activation, EE_System::detect_req_type_given_activation_history($activation_history, '', '1.0.0.dev.000' ) ); - $activation_history[ '1.0.0.dev.000'] = array( date( 'Y-m-d H:i:s' ) ); - - //detect upgrade to NEW version - $this->assertEquals( EE_System::req_type_upgrade, EE_System::detect_req_type_given_activation_history($activation_history, '', '1.2.0.dev.000' ) ); - $activation_history[ '1.2.0.dev.000' ] = array( date( 'Y-m-d H:i:s', time() + 1 ) ); - - //detect normal request - $this->assertEquals( EE_System::req_type_normal, EE_System::detect_req_type_given_activation_history($activation_history, '', '1.2.0.dev.000' ) ); - - //detect downgrade to NEW version - $this->assertEquals( EE_System::req_type_downgrade, EE_System::detect_req_type_given_activation_history($activation_history, '', '1.1.0.dev.000' ) ); - $activation_history[ '1.1.0.dev.000' ] = array( date( 'Y-m-d H:i:s', time() + 2 ) ); - - //detect downgrade to KNOWN version - $this->assertEquals( EE_System::req_type_downgrade, EE_System::detect_req_type_given_activation_history($activation_history, '', '1.0.0.dev.000' ) ); - $activation_history[ '1.0.0.dev.000' ][] = date( 'Y-m-d H:i:s', time() + 3 ) ; - - //detect upgrade to KNOWN version - $this->assertEquals( EE_System::req_type_upgrade, EE_System::detect_req_type_given_activation_history($activation_history, '', '1.1.0.dev.000' ) ); - $activation_history[ '1.1.0.dev.000' ][] = date( 'Y-m-d H:i:s', time() + 4 ) ; - } - - /** - * tests that we are detecting activations correctly even when the same version has - * been activated multiple times - */ - function test_detect_req_type_given_activation_history__multiple_activations(){ - $activation_history = array( - '3.1.36.5.P' => array( 'unknown-date' ), - '4.3.0.alpha.019' => array( '2014-06-09 18:10:35', ), - '4.6.0.dev.016' => array( - '2014-10-15 15:43:08', - '2014-10-15 18:16:41', - '2014-10-15 20:09:07' - ), - '4.5.0.beta.020' => array( - '2014-10-15 16:52:35', - ) - - ); - $this->assertEquals( EE_System::req_type_downgrade, EE_System::detect_req_type_given_activation_history($activation_history, '', '4.5.0.beta.020' ) ); - } - /** - * - */ - function test_detect_req_type_given_activation_history__on_activation(){ - $activation_history = array(); - update_option( 'test_activation_indicator_option', TRUE ); - - //detect brand new activation - $this->assertEquals( EE_System::req_type_new_activation, EE_System::detect_req_type_given_activation_history($activation_history, 'test_activation_indicator_option', '1.0.0.dev.000' ) ); - $activation_history[ '1.0.0.dev.000'] = array( date( 'Y-m-d H:i:s' ) ); - update_option( 'test_activation_indicator_option', TRUE ); - - //detect upgrade to NEW version - $this->assertEquals( EE_System::req_type_upgrade, EE_System::detect_req_type_given_activation_history($activation_history, 'test_activation_indicator_option', '1.2.0.dev.000' ) ); - $activation_history[ '1.2.0.dev.000' ] = array( date( 'Y-m-d H:i:s', time() + 1 ) ); - update_option( 'test_activation_indicator_option', TRUE ); - - //detect reactivation request; WOULD be a normal request if the activation indicator weren't set - $this->assertEquals( EE_System::req_type_reactivation, EE_System::detect_req_type_given_activation_history($activation_history, 'test_activation_indicator_option', '1.2.0.dev.000' ) ); - - //detect downgrade to NEW version - $this->assertEquals( EE_System::req_type_downgrade, EE_System::detect_req_type_given_activation_history($activation_history, 'test_activation_indicator_option', '1.1.0.dev.000' ) ); - $activation_history[ '1.1.0.dev.000' ] = array( date( 'Y-m-d H:i:s', time() + 2 ) ); - update_option( 'test_activation_indicator_option', TRUE ); - - //detect downgrade to KNOWN version - $this->assertEquals( EE_System::req_type_downgrade, EE_System::detect_req_type_given_activation_history($activation_history, 'test_activation_indicator_option', '1.0.0.dev.000' ) ); - $activation_history[ '1.0.0.dev.000' ][] = date( 'Y-m-d H:i:s', time() + 3 ) ; - update_option( 'test_activation_indicator_option', TRUE ); - - //detect upgrade to KNOWN version - $this->assertEquals( EE_System::req_type_upgrade, EE_System::detect_req_type_given_activation_history($activation_history, 'test_activation_indicator_option', '1.1.0.dev.000' ) ); - $activation_history[ '1.1.0.dev.000' ][] = date( 'Y-m-d H:i:s', time() + 4 ) ; - update_option( 'test_activation_indicator_option', TRUE ); - } - - /** - * @group 8154 - */ - function test__new_version_is_higher(){ - $class = new ReflectionClass("EE_System"); - $method = $class->getMethod("_new_version_is_higher"); - $method->setAccessible(true); - - $current_version = '4.7.0.rc.000'; - $activation_history = array( - $current_version => array( - '2015-03-12 04:53:12' - ), - '3.1.37.1.P' => - array( - 0 => 'unknown-date', - ), - ); - $this->assertEquals( 0, $method->invoke(EE_System::instance(), $activation_history, $current_version ) ); - $this->assertEquals( 1, $method->invoke( EE_System::instance(), $activation_history, '4.8.0.rc.000' ) ); - $this->assertEquals( -1, $method->invoke( EE_System::instance(), $activation_history, '4.4.0.rc.000' ) ); - $this->assertEquals( 1, $method->invoke( EE_System::instance(), array(), '4.8.0.rc.000' ) ); - } - - - /** - * Sets the wordpress option 'espresso_db_update' - * @param array $espresso_db_upgrade top-level-keys shoudl be version numbers, - * and their values should be an array of mysql datetimes when that version was activated - */ - private function _pretend_espresso_db_update_is($espresso_db_upgrade){ - if($espresso_db_upgrade === NULL){ - delete_option('espresso_db_update',$espresso_db_upgrade); - }else{ - update_option( 'espresso_db_update',$espresso_db_upgrade ); - } - } - - /** - * - * @param string $version_string eg "4.3.2.alpha.003 - * @param string $version_amount_to_add eg "0.0.0.0.1" - * @return string eg if given the mentioned inputs, would be "4.3.2.alpha.4"; - */ - private function _add_to_version($version_string,$version_amount_to_add = '0.1.0.0.0'){ - $version_parts = explode(".",$version_string); - $version_amount_to_add_parts = explode(".",$version_amount_to_add); - foreach($version_parts as $key => $version_part){ - if(is_numeric($version_part)){ - $characters_in_version_part = strlen( $version_part ); - $version_parts[$key] = str_pad( $version_parts[$key] + $version_amount_to_add_parts[$key], $characters_in_version_part, '0', STR_PAD_LEFT ); - } - } - return implode(".",$version_parts); - } - /** - * restore the epsresso_db_update option - */ - function tearDown() { - update_option('espresso_db_update',$this->_original_espresso_db_update); - EE_System::reset()->detect_req_type(); - EE_Data_Migration_Manager::reset(); - update_option( EE_Data_Migration_Manager::current_database_state, $this->_original_db_state ); - parent::tearDown(); - } -} - -// End of file EE_System_Test.php \ No newline at end of file diff --git a/tests/testcases/core/EE_System_Test_With_Addons.php b/tests/testcases/core/EE_System_Test_With_Addons.php deleted file mode 100644 index 41956f0b48b..00000000000 --- a/tests/testcases/core/EE_System_Test_With_Addons.php +++ /dev/null @@ -1,598 +0,0 @@ -_table_analysis = new TableAnalysis(); - $this->_table_manager = new TableManager($this->_table_analysis); - $this->_pretend_addon_hook_time(); - $mock_addon_path = EE_TESTS_DIR . 'mocks/addons/eea-new-addon/'; - EE_Registry::instance()->addons = new RegistryContainer(); - EE_Register_Addon::register( - $this->_addon_name, - array( - 'version' => '1.0.0.dev.000', - 'min_core_version' => '4.0.0', - 'main_file_path' => $mock_addon_path . 'eea-new-addon.php', - 'dms_paths' => $mock_addon_path . 'core/data_migration_scripts', - ) - ); - // now verify that this is the only addon - $this->assertCount(1, EE_Registry::instance()->addons); - //double-check that worked fine - $this->assertArrayHasKey( - 'EE_New_Addon', - EE_Registry::instance()->addons - ); - $this->assertInstanceOf( - 'EE_New_Addon', - EE_Registry::instance()->addons->EE_New_Addon - ); - $DMSs_available = EE_Data_Migration_Manager::reset()->get_all_data_migration_scripts_available(); - $this->assertArrayHasKey('EE_DMS_New_Addon_1_0_0', $DMSs_available); - $this->_addon = EE_Registry::instance()->addons->EE_New_Addon; - $this->assertInstanceOf('EE_New_Addon', $this->_addon); - $this->_addon_classname = get_class($this->_addon); - $this->_addon_activation_history = $this->_addon->get_activation_history(); - $this->_current_db_state = get_option(EE_Data_Migration_Manager::current_database_state); - delete_option(EE_Data_Migration_Manager::current_database_state); - update_option( - EE_Data_Migration_Manager::current_database_state, - array('Core' => espresso_version()) - ); - add_filter( - 'FHEE__EEH_Activation__create_table__short_circuit', - array($this, 'dont_short_circuit_new_addon_table'), - 20, - 2 - ); - } - - - public function tearDown() - { - //if somehow $this->_addon isn't set, we don't need to worry about deregistering it right? - if ($this->_addon instanceof EE_Addon) { - update_option( - $this->_addon->get_activation_history_option_name(), - $this->_addon_activation_history - ); - update_option( - EE_Data_Migration_Manager::current_database_state, - $this->_current_db_state - ); - EE_Register_Addon::deregister($this->_addon_name); - try { - EE_Registry::instance()->addons->EE_New_Addon; - $this->fail('EE_New_Addon is still registered. Deregister failed'); - } catch (Exception $e) { - $this->assertInstanceOf('OutOfBoundsException', $e); - } - //verify DMSs deregistered - $DMSs_available = EE_Data_Migration_Manager::reset()->get_all_data_migration_scripts_available(); - $this->assertArrayNotHasKey('EE_DMS_New_Addon_1_0_0', $DMSs_available); - $this->_stop_pretending_addon_hook_time(); - // drop all the temporary tables we created during this test, - // because each subsequent test expects them to be gone - $this->_table_manager->dropTables($this->_temp_tables_added_by_addon); - } - parent::tearDown(); - } - - - /** - * OK's the creation of the esp_new_addon table, because this hooks in AFTER EE_UNitTestCase's callback on this - * same hook - * - * @global wpdb $wpdb - * @param boolean $short_circuit whether or not to short-circuit - * @param string $table_name name we're about to create. Should NOT have the $wpdb->prefix on it - * @return array|bool - */ - public function dont_short_circuit_new_addon_table($short_circuit = false, $table_name = '') - { - //allow creation of new_addon tables. Unfortunately, this also allows their modification, which causes - //implicit commits. But I like allowing re-defining the tables on test - //test_detect_activations_or_upgrades__new_install_on_core_and_addon_simultaneously - //so we can confirm a notices are sent when attempting to redefine an addon table - if (in_array($table_name, $this->_temp_tables_added_by_addon, true)) { - //it's not altering. it's ok to allow this - return false; - } - return $short_circuit; - } - - - private function _add_mock_dms() - { - add_filter('FHEE__EE_Data_Migration_Manager__get_data_migration_script_folders', array($this, 'add_mock_dms')); - EE_Data_Migration_Manager::reset(); - } - - - private function _remove_mock_dms() - { - remove_filter( - 'FHEE__EE_Data_Migration_Manager__get_data_migration_script_folders', - array($this, 'add_mock_dms') - ); - EE_Data_Migration_Manager::reset(); - } - - - public function add_mock_dms($dms_folders) - { - $dms_folders[] = EE_TESTS_DIR . 'mocks/core/data_migration_scripts'; - return $dms_folders; - } - - - /** - * tests that we're correctly detecting activation or upgrades in registered - * addons. - * - * @group agg - * @group 8328 - */ - public function test_detect_activations_or_upgrades__new_install() - { - global $wp_actions; - //its activation history wp option shouldn't exist - $this->assertWPOptionDoesNotExist($this->_addon->get_activation_history_option_name()); - //and it also shouldn't be in the current db state - $current_db_state = get_option(EE_Data_Migration_Manager::current_database_state); - //just for assurance, make sure New Addon is the only existing addon - $this->assertArrayNotHasKey($this->_addon_name, $current_db_state); - $times_its_new_install_hook_fired_before = isset($wp_actions["AHEE__{$this->_addon_classname}__new_install"]) - ? $wp_actions["AHEE__{$this->_addon_classname}__new_install"] : 0; - //set the activator option - update_option($this->_addon->get_activation_indicator_option_name(), true); - $this->assertWPOptionExists($this->_addon->get_activation_indicator_option_name()); - $this->assertTableDoesNotExist('esp_new_addon_thing'); - //now check for activations/upgrades in addons - EE_System::reset(); - $this->assertEquals(EE_System::req_type_new_activation, $this->_addon->detect_req_type()); - $this->assertEquals( - $times_its_new_install_hook_fired_before + 1, - $wp_actions["AHEE__{$this->_addon_classname}__new_install"] - ); - $this->assertWPOptionDoesNotExist($this->_addon->get_activation_indicator_option_name()); - //now we also want to check that the addon will have created the necessary table - //that it needed upon new activation - $this->assertTableExists('esp_new_addon_thing'); - } - - - /** - * tests that we're correctly detecting activation or upgrades in registered - * addons. - * - * @group agg - */ - public function test_detect_activations_or_upgrades__new_install_on_core_and_addon_simultaneously() - { - global $wp_actions, $wpdb; - //pretend core was just activated - delete_option('espresso_db_update'); - update_option('ee_espresso_activation', true); - delete_option('ee_pers_admin_notices'); - //its activation history wp option shouldn't exist - $this->assertWPOptionDoesNotExist($this->_addon->get_activation_history_option_name()); - //and it also shouldn't be in the current db state - $current_db_state = get_option(EE_Data_Migration_Manager::current_database_state); - //just for assurance, make sure New Addon is the only existing addon - $this->assertArrayNotHasKey($this->_addon_name, $current_db_state); - $times_addon_new_install_hook_fired = isset($wp_actions["AHEE__{$this->_addon_classname}__new_install"]) - ? $wp_actions["AHEE__{$this->_addon_classname}__new_install"] - : 0; - $times_core_new_install_hook_fired = isset($wp_actions['AHEE__EE_System__detect_if_activation_or_upgrade__new_activation']) - ? $wp_actions['AHEE__EE_System__detect_if_activation_or_upgrade__new_activation'] - : 0; - //set the activator option - update_option($this->_addon->get_activation_indicator_option_name(), true); - $this->assertWPOptionExists($this->_addon->get_activation_indicator_option_name()); - $this->assertTableDoesNotExist('esp_new_addon_thing'); - EE_System::reset(); - $this->assertEquals(EE_System::req_type_new_activation, EE_System::instance()->detect_req_type()); - $this->assertEquals(EE_System::req_type_new_activation, $this->_addon->detect_req_type()); - $this->assertEquals( - $times_addon_new_install_hook_fired + 1, - $wp_actions["AHEE__{$this->_addon_classname}__new_install"] - ); - $this->assertEquals( - $times_core_new_install_hook_fired + 1, - $wp_actions['AHEE__EE_System__detect_if_activation_or_upgrade__new_activation'] - ); - $this->assertWPOptionDoesNotExist($this->_addon->get_activation_indicator_option_name()); - $this->assertWPOptionDoesNotExist('ee_espresso_activation'); - $this->assertTableExists('esp_new_addon_thing'); - //verify we haven't remarked that there we tried adding a duplicate table - $notices = get_option('ee_pers_admin_notices', array()); - $this->assertArrayNotHasKey('bad_table_' . $wpdb->prefix . 'esp_new_addon_thing_detected', $notices); - //double-check that when we intentionally try to add a table we just asserted exists - //that the warning gets sent out - global $track_it; - $track_it = true; - try { - EEH_Activation::create_table( - 'esp_new_addon_thing', - 'BORKED SQL', - 'ENGINE=MyISAM ', - true - ); - $this->fail('Borked SQL didn\'t cause EEH_Activation::create_table to throw an EE_Error. It should have'); - } catch (EE_Error $e) { - $this->assertTrue(true); - } - } - - - public function test_detect_activations_or_upgrades__upgrade_on_activation() - { - global $wp_actions; - $this->_addon_classname = get_class($this->_addon); - //first make sure the mock DMS can migrate from v 0.0.1 - $dms = new EE_DMS_New_Addon_1_0_0(); - $this->assertTrue( - $dms->can_migrate_from_version( - array($this->_addon_name => $this->_pretend_addon_previous_version) - ) - ); - //it should have an entry in its activation history and db state - $activation_history_option_name = $this->_addon->get_activation_history_option_name(); - update_option($activation_history_option_name, array($this->_pretend_addon_previous_version)); - $db_state = get_option(EE_Data_Migration_Manager::current_database_state); - $db_state[$this->_addon_name] = $this->_pretend_addon_previous_version; - update_option(EE_Data_Migration_Manager::current_database_state, $db_state); - //pretend the activation indicator option was set (by WP calling its activation hook) - update_option($this->_addon->get_activation_indicator_option_name(), true); - $times_its_new_install_hook_fired_before = isset($wp_actions["AHEE__{$this->_addon_classname}__upgrade"]) - ? $wp_actions["AHEE__{$this->_addon_classname}__upgrade"] : 0; - //the site shouldn't be in MM before - $this->assertEquals( - EE_Maintenance_Mode::level_0_not_in_maintenance, - EE_Maintenance_Mode::instance()->level() - ); - //now check for activations/upgrades in addons - EE_System::reset(); - $this->assertEquals(EE_System::req_type_upgrade, $this->_addon->detect_req_type()); - $this->assertEquals( - $times_its_new_install_hook_fired_before + 1, - $wp_actions["AHEE__{$this->_addon_classname}__upgrade"] - ); - //the fact that there's an applicable DMS means the site should be placed in maintenance mode - $this->assertEquals( - EE_Maintenance_Mode::level_2_complete_maintenance, - EE_Maintenance_Mode::instance()->level() - ); - //check that the activation indicator option was removed - $this->assertWPOptionDoesNotExist($this->_addon->get_activation_indicator_option_name()); - //ok all done - EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_0_not_in_maintenance); - } - - - /** - * tests we detect an upgrade even when the plugin isn't newly activated - * - * @global array $wp_actions - */ - public function test_detect_activations_or_upgrades__upgrade_on_normal_request() - { - global $wp_actions; - //first make sure the mock DMS can migrate from v 0.0.1 - $dms = new EE_DMS_New_Addon_1_0_0(); - $this->assertTrue( - $dms->can_migrate_from_version( - array($this->_addon_name => $this->_pretend_addon_previous_version) - ) - ); - //it should have an entry in its activation history and db state - $activation_history_option_name = $this->_addon->get_activation_history_option_name(); - update_option($activation_history_option_name, array($this->_pretend_addon_previous_version)); - $db_state = get_option(EE_Data_Migration_Manager::current_database_state); - $db_state[$this->_addon_name] = $this->_pretend_addon_previous_version; - update_option(EE_Data_Migration_Manager::current_database_state, $db_state); - $times_its_new_install_hook_fired_before = isset($wp_actions["AHEE__{$this->_addon_classname}__upgrade"]) - ? $wp_actions["AHEE__{$this->_addon_classname}__upgrade"] : 0; - //the site shouldn't be in MM before - $this->assertEquals( - EE_Maintenance_Mode::level_0_not_in_maintenance, - EE_Maintenance_Mode::instance()->level() - ); - //now check for activations/upgrades in addons - EE_System::reset(); - $this->assertEquals(EE_System::req_type_upgrade, $this->_addon->detect_req_type()); - $this->assertEquals( - $times_its_new_install_hook_fired_before + 1, - $wp_actions["AHEE__{$this->_addon_classname}__upgrade"] - ); - //the fact that there's an applicable DMS means the site should be placed in maintenance mode - $this->assertEquals( - EE_Maintenance_Mode::level_2_complete_maintenance, - EE_Maintenance_Mode::instance()->level() - ); - //ok all done - EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_0_not_in_maintenance); - } - - - public function test_detect_activations_or_upgrades__reactivation() - { - global $wp_actions; - $this->assertEquals( - EE_Maintenance_Mode::level_0_not_in_maintenance, - EE_Maintenance_Mode::instance()->level() - ); - //it should have an entry in its activation history and db state - $activation_history_option_name = $this->_addon->get_activation_history_option_name(); - update_option( - $activation_history_option_name, - array($this->_addon->version() => array(current_time('mysql'))) - ); - $db_state = get_option(EE_Data_Migration_Manager::current_database_state); - $db_state['New_Addon'] = $this->_addon->version(); - update_option(EE_Data_Migration_Manager::current_database_state, $db_state); - //set the activator option - update_option($this->_addon->get_activation_indicator_option_name(), true); - $this->assertWPOptionExists($this->_addon->get_activation_indicator_option_name()); - $times_its_new_install_hook_fired_before = isset($wp_actions["AHEE__{$this->_addon_classname}__reactivation"]) - ? $wp_actions["AHEE__{$this->_addon_classname}__reactivation"] : 0; - //now check for activations/upgrades in addons - EE_System::reset(); - $this->assertEquals(EE_System::req_type_reactivation, $this->_addon->detect_req_type()); - $this->assertEquals( - $times_its_new_install_hook_fired_before + 1, - $wp_actions["AHEE__{$this->_addon_classname}__reactivation"] - ); - $this->assertEquals( - EE_Maintenance_Mode::level_0_not_in_maintenance, - EE_Maintenance_Mode::instance()->level() - ); - $this->assertWPOptionDoesNotExist($this->_addon->get_activation_indicator_option_name()); - //ok all done - EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_0_not_in_maintenance); - } - - - /** - * Checks that even though the addon was activated, because it happened during - * maintenance mode, we couldn't do any of its setup logic. (SO it should be run - * later, when the site is taken out of MM) - * - * @global array $wp_actions - * @group 6812 - * @group 6910 - */ - public function test_detect_actiavtions_or_upgrade__activation_during_maintenance_mode() - { - global $wp_actions; - //its activation history wp option shouldn't exist - delete_option($this->_addon->get_activation_history_option_name()); - //and it also shouldn't be in the current db state - $current_db_state = get_option(EE_Data_Migration_Manager::current_database_state); - //just for assurance, make sure New Addon is the only existing addon - unset($current_db_state[$this->_addon_name]); - update_option(EE_Data_Migration_Manager::current_database_state, $current_db_state); - $times_reactivation_hook_fired_before = isset($wp_actions["AHEE__{$this->_addon_classname}__new_install"]) - ? $wp_actions["AHEE__{$this->_addon_classname}__new_install"] : 0; - //set the activator option - update_option($this->_addon->get_activation_indicator_option_name(), true); - $this->assertWPOptionExists($this->_addon->get_activation_indicator_option_name()); - //lastly, and imporatntly ADD A DMS SO MAINTENANCE MODE will be set - $this->_add_mock_dms(); - //now check for activations/upgrades in addons - EE_System::reset(); - $this->assertEquals( - EE_Maintenance_Mode::level_2_complete_maintenance, - EE_Maintenance_Mode::instance()->level() - ); - $this->assertEquals(EE_System::req_type_new_activation, $this->_addon->detect_req_type()); - $this->assertEquals( - $times_reactivation_hook_fired_before + 1, - isset($wp_actions["AHEE__{$this->_addon_classname}__new_install"]) - ? $wp_actions["AHEE__{$this->_addon_classname}__new_install"] : 0 - ); - $this->assertArrayContains( - 'New_Addon', - EE_Data_Migration_Manager::instance()->get_db_initialization_queue() - ); - $this->assertWPOptionDoesNotExist($this->_addon->get_activation_indicator_option_name()); - $this->assertTableDoesNotExist('esp_new_addon_thing'); - //ok, now let's pretend the site was teaken out of MM because migrations were finished - $this->_remove_mock_dms(); - EE_Maintenance_Mode::reset()->set_maintenance_level(EE_Maintenance_Mode::level_0_not_in_maintenance); - EE_Data_Migration_Manager::instance()->initialize_db_for_enqueued_ee_plugins(); - //now we also want to check that the addon will have created the necessary table - //that it needed upon new activation - $this->assertEquals( - array(), - EE_Data_Migration_Manager::instance()->check_for_applicable_data_migration_scripts() - ); - $this->assertEquals( - EE_Maintenance_Mode::level_0_not_in_maintenance, - EE_Maintenance_Mode::instance()->real_level() - ); - $this->assertTableExists('esp_new_addon_thing'); - //check for activations/upgrades again. It should be a normal request - EE_System::reset(); - $this->assertEquals(EE_System::req_type_normal, $this->_addon->detect_req_type()); - $this->assertEquals( - $times_reactivation_hook_fired_before + 1, - $wp_actions["AHEE__{$this->_addon_classname}__new_install"] - ); - $this->assertWPOptionDoesNotExist($this->_addon->get_activation_indicator_option_name()); - } - - - /** - * Checks that even though the addon was upgraded, because it happened during - * maintenance mode, we couldn't do any of its setup logic. (SO it should be run - * later, when the site is taken out of MM by the migration manager) - * - * @group 6910 - */ - public function test_detect_actiavtions_or_upgrade__upgrade_during_maintenance_mode() - { - global $wp_actions; - //pretend an older version of this addon was activated a while ago - $addon_activation_history = array( - '0.9.0.dev.000' => array( - date('Y-m-d H:i:s', current_time('timestamp') - DAY_IN_SECONDS * 10), - ), - ); - update_option($this->_addon->get_activation_history_option_name(), $addon_activation_history); - //and it also shouldn't be in the current db state - $current_db_state = get_option(EE_Data_Migration_Manager::current_database_state); - //just for assurance, make sure New Addon is the only existing addon - unset($current_db_state[$this->_addon_name]); - update_option(EE_Data_Migration_Manager::current_database_state, $current_db_state); - $times_reactivation_hook_fired_before = isset($wp_actions["AHEE__{$this->_addon_classname}__upgrade"]) - ? $wp_actions["AHEE__{$this->_addon_classname}__upgrade"] : 0; - //lastly, and importantly SET MAINTENANCE MODE LEVEL 2 - $this->_add_mock_dms(); - //now check for activations/upgrades in addons - EE_System::reset(); - $this->assertEquals( - EE_Maintenance_Mode::level_2_complete_maintenance, - EE_Maintenance_Mode::instance()->level() - ); - $this->assertEquals(EE_System::req_type_upgrade, $this->_addon->detect_req_type()); - $this->assertEquals( - $times_reactivation_hook_fired_before + 1, - isset($wp_actions["AHEE__{$this->_addon_classname}__upgrade"]) - ? $wp_actions["AHEE__{$this->_addon_classname}__upgrade"] : 0 - ); - $this->assertArrayContains( - 'New_Addon', - EE_Data_Migration_Manager::instance()->get_db_initialization_queue() - ); - $addon_activation_history = $this->_addon->get_activation_history(); - $this->assertArrayHasKey('0.9.0.dev.000', $addon_activation_history); - $this->assertArrayHasKey('1.0.0.dev.000', $addon_activation_history); - $this->assertTableDoesNotExist('esp_new_addon_thing'); - //ok, now let's pretend the site was taken out of MM because migrations were finished - $this->_remove_mock_dms(); - EE_Maintenance_Mode::reset()->set_maintenance_level(EE_Maintenance_Mode::level_0_not_in_maintenance); - EE_Data_Migration_Manager::instance()->initialize_db_for_enqueued_ee_plugins(); - //now we also want to check that the addon will have created the necessary table - //that it needed upon new activation - $this->assertEquals( - array(), - EE_Data_Migration_Manager::instance()->check_for_applicable_data_migration_scripts() - ); - $this->assertEquals( - EE_Maintenance_Mode::level_0_not_in_maintenance, - EE_Maintenance_Mode::instance()->real_level() - ); - $this->assertTableExists('esp_new_addon_thing'); - //check for activations/upgrades again. It should be a normal request - EE_System::reset(); - $this->assertEquals(EE_System::req_type_normal, $this->_addon->detect_req_type()); - $this->assertEquals( - $times_reactivation_hook_fired_before + 1, - $wp_actions["AHEE__{$this->_addon_classname}__upgrade"] - ); - $this->assertWPOptionDoesNotExist($this->_addon->get_activation_indicator_option_name()); - } -} - -// End of file EE_System_Test_With_Addons.php -// Location: tests/testcases/core/EE_System_Test_With_Addons.php diff --git a/tests/testcases/core/EeSystemWithAddonTest.php b/tests/testcases/core/EeSystemWithAddonTest.php deleted file mode 100644 index 6e6826b8031..00000000000 --- a/tests/testcases/core/EeSystemWithAddonTest.php +++ /dev/null @@ -1,38 +0,0 @@ -pretendReactivation(); - //do our assertions - $this->assertWPOptionExists($this->addon->get_activation_indicator_option_name()); - $this->assertEquals(EE_System::req_type_reactivation, $this->addon->detect_req_type()); - - //test EE_System reset which simulates activation/upgrades - //simulate activation process - EE_System::reset(); - $this->assertEquals( - $times_its_new_install_hook_fired_before + 1, - $wp_actions["AHEE__EE_NewAddonMock__reactivation"] - ); - $this->assertWPOptionDoesNotExist($this->addon->get_activation_indicator_option_name()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/Psr4AutoloaderTest.php b/tests/testcases/core/Psr4AutoloaderTest.php deleted file mode 100644 index 5c28056d037..00000000000 --- a/tests/testcases/core/Psr4AutoloaderTest.php +++ /dev/null @@ -1,90 +0,0 @@ -loader = new Psr4AutoloaderMock; - $this->loader->setFiles( array( - '/vendor/foo.bar/src/ClassName.php', - '/vendor/foo.bar/src/DoomClassName.php', - '/vendor/foo.bar/tests/ClassNameTest.php', - '/vendor/foo.bardoom/src/ClassName.php', - '/vendor/foo.bar.baz.dib/src/ClassName.php', - '/vendor/foo.bar.baz.dib.zim.gir/src/ClassName.php', - ) ); - $this->loader->addNamespace( - 'Foo\Bar', - '/vendor/foo.bar/src' - ); - $this->loader->addNamespace( - 'Foo\Bar', - '/vendor/foo.bar/tests' - ); - $this->loader->addNamespace( - 'Foo\BarDoom', - '/vendor/foo.bardoom/src' - ); - $this->loader->addNamespace( - 'Foo\Bar\Baz\Dib', - '/vendor/foo.bar.baz.dib/src' - ); - $this->loader->addNamespace( - 'Foo\Bar\Baz\Dib\Zim\Gir', - '/vendor/foo.bar.baz.dib.zim.gir/src' - ); - } - - - - public function testExistingFile() { - $actual = $this->loader->loadClass( 'Foo\Bar\ClassName' ); - $expect = '/vendor/foo.bar/src/ClassName.php'; - $this->assertSame( $expect, $actual ); - $actual = $this->loader->loadClass( 'Foo\Bar\ClassNameTest' ); - $expect = '/vendor/foo.bar/tests/ClassNameTest.php'; - $this->assertSame( $expect, $actual ); - } - - - - public function testMissingFile() { - $actual = $this->loader->loadClass( 'No_Vendor\No_Package\NoClass' ); - $this->assertFalse( $actual ); - } - - - - public function testDeepFile() { - $actual = $this->loader->loadClass( 'Foo\Bar\Baz\Dib\Zim\Gir\ClassName' ); - $expect = '/vendor/foo.bar.baz.dib.zim.gir/src/ClassName.php'; - $this->assertSame( $expect, $actual ); - } - - - - public function testConfusion() { - $actual = $this->loader->loadClass( 'Foo\Bar\DoomClassName' ); - $expect = '/vendor/foo.bar/src/DoomClassName.php'; - $this->assertSame( $expect, $actual ); - $actual = $this->loader->loadClass( 'Foo\BarDoom\ClassName' ); - $expect = '/vendor/foo.bardoom/src/ClassName.php'; - $this->assertSame( $expect, $actual ); - } - - - -} -// End of file Psr4AutoloaderTest.php -// Location: /tests/testcases/core/Psr4AutoloaderTest.php \ No newline at end of file diff --git a/tests/testcases/core/admin/EE_Admin_Hooks_Tests.php b/tests/testcases/core/admin/EE_Admin_Hooks_Tests.php deleted file mode 100644 index de59c6b9c66..00000000000 --- a/tests/testcases/core/admin/EE_Admin_Hooks_Tests.php +++ /dev/null @@ -1,220 +0,0 @@ -loadAdminMocks(); - $this->_eeAdminMock = new Admin_Mock_Valid_Admin_Page(false); - $this->_testRoute = admin_url('admin.php?page=mock_valid_admin_page'); - - //go to mock_valid_admin_page route for test - $this->go_to($this->_testRoute); - $this->defineAdminConstants(); - $this->_eeAdminHookMock = new mock_valid_admin_page_Admin_Mock_Valid_Hooks( $this->_eeAdminMock ); - } - - - /** - * This tests a valid admin hook construct. - * - * Not only will this catch anything wrong with constructing a - * Admin_Hook but we're also testing that public properties - * and methods perform as expected. - * - * @since 4.3.0 - */ - public function test_valid_constructor() { - //test things setup after construct - $this->assertTrue( $this->_eeAdminHookMock->verify_adminpage_obj() instanceof Admin_Mock_Valid_Admin_Page ); - $this->assertFalse( $this->_eeAdminHookMock->verify_extend() ); - } - - /** - * @since 4.3.0 - * @depends test_valid_constructor - */ - public function test_enqueue_scripts_styles() { - $this->_eeAdminHookMock->enqueue_scripts_styles(); - $this->assertTrue( wp_style_is( 'test-css', 'registered' ) ); - $this->assertTrue( wp_style_is( 'test-css' ) ); - $this->assertFalse( wp_style_is( 'event-editor-css', 'registered' ) ); - $this->assertTrue( wp_script_is( 'test-js', 'registered' ) ); - $this->assertTrue( wp_script_is( 'test-js' ) ); - - //test exception if no registers index in _scripts_styles property. - $scripts_styles_cache = $this->_eeAdminHookMock->get_property( '_scripts_styles' ); - - //let's set a scripts styles array with no registers. - $new_scripts_styles['something'] = 'fail'; - $this->_eeAdminHookMock->set_property( '_scripts_styles', $new_scripts_styles ); - $this->setExpectedException('EE_Error'); - $this->_eeAdminHookMock->enqueue_scripts_styles(); - - - //test for exception with missing params - $this->_eeAdminHookMock->set_property( '_scripts_styles', $scripts_styles_cache ); - $new_scripts_styles = $scripts_styles_cache; - unset( $new_scripts_styles['registers']['test-css']['url'] ); - $this->_eeAdminHookMock->set_property( '_scripts_styles', $new_scripts_styles ); - $this->setExpectedException('EE_Error'); - $this->_eeAdminHookMock->enqueue_scripts_styles(); - - //restore correct scripts styles - $this->_eeAdminHookMock->set_property( '_scripts_styles', $scripts_styles_cache ); - } - - - /** - * @since 4.3.0 - * @depends test_valid_constructor - */ - public function test__set_defaults() { - $this->assertEquals( 'default', $this->_eeAdminHookMock->verify_current_route() ); - $this->assertEquals( $this->_eeAdminHookMock->caller, 'mock_valid_admin_page_Admin_Mock_Valid_Hooks' ); - $this->assertFalse( $this->_eeAdminHookMock->verify_extend() ); - } - - - /** - * @since 4.3.0 - * @depends test_valid_constructor - */ - public function test__set_page_object() { - $this->assertTrue( $this->_eeAdminHookMock->verify_page_object() instanceof Admin_Mock_Valid_Admin_Page ); - - //test exception if _name is empty - $cached_name = $this->_eeAdminHookMock->get_property( '_name' ); - $this->_eeAdminHookMock->set_property( '_name', NULL ); - $this->setExpectedException( 'EE_Error' ); - $this->_eeAdminHookMock->call_method( '_set_page_object' ); - - //test exception if class does not exist - $this->_eeAdminHookMock->set_property( '_name', 'fail' ); - $this->setExpectedException( 'EE_Error' ); - $this->_eeAdminHookMock->call_method( '_set_page_object' ); - - //restore _name - $this->_eeAdminHookMock->set_property( '_name', $cached_name ); - } - - - /** - * @since 4.3.0 - * @depends test_valid_constructor - */ - public function test__init_hooks() { - $this->assertEquals( has_filter( 'admin_init', array( $this->_eeAdminHookMock, 'init_callback_test' ) ), 10 ); - - //test exception if method doesn't exist - $cached_init_func = $this->_eeAdminHookMock->get_property( '_init_func' ); - $this->_eeAdminHookMock->set_property( '_init_func', array( 'fail' => 'fail' ) ); - $this->setExpectedException( 'EE_Error' ); - $this->_eeAdminHookMock->call_method( '_init_hooks' ); - - //restore - $this->_eeAdminHookMock->set_property( '_init_func', $cached_init_func ); - } - - - - - /** - * This tests the addition of metaboxes which actually gets - * kicked off by the public add_metaboxes method. - * - * @since 4.3.0 - * @depends test_valid_constructor - */ - public function test__add_metabox() { - //test exception if the callback for the metabox doesn't exist - $cached_metabox = $this->_eeAdminHookMock->get_property( '_metaboxes' ); - $new_metabox = $cached_metabox; - $new_metabox[0]['func'] = 'invalid'; - $this->_eeAdminHookMock->set_property( '_metaboxes', $new_metabox ); - $this->setExpectedException( 'EE_Error' ); - $this->_eeAdminHookMock->add_metaboxes(); - //restore - $this->_eeAdminHookMock->set_property( '_metaboxes', $cached_metabox ); - } - - - - /** - * @since 4.3.0 - * @depends test_valid_constructor - */ - public function test__load_custom_methods() { - $this->assertTrue( $this->_eeAdminHookMock->route_callback ); - $this->assertEquals( has_action('AHEE__Admin_Mock_Valid_Admin_Page___redirect_after_action__before_redirect_modification_default', array( $this->_eeAdminHookMock, '_redirect_action_early_default' ) ), 10 ); - $this->assertEquals( has_action('AHEE_redirect_Admin_Mock_Valid_Admin_Pagedefault', array( $this->_eeAdminHookMock, '_redirect_action_default' ) ), 10 ); - $this->assertEquals( has_filter( 'FHEE_redirect_Admin_Mock_Valid_Admin_Pagedefault', array( $this->_eeAdminHookMock, '_redirect_filter_default' ) ), 10 ); - } - - - - /** - * @since 4.3.0 - * @depends test_valid_constructor - */ - public function test__load_routed_hooks() { - $this->assertEquals( has_action('admin_footer', array( $this->_eeAdminHookMock, 'default_admin_footer' ) ), 10 ); - $this->assertEquals( has_filter( 'FHEE_list_table_views_mock_valid_admin_page_default', array( $this->_eeAdminHookMock, 'default_FHEE_list_table_views_mock_valid_admin_page_default' ) ), 10 ); - $this->assertEquals( has_filter( 'FHEE_list_table_views_mock_valid_admin_page', array( $this->_eeAdminHookMock, 'default_FHEE_list_table_views_mock_valid_admin_page' ) ), 10 ); - $this->assertEquals( has_filter( 'FHEE_list_table_views', array( $this->_eeAdminHookMock, 'default_FHEE_list_table_views' ) ), 10 ); - $this->assertEquals( has_action( 'AHEE__EE_Admin_Page___display_admin_page__modify_metaboxes', array( $this->_eeAdminHookMock, 'default_AHEE__EE_Admin_Page___display_admin_page__modify_metaboxes') ), 10 ); - } - - - - /** - * @since 4.3.0 - * @depends test_valid_constructor - */ - public function test__ajax_hooks() { - $this->assertEquals( has_action( 'wp_ajax_ajax_test', array( $this->_eeAdminHookMock, 'ajax_test_callback' ) ), 10 ); - } - - - - /** - * This tests the loading of an EE_Admin_Page_Hooks class that is setup incorrectly. (it'll just return really early). - * - * @since 4.3.0 - */ - public function test_invalid_constructor() { - $this->go_to( admin_url() ); - //go to mock_valid_admin_page route for test - $this->_eeAdminHookMock = new dummy_not_exist_Hooks( $this->_eeAdminMock ); - - //should have exited early so there should be no page object set. - $this->assertEmpty( $this->_eeAdminHookMock->verify_page_object() ); - } - - -} - -//class EE_Admin_Hook diff --git a/tests/testcases/core/admin/EE_Admin_Tests.php b/tests/testcases/core/admin/EE_Admin_Tests.php deleted file mode 100644 index 8e59dd184ff..00000000000 --- a/tests/testcases/core/admin/EE_Admin_Tests.php +++ /dev/null @@ -1,335 +0,0 @@ -load_core('EE_Admin'); - $this->assertInstanceOf('EE_Admin', $admin_instance); - - //tests filters have been added that are expected here. Remember the has_{filter/action} returns the priority set by the caller. - $this->assertEquals( has_filter('plugin_action_links', array($admin_instance, 'filter_plugin_actions') ), 10 ); - $this->assertEquals( has_action('AHEE__EE_System__core_loaded_and_ready', array($admin_instance, 'get_request') ), 10 ); - $this->assertEquals( has_action('AHEE__EE_System__initialize_last', array($admin_instance, 'init') ), 10 ); - $this->assertEquals( has_action('AHEE__EE_Admin_Page__route_admin_request', array($admin_instance, 'route_admin_request') ), 100 ); - $this->assertEquals( has_action('wp_loaded', array($admin_instance, 'wp_loaded') ), 100 ); - $this->assertEquals( has_action('admin_init', array($admin_instance, 'admin_init') ), 100 ); - $this->assertEquals( has_action('admin_enqueue_scripts', array($admin_instance, 'enqueue_admin_scripts') ), 20 ); - $this->assertEquals( has_action('admin_notices', array($admin_instance, 'display_admin_notices') ), 10 ); - $this->assertEquals( has_filter('admin_footer_text', array($admin_instance, 'espresso_admin_footer') ), 10 ); - } - - /** - * Tests constants that should be defined after EE_Admin::__construct() - * - * @since 4.3.0 - * - * @depends test_loading_admin - */ - public function test_define_all_constants() { - $this->assertTrue( defined('EE_ADMIN_URL') ); - $this->assertTrue( defined('EE_ADMIN_PAGES_URL') ); - $this->assertTrue( defined('EE_ADMIN_TEMPLATE') ); - $this->assertTrue( defined('WP_ADMIN_PATH' ) ); - $this->assertTrue( defined('WP_AJAX_URL') ); - } - - - - /** - * Tests that the filter_plugin_actions callback for plugin_action_links works as expected. - * - * @since 4.3.0 - * - * @depends test_loading_admin - */ - public function test_filter_plugin_actions() { - //make sure maintenance class is loaded and set to 0 - $this->setMaintenanceMode(); - $main_file = EE_PLUGIN_BASENAME; - $original_link = array('link'); - $expected = array('' . __( 'Settings', 'event_espresso' ) . '', '' . __( 'Events', 'event_espresso' ) . '', 'link'); - - //first test if plugin does NOT equal main file. - $filtered = EE_Admin::instance()->filter_plugin_actions( $original_link, 'fail' ); - $this->assertEquals( $original_link, $filtered ); - - //test if plugin DOES equal main file and maintenance mode level left at 0. - $filtered = EE_Admin::instance()->filter_plugin_actions( $original_link, $main_file ); - $this->assertEquals( $expected, $filtered ); - - //test if plugin DOES equal main file and maintenance mode level is 1. - $this->setMaintenanceMode(1); - $filtered = EE_Admin::instance()->filter_plugin_actions( $original_link, $main_file ); - $this->assertEquals( $expected, $filtered ); - - //test if plugin DOES equal main file and maintenance mode level is 2. - $this->setMaintenanceMode(2); - $expected = array('' . __('Maintenance Mode Active', 'event_espresso' ) . '', 'link'); - $filtered = EE_Admin::instance()->filter_plugin_actions($original_link, $main_file); - $this->assertEquals( $expected, $filtered ); - - //set maintenance mode back to normal. - $this->setMaintenanceMode(); - } - - - - - /** - * ensure that Request Handler and CPT_Strategy classes are loaded by the get_request method - * as expected. - * - * @since 4.3.0 - * - * @depends test_loading_admin - */ - public function test_get_request() { - EE_Admin::instance()->get_request(); - $this->assertTrue( class_exists('EE_Request_Handler') ); - $this->assertTrue( class_exists('EE_CPT_Strategy') ); - } - - - - - - /** - * This tests the init callback in EE_Admin. - * - * @since 4.3.0 - * - * @depends test_loading_admin - */ - public function test_init() { - $admin = EE_Admin::instance(); - - //test when maintenance mode is set at level 2 - $this->setMaintenanceMode(2); - $admin->init(); - $this->assertFalse( has_action('dashboard_glance_items', array( $admin, 'dashboard_glance_items' ) ) ); - $this->assertFalse( has_filter( 'get_edit_post_link', array( $admin, 'modify_edit_post_link') ) ); - //should happen with both conditions - $this->assertEquals( has_filter( 'content_save_pre', array( $admin, 'its_eSpresso' ) ), 10 ); - $this->assertEquals( has_action('admin_head', array( $admin, 'enable_hidden_ee_nav_menu_metaboxes' ) ), 10 ); - $this->assertEquals( has_action('admin_head', array( $admin, 'register_custom_nav_menu_boxes' ) ), 10 ); - $this->assertEquals( has_filter('nav_menu_meta_box_object', array( $admin, 'remove_pages_from_nav_menu' ) ), 10 ); - - //test when maintenance mode is set to something other than 2 - $this->setMaintenanceMode(); - //reset filters for test - $this->clearAllFilters( array('FHEE__EE_Admin_Page_Loader___get_installed_pages__installed_refs') ); - - $admin->init(); - - $this->assertFalse( has_filter('FHEE__EE_Admin_Page_Loader___get_installed_pages__installed_refs', array( $admin, 'hide_admin_pages_except_maintenance_mode' ) ) ); - $this->assertEquals( has_filter('content_save_pre', array( $admin, 'its_eSpresso' ) ), 10 ); - $this->assertEquals( has_action('dashboard_glance_items', array( $admin, 'dashboard_glance_items' ) ), 10 ); - //should happen with both conditions - $this->assertEquals( has_action('admin_head', array( $admin, 'enable_hidden_ee_nav_menu_metaboxes' ) ), 10 ); - $this->assertEquals( has_action('admin_head', array( $admin, 'register_custom_nav_menu_boxes' ) ), 10 ); - $this->assertEquals( has_filter('nav_menu_meta_box_object', array( $admin, 'remove_pages_from_nav_menu' ) ), 10 ); - $this->assertEquals( has_filter( 'get_edit_post_link', array( $admin, 'modify_edit_post_link') ), 10 ); - - //default should have Admin Page Loader loaded up. - $this->assertTrue( class_exists( 'EE_Admin_Page_Loader' ) ); - } - - - - - /** - * Test callback for removing pages from nav menu - * - * @since 4.3.0 - * @depends test_loading_admin - */ - public function test_remove_pages_from_nav_menu() { - //test non page post type object - $posttypeStub = new stdClass(); - $posttypeStub->name = 'non_page'; - $expected = 'non_page'; - $result = EE_Admin::instance()->remove_pages_from_nav_menu( $posttypeStub ); - $this->assertEquals( $expected, $result->name ); - - //test when posttype DOES equal page - $posttypeStub->name = 'page'; - $this->setCoreConfig(); - $expected = EE_Registry::instance()->CFG->core->get_critical_pages_array(); - $result = EE_Admin::instance()->remove_pages_from_nav_menu( $posttypeStub ); - $test_response = !empty( $result->_default_query['post__not_in'] ) ? $result->_default_query['post__not_in'] : NULL; - $this->assertEquals( $expected, $test_response ); - } - - - /** - * test enable_hidden_ee_nav_menu_metaboxes() - * - * @since 4.3.0 - * @depends test_loading_admin - */ - public function test_enable_hidden_ee_nav_menu_metaboxes() { - - //first we'll add dummy metabox to simulate our metaboxes. - add_meta_box( 'add-espresso_events', __('Event Espresso Pages', 'event_espresso'), '__return_true', 'nav-menus', 'side', 'core' ); - - //need to set the current user - //$current_user = get_current_user_id(); - wp_set_current_user( $this->factory->user->create( array( 'role' => 'administrator' ) ) ); - - //set the current page to the be the nav-menus.php page - global $pagenow; - $pagenow = 'nav-menus.php'; - - //run test - //should be a registered metabox with the add-espresso_events id. - global $wp_meta_boxes; - $this->assertArrayHasKey( 'add-espresso_events', $wp_meta_boxes['nav-menus']['side']['core'], 'There should be a registered metabox with the key add-espresso_events and there isn\'t' ); - - //now let's verify that the method being tested works as expected - EE_Admin::instance()->enable_hidden_ee_nav_menu_metaboxes(); - $hidden_metaboxes = get_user_option( get_current_user_id(), 'metaboxhidden_nav-menus' ); - $this->assertEmpty( $hidden_metaboxes ); - } - - - - /** - * testing output for the dashboard upcoming widget hook callback - * - * @since 4.3.0 - * @depends test_loading_admin - */ - public function test_dashboard_glance_items() { - //add some events and registrations - $this->factory->event->create_many(10); - $this->factory->registration->create_many(5, array( 'STS_ID' => EEM_Registration::status_id_not_approved ) ); - $this->factory->registration->create_many(3); - - //expected events dashboard items - $xpct_events_url = EEH_URL::add_query_args_and_nonce( array( 'page' => 'espresso_events'), admin_url('admin.php') ); - $xpct_events_text = sprintf( _n( '%s Event', '%s Events', 10 ), number_format_i18n( 10 ) ); - $xpct_events_title = __('Click to view all Events', 'event_espresso'); - $xpct_event_assembled = sprintf( '%s', $xpct_events_url, $xpct_events_title, $xpct_events_text ); - - //expected registration dashboard items - $xpct_registration_url = EEH_URL::add_query_args_and_nonce( array('page' => 'espresso_registrations' ), admin_url('admin.php') ); - $xpct_registration_text = sprintf( _n( '%s Registration', '%s Registrations', 5 ), number_format_i18n(5) ); - $xpct_registration_title = __('Click to view all registrations', 'event_espresso'); - $xpct_registration_assembled = sprintf( '%s', $xpct_registration_url, $xpct_registration_title, $xpct_registration_text ); - - $generated_items = EE_Admin::instance()->dashboard_glance_items( array() ); - //first assert the elements are an array. - $this->assertInternalType('array', $generated_items); - - //assert the count for the array is two - $this->assertCount( - 2, - $generated_items, - sprintf('$generated_items should have 2 elements: ', print_r($generated_items, true)) - ); - - //assert that the first item matches the xpctd event string. - $this->assertEquals( $xpct_event_assembled, $generated_items[0] ); - - //assert that the second item matches the xpctd registration string - $this->assertEquals( $xpct_registration_assembled, $generated_items[1] ); - } - - //@todo public methods to write tests for - - //function test_dashboard_glance_items() - //function test_parse_post_content_on_save() - - - /** - * Test its_eSpresso method that converts incorrect spelling of Espresso in shortcodes with the correct spelling. - * - * @since 4.3.0 - * @depends test_loading_admin - */ - public function test_its_eSpresso() { - //test works as expected with string to correct. - $expected = '[ESPRESSO_CONTENT]'; - $test = '[EXPRESSO_CONTENT]'; - $result = EE_Admin::instance()->its_eSpresso( $test ); - $this->assertEquals( $result, $expected ); - - //test works as expected with string that should NOT be corrected. - $expected = 'some_string'; - $result = EE_Admin::instance()->its_eSpresso('some_string'); - $this->assertEquals( $result, $expected ); - } - - - - - /** - * Test the powered by Event Espresso footer. - * - * @since 4.3.0 - * @depends test_loading_admin - */ - public function test_espresso_admin_footer() { - // simulate being on admin page. For the purpose of this test it doesn't matter what admin page it is. - // we don't want modules or shortcodes loading for this test so let's unset that. - set_current_screen('user-new'); - $actual = EE_Admin::instance()->espresso_admin_footer(); - //assert contains powered by text. - $this->assertContains('Online event registration and ticketing powered by ', $actual); - //assert contains eventespresso.com link - $this->assertContains('https://eventespresso.com/', $actual); - global $current_screen; - $current_screen = null; - } - - - - /** - * Test the filter callback for get_edit_post_link - * - * @since 4.3.0 - * @depends test_loading_admin - */ - public function test_modify_edit_post_link() { - //add contact post - $attendee = EE_Attendee::new_instance( array( 'ATT_full_name' => 'Test Dude' ) ); - $attendee->save(); - $id = $attendee->ID(); - - //dummy link for testing - $orig_link = 'http://testdummylink.com'; - $expected_link = EEH_URL::add_query_args_and_nonce( array( 'action' => 'edit_attendee', 'post' => $id ), admin_url('admin.php?page=espresso_registrations' ) ); - - //first test that if the id given doesn't match our post type that the original link is returned. - $notmodified = EE_Admin::instance()->modify_edit_post_link( $orig_link, 5555, '' ); - $this->assertEquals( $orig_link, $notmodified ); - - //next test that if the id given matches our post type that the expected link is generated - $ismodified = EE_Admin::instance()->modify_edit_post_link( $orig_link, $id, '' ); - - $this->assertEquals( $expected_link, $ismodified ); - } - -} -// Location: testcases/core/admin/EE_Admin_Tests.php diff --git a/tests/testcases/core/business/EE_Registration_Processor_Test.php b/tests/testcases/core/business/EE_Registration_Processor_Test.php deleted file mode 100644 index 6fc79febda3..00000000000 --- a/tests/testcases/core/business/EE_Registration_Processor_Test.php +++ /dev/null @@ -1,41 +0,0 @@ -new_model_obj_with_dependencies( 'Transaction' , array( 'TXN_total' => 2.99)); - $regs = array(); - for( $i=0; $i<3; $i++ ) { - $regs[] = $this->new_model_obj_with_dependencies( 'Registration', array( 'REG_final_price' => 1, 'TXN_ID' => $txn->ID() ) ); - } - //ok so there's a 1 cent difference. The REG_final_price_sum should be 1 cent more than the transaction total - $reg_final_price_sum = EEM_Registration::instance()->sum( array( array( 'TXN_ID' => $txn->ID() ) ), 'REG_final_price' ); - $this->assertEquals( $txn->total() + 0.01, $reg_final_price_sum ); - - $reg_processor = EE_Registry::instance()->load_class( 'Registration_Processor' ); - $success = $reg_processor->fix_reg_final_price_rounding_issue( $txn ); - $this->assertTrue( $success ); - $new_reg_final_price_sum = EEM_Registration::instance()->sum( array( array( 'TXN_ID' => $txn->ID() ) ), 'REG_final_price' ); - $this->assertEquals( $txn->total(), $new_reg_final_price_sum ); - //specifically, the first reg should now be $0.99, but the others should still be $1 each - $this->assertEquals( .99, $regs[0]->final_price() ); - $this->assertEquals( 1, $regs[1]->final_price() ); - $this->assertEquals( 1, $regs[2]->final_price() ); - } -} - -// End of file EE_Registration_Processor_Test.php \ No newline at end of file diff --git a/tests/testcases/core/data_migration_scripts/EE_DMS_Core_4_10_0_Tests.php b/tests/testcases/core/data_migration_scripts/EE_DMS_Core_4_10_0_Tests.php deleted file mode 100644 index 8023b16c8b0..00000000000 --- a/tests/testcases/core/data_migration_scripts/EE_DMS_Core_4_10_0_Tests.php +++ /dev/null @@ -1,226 +0,0 @@ -new_model_obj_with_dependencies('Event'); - $e->add_question_group(1, true); - $this->assertEquals(1, EEM_Event_Question_Group::instance()->count()); - $this->migrateFiveEventQuestionGroups(); - // It should have actually not migrated anything over. - $this->assertEquals(1, EEM_Event_Question_Group::instance()->count()); - } - - /** - * An event with personal and address question group for primary attendees. - * @since 4.10.0.p - */ - public function testMigratePersonalAndAdditionalForPrimary() - { - $e = $this->new_model_obj_with_dependencies('Event'); - $e->add_question_group(1, true); - $e->add_question_group(2, true); - $this->assertEquals(2, EEM_Event_Question_Group::instance()->count()); - $this->migrateFiveEventQuestionGroups(); - $this->assertEquals(2, EEM_Event_Question_Group::instance()->count()); - foreach(EEM_Event_Question_Group::instance()->get_all() as $eqg) { - $this->assertTrue($eqg->get('EQG_primary')); - $this->assertFalse($eqg->get('EQG_additional')); - } - } - - /** - * An event with personal question group for primary and additional attendees. - * @since 4.10.0.p - */ - public function testMigratePersonalForPrimaryAndAdditional() - { - $e = $this->new_model_obj_with_dependencies('Event'); - $e->add_question_group(1, true); - // Manually enter the duplicate row. In 4.9 and lower, this meant the question group was for additional - // attendees. - EEM_Event_Question_Group::instance()->insert( - [ - 'EVT_ID' => $e->ID(), - 'QSG_ID' => 1, - 'EQG_primary' => false, - ] - ); - $this->assertEquals(2, EEM_Event_Question_Group::instance()->count()); - $this->migrateFiveEventQuestionGroups(); - // That "duplicate" row should have been removed... - $this->assertEquals(1, EEM_Event_Question_Group::instance()->count()); - // ...and `EQG_additional` should have been populated on the sole row. - $eqg = EEM_Event_Question_Group::instance()->get_one(); - $this->assertTrue($eqg->get('EQG_primary')); - $this->assertTrue($eqg->get('EQG_additional')); - - } - - /** - * Tests what happens when we need to do the migrations across multiple requests. - * In the first iteration of this script, this cause problems because we were modifying the original set, - * which made the limit part of our queries off. - * @since 4.10.0.p - */ - public function testMigrateMultipleSteps() - { - // Create 10 event-question-group rows that need to be migrated. - for($i=0; $i<10; $i++) { - $e = $this->new_model_obj_with_dependencies('Event'); - $e->add_question_group(1, true); - // Manually create a "duplicate" row that has EQG_primary=false. This was the old way of representing - // a question group that applied to additional attendees. - EEM_Event_Question_Group::instance()->insert( - [ - 'EVT_ID' => $e->ID(), - 'QSG_ID' => 1, - 'EQG_primary' => false - ] - ); - } - $this->assertEquals(20, EEM_Event_Question_Group::instance()->count()); - // Run two migration steps of size 5. - $stage = $this->migrateFiveEventQuestionGroups(); - $stage->migration_step(5); - - // All 10 of them should have been removed - $this->assertEquals(10, EEM_Event_Question_Group::instance()->count()); - } - - /** - * An event with personal question group for primary and additional attendees. - * @since 4.10.0.p - */ - public function testMigrateManyQuestionGroupslForPrimaryAndAdditional() - { - // Create 2 custom question groups. - $cqg1 = $this->new_model_obj_with_dependencies('Question_Group'); - $q1 = $this->new_model_obj_with_dependencies('Question'); - $cqg1->_add_relation_to($q1,'Question'); - $cqg2 = $this->new_model_obj_with_dependencies('Question_Group'); - $q2 = $this->new_model_obj_with_dependencies('Question'); - $cqg2->_add_relation_to($q2, 'Question'); - - // Create an event with ALL the question groups. - $e = $this->new_model_obj_with_dependencies('Event'); - $e->add_question_group(EEM_Question_Group::system_personal, true); - $e->add_question_group(EEM_Question_Group::system_address, true); - $e->add_question_group($cqg1, true); - $e->add_question_group($cqg2, true); - - foreach(array( - EEM_Question_Group::system_personal, - EEM_Question_Group::system_address, - $cqg1->ID(), - $cqg2->ID() - ) as $question_group_id) { - $e->add_question_group($question_group_id, true); - // Manually enter the duplicate row. In 4.9 and lower, this meant the question group was for additional - // attendees. - EEM_Event_Question_Group::instance()->insert( - [ - 'EVT_ID' => $e->ID(), - 'QSG_ID' => $question_group_id, - 'EQG_primary' => false, - ] - ); - } - - $this->assertEquals(8, EEM_Event_Question_Group::instance()->count()); - $this->migrateFiveEventQuestionGroups(); - $this->migrateFiveEventQuestionGroups(); - // That "duplicate" row should have been removed... - $this->assertEquals(4, EEM_Event_Question_Group::instance()->count()); - // And double-check we still find those groups are related. - $primary_attendee_question_groups = EEM_Event::instance()->get_event_question_groups($e->ID(), true); - $this->assertEquals(4, count($primary_attendee_question_groups)); - $additional_attendee_question_groups = EEM_Event::instance()->get_event_question_groups($e->ID(), false); - $this->assertEquals(4, count($additional_attendee_question_groups)); - } - - /** - * An event with personal question groups additional attendees only. - * @since 4.10.0.p - */ - public function testMigrateManyQuestionGroupslForAdditionalAttendeesOnly() - { - // Create 2 custom question groups. - $cqg1 = $this->new_model_obj_with_dependencies('Question_Group'); - $q1 = $this->new_model_obj_with_dependencies('Question'); - $cqg1->_add_relation_to($q1,'Question'); - $cqg2 = $this->new_model_obj_with_dependencies('Question_Group'); - $q2 = $this->new_model_obj_with_dependencies('Question'); - $cqg2->_add_relation_to($q2, 'Question'); - - // Create an event with ALL the question groups. - $e = $this->new_model_obj_with_dependencies('Event'); - $e->add_question_group(EEM_Question_Group::system_personal, true); - - foreach(array( - EEM_Question_Group::system_personal, - EEM_Question_Group::system_address, - $cqg1->ID(), - $cqg2->ID() - ) as $question_group_id) { - - // Manually enter the duplicate row. In 4.9 and lower, this meant the question group was for additional - // attendees. - EEM_Event_Question_Group::instance()->insert( - [ - 'EVT_ID' => $e->ID(), - 'QSG_ID' => $question_group_id, - 'EQG_primary' => false, - ] - ); - } - - $this->assertEquals(5, EEM_Event_Question_Group::instance()->count()); - $this->migrateFiveEventQuestionGroups(); - $this->migrateFiveEventQuestionGroups(); - // That "duplicate" row should have been removed... - $this->assertEquals(4, EEM_Event_Question_Group::instance()->count()); - // And double-check we still find those groups are related. - $primary_attendee_question_groups = EEM_Event::instance()->get_event_question_groups($e->ID(), true); - $this->assertEquals(1, count($primary_attendee_question_groups)); - $additional_attendee_question_groups = EEM_Event::instance()->get_event_question_groups($e->ID(), false); - $this->assertEquals(4, count($additional_attendee_question_groups)); - } - - - // More than 50 question groups (make sure they all get migrated) - - - protected function migrateFiveEventQuestionGroups() - { - $script = LoaderFactory::getLoader()->getShared('EE_DMS_Core_4_10_0'); - $stage = new EE_DMS_4_10_0_Event_Question_Group(); - $stage->migration_step(5); - return $stage; - } -} - -// End of file EE_DMS_4_10_0_Tests.php \ No newline at end of file diff --git a/tests/testcases/core/data_migration_scripts/EE_DMS_Core_4_1_0_Tests.php b/tests/testcases/core/data_migration_scripts/EE_DMS_Core_4_1_0_Tests.php deleted file mode 100644 index b070cddc25f..00000000000 --- a/tests/testcases/core/data_migration_scripts/EE_DMS_Core_4_1_0_Tests.php +++ /dev/null @@ -1,31 +0,0 @@ -assertTrue( $this->table_exists_check( 'esp_event_message_template' ) ); - } - - function table_exists_check( $name ) { - global $wpdb; - $table_name = $wpdb->prefix . $name; - return $wpdb->get_var( "SHOW TABLES LIKE '$table_name'" ) == $table_name; - } -} diff --git a/tests/testcases/core/data_migration_scripts/EE_DMS_Core_4_6_0_Tests.php b/tests/testcases/core/data_migration_scripts/EE_DMS_Core_4_6_0_Tests.php deleted file mode 100644 index 981c2d69a32..00000000000 --- a/tests/testcases/core/data_migration_scripts/EE_DMS_Core_4_6_0_Tests.php +++ /dev/null @@ -1,46 +0,0 @@ -new_model_obj_with_dependencies( 'Attendee' ); - $att1->update_post_meta( $postmeta_name, $billing_info ); - $att2 = $this->new_model_obj_with_dependencies( 'Attendee' ); - $att2->update_post_meta( $postmeta_name, $billing_info ); - - //load teh dms, which should autoload the stage we want to test - $script = EE_Registry::instance()->load_dms( 'EE_DMS_Core_4_6_0' ); - $stage = new EE_DMS_4_6_0_billing_info(); - $stage->_construct_finalize( $script ); - $this->assertEquals( 2, $stage->count_records_to_migrate() ); -// var_dump($stage); - $stage->migration_step( 1 ); - $this->assertEquals( 1, $stage->count_records_migrated() ); - //get that updated postmeta - $new_billing_info = $att1->get_post_meta( $postmeta_name, TRUE ); - $this->assertNotEquals( $billing_info, $new_billing_info ); - $this->assertArrayHasKey( 'first_name', $new_billing_info ); - //verify we only migrated what we said we would- the first item only - $this->assertEquals( $billing_info, $att2->get_post_meta( $postmeta_name, TRUE ) ); - - - //now migrate the next one - $stage->migration_step( 1 ); - } -} - -// End of file EE_DMS_Core_4_6_0_Tests.php \ No newline at end of file diff --git a/tests/testcases/core/data_migration_scripts/EE_DMS_Core_4_8_0_Tests.php b/tests/testcases/core/data_migration_scripts/EE_DMS_Core_4_8_0_Tests.php deleted file mode 100644 index 6681dcc0133..00000000000 --- a/tests/testcases/core/data_migration_scripts/EE_DMS_Core_4_8_0_Tests.php +++ /dev/null @@ -1,36 +0,0 @@ -load_dms( 'EE_DMS_Core_4_8_0' ); - $stage = new EE_DMS_4_8_0_pretax_totals(); - - // ok let's create a line item to with the LIN_code='tickets' - $tickets_subtotal = $this->new_model_obj_with_dependencies( 'Line_Item', array( 'LIN_code' => 'tickets' ) ); - // and another that DOESN"T match it - $other_line_item = $this->new_model_obj_with_dependencies( 'Line_Item', array( 'LIN_code' => 'not-tickets' ) ); - $stage->migration_step(); - $new_tickets_subtotal = EEM_Line_Item::instance()->refresh_entity_map_from_db( $tickets_subtotal->ID() ); - $this->assertEquals( 'pre-tax-subtotal', $new_tickets_subtotal->get( 'LIN_code' ) ); - - $new_other_line_item = EEM_Line_Item::instance()->refresh_entity_map_from_db( $other_line_item->ID() ); - $this->assertEquals( 'not-tickets', $new_other_line_item->get( 'LIN_code' ) ); - } -} - -// End of file EE_DMS_Core_4_8_0_Tests.php \ No newline at end of file diff --git a/tests/testcases/core/db_classes/EE_Attendee_Test.php b/tests/testcases/core/db_classes/EE_Attendee_Test.php deleted file mode 100644 index 03d262185eb..00000000000 --- a/tests/testcases/core/db_classes/EE_Attendee_Test.php +++ /dev/null @@ -1,102 +0,0 @@ -save(); - $this->assertNotEquals($a->ID(),0); - $e1 = EE_Event::new_instance(array('EVT_name'=>'1')); - $e1->save(); - $this->assertNotEquals($e1->ID(),0); - $e2 = EE_Event::new_instance(array('EVT_name'=>'2')); - $e2->save(); - $this->assertNotEquals($e2->ID(),0); - $e3 = EE_Event::new_instance(array('EVT_name'=>'3')); - $e3->save(); - $this->assertNotEquals($e3->ID(),0); - $r1 = EE_Registration::new_instance(array('EVT_ID'=>$e1->ID(),'ATT_ID'=>$a->ID())); - $r1->save(); - $this->assertNotEquals($r1->ID(),0); - $r2 = EE_Registration::new_instance(array('EVT_ID'=>$e2->ID(),'ATT_ID'=>$a->ID())); - $r2->save(); - $this->assertNotEquals($r2->ID(),0); - $events = $a->events(); - $this->assertArrayContains($e1,$events); - $this->assertArrayContains($e2,$events); - $this->assertArrayDoesNotContain($e3,$events); - } - - public function test_get_billing_info_postmeta_name(){ - /* - * @var $reg EE_Registration - */ - $reg = $this->new_model_obj_with_dependencies('Registration'); - - $att = $reg->attendee(); - $payment_method = $reg->transaction()->payment_method(); - $key = $att->get_billing_info_postmeta_name( $payment_method ); - $this->assertEquals('billing_info_Admin_Only', $key ); - } - public function test_save_and_clean_billing_info_for_payment_method(){ - $pm = EE_Payment_Method::new_instance(array( 'PMD_type'=>'Aim' ) ); - $pm->save(); - //reset the country model because it caches its list of countries which is used when - //making most billing forms - EEM_Country::reset(); - $form = $pm->type_obj()->billing_form(); - $form_name = $form->name(); - $form_values = array( - 'first_name' => 'e', - 'last_name' => 'e', - 'email' => 'developers@eventespresso.com', - 'address' => '123', - 'address2' => '', - 'city' => 'someville', - 'state' => 12, - 'country' => 'US', - 'zip' => '1235', - 'phone' => '9991231234', - 'credit_card'=>'4007000000027', - 'exp_month'=>'12', - 'exp_year'=>'2020', - 'cvv'=>'123', - ); - $form->receive_form_submission( array( $form_name => $form_values ) ); - $this->assertTrue( $form->is_valid(), 'error was: ' . $form->get_validation_error_string() ); - $p = $this->new_model_obj_with_dependencies('Payment', array( 'PMD_ID'=>$pm->ID() ) ); - $reg = $this->new_model_obj_with_dependencies('Registration',array( 'TXN_ID' => $p->TXN_ID() ) ); - $att = $reg->attendee(); - $att->save_and_clean_billing_info_for_payment_method( $form, $pm ); - //ok so now it should ahve been saved. Let's verify that - $billing_info_form = $att->billing_info_for_payment_method( $pm ); - $this->assertInstanceOf( 'EE_Billing_Attendee_Info_Form', $billing_info_form ); - //it should ahve been cleaned too, so lets tweak teh form values ot what they should be - $form_values[ 'credit_card' ] = 'XXXXXXXXX0027'; - $form_values[ 'cvv' ] = 'XXX'; - $form_values[ 'exp_month' ] = ''; - $form_values[ 'exp_year' ] = 0; - foreach($form_values as $input_name => $value){ - $input = $billing_info_form->get_input( $input_name); - $this->assertInstanceOf( 'EE_Form_Input_Base', $input ); - $this->assertEquals( $value, $input->raw_value(), $input_name ); - } - } -} - -// End of file tests/testcases/core/db_classes/EE_Attendee_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_classes/EE_Base_Class_Test.php b/tests/testcases/core/db_classes/EE_Base_Class_Test.php deleted file mode 100644 index 33272775b51..00000000000 --- a/tests/testcases/core/db_classes/EE_Base_Class_Test.php +++ /dev/null @@ -1,1236 +0,0 @@ - array(EE_MOCKS_DIR . 'core/db_models/'), - 'class_paths' => array(EE_MOCKS_DIR . 'core/db_classes/'), - ) - ); - } - - - public function tearDown() - { - EE_Register_Model::deregister('Mock'); - parent::tearDown(); - } - - static function setUpBeforeClass() - { - // EEH_Activation::create_table('esp_mock', - // "MCK_ID int(11) NOT NULL, - // PRIMARY KEY (MCK_ID)"); - // require_once(EE_TESTS_DIR.'mocks/core/db_models/EEM_Mock.model.php'); - // require_once(EE_TESTS_DIR.'mocks/core/db_classes/EE_Mock.class.php'); - parent::setUpBeforeClass(); - } - - - /** - * @return \EE_Attendee - */ - function test_new_instance() - { - $a = EE_Attendee::new_instance(); - $this->assertNotNull($a); - $this->assertInstanceOf('EE_Attendee', $a); - return $a; - } - - - /** - * @group 9273 - * @see https://events.codebasehq.com/projects/event-espresso/tickets/9273 - */ - function test_new_instance_with_existing_object_and_incoming_date_formats() - { - //setup a EE_Payment object and save - $payment_object = EE_Payment::new_instance(); - $payment_object->save(); - $payment_object_id = $payment_object->ID(); - //now let's setup a new payment object using that ID but with different formats than the defaults - //that way we can verify the timestamp gets set correctly. - $expected_date = '2016-24-01'; - $payment_object_to_test = EE_Payment::new_instance( - array( - 'PAY_ID' => $payment_object_id, - 'PAY_timestamp' => '2016-24-01 3:45 pm', - ), - '', - array('Y-d-m', 'g:i a') - ); - $this->assertEquals($expected_date, $payment_object_to_test->get_date('PAY_timestamp')); - } - - - function test_set_and_get() - { - $a = EE_Attendee::new_instance(); - $a->set('ATT_fname', 'value1'); - $this->assertEquals($a->get('ATT_fname'), 'value1'); - //verify that we can change it - $a->set('ATT_fname', 'value2'); - $this->assertEquals($a->get('ATT_fname'), 'value2'); - } - - - function test_set_and_get_with_caching() - { - $t = EE_Transaction::new_instance(); - $t->set('TXN_total', 10.53); - $this->assertEquals($t->get('TXN_total'), 10.53); - $this->assertEquals($t->get_pretty('TXN_total'), '$10.53 (USD)'); - //make sure the caching of pretty and normal fields doesn't mess us up - $this->assertEquals($t->get('TXN_total'), 10.53); - $t->set('TXN_total', 0.00); - $this->assertEquals($t->get('TXN_total'), 0); - $this->assertEquals($t->get_pretty('TXN_total'), '$0.00 (USD)'); - $this->assertEquals($t->get('TXN_total'), 0); - } - - - function test_save_string_pk() - { - //test saving something with an auto-increment PK - $c = EE_Country::new_instance(array('CNT_ISO' => '12')); - $results = $c->save(); - $this->assertEquals($results, $c->ID()); - $c->set('CNT_cur_code', 'FOO'); - $results2 = $c->save(); - $this->assertEquals(true, $results2); - } - - - function test_save_autoincrement_pk() - { - //test saving something with an auto-increment PK - $t = EE_Transaction::new_instance(); - $id = $t->save(); - $this->assertNotNull($id); - $this->assertEquals($t->ID(), $id); - $t2 = EEM_Transaction::instance()->get_one_by_ID($id); - $this->assertEquals($id, $t2->ID()); - //and check that its correctly saved to the model's entity map - $existing_t_in_entity_map = EEM_Transaction::instance()->get_from_entity_map($id); - $this->assertInstanceOf('EE_Transaction', $existing_t_in_entity_map); - } - - - /** - * @group 8622 - */ - function test_save__allow_persist_changed() - { - $t = EE_Transaction::new_instance(); - $t->set_allow_persist(false); - $result = $t->save(); - $this->assertEquals(0, $result); - $t->set_allow_persist(true); - $result2 = $t->save(); - $this->assertNotEquals(0, $result2); - } - - /** - * @since 4.9.76.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - */ - function test_save_no_pk(){ - $term_taxonomy = $this->new_model_obj_with_dependencies('Term_Taxonomy', array('taxonomy'=>'monkeys')); - $e = $this->new_model_obj_with_dependencies('Event'); - $tr = EE_Term_Relationship::new_instance(array('object_id'=>$e->ID())); - $results = $tr->save(); - $this->assertNotNull($results); - } - /** - * @group 8686 - */ - function test_add_relation_to() - { - $t = EE_Transaction::new_instance(); - $t->save(); - $r = EE_Registration::new_instance(); - $r->save(); - //verify the relations - try { - $r->transaction(); - } catch (Exception $e) { - $this->assertTrue(true); - } - $rs_from_t = $t->registrations(); - $this->assertTrue(empty($rs_from_t)); - //add a relation and verify it changes the model object with the PK - $r->_add_relation_to($t, 'Transaction'); - $this->assertEquals($t->ID(), $r->get('TXN_ID')); - //and we get expected results when fetching using it - $t_from_r = $r->transaction(); - $this->assertEquals($t, $t_from_r); - $rs_from_t = $t->registrations(); - $this->assertFalse(empty($rs_from_t)); - } - - /** - * @group 8686 - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - */ - function testAddRelationToHABTM() - { - $q = $this->new_model_obj_with_dependencies('Question'); - $qg = $this->new_model_obj_with_dependencies('Question_Group'); - $this->assertFalse(EEM_Question_Group_Question::instance()->exists( - array( - array( - 'QST_ID' => $q->ID(), - 'QSG_ID' => $qg->ID() - ) - ) - )); - $first_join_row_order = 100; - $q->_add_relation_to( - $qg, - 'Question_Group', - array('QGQ_order' => $first_join_row_order) - ); - $this->assertEquals( - 1, - EEM_Question_Group_Question::instance()->count( - array( - array( - 'QST_ID' => $q->ID(), - 'QSG_ID' => $qg->ID() - ) - ) - ) - ); - // ok great. Do it again and make sure no new entries added to the DB. - $second_join_entry_order = 200; - $q->_add_relation_to( - $qg, - 'Question_Group', - array('QGQ_order' => $second_join_entry_order) - ); - $this->markTestIncomplete( - 'This was reverted in order to fix https://github.com/eventespresso/event-espresso-core/issues/873' - ); - $this->assertEquals( - 1, - EEM_Question_Group_Question::instance()->count( - array( - array( - 'QST_ID' => $q->ID(), - 'QSG_ID' => $qg->ID() - ) - ) - ) - ); - $join_entry = EEM_Question_Group_Question::instance()->get_one( - array( - array( - 'QST_ID' => $q->ID(), - 'QSG_ID' => $qg->ID() - ) - ) - ); - $this->assertEquals($second_join_entry_order, $join_entry->get('QGQ_order')); - } - - /** - * @group 8686 - */ - function test_add_relation_to__unsaved() - { - $t = EE_Transaction::new_instance(); - $r = EE_Registration::new_instance(); - $t->_add_relation_to($r, 'Registration'); - $t_from_r = $r->transaction(); - $this->assertEquals($t, $t_from_r); - $rs_from_t = $t->registrations(); - $this->assertFalse(empty($rs_from_t)); - } - - - /** - * @group 7084 - */ - function test_set_defaults_on_unspecified_fields() - { - $r = EE_Registration::new_instance(array('TXN_ID' => 99)); - $this->assertEquals(99, $r->transaction_ID()); - //the STS_ID should have been set to the default, not left NULL - $this->assertEquals(EEM_Registration::instance()->field_settings_for('STS_ID')->get_default_value(), - $r->status_ID()); - } - - - function test_get_first_related() - { - $t = EE_Transaction::new_instance(); - $t->save(); - $r = EE_Registration::new_instance(); - $r->save(); - $t->_add_relation_to($r, 'Registration'); - $r_from_t = $t->get_first_related('Registration'); - $this->assertEquals($r->ID(), $r_from_t->ID()); - $t_from_r = $r->get_first_related('Transaction'); - $this->assertEquals($t->ID(), $t_from_r->ID()); - } - - - function test_get_many_related() - { - $t = EE_Transaction::new_instance(); - $t->save(); - $r = EE_Registration::new_instance(); - $r->save(); - $r2 = EE_Registration::new_instance(); - $r2->save(); - $t->_add_relation_to($r, 'Registration'); - $t->_add_relation_to($r2, 'Registration'); - $rs_from_t = $t->get_many_related('Registration'); - $this->assertCount(2, $rs_from_t); - foreach ($rs_from_t as $r_from_t) { - $this->assertInstanceOf('EE_Registration', $r_from_t); - } - } - - - function test_cache_related() - { - $t = EE_Transaction::new_instance(); - //note that we did NOT save it - $r = EE_Registration::new_instance(); - $t->_add_relation_to($r, 'Registration'); - $this->assertEquals($t->ID(), 0); - $this->assertEquals($r->ID(), 0); - //get the registration cached on the transaction - $r_from_t = $t->get_first_related('Registration'); - $this->assertEquals($r, $r_from_t); - } - - - /** - * @group 8686 - */ - function test_remove_relation_to() - { - $t = EE_Transaction::new_instance(); - $t->save(); - $r = EE_Registration::new_instance(array('TXN_ID' => $t->ID())); - $r->save(); - $t_from_r = $r->get_first_related('Transaction'); - $this->assertEquals($t, $t_from_r); - $rs_from_t = $t->get_many_related('Registration'); - $this->assertFalse(empty($rs_from_t)); - //remove the relation - $t_removed = $r->_remove_relation_to($t, 'Transaction'); - $this->assertEquals($t, $t_removed); - $t_from_r = $r->get_first_related('Transaction'); - $this->assertNull($t_from_r); - //and verify the cached reciprocal relation is updated too - $rs_from_t = $t->get_many_related('Registration'); - $this->assertTrue(empty($rs_from_t)); - } - - - /** - * @group 8686 - */ - function test_remove_relations() - { - $t = EE_Transaction::new_instance(); - $t->save(); - $r = EE_Registration::new_instance(array('TXN_ID' => $t->ID())); - $r->save(); - $t_from_r = $r->get_first_related('Transaction'); - $this->assertEquals($t, $t_from_r); - $rs_from_t = $t->get_many_related('Registration'); - $this->assertFalse(empty($rs_from_t)); - //ok now remove the relation between them - $r->_remove_relations('Transaction'); - $t_from_r = $r->get_first_related('Transaction'); - $this->assertNull($t_from_r); - //and verify the cached reciprocal relation is updated too - $rs_from_t = $t->get_many_related('Registration'); - $this->assertTrue(empty($rs_from_t)); - } - - - function test_count_related() - { - $e1 = EE_Event::new_instance(array('EVT_name' => '1')); - $e1->save(); - $this->assertNotEquals($e1->ID(), 0); - $e2 = EE_Event::new_instance(array('EVT_name' => '2')); - $e2->save(); - $this->assertNotEquals($e2->ID(), 0); - $e3 = EE_Event::new_instance(array('EVT_name' => '3')); - $e3->save(); - $v = EE_Venue::new_instance(array('VNU_name' => 'v1')); - $v->save(); - $v->_add_relation_to($e1, 'Event'); - $v->_add_relation_to($e2, 'Event'); - $this->assertEquals($v->count_related('Event'), 2); - } - - - function test_sum_related() - { - $t = EE_Transaction::new_instance(); - $t->save(); - $p1 = EE_Payment::new_instance(array('PAY_amount' => 1, 'TXN_ID' => $t->ID())); - $p1->save(); - $p2 = EE_Payment::new_instance(array('PAY_amount' => 2, 'TXN_ID' => $t->ID())); - $p2->save(); - $p1 = EE_Payment::new_instance(array('PAY_amount' => 1000, 'TXN_ID' => 0)); - $p1->save(); - $this->assertEquals($t->sum_related('Payment', array(), 'PAY_amount'), 3); - $t->_remove_relation_to($p2, 'Payment'); - $this->assertEquals($t->sum_related('Payment', array(), 'PAY_amount'), 1); - } - - - function test_cache_specifying_id() - { - $t = EE_Transaction::new_instance(); - $r = EE_Registration::new_instance(); - $t->cache('Registration', $r, 'r'); - $related_rs = $t->get_many_related('Registration'); - $this->assertArrayHasKey('r', $related_rs); - $this->assertArrayNotHasKey('r2', $related_rs); - $r_from_t = $t->get_one_from_cache('Registration'); - $this->assertEquals($r, $r_from_t); - $r2 = EE_Registration::new_instance(); - $t->cache('Registration', $r2, 'r2'); - $rs_from_t = $t->get_all_from_cache('Registration'); - $this->assertArrayContains($r, $rs_from_t); - $this->assertArrayContains($r2, $rs_from_t); - } - - - function test_update_cache_after_save() - { - $t = EE_Transaction::new_instance(); - $r = EE_Registration::new_instance(); - $t->cache('Registration', $r, 'monkey_code'); - $related_rs = $t->get_many_related('Registration'); - $this->assertArrayHasKey('monkey_code', $related_rs); - $r->save(); - $t->update_cache_after_object_save('Registration', $r, 'monkey_code'); - $related_rs = $t->get_many_related('Registration'); - $this->assertArrayHasKey($r->ID(), $related_rs); - $this->assertArrayNotHasKey('monkey_code', $related_rs); - } - - - function test_is_set() - { - $t = EE_Transaction::new_instance(); - $this->assertTrue($t->is_set('TXN_ID')); - $this->assertFalse($t->is_set('monkey_brains')); - } - - - /** - * tests that clearing all from a cache works as expected - */ - function test_clear_cache__all() - { - $t = EE_Transaction::new_instance(); - //test that clear cache for an item that ISN'T cached doesn't produce an error. - $response = $t->clear_cache('Registration'); - $this->assertNull($response); - $r = EE_Registration::new_instance(array('REG_code' => 'monkey1')); - $r2 = EE_Registration::new_instance(array('REG_code' => 'monkey2')); - $t->cache('Registration', $r); - $t->cache('Registration', $r2); - $rs_cached = $t->get_all_from_cache('Registration'); - $this->assertArrayContains($r, $rs_cached); - $this->assertArrayContains($r2, $rs_cached); - //ok but if we call clear cache again without specifying what we want, - //we should actually do nothing - $r_null = $t->clear_cache('Registration'); - $this->assertNull($r_null); - $this->assertArrayContains($r, $rs_cached); - $this->assertArrayContains($r2, $rs_cached); - //ok now clear everything - $success = $t->clear_cache('Registration', null, true); - $this->assertTrue($success); - $cached_regs = $t->get_all_from_cache('Registration'); - $this->assertEmpty($cached_regs); - } - - - /** - * test that after we've cached something, we can remove it specifically - * by only knowing the object - */ - function test_clear_cache__specific_object() - { - $t = EE_Transaction::new_instance(); - $r = EE_Registration::new_instance(array('REG_code' => 'monkey1')); - $r2 = EE_Registration::new_instance(array('REG_code' => 'monkey2')); - $t->cache('Registration', $r); - $t->cache('Registration', $r2); - $rs_cached = $t->get_all_from_cache('Registration'); - $this->assertArrayContains($r, $rs_cached); - $this->assertArrayContains($r2, $rs_cached); - $r_removed = $t->clear_cache('Registration', $r); - $this->assertEquals($r, $r_removed); - $this->assertArrayContains($r2, $t->get_all_from_cache('Registration')); - $this->assertArrayDoesNotContain($r, $t->get_all_from_cache('Registration')); - //now check if we clear the cache for an item that isn't in the cache, it returns null - $r3 = EE_Registration::new_instance(array('REG_code' => 'mystery monkey')); - $r_null = $t->clear_cache('Registration', $r3); - $this->assertNull($r_null); - } - - - /** - * test that after we've cached something using a specific index, - * we can remove it using a specific index - */ - function test_clear_cache__specific_index() - { - $t = EE_Transaction::new_instance(); - $r = EE_Registration::new_instance(array('REG_code' => 'monkey1')); - $r2 = EE_Registration::new_instance(array('REG_code' => 'monkey2')); - $t->cache('Registration', $r, 'monkey1'); - $t->cache('Registration', $r2, 'monkey2'); - $rs_cached = $t->get_all_from_cache('Registration'); - $this->assertArrayContains($r, $rs_cached); - $this->assertArrayContains($r2, $rs_cached); - $r_cached = $t->clear_cache('Registration', 'monkey1'); - $this->assertEquals($r, $r_cached); - $this->assertArrayDoesNotContain($r, $t->get_all_from_cache('Registration')); - //also check that if the index isn't set, we just return null - $r_null = $t->clear_cache('Registration', 'mystery monkey'); - $this->assertNull($r_null); - } - - - /** - * tests that clearing the cache on a belongsTo relation works - */ - function test_clear_cache__belongs_to() - { - $t = EE_Transaction::new_instance(array('TXN_total' => '99')); - $r = EE_Registration::new_instance(array('REG_code' => 'monkey1')); - $success = $r->cache('Transaction', $t); - $this->assertTrue($success); - $t_cached = $r->get_one_from_cache('Transaction'); - $this->assertEquals($t, $t_cached); - $t_removed = $r->clear_cache('Transaction'); - $this->assertEquals($t, $t_removed); - $t_null = $r->get_one_from_cache('Transaction'); - $this->assertNull($t_null); - } - - - function test_set_and_get_extra_meta() - { - $e = EE_Event::new_instance(); - $e->save(); - $e->update_extra_meta('monkey', 'baboon'); - $this->assertEquals('baboon', $e->get_extra_meta('monkey', true)); - $e->update_extra_meta('monkey', 'chimp'); - $this->assertEquals('chimp', $e->get_extra_meta('monkey', true)); - } - - - /** - * Created to attempt to reproduce a bug found when fixing - * https://events.codebasehq.com/projects/event-espresso/tickets/6373 - * - * @since 4.5.0 - */ - function test_set_primary_key_clear_relations() - { - /** @type EE_Event $event */ - $event = $this->factory->event->create(); - /** @type EE_Datetime $datetime */ - $datetime = $this->factory->datetime->create(); - $event->_add_relation_to($datetime, 'Datetime'); - $event->save(); - //now to reproduce we grab the event from the db. - $evt_from_db = EEM_Event::instance()->get_one_by_ID($event->ID()); - //clone event - $new_event = clone $evt_from_db; - //set pk to zero so we save new event and save. - $new_event->set('EVT_ID', 0); - $new_event->save(); - //now let's set the a clone of the dtt relation manually to the new event by cloning the dtt (which should work) - $orig_datetimes = $evt_from_db->get_many_related('Datetime'); - $this->assertEquals(1, count($orig_datetimes)); - /** @type EE_Datetime $new_datetime */ - $new_datetime = null; - foreach ($orig_datetimes as $orig_dtt) { - $new_datetime = clone $orig_dtt; - $new_datetime->set('DTT_ID', 0); - $new_datetime->set('EVT_ID', $new_event->ID()); - $new_datetime->save(); - } - $this->assertInstanceOf('EE_Datetime', $new_datetime); - //k now for the tests. first $new_event should NOT have the original datetime as a relation by default. When an object's id is set to 0 its relations should be cleared. - //get from db - /** @type EE_Event $test_cloned_event_from_db */ - $test_cloned_event_from_db = EEM_Event::instance()->get_one_by_ID($new_event->ID()); - $dtt_relation_on_clone = $test_cloned_event_from_db->first_datetime(); - $this->assertInstanceOf('EE_Datetime', $dtt_relation_on_clone); - $this->assertEquals($new_datetime->ID(), $dtt_relation_on_clone->ID()); - //test that the original event still has its relation to original EE_Datetime - /** @type EE_Event $orig_evt */ - $orig_evt = EEM_Event::instance()->get_one_by_ID($evt_from_db->ID()); - $dtt_relation_on_orig = $orig_evt->first_datetime(); - $this->assertInstanceOf('EE_Datetime', $dtt_relation_on_orig); - $this->assertEquals($dtt_relation_on_orig->ID(), $datetime->ID()); - } - - - /** - * @group 7151 - */ - public function test_in_entity_map() - { - $att = EE_Attendee::new_instance(array('ATT_fname' => 'mike')); - $this->assertFalse($att->in_entity_map()); - $att->save(); - $this->assertTrue($att->in_entity_map()); - EEM_Attendee::instance()->reset(); - //when we serialized it, it forgot if it was in the entity map or not - $this->assertFalse($att->in_entity_map()); - try { - //should throw an exception because we hate saving - //a model object that's not in the entity mapper - $att->save(); - } catch (EE_Error $e) { - $this->assertTrue(true); - } - EEM_Attendee::instance()->add_to_entity_map($att); - //we should all acknowledge it's in the entity map now - $this->assertTrue($att->in_entity_map()); - //we shouldn't complain at saving it now, it's in the entity map and so we're allowed - $att->save(); - //also, when we clone an item in the entity map, it shouldn't be considered in the entity map - $att2 = clone $att; - $this->assertFalse($att2->in_entity_map()); - } - - - /** - * @group 7151 - */ - public function test_refresh_from_db() - { - $att = EE_Attendee::new_instance(array('ATT_fname' => 'bob')); - try { - $att->refresh_from_db(); - } catch (EE_Error $e) { - $this->assertTrue(true); - } - $att->save(); - $att->refresh_from_db(); - EEM_Attendee::instance()->reset(); - try { - $att->refresh_from_db(); - } catch (EE_Error $e) { - $this->assertTrue(true); - } - } - - - public function test_delete_permanently_with_extra_meta() - { - $attendee = EE_Attendee::new_instance(array( - 'ATT_fname' => 'bob', - 'ATT_lname' => 'deleteme', - 'ATT_email' => 'ef@ew.dw', - )); - $attendee->save(); - $attendee->add_extra_meta('shouldnt_prevent_deletion', 'no_sirry'); - $this->assertEquals('no_sirry', $attendee->get_extra_meta('shouldnt_prevent_deletion', true)); - $attendee->delete_permanently(); - //if that didn't throw an error, we're good - } - - - /** - * @group 7358 - */ - public function test_get_raw() - { - $l2 = EE_Line_Item::new_instance(array()); - $this->assertTrue(1 == $l2->get_raw('LIN_quantity')); - $l2->save(); - $l2_from_db = EEM_Line_Item::reset()->get_one_by_ID($l2->ID()); - //double check its NULL in the DB - $qty_col_with_one_result = EEM_Line_Item::instance()->get_col(array(array('LIN_ID' => $l2->ID())), - 'LIN_quantity'); - $qty_col_in_db = reset($qty_col_with_one_result); - $this->assertTrue(1 == $qty_col_in_db); - //and now verify get_raw is returning that same value - $this->assertTrue(1 == $l2_from_db->get_raw('LIN_quantity')); - } - - - /** - * Tests when we set a field to INFINITY, it stays that way even after we re-fetch it from the db - * - * @group 7358 - */ - public function test_infinite_fields_stay_that_way() - { - /** @type EE_Datetime $datetime */ - $datetime = $this->new_model_obj_with_dependencies('Datetime'); - $datetime->set_reg_limit(EE_INF); - $datetime->save(); - /** @type EE_Datetime $datetime_from_db */ - $datetime_from_db = EEM_Datetime::reset()->get_one_by_ID($datetime->ID()); - $this->assertEquals($datetime->reg_limit(), $datetime_from_db->reg_limit()); - } - - - /** - * @since 4.6.12+ - */ - public function test_get_i18n_datetime() - { - //setup a datetime object with some known values for testing with. - $original_timezone = get_option('timezone_string'); - update_option('timezone_string', 'America/Toronto'); - $dateTimeZone = new DateTimeZone('America/Toronto'); - $currentTime = new DateTime("now", $dateTimeZone); - $futureTime = clone $currentTime; - $futureTime->add(new DateInterval('P2D')); - /** @type EE_Datetime $datetime */ - $datetime = $this->factory->datetime->create(array( - 'DTT_EVT_start' => $currentTime->format('Y-m-d H:i:s'), - 'DTT_EVT_end' => $futureTime->format('Y-m-d H:i:s'), - 'formats' => array('Y-m-d', 'H:i:s'), - )); - $this->assertInstanceOf('EE_Datetime', $datetime); - //test get_i18n_datetime - $this->assertEquals($currentTime->format('Y-m-d H:i:s'), $datetime->get_i18n_datetime('DTT_EVT_start')); - $this->assertEquals($futureTime->format('Y-m-d H:i:s'), $datetime->get_i18n_datetime('DTT_EVT_end')); - $id = $datetime->ID(); - //test when retrieved from the database. - EEM_Datetime::reset(); - $dbDatetime = EEM_Datetime::instance()->get_one_by_ID($id); - //set formats to match expected - $dbDatetime->set_date_format('Y-m-d'); - $dbDatetime->set_time_format('H:i:s'); - $this->assertEquals($currentTime->format('Y-m-d H:i:s'), $dbDatetime->get_i18n_datetime('DTT_EVT_start')); - $this->assertEquals($futureTime->format('Y-m-d H:i:s'), $dbDatetime->get_i18n_datetime('DTT_EVT_end')); - //restore timezone - update_option('timezone_string', $original_timezone); - } - - - /** - * @since 4.7.0 - * Note: in this test we're using EE_Datetime methods that utilize this method on - * EE_Base_Class - */ - public function test_set_date_time() - { - //setup a datetime object with some known values for testing with. - $original_timezone = get_option('timezone_string'); - update_option('timezone_string', 'America/Toronto'); - $dateTimeZone = new DateTimeZone('America/Toronto'); - $currentTime = new DateTime("now", $dateTimeZone); - $futureTime = clone $currentTime; - $futureTime->add(new DateInterval('P2D')); - /** @type EE_Datetime $datetime */ - $datetime = $this->factory->datetime->create( - array( - 'DTT_EVT_start' => $currentTime->format('Y-m-d H:i:s'), - 'DTT_EVT_end' => $futureTime->format('Y-m-d H:i:s'), - 'formats' => array('Y-m-d', 'H:i:s'), - ) - ); - $this->assertInstanceOf('EE_Datetime', $datetime); - //create a second datetime for polluting the formats on EE_Datetime_Field. - // Note: the purpose of this is to test that when th EE_Datetime_Field gets the new formats from this object, that they are NOT persisting to the original datetime created that has different formats (but utilizes the same EE_Date) - $this->factory->datetime->create( - array( - 'DTT_EVT_start' => $currentTime->format('d/m/Y g:i a'), - 'DTT_EVT_end' => $futureTime->format('d/m/Y g:i a'), - 'formats' => array('d/m/Y', 'g:i a'), - ) - ); - //test setting the time to 8am using a time string. - $datetime->set_start_time('8:00:00'); - $this->assertEquals($currentTime->setTime(8, 0, 0)->format('Y-m-d H:i:s'), $datetime->get('DTT_EVT_start')); - //test setting the time to 11pm using a date object - $currentTime->setTime(23, 0, 0); - $datetime->set_start_time($currentTime); - $this->assertEquals($currentTime->format('Y-m-d H:i:s'), $datetime->get('DTT_EVT_start')); - //test setting the date to 12-31-2012 on start date using a date string. - $currentTime->setDate('2012', '12', '31'); - $datetime->set_start_date('2012-12-31'); - $this->assertEquals($currentTime->format('Y-m-d H:i:s'), $datetime->get('DTT_EVT_start')); - //test setting the date to 12-15 using a date object. - $currentTime->setDate('2012', '12', '15'); - $datetime->set_start_date($currentTime); - $this->assertEquals($currentTime->format('Y-m-d H:i:s'), $datetime->get('DTT_EVT_start')); - //reset timezone_string back to original - update_option('timezone_string', $original_timezone); - } - - - /** - * @since 4.6.x - */ - public function test_next_x() - { - //create 5 events for testing with. - $events = $this->factory->event->create_many(5); - //grab the first event in the list as the reference - $event = reset($events); - $this->assertInstanceOf('EE_Event', $event); - //test method retrieving object - $next_events = $event->next_x('EVT_ID', 2); - //verify we have two returned. - $this->assertEquals(2, count($next_events)); - //loop through and verify the events returned are correct. - $pointer = 1; - foreach ($next_events as $next_event) { - $this->assertInstanceOf('EE_Event', $next_event); - $this->assertEquals($event->ID() + $pointer, $next_event->ID()); - $pointer++; - } - //test retrieving just ids - $next_events = $event->next_x('EVT_ID', 2, array(), 'EVT_ID'); - //verify we have two returned - $this->assertEquals(2, count($next_events)); - //loop through and verify the IDS returned are correct. - $pointer = 1; - foreach ($next_events as $next_event) { - $this->assertTrue(array_key_exists('EVT_ID', $next_event)); - $this->assertEquals($event->ID() + $pointer, $next_event['EVT_ID']); - $pointer++; - } - } - - - /** - * @since 4.6.x - */ - public function test_previous_x() - { - //create 5 events for testing with. - $events = $this->factory->event->create_many(5); - //grab the last event in the list as the reference - $event = end($events); - $this->assertInstanceOf('EE_Event', $event); - //test method retrieving object - $previous_events = $event->previous_x('EVT_ID', 2); - //verify we have two returned. - $this->assertEquals(2, count($previous_events)); - //loop through and verify the events returned are correct. - $pointer = 1; - foreach ($previous_events as $next_event) { - $this->assertInstanceOf('EE_Event', $next_event); - $this->assertEquals($event->ID() - $pointer, $next_event->ID()); - $pointer++; - } - //test retrieving just ids - $previous_events = $event->previous_x('EVT_ID', 2, array(), 'EVT_ID'); - //verify we have two returned - $this->assertEquals(2, count($previous_events)); - //loop through and verify the IDS returned are correct. - $pointer = 1; - foreach ($previous_events as $next_event) { - $this->assertTrue(array_key_exists('EVT_ID', $next_event)); - $this->assertEquals($event->ID() - $pointer, $next_event['EVT_ID']); - $pointer++; - } - } - - - /** - * @since 4.6.x - */ - public function test_next() - { - //create 5 events for testing with. - $events = $this->factory->event->create_many(5); - //grab the first event in the list as the reference - $event = reset($events); - $this->assertInstanceOf('EE_Event', $event); - //test method retrieving object - $next_event = $event->next('EVT_ID'); - //verify we have an event returned and that its the right one in sequence. - $this->assertInstanceOf('EE_Event', $next_event); - $this->assertEquals($event->ID() + 1, $next_event->ID()); - //test retrieving just id - $next_event = $event->next('EVT_ID', array(), 'EVT_ID'); - //verify the returned array has the right key and value. - $this->assertTrue(is_array($next_event)); - $this->assertTrue(array_key_exists('EVT_ID', $next_event)); - $this->assertEquals($event->ID() + 1, $next_event['EVT_ID']); - } - - - /** - * @since 4.6.x - */ - public function test_previous() - { - //create 5 events for testing with. - $events = $this->factory->event->create_many(5); - //grab the last event in the list as the reference - $event = end($events); - $this->assertInstanceOf('EE_Event', $event); - //test method retrieving object - $previous_event = $event->previous('EVT_ID'); - //verify we have an event returned and that its the right one in sequence. - $this->assertInstanceOf('EE_Event', $previous_event); - $this->assertEquals($event->ID() - 1, $previous_event->ID()); - //test retrieving just id - $previous_event = $event->previous('EVT_ID', array(), 'EVT_ID'); - //verify the returned array has the right key and value. - $this->assertTrue(is_array($previous_event)); - $this->assertTrue(array_key_exists('EVT_ID', $previous_event)); - $this->assertEquals($event->ID() - 1, $previous_event['EVT_ID']); - } - - - /** - * @group github-102 - * @group 8589 - */ - public function test_get__serialized_data__once() - { - $log_message = array( - 'key1' => 'value1', - 'key2' => 'value2', - ); - $log = EE_Change_Log::new_instance(); - $log->set('LOG_message', $log_message); - $log->save(); - //verify that when we get its LOG_message its still serialized - $this->assertTrue(is_array($log->get('LOG_message'))); - $this->assertEquals($log_message, $log->get('LOG_message')); - //now when we get it from the DB, and get its LOG_message, its still serialized - $log_id = $log->ID(); - EEM_Change_Log::reset(); - unset($log); - $log_from_db = EEM_Change_Log::instance()->get_one_by_ID($log_id); - $this->assertTrue(is_array($log_from_db->get('LOG_message'))); - $this->assertEquals($log_message, $log_from_db->get('LOG_message')); - } - - - /** - * @group github-102 - * @group 8589 - */ - public function test_get__serialized_data__twice() - { - $log_message = serialize(array( - 'key1' => 'value1', - 'key2' => 'value2', - )); - $log = EE_Change_Log::new_instance(); - $log->set('LOG_message', $log_message); - $log->save(); - //verify that when we get its LOG_message its still serialized - $this->assertTrue(is_array($log->get('LOG_message'))); - $this->assertEquals(unserialize($log_message), $log->get('LOG_message')); - //now when we get it from the DB, and get its LOG_message, its still serialized - $log_id = $log->ID(); - EEM_Change_Log::reset(); - unset($log); - $log_from_db = EEM_Change_Log::instance()->get_one_by_ID($log_id); - $this->assertTrue(is_array($log_from_db->get('LOG_message'))); - $this->assertEquals(unserialize($log_message), $log_from_db->get('LOG_message')); - } - - - /** - * @group 8686 - */ - public function test_delete__remove_from_related_items_in_entity_mapper() - { - $p = $this->new_model_obj_with_dependencies('Payment'); - $r = $this->new_model_obj_with_dependencies('Registration'); - $p->_add_relation_to($r, 'Registration'); - $reg_payments = $p->registration_payments(); - $this->assertFalse(empty($reg_payments)); - //now delete the relation entry - foreach ($p->registration_payments() as $registration_payment) { - if ($registration_payment instanceof EE_Registration_Payment) { - $this->assertEquals(1, $registration_payment->delete()); - } - } - //now there should eb no more registration payments on that payment right? - $reg_payments = $p->registration_payments(); - $this->assertTrue(empty($reg_payments)); - } - - - /** - * @group 8686 - */ - public function test_remove_relation_to__reciprocal() - { - $p = $this->new_model_obj_with_dependencies('Payment'); - $r = $this->new_model_obj_with_dependencies('Registration'); - $p->_add_relation_to($r, 'Registration'); - $regs_on_p = $p->get_many_related('Registration'); - $pays_on_r = $r->get_many_related('Payment'); - $this->assertFalse(empty($regs_on_p)); - $this->assertFalse(empty($pays_on_r)); - //now remove the relations - foreach ($p->get_many_related('Registration') as $registration) { - if ($registration instanceof EE_Registration) { - $this->assertEquals($registration, $p->_remove_relation_to($registration, 'Registration')); - } - } - //now there shoudl eb no more relations between those two right? - $regs_on_p = $p->get_many_related('Registration'); - $pays_on_r = $r->get_many_related('Payment'); - $this->assertTrue(empty($regs_on_p)); - $this->assertTrue(empty($pays_on_r)); - } - - /** - * Tests that if you create a model object and immediately change its timezone, the related model - * objects timezones should be changed too. But currently that isn't the case. - * - * @group 10751 - * @group 10905 - */ - public function test_automatically_set_timezone_on_related_model_obj__same_request() - { - //this is basically taken from https://github.com/eventespresso/event-espresso-core/blob/master/docs/F--Datetime-System/dates-times-timezones-in-models.md - $dtt = $this->new_model_obj_with_dependencies('Datetime'); - $event = EEM_Event::instance()->get_one_by_ID($dtt->get('EVT_ID')); - $event->set_timezone('Europe/London'); - $dtt = $event->get_first_related('Datetime'); - //first check we haven't accidentally changed the event's timezone - $this->assertEquals('Europe/London', $event->get_timezone()); - //then verify we successfully swapped the datetime's timezone - $this->assertEquals('Europe/London', $dtt->get_timezone()); - } - - - /** - * Verifies that when we set the timezone on a model object, related objects adopt that same timezone - * - * @group 10905 - */ - public function setTimezone() - { - $t = $this->new_typical_transaction(); - $datetime = EEM_Datetime::instance()->get_one(array(array('EVT_ID' => $t->primary_registration()->event_ID()))); - //set the timezone on the datetime, which should also set it on the ticket - $datetime->set_timezone('Europe/London'); - $ticket = $datetime->get_first_related('Ticket'); - $this->assertEquals('Europe/London', $ticket->get_timezone()); - - //now verify that if we change the timezone on the datetime, the ticket will also get changed - $datetime->set_timezone('America/New_York'); - $ticket = $datetime->get_first_related('Ticket'); - $this->assertEquals('America/New_York', $ticket->get_timezone()); - - } - - - /** - * Tests that if you save some model objects, and during a subsequent request change the timezone - * of one, its related model objects timezones will also be changed. - * This could be considered the same as E - * E_Base_Class_Test::test_automatically_set_timezone_on_related_model_obj__same_request - * except this one asserts setting the event's timezone changes the datetime's timezone when done - * across multiple requests. - * - * @group 10751 - */ - public function test_automatically_set_timezone_on_related_model_obj__separate_requests() - { - //this is basically taken from https://github.com/eventespresso/event-espresso-core/blob/master/docs/F--Datetime-System/dates-times-timezones-in-models.md - $dtt = $this->new_model_obj_with_dependencies('Datetime'); - //simulate a new request: forgot about these model objects from the entity map - //so we'll fetch them newly from the database after resetting their models - EEM_Datetime::reset(); - EEM_Event::reset(); - $event = EEM_Event::instance()->get_one_by_ID($dtt->get('EVT_ID')); - $event->set_timezone('Europe/London'); - $dtt = $event->get_first_related('Datetime'); - //first check we haven't accidentally changed the event's timezone - $this->assertEquals('Europe/London', $event->get_timezone()); - //then verify we successfully swapped the datetime's timezone - $this->assertEquals('Europe/London', $dtt->get_timezone()); - } - - - /** - * Tests that the f() function correctly escapes the value for display in a form input's value. - * - * @group 11195 - */ - public function testF() - { - $t = $this->new_model_obj_with_dependencies( - 'Ticket', - array( - 'TKT_description' => '"haha I echo this outside a form!', - ) - ); - ob_start(); - $t->f('TKT_description'); - $output = ob_get_clean(); - $this->assertEquals( - '"</textarea>haha I echo this outside a form!', - $output - ); - } - - - /** - * Tests if we prepare a model field with f(), then put in a form input, - * and the browser does it usual converting of HTML entities into what they represent - * when the form is submitted, that we end up with the same content that we started with. - * - * @group 11195 - */ - public function testFThenSetRoundTrip() - { - $original_value = 'my bold text "with quotes!" and "html entities" like'; - $t = $this->new_model_obj_with_dependencies( - 'Ticket', - array( - 'TKT_description' => $original_value, - ) - ); - $value_in_form = $t->get_pretty('TKT_description', 'form_input'); - //when it's rendered in the browser, they decode HTML entities. - // and the DECODED HTML entities get submitted in the form data - $submitted_value = html_entity_decode($value_in_form); - $t2 = EE_Ticket::new_instance( - array( - 'TKT_description' => $submitted_value, - ) - ); - $this->assertEquals( - $original_value, - $t2->get('TKT_description') - ); - } - - - /** - * @group 11344 - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws \PHPUnit\Framework\Exception - */ - public function testGetDateTimeObject() - { - //use EE_Mock (which simulates EE_Datetime) for tests - /** @var EE_Mock $ee_mock */ - $ee_mock = EE_Mock::new_instance(); - - //verify we get a DateTime object when requesting one - $this->assertInstanceOf('DateTime', $ee_mock->get_DateTime_object('MCK_datetime')); - - //verify we always get a different instance of datetime from what is stored internally when retrieving. - $this->assertNotEquals( - spl_object_hash($ee_mock->internalDateTimeObject('MCK_datetime')), - spl_object_hash($ee_mock->get_DateTime_object('MCK_datetime')) - ); - } - - - /** - * @group 11344 - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - */ - public function testClone() - { - /** @var EE_Mock $ee_mock */ - $ee_mock = EE_Mock::new_instance(); - $original_datetime = $ee_mock->internalDateTimeObject('MCK_datetime'); - - //clone our EE_Datetime and verify the DateTime for the same field is also a new instance. - $new_ee_datetime = clone $ee_mock; - - $this->assertEquals( - spl_object_hash($ee_mock->internalDateTimeObject('MCK_datetime')), - spl_object_hash($original_datetime) - ); - $this->assertNotEquals( - spl_object_hash($ee_mock->internalDateTimeObject('MCK_datetime')), - spl_object_hash($new_ee_datetime->internalDateTimeObject('MCK_datetime')) - ); - } - - /** - * @since 4.9.80.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testAdjustNumericFieldsInDb() - { - $original_sold_count = 5; - $original_reserved_count = 10; - $d = $this->new_model_obj_with_dependencies( - 'Datetime', - [ - 'DTT_sold' => $original_sold_count, - 'DTT_reserved' => $original_reserved_count - ] - ); - $d->adjustNumericFieldsInDb( - [ - 'DTT_sold' => 1, - 'DTT_reserved' => -1, - ] - ); - $this->assertEquals($original_sold_count + 1, $d->sold()); - $this->assertEquals($original_reserved_count - 1, $d->reserved()); - } -} diff --git a/tests/testcases/core/db_classes/EE_CPT_Base_Test.php b/tests/testcases/core/db_classes/EE_CPT_Base_Test.php deleted file mode 100644 index 0d4f7a04c90..00000000000 --- a/tests/testcases/core/db_classes/EE_CPT_Base_Test.php +++ /dev/null @@ -1,184 +0,0 @@ -'e1')); - $this->assertEquals('espresso_events',$e->post_type()); - $e->save(); - $this->assertEquals('espresso_events',$e->post_type()); - - $a = EE_Attendee::new_instance( array( 'ATT_fname' => 'mr', 'ATT_lname' => 'perfect' ) ); - $this->assertEquals('espresso_attendees',$a->post_type()); - $a->save(); - $this->assertEquals('espresso_attendees',$a->post_type()); - } - - - public function test_parent(){ - $e = EE_Event::new_instance(array('parent'=>12)); - $this->assertEquals($e->parent(),12); - } - - - - /** - * @group 10851 - */ - public function testWpPostSavedModelObj() - { - /** @var EE_Event $e */ - $e = $this->new_model_obj_with_dependencies('Event'); - $post = $e->wp_post(); - $this->assertEquals( - $e->ID(), - $post->ID - ); - $this->assertEquals( - $e->description(), - $post->post_content - ); - $this->assertEquals( - $e->get_datetime('EVT_created','Y-m-d', 'H:i:s'), - $post->post_date - ); - } - - - /** - * @group 10851 - */ - public function testWpPostUnsavedModelObj() - { - /** @var EE_Event $e */ - $e = $this->new_model_obj_with_dependencies('Event',null,false); - $post = $e->wp_post(); - $this->assertEquals( - $e->ID(), - $post->ID - ); - $this->assertEquals( - $e->description(), - $post->post_content - ); - $this->assertEquals( - $e->get_datetime('EVT_created','Y-m-d', 'H:i:s'), - $post->post_date - ); - } - - - /** - * Creates two events: one with registrations, the other without. - * Verify that if we loop over them and render their pretty content (which renders shortcodes) - * we don't accidentally cache the shortcode from one event to the other - * @group 10851 - */ - public function testGetPrettyCurrentPostRemainingTheSame() - { - $this->loadShortcodesManagerAndShortcodes(); - $transaction = $this->new_typical_transaction(); - $event_with_registrations = $transaction->primary_registration()->event(); - $event_with_registrations->set_description('[ESPRESSO_EVENT_ATTENDEES]'); - - $other_event = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'EVT_desc' => '[ESPRESSO_EVENT_ATTENDEES]' - ) - ); - $dtt = $this->new_model_obj_with_dependencies('Datetime'); - $other_event->_add_relation_to( $dtt, 'Datetime' ); - $dtt->_add_relation_to( - $this->new_model_obj_with_dependencies('Ticket'), - 'Ticket' - ); - $event_with_reg_desc = $event_with_registrations->get_pretty('EVT_desc'); - $other_event_desc = $other_event->get_pretty('EVT_desc'); - - //the shortcode for each event should be different when rendered - $this->assertNotEquals( - $event_with_reg_desc, - $other_event_desc, - "'{$event_with_reg_desc}' should not be the same as '{$other_event_desc}'" - ); - } - - - /** - * @ticket 418 https://github.com/eventespresso/event-espresso-core/issues/418 - */ - public function testAddEventCategory() - { - $e = $this->new_model_obj_with_dependencies('Event'); - /** - * @var $e EE_Event - */ - $ee_term_taxonomy = $e->add_event_category( - 'Rebel Ships', - 'Events look at important Rebel Space Ships' - ); - $this->assertTrue($ee_term_taxonomy instanceof EE_Term_Taxonomy); - $this->assertNotEquals(0, $ee_term_taxonomy->get('term_count')); - $this->assertEquals('espresso_event_categories', $ee_term_taxonomy->taxonomy()); - } - - - /** - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @throws \EventEspresso\core\exceptions\InvalidDataTypeException - * @throws \EventEspresso\core\exceptions\InvalidInterfaceException - */ - public function testAddEventCategoryNoDuplicates() - { - $e = $this->new_model_obj_with_dependencies('Event'); - $wp_term = $this->factory()->term->create_and_get( - array( - 'name' => 'cars', - 'taxonomy' => 'category', - 'description' => 'regardless of whether this is a valid taxonomy, its certainl not the EE event category' - ) - ); - $this->assertNotInstanceOf('WP_Error', $wp_term); - $ee_term = $this->new_model_obj_with_dependencies( - 'Term', - array( - 'name' => 'cars', - 'slug' => 'cars', - - ) - ); - $ee_term_taxonomy = $this->new_model_obj_with_dependencies( - 'Term_Taxonomy', - array( - 'term_id' => $ee_term->ID(), - 'taxonomy' => EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY - ) - ); - //when adding the term to this event, it shouldn't creating a new one - $term_taxonomy_used_for_relation = $e->add_event_category( - 'cars', - 'an actual ee category' - ); - $this->assertEquals($ee_term_taxonomy, $term_taxonomy_used_for_relation); - } -} - -// End of file EE_CPT_Base_Test.php diff --git a/tests/testcases/core/db_classes/EE_Datetime_Test.php b/tests/testcases/core/db_classes/EE_Datetime_Test.php deleted file mode 100644 index dbe8d3533b7..00000000000 --- a/tests/testcases/core/db_classes/EE_Datetime_Test.php +++ /dev/null @@ -1,258 +0,0 @@ - $original_sold_count, - 'DTT_reserved' => $original_reserved_count - ] - ); - $this->assertEquals($d->get('DTT_sold'), $original_sold_count); - $this->assertEquals($d->get('DTT_reserved'), $original_reserved_count); - $d->increaseSold(); - $this->assertEquals($d->get('DTT_sold'), $original_sold_count + 1); - $this->assertEquals($d->get('DTT_reserved'), $original_reserved_count - 1); - $d->increaseSold(2, false); - $this->assertEquals($d->get('DTT_sold'), $original_sold_count + 3); - $this->assertEquals($d->get('DTT_reserved'), $original_reserved_count - 1); - } - function test_decrease_sold(){ - $d = EE_Datetime::new_instance(array('DTT_sold'=>5)); - $d->decreaseSold(); - $this->assertEquals(4,$d->get('DTT_sold')); - $d->decreaseSold(2); - $this->assertEquals(2,$d->get('DTT_sold')); - } - /** - * because at one point EE_Datetime overrode ID() from its parent - * (not really for any good reason at the time of writing) - */ - function test_id(){ - $d = EE_Datetime::new_instance(); - $id = $d->save(); - $this->assertEquals($id,$d->ID()); - } - function test_start(){ - $start_time = new DateTime("now"); - $d = EE_Datetime::new_instance(array('DTT_EVT_start'=>$start_time->format('U'))); - $this->assertEquals($start_time->format('U'),$d->start()); - } - function test_end(){ - $end_time =new DateTime("now"); - $d = EE_Datetime::new_instance(array('DTT_EVT_end'=>$end_time->format('U'))); - $this->assertEquals($end_time->format('U'),$d->end()); - } - function test_reg_limit(){ - $d = EE_Datetime::new_instance(array('DTT_reg_limit'=>10)); - $this->assertEquals(10,$d->get('DTT_reg_limit')); - } - function test_sold(){ - $d = EE_Datetime::new_instance(array('DTT_sold'=>10)); - $this->assertEquals(10,$d->sold()); - } - function test_sold_out(){ - $d = EE_Datetime::new_instance(array('DTT_reg_limit'=>10)); - $this->assertFalse($d->sold_out()); - $d->set_sold(10); - $this->assertTrue($d->sold_out()); - $d->set('DTT_reg_limit',EE_INF); - $this->assertFalse($d->sold_out()); - } - function test_spaces_remaining(){ - $d = EE_Datetime::new_instance(array('DTT_reg_limit'=>20,'DTT_sold'=>5)); - $this->assertEquals(15,$d->spaces_remaining()); - } - function test_is_upcoming(){ - $d = EE_Datetime::new_instance(array('DTT_EVT_start'=>time() + 1000 )); - $this->assertTrue($d->is_upcoming()); - $d->set('DTT_EVT_start',time() - 1000 ); - $this->assertFalse($d->is_upcoming()); - } - function test_is_active(){ - $d = EE_Datetime::new_instance(array('DTT_EVT_start'=>time() - 1000, 'DTT_EVT_end'=>time() + 1000)); - $this->assertTrue($d->is_active()); - $d->set('DTT_EVT_start',time() + 500); - $this->assertFalse($d->is_active()); - } - function test_is_expired(){ - $d = EE_Datetime::new_instance(array('DTT_EVT_end'=>time() - 1000)); - $this->assertTrue($d->is_expired()); - $d->set('DTT_EVT_end',time() + 1000); - $this->assertFalse($d->is_expired()); - } - function test_get_dtt_display_name(){ - //test using actual dates because now could result in different results depending on what time of day it is - $base_date = date_create_from_format( 'Y-m-d H:i:s', '2015-01-01 00:00:00' ); - $testing_date = clone $base_date; - - //setup datetime with different months for start and end dates. - $testing_date->add( new DateInterval( 'P1M' ) ); - $d = EE_Datetime::new_instance(array('DTT_name'=>'monkey time', 'DTT_EVT_start'=>$base_date->format('U'), 'DTT_EVT_end'=>$testing_date->format('U'))); - $d->set_date_format( 'Y-m-d' ); - $d->set_time_format( 'h:i a' ); - $this->assertEquals( $base_date->format('M j\, Y g:i a') . ' - ' . $testing_date->format('M j\, Y g:i a'),$d->get_dtt_display_name()); - $this->assertEquals('monkey time',$d->get_dtt_display_name(true)); - - //setup datetime with start date and end date with same month but different days. - $testing_date->sub( new DateInterval( 'P15D' ) ); - $d = EE_Datetime::new_instance(array('DTT_name'=>'monkey time', 'DTT_EVT_start'=>$base_date->format('U'), 'DTT_EVT_end'=>$testing_date->format('U'))); - $d->set_date_format( 'Y-m-d' ); - $d->set_time_format( 'h:i a' ); - $this->assertEquals( $base_date->format( 'M j\, g:i a') . ' - ' . $testing_date->format( 'M j\, g:i a Y' ), $d->get_dtt_display_name() ); - - //setup datetime with start date and end date the same day but different times. - $testing_date = clone $base_date; - $testing_date->add( new DateInterval( 'PT1H' ) ); - $d = EE_Datetime::new_instance(array('DTT_name'=>'monkey time', 'DTT_EVT_start'=>$base_date->format('U'), 'DTT_EVT_end'=>$testing_date->format('U'))); - $d->set_date_format( 'Y-m-d' ); - $d->set_time_format( 'h:i a' ); - $this->assertEquals( $base_date->format( 'F j\, Y' ) . ' @ ' . $base_date->format( 'g:i a') . ' - ' . $testing_date->format( 'g:i a' ), $d->get_dtt_display_name() ); - } - - - - - /** - * This tests the ticket_types_available_for_purchase method. - * @since 4.6.0 - * @group testDate - */ - public function test_ticket_types_available_for_purchase() { - //setup some dates we'll use for testing with. - $timezone = new DateTimeZone( 'America/Toronto' ); - $now_for_test = new DateTime( 'now', $timezone ); - // set time explicitly - $now_for_test->setTime(14, 00); - $upcoming_start_date = clone $now_for_test; - $past_start_date = clone $now_for_test; - $upcoming_end_date = clone $now_for_test; - $upcoming_start_date->add(new DateInterval('P1D')); - $past_start_date->sub(new DateInterval('P2D')); - $upcoming_end_date->add(new DateInterval('P2D')); - $current = clone $now_for_test; - $formats = array( 'Y-d-m', 'h:i a' ); - $full_format = implode( ' ', $formats ); - - //create some tickets - $tickets = array( - 'expired_ticket' => array( 'TKT_start_date' => $past_start_date->format($full_format), 'TKT_end_date' => $past_start_date->format($full_format), 'timezone' => 'America/Toronto', 'formats' =>$formats ), - 'upcoming_ticket' => array( 'TKT_start_date' => $past_start_date->format( $full_format ), 'TKT_end_date' => $upcoming_start_date->format( $full_format ), 'timezone' => 'America/Toronto', 'formats' => $formats ) - ); - - $datetimes = array( - 'expired_datetime' => $this->factory->datetime->create( array( 'DTT_EVT_start' => $past_start_date->format( $full_format ), 'DTT_EVT_end' => $past_start_date->format( $full_format), 'timezone' => 'America/Toronto', 'formats' => $formats ) ), - 'upcoming_datetime' => $this->factory->datetime->create( array( 'DTT_EVT_start' => $upcoming_start_date->format( $full_format ), 'DTT_EVT_end' => $upcoming_end_date->format( $full_format), 'timezone' => 'America/Toronto', 'formats' => $formats ) ), - 'active_datetime' => $this->factory->datetime->create( array( 'DTT_EVT_start' => $current->format( $full_format ), 'DTT_EVT_end' => $upcoming_end_date->format( $full_format), 'timezone' => 'America/Toronto', 'formats' => $formats ) ), - 'sold_out_datetime' => $this->factory->datetime->create( array( 'DTT_EVT_start' => $upcoming_start_date->format( $full_format ), 'DTT_EVT_end' => $upcoming_start_date->format( $full_format), 'DTT_reg_limit' => 10, 'DTT_sold' => 10, 'timezone' => 'America/Toronto', 'formats' => $formats ) ) - ); - - //assign tickets to all datetimes - foreach ( $datetimes as $datetime ) { - foreach( $tickets as $ticket_args ) { - $tkt = $this->factory->ticket->create ( $ticket_args ); - $datetime->_add_relation_to( $tkt, 'Ticket' ); - $datetime->save(); - } - } - - //okay NOW we have some objects for testing with. - - //test expired_datetime - $this->assertEmpty( $datetimes['expired_datetime']->ticket_types_available_for_purchase() ); - - //test upcoming datetime - $tickets = $datetimes['upcoming_datetime']->ticket_types_available_for_purchase(); - $this->assertEquals( 1, count( $tickets ) ); - $this->assertInstanceOf( 'EE_Ticket', reset( $tickets ) ); - - //test active datetime - $tickets = $datetimes['active_datetime']->ticket_types_available_for_purchase(); - $this->assertEquals( 1, count( $tickets ) ); - $this->assertInstanceOf( 'EE_Ticket', reset( $tickets ) ); - - //test sold out datetime - $this->assertEmpty( $datetimes['sold_out_datetime']->ticket_types_available_for_purchase() ); - } - - - - /** - * @since 4.6.x - */ - public function test_time_range() { - //setup a datetime for testing - $start_date = new DateTime( 'now' ); - $end_date = new DateTime( 'now + 3 hours' ); - $datetime = $this->factory->datetime->create( - array( - 'DTT_EVT_start' => $start_date->format( 'Y-m-d H:i:s' ), - 'DTT_EVT_end' => $end_date->format( 'Y-m-d H:i:s' ), - 'timezone' => 'UTC', 'formats' => array( 'Y-m-d', 'H:i:s' ) - ) - ); - - //assert we have a datetime - $this->assertInstanceOf( 'EE_Datetime', $datetime ); - - //verify that the expected time format is generated. - $this->assertEquals( $start_date->format( 'H:i:s' ) . ' - ' . $end_date->format( 'H:i:s' ), $datetime->time_range() ); - } - - - - /** - * @group 8861 - * @doesNotPerformAssertions - */ - public function test_tickets_remaining() { - $this->loadTestScenarios(); - $scenarios = $this->scenarios->get_scenarios_by_type( 'datetime' ); - foreach ( $scenarios as $scenario ) { - /* @type EE_Datetime $datetime */ - $datetime = $scenario->get_scenario_object(); - $datetime_id_to_tickets_map = $scenario->get_expected( 'datetime_id_to_tickets_map' ); - if ( isset( $datetime_id_to_tickets_map[ $datetime->ID() ] ) ) { - $tickets_remaining = $datetime->tickets_remaining(); - //echo "\n tickets_remaining: " . $tickets_remaining; - $tickets_expected = $datetime_id_to_tickets_map[ $datetime->ID() ]; - //echo "\n tickets_expected: " . $tickets_expected; - $this->assertEquals( $tickets_expected, $tickets_remaining ); - } - } - } - - -} - -// End of file EE_Datetime_Test.php -// Location: tests/testcases/core/db_classes/EE_Datetime_Test.php diff --git a/tests/testcases/core/db_classes/EE_Event_Test.php b/tests/testcases/core/db_classes/EE_Event_Test.php deleted file mode 100644 index d457a934e01..00000000000 --- a/tests/testcases/core/db_classes/EE_Event_Test.php +++ /dev/null @@ -1,792 +0,0 @@ - 'power1')); - $e->save(); - $d = EE_Datetime::new_instance(array('EVT_ID' => $e->ID())); - $d->save(); - $primary_datetime = $e->primary_datetime(); - $this->assertEquals($d, $primary_datetime); - } - - - - public function test_datetimes_ordered() - { - $e = EE_Event::new_instance(array('EVT_name' => 'power1')); - $e->save(); - $d_exp = EE_Datetime::new_instance( - array( - 'EVT_ID' => $e->ID(), - 'DTT_EVT_start' => time() - 10, - 'DTT_EVT_end' => time() - 5, - ) - ); - $d_exp->save(); - $d_del = EE_Datetime::new_instance( - array( - 'EVT_ID' => $e->ID(), - 'DTT_EVT_start' => time() - 5, - 'DTT_EVT_end' => time() + 5, - 'DTT_deleted' => true, - ) - ); - $d_del->save(); - $d_ok = EE_Datetime::new_instance( - array( - 'EVT_ID' => $e->ID(), - 'DTT_EVT_start' => time() - 1, - 'DTT_EVT_end' => time() + 5, - ) - ); - $d_ok->save(); - $ds = $e->datetimes_ordered(); - $this->assertArrayContains($d_exp, $ds); - //$this->assertArrayDoesNotContain($d_del,$ds); @todo: bug, this assert actually fails because we have deactivated default where params - $this->assertArrayContains($d_ok, $ds); - //do it so it hides expired - $ds = $e->datetimes_ordered(false); - $this->assertArrayDoesNotContain($d_exp, $ds); -// $this->assertArrayDoesNotContain($d_del, $ds); @todo: bug, this assert actually fails because we have deactivated - $this->assertArrayContains($d_ok, $ds); - //do it so it hides expired but shows deleted - $ds = $e->datetimes_ordered(false, true); - $this->assertArrayDoesNotContain($d_exp, $ds); - $this->assertArrayContains($d_del, $ds); - $this->assertArrayContains($d_ok, $ds); - //do it so it shows the deleted one - $ds = $e->datetimes_ordered(true, true); - $this->assertArrayContains($d_exp, $ds); - $this->assertArrayContains($d_del, $ds); - $this->assertArrayContains($d_ok, $ds); - //double-check the ordering. - $first_d = array_shift($ds); - $this->assertEquals($d_exp, $first_d); - $second_d = array_shift($ds); - $this->assertEquals($d_del, $second_d); - $third_d = array_shift($ds); - $this->assertEquals($d_ok, $third_d); - } - - - - public function test_active_status() - { - /** @type EE_Event $e */ - $e = EE_Event::new_instance(array('status' => 'publish')); - $e->save(); - //echo "\n\n create Ticket"; - $t = EE_Ticket::new_instance( - array( - 'TKT_start_date' => time() - 100, - 'TKT_end_date' => time() + 50, - 'TKT_qty' => 100, - 'TKT_sold' => 0, - ) - ); - $t->save(); - $d_now = EE_Datetime::new_instance( - array( - 'EVT_ID' => $e->ID(), - 'DTT_EVT_start' => time() - 100, - 'DTT_EVT_end' => time() + 50, - ) - ); - $d_now->_add_relation_to($t, 'Ticket'); - $d_now->save(); - $d_exp = EE_Datetime::new_instance( - array( - 'EVT_ID' => $e->ID(), - 'DTT_EVT_start' => time() - 10, - 'DTT_EVT_end' => time() - 5, - ) - ); - $d_exp->_add_relation_to($t, 'Ticket'); - $d_exp->save(); - $d_upcoming = EE_Datetime::new_instance( - array( - 'EVT_ID' => $e->ID(), - 'DTT_EVT_start' => time() + 10, - 'DTT_EVT_end' => time() + 15, - ) - ); - $d_upcoming->_add_relation_to($t, 'Ticket'); - $d_upcoming->save(); - // add tickets - $ticket_1 = $this->new_model_obj_with_dependencies( - 'Ticket', array('TKT_qty' => '10', 'TKT_sold' => '5', 'TKT_reserved' => '0') - ); - $d_now->_add_relation_to($ticket_1, 'Ticket'); - $ticket_2 = $this->new_model_obj_with_dependencies( - 'Ticket', array('TKT_qty' => '10', 'TKT_sold' => '5', 'TKT_reserved' => '0') - ); - $d_exp->_add_relation_to($ticket_2, 'Ticket'); - $ticket_3 = $this->new_model_obj_with_dependencies( - 'Ticket', array('TKT_qty' => '10', 'TKT_sold' => '5', 'TKT_reserved' => '0') - ); - $d_upcoming->_add_relation_to($ticket_3, 'Ticket'); - //test - $this->assertEquals(EE_Datetime::active, $e->get_active_status(true)); - $e->_remove_relation_to($d_now, 'Datetime'); - $this->assertEquals(EE_Datetime::upcoming, $e->get_active_status(true)); - $e->_remove_relation_to($d_upcoming, 'Datetime'); - $this->assertEquals(EE_Datetime::expired, $e->get_active_status(true)); - } - - - - public function test_get_number_of_tickets_sold() - { - $e = EE_Event::new_instance(); - $e->save(); - $d_now = EE_Datetime::new_instance( - array( - 'EVT_ID' => $e->ID(), - 'DTT_EVT_start' => time() - 100, - 'DTT_EVT_end' => time() - 50, - 'DTT_sold' => 5, - ) - ); - $d_now->save(); - $d_exp = EE_Datetime::new_instance( - array( - 'EVT_ID' => $e->ID(), - 'DTT_EVT_start' => time() - 10, - 'DTT_EVT_end' => time() - 5, - 'DTT_sold' => 15, - ) - ); - $d_exp->save(); - $this->assertEquals(20, $e->get_number_of_tickets_sold()); - $e->_remove_relation_to($d_now, 'Datetime'); - $this->assertEquals(15, $e->get_number_of_tickets_sold()); - } - - - - /** - * @since 4.8.0 - */ - public function test_total_available_spaces() - { - $this->loadTestScenarios(); - //grab test scenarios. - $scenarios = $this->scenarios->get_scenarios_by_type('event'); - foreach ($scenarios as $scenario) { - $expected = $scenario->get_expected('total_available_spaces'); - if ($expected) { - /** @type EE_Event $event */ - $event = $scenario->get_scenario_object(); - $calculator = new EventEspresso\core\domain\services\event\EventSpacesCalculator($event); - $this->assertEquals( - $expected, - $event->total_available_spaces(), - 'Testing ' . $scenario->name . ' for "total_available_spaces"' - ); - $this->assertEquals( - $expected, - $calculator->totalSpacesAvailable(), - 'Testing ' . $scenario->name . ' for "totalSpacesAvailable"' - ); - } - } - } - - - - /** - * @since 4.8.0 - */ - public function test_spaces_remaining_for_sale() - { - $this->loadTestScenarios(); - //grab test scenarios - $scenarios = $this->scenarios->get_scenarios_by_type('event'); - foreach ($scenarios as $scenario) { - if ($scenario->skip()) { - continue; - } - $expected = $scenario->get_expected('total_remaining_spaces'); - if ($expected !== false) { - /** @type EE_Event $event */ - $event = $scenario->get_scenario_object(); - $calculator = new EventEspresso\core\domain\services\event\EventSpacesCalculator($event); - $this->assertEquals( - $expected, - $event->spaces_remaining_for_sale(), - 'Testing ' . $scenario->name . ' for "total_remaining_spaces"' - ); - $this->assertEquals( - $expected, - $calculator->spacesRemaining(), - 'Testing ' . $scenario->name . ' for "total_remaining_spaces"' - ); - } - } - } - - - - /** - * @since 4.8.0 - */ - public function test_spaces_remaining_for_sale_for_Event_Scenario_H() - { - $this->loadTestScenarios(); - //grab test scenario - $scenario = $this->scenarios->get_scenario_by_name('Event Scenario H - Two Classes'); - // verify - if ( - ! $scenario instanceof EE_Test_Scenario - || ( - $scenario instanceof EE_Test_Scenario - && $scenario->name !== 'Event Scenario H - Two Classes' - ) - ) { - return; - } - /** @type EE_Event $event */ - $event = $scenario->get_scenario_object(); - $calculator = new EventEspresso\core\domain\services\event\EventSpacesCalculator($event); - $expected = $scenario->get_expected('total_remaining_spaces'); - if ($expected !== false) { - $this->assertEquals( - $expected, - $event->spaces_remaining_for_sale(), - 'Testing ' . $scenario->name - ); - $this->assertEquals( - $expected, - $calculator->spacesRemaining(), - 'Testing ' . $scenario->name . ' for "total_remaining_spaces"' - ); - } - $this->assertEquals( - EE_Datetime::upcoming, - $event->get_active_status(true), - $scenario->name . ' active_status after initial 6 ticket sales' - ); - // now sell 2 more tickets - $scenario->run_additional_logic(array('qty' => 2)); - $expected = $scenario->get_expected('total_remaining_spaces_4'); - $this->assertEquals( - $expected, - $event->spaces_remaining_for_sale(), - 'Testing ' . $scenario->name . ' after selling an additional 2 tickets' - ); - $this->assertEquals( - $expected, - $calculator->spacesRemaining(), - 'Testing ' . $scenario->name . ' for "total_remaining_spaces" after selling an additional 2 tickets' - ); - $this->assertEquals( - EE_Datetime::upcoming, - $event->get_active_status(true), - $scenario->name . ' active_status after an additional 2 ticket sales' - ); - // now sell the last 4 tickets - $scenario->run_additional_logic(array('qty' => 4)); - $expected = $scenario->get_expected('total_remaining_spaces_0'); - $this->assertEquals( - $expected, - $event->spaces_remaining_for_sale(), - 'Testing ' . $scenario->name . ' after selling the last 4 tickets' - ); - $this->assertEquals( - $expected, - $calculator->spacesRemaining(), - 'Testing ' . $scenario->name . ' for "total_remaining_spaces" after selling the last 4 tickets' - ); - $this->assertEquals( - EE_Datetime::sold_out, - $event->get_active_status(true), - $scenario->name . ' active_status after selling the last 4 tickets' - ); - } - - - - /** - * @since 4.8.0 - */ - public function test_spaces_remaining_for_sale_for_Event_Scenario_I() - { - $this->loadTestScenarios(); - //grab test scenario - $scenario = $this->scenarios->get_scenario_by_name('Event Scenario I - Four Tickets One Date'); - // verify - if ( - ! $scenario instanceof EE_Test_Scenario - || ( - $scenario instanceof EE_Test_Scenario - && $scenario->name !== 'Event Scenario I - Four Tickets One Date' - ) - ) { - return; - } - /** @type EE_Event $event */ - $event = $scenario->get_scenario_object(); - $calculator = new EventEspresso\core\domain\services\event\EventSpacesCalculator($event); - $expected = $scenario->get_expected('total_remaining_spaces'); - if ($expected !== false) { - $this->assertEquals( - $expected, - $event->spaces_remaining_for_sale(), - 'Testing ' . $scenario->name - ); - $this->assertEquals( - $expected, - $calculator->spacesRemaining(), - 'Testing ' . $scenario->name . ' for "total_remaining_spaces"' - ); - } - $this->assertEquals( - EE_Datetime::upcoming, - $event->get_active_status(true), - $scenario->name . ' active_status after initial setup' - ); - // now sell first batch of tickets - $scenario->run_additional_logic(array('tkt_id' => 1, 'qty' => 2)); - $scenario->run_additional_logic(array('tkt_id' => 2, 'qty' => 2)); - $expected = $scenario->get_expected('total_remaining_spaces_20'); - $this->assertEquals( - $expected, - $event->spaces_remaining_for_sale(), - 'Testing ' . $scenario->name . ' after selling first 4 tickets' - ); - $this->assertEquals( - $expected, - $calculator->spacesRemaining(), - 'Testing ' . $scenario->name . ' for "total_remaining_spaces" after selling first 4 tickets' - ); - $this->assertEquals( - EE_Datetime::upcoming, - $event->get_active_status(true), - $scenario->name . ' active_status after selling first 4 tickets' - ); - // now sell second batch of tickets - THIS IS WHEN IT USED TO SELL OUT - $scenario->run_additional_logic(array('tkt_id' => 1, 'qty' => 2)); - $scenario->run_additional_logic(array('tkt_id' => 3, 'qty' => 1)); - $scenario->run_additional_logic(array('tkt_id' => 4, 'qty' => 1)); - $expected = $scenario->get_expected('total_remaining_spaces_16'); - $this->assertEquals( - $expected, - $event->spaces_remaining_for_sale(), - 'Testing ' . $scenario->name . ' after selling 8 tickets' - ); - $this->assertEquals( - $expected, - $calculator->spacesRemaining(), - 'Testing ' . $scenario->name . ' for "total_remaining_spaces" after selling 8 tickets' - ); - $this->assertEquals( - EE_Datetime::upcoming, - $event->get_active_status(true), - $scenario->name . ' active_status after selling 8 tickets' - ); - // now sell third batch of tickets - $scenario->run_additional_logic(array('tkt_id' => 1, 'qty' => 1)); - $scenario->run_additional_logic(array('tkt_id' => 2, 'qty' => 1)); - $scenario->run_additional_logic(array('tkt_id' => 3, 'qty' => 2)); - $expected = $scenario->get_expected('total_remaining_spaces_12'); - $this->assertEquals( - $expected, - $event->spaces_remaining_for_sale(), - 'Testing ' . $scenario->name . ' after selling 12 tickets' - ); - $this->assertEquals( - $expected, - $calculator->spacesRemaining(), - 'Testing ' . $scenario->name . ' for "total_remaining_spaces" after selling 12 tickets' - ); - $this->assertEquals( - EE_Datetime::upcoming, - $event->get_active_status(true), - $scenario->name . ' active_status after selling 12 tickets' - ); - // and a fourth batch of tickets - $scenario->run_additional_logic(array('tkt_id' => 1, 'qty' => 1)); - $scenario->run_additional_logic(array('tkt_id' => 2, 'qty' => 1)); - $scenario->run_additional_logic(array('tkt_id' => 3, 'qty' => 1)); - $scenario->run_additional_logic(array('tkt_id' => 4, 'qty' => 1)); - $expected = $scenario->get_expected('total_remaining_spaces_8'); - $this->assertEquals( - $expected, - $event->spaces_remaining_for_sale(), - 'Testing ' . $scenario->name . ' after selling 16 tickets' - ); - $this->assertEquals( - $expected, - $calculator->spacesRemaining(), - 'Testing ' . $scenario->name . ' for "total_remaining_spaces" after selling 16 tickets' - ); - $this->assertEquals( - EE_Datetime::upcoming, - $event->get_active_status(true), - $scenario->name . ' active_status after selling 16 tickets' - ); - // and a fifth - $scenario->run_additional_logic(array('tkt_id' => 2, 'qty' => 2)); - $scenario->run_additional_logic(array('tkt_id' => 3, 'qty' => 1)); - $scenario->run_additional_logic(array('tkt_id' => 4, 'qty' => 1)); - $expected = $scenario->get_expected('total_remaining_spaces_4'); - $this->assertEquals( - $expected, - $event->spaces_remaining_for_sale(), - 'Testing ' . $scenario->name . ' after selling 20 tickets' - ); - $this->assertEquals( - $expected, - $calculator->spacesRemaining(), - 'Testing ' . $scenario->name . ' for "total_remaining_spaces" after selling 20 tickets' - ); - $this->assertEquals( - EE_Datetime::upcoming, - $event->get_active_status(true), - $scenario->name . ' active_status after selling 20 tickets' - ); - // last batch - $scenario->run_additional_logic(array('tkt_id' => 3, 'qty' => 1)); - $scenario->run_additional_logic(array('tkt_id' => 4, 'qty' => 3)); - $expected = $scenario->get_expected('total_remaining_spaces_0'); - $this->assertEquals( - $expected, - $event->spaces_remaining_for_sale(), - 'Testing ' . $scenario->name . ' after selling all 24 tickets' - ); - $this->assertEquals( - $expected, - $calculator->spacesRemaining(), - 'Testing ' . $scenario->name . ' for "total_remaining_spaces" after selling all 24 tickets' - ); - $this->assertEquals( - EE_Datetime::sold_out, - $event->get_active_status(true), - $scenario->name . ' active_status after selling all 24 tickets' - ); - } - - - /** - * @group sold_out_status_check - * @throws DomainException - * @throws EE_Error - * @throws \EventEspresso\core\exceptions\UnexpectedEntityException - */ - public function test_perform_sold_out_status_check() - { - $this->markTestSkipped('Temporarily skipped because of sporadic, unexplained fails. See https://events.codebasehq.com/projects/event-espresso/tickets/11394'); - $event = EE_Event::new_instance( - array( - 'status' => 'publish' - ) - ); - $event->save(); - $datetime = EE_Datetime::new_instance( - array( - 'EVT_ID' => $event->ID(), - 'DTT_EVT_start' => time() + WEEK_IN_SECONDS, - 'DTT_EVT_end' => time() + WEEK_IN_SECONDS + DAY_IN_SECONDS, - 'DTT_reg_limit' => 4, - 'DTT_sold' => 2, - ) - ); - $datetime->save(); - $ticket_A = EE_Ticket::new_instance( - array( - 'TKT_name' => 'Ticket A', - 'TKT_qty' => 4, - 'TKT_sold' => 2, - ) - ); - $ticket_A->save(); - $ticket_A->_add_relation_to($datetime, 'Datetime'); - $this->assertEquals('publish', $event->status()); - $this->assertEquals(EE_Datetime::upcoming, $event->get_active_status()); - $ticket_A->increaseSold(2); - $this->assertEquals('publish', $event->status()); - $this->assertEquals(EE_Datetime::upcoming, $event->get_active_status(true)); - // now perform sold out check - $sold_out = $event->perform_sold_out_status_check(); - $this->assertTrue($sold_out); - $this->assertEquals(EEM_Event::sold_out, $event->status()); - $this->assertEquals(EE_Datetime::sold_out, $event->get_active_status(true)); - } - - - /** - * @group sold_out_status_check - * @throws DomainException - * @throws EE_Error - * @throws \EventEspresso\core\exceptions\UnexpectedEntityException - */ - public function test_perform_sold_out_status_check_with_expired_ticket() - { - $event = EE_Event::new_instance( - array( - 'status' => 'publish' - ) - ); - $event->save(); - $datetime = EE_Datetime::new_instance( - array( - 'EVT_ID' => $event->ID(), - 'DTT_EVT_start' => time() + WEEK_IN_SECONDS, - 'DTT_EVT_end' => time() + WEEK_IN_SECONDS + DAY_IN_SECONDS, - 'DTT_reg_limit' => 4, - 'DTT_sold' => 2, - ) - ); - $datetime->save(); - // expired early bird ticket - $ticket_A = EE_Ticket::new_instance( - array( - 'TKT_name' => 'Ticket A', - 'TKT_start_date' => time() - MONTH_IN_SECONDS, - 'TKT_end_date' => time() - WEEK_IN_SECONDS, - 'TKT_qty' => 4, - 'TKT_sold' => 2, - ) - ); - $ticket_A->save(); - $ticket_A->_add_relation_to($datetime, 'Datetime'); - // regular on sale ticket - $ticket_B = EE_Ticket::new_instance( - array( - 'TKT_name' => 'Ticket B', - 'TKT_start_date' => time() - WEEK_IN_SECONDS, - 'TKT_end_date' => time() + WEEK_IN_SECONDS, - 'TKT_qty' => 4, - 'TKT_sold' => 0, - ) - ); - $ticket_B->save(); - $ticket_B->_add_relation_to($datetime, 'Datetime'); - $this->assertEquals('publish', $event->status()); - $this->assertEquals(EE_Datetime::upcoming, $event->get_active_status()); - $ticket_B->increaseSold(2); - $this->assertEquals('publish', $event->status()); - $this->assertEquals(EE_Datetime::upcoming, $event->get_active_status(true)); - // now perform sold out check - $sold_out = $event->perform_sold_out_status_check(); - $this->assertTrue($sold_out); - $this->assertEquals(EEM_Event::sold_out, $event->status()); - $this->assertEquals(EE_Datetime::sold_out, $event->get_active_status(true)); - } - - /** - * @since 4.10.0.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - */ - public function testAddQuestionGroupPrimary() - { - $e = $this->new_model_obj_with_dependencies('Event'); - $this->assertEquals( - 0, - EEM_Event_Question_Group::instance()->count( - [ - [ - 'EVT_ID' => $e->ID(), - 'QSG_ID' => 1, - 'EQG_primary' => true - ] - ] - ) - ); - $e->add_question_group(1, true); - $this->assertEquals( - 1, - EEM_Event_Question_Group::instance()->count( - [ - [ - 'EVT_ID' => $e->ID(), - 'QSG_ID' => 1, - 'EQG_primary' => true - ] - ] - ) - ); - } - - /** - * @since 4.10.0.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testAddQuestionGroupAdditional() - { - $e = $this->new_model_obj_with_dependencies('Event'); - $this->assertEquals( - 0, - EEM_Event_Question_Group::instance()->count( - [ - [ - 'EVT_ID' => $e->ID(), - 'QSG_ID' => 1, - 'EQG_additional' => true - ] - ] - ) - ); - $e->add_question_group(1, false); - $this->assertEquals( - 1, - EEM_Event_Question_Group::instance()->count( - [ - [ - 'EVT_ID' => $e->ID(), - 'QSG_ID' => 1, - 'EQG_additional' => true - ] - ] - ) - ); - } - - /** - * @since 4.10.0.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testRemoveQuestionGroupPrimary() - { - $e = $this->new_model_obj_with_dependencies('Event'); - $e->add_question_group(1, true); - $this->assertEquals( - 1, - EEM_Event_Question_Group::instance()->count( - [ - [ - 'EVT_ID' => $e->ID(), - 'QSG_ID' => 1, - 'EQG_primary' => true - ] - ] - ) - ); - $e->remove_question_group(1, true); - $this->assertEquals( - 0, - EEM_Event_Question_Group::instance()->count( - [ - [ - 'EVT_ID' => $e->ID(), - 'QSG_ID' => 1, - 'EQG_primary' => true - ] - ] - ) - ); - } - - /** - * @since 4.10.0.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testRemoveQuestionGroupAdditional() - { - $e = $this->new_model_obj_with_dependencies('Event'); - $e->add_question_group(1, false); - $this->assertEquals( - 1, - EEM_Event_Question_Group::instance()->count( - [ - [ - 'EVT_ID' => $e->ID(), - 'QSG_ID' => 1, - 'EQG_additional' => true - ] - ] - ) - ); - $e->remove_question_group(1, false); - $this->assertEquals( - 0, - EEM_Event_Question_Group::instance()->count( - [ - [ - 'EVT_ID' => $e->ID(), - 'QSG_ID' => 1, - 'EQG_additional' => true - ] - ] - ) - ); - } - - /** - * @since 4.10.0.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testRemoveQuestionGroupAdditionalStillPrimary() - { - $e = $this->new_model_obj_with_dependencies('Event'); - $e->add_question_group(1, true); - $e->add_question_group(1, false); - $this->assertEquals( - 1, - EEM_Event_Question_Group::instance()->count( - [ - [ - 'EVT_ID' => $e->ID(), - 'QSG_ID' => 1, - 'EQG_primary' => true, - 'EQG_additional' => true - ] - ] - ) - ); - $e->remove_question_group(1, false); - $this->assertEquals( - 1, - EEM_Event_Question_Group::instance()->count( - [ - [ - 'EVT_ID' => $e->ID(), - 'QSG_ID' => 1, - 'EQG_primary' => true, - 'EQG_additional' => false - ] - ] - ) - ); - } -} -// End of file EE_Event_Test.php -// Location: /tests/testcases/core/db_classes/EE_Event_Test.php diff --git a/tests/testcases/core/db_classes/EE_Import_Test.php b/tests/testcases/core/db_classes/EE_Import_Test.php deleted file mode 100644 index 7666efa4864..00000000000 --- a/tests/testcases/core/db_classes/EE_Import_Test.php +++ /dev/null @@ -1,549 +0,0 @@ -new_model_obj_with_dependencies('Event'); - $original_datetime1 = clone $this->new_model_obj_with_dependencies( 'Datetime', array( 'EVT_ID' => $original_event1->ID() ) ); - $original_ticket1 = clone $this->new_model_obj_with_dependencies( 'Ticket' ); - $original_datetime_ticket = clone $this->new_model_obj_with_dependencies( 'Datetime_Ticket', array( 'DTT_ID' => $original_datetime1->ID(), 'TKT_ID' => $original_ticket1->ID() ) ); - - - //now let's make some model objects that AREN'T in this database - //that could confuse the importer - $other_db_event = $this->new_model_obj_with_dependencies('Event', array(), false ); - $other_db_event_props = $other_db_event->model_field_array(); - $other_db_event_props[ 'EVT_ID' ] = $original_event1->ID(); - - $other_db_event2 = $this->new_model_obj_with_dependencies( 'Event', array(), false ); - $other_db_event2_props = $other_db_event2->model_field_array(); - $other_db_event2_props[ 'EVT_ID' ] = 1000; - - $other_db_datetime = $this->new_model_obj_with_dependencies( 'Datetime', array( 'EVT_ID' => $original_event1->ID() ), false ); - $other_db_datetime_props = $other_db_datetime->model_field_array(); - $other_db_datetime_props[ 'DTT_ID' ] = $original_datetime1->ID(); - - $other_db_ticket = $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_ID' => $original_ticket1->ID() ), false ); - $other_db_ticket_props = $other_db_ticket->model_field_array(); - $other_db_ticket_props[ 'TKT_ID' ] = $original_ticket1->ID(); - - $other_db_datetime_ticket = EE_Datetime_Ticket::new_instance( array( 'DTT_ID' => $original_datetime1->ID(), 'TKT_ID' => $original_ticket1->ID() ), false ); - $other_db_datetime_ticket_props = $other_db_datetime_ticket->model_field_array(); - $other_db_datetime_ticket_props[ 'DTK_ID' ] = $original_datetime_ticket->ID(); - - $event_count = EEM_Event::instance()->count(); - $datetime_count = EEM_Datetime::instance()->count(); - $ticket_count = EEM_Ticket::instance()->count(); - $datetime_ticket_count = EEM_Datetime_Ticket::instance()->count(); - - - $csv_data_rows = array( - 'Event' => array( - $other_db_event_props, - $other_db_event2_props - ), - 'Datetime' => array( - $other_db_datetime_props - ), - 'Ticket' => array( - $other_db_ticket_props - ), - 'Datetime_Ticket' => array( - $other_db_datetime_ticket_props - ) - ); - - //ok give it a whirl... - $new_mappings = EE_Import::instance()->save_data_rows_to_db($csv_data_rows, true, array() ); - //what should have happened: - //we should have a mapping for each newly-inserted - //events... - $this->assertNotEmpty( $new_mappings ); - $this->assertArrayHasKey( 'Event', $new_mappings ); - $event1_mapping = $new_mappings[ 'Event' ][ $original_event1->ID() ]; - $this->assertNotEmpty( $event1_mapping ); - $this->assertNotEquals( $original_event1->ID(), $event1_mapping ); - $event2_mapping = $new_mappings[ 'Event' ][ 1000 ]; - $this->assertNotEmpty( $event2_mapping ); - $this->assertNotEquals( 1000, $event1_mapping ); - //newly inerted datetime... - $this->assertNotEmpty( $new_mappings ); - $this->assertArrayHasKey( 'Datetime', $new_mappings ); - $datetime1_mapping = $new_mappings[ 'Datetime' ][ $original_datetime1->ID() ]; - $this->assertNotEmpty( $datetime1_mapping ); - $this->assertNotEquals( $original_datetime1->ID(), $datetime1_mapping ); - //newly inserted ticket - $this->assertNotEmpty( $new_mappings ); - $this->assertArrayHasKey( 'Ticket', $new_mappings ); - $ticket1_mapping = $new_mappings[ 'Ticket' ][ $original_ticket1->ID() ]; - $this->assertNotEmpty( $ticket1_mapping ); - $this->assertNotEquals( $original_ticket1->ID(), $ticket1_mapping ); - //and newly inserted datetime-ticke... - $this->assertNotEmpty( $new_mappings ); - $this->assertArrayHasKey( 'Datetime_Ticket', $new_mappings ); - $datetime_ticket_mapping = $new_mappings[ 'Datetime_Ticket' ][ $original_datetime_ticket->ID() ]; - $this->assertNotEmpty( $datetime_ticket_mapping ); - $this->assertNotEquals( $original_datetime_ticket->ID(), $datetime_ticket_mapping ); - - - //we should have inserted 2 new events, 1 new datetime, 1 new ticket and 1 new relation - $this->assertEquals( $event_count + 2, EEM_Event::instance()->count() ); - $this->assertEquals( $datetime_count + 1, EEM_Datetime::instance()->count() ); - $this->assertEquals( $ticket_count + 1, EEM_Ticket::instance()->count() ); - $this->assertEquals( $datetime_ticket_count + 1, EEM_Datetime_Ticket::instance()->count() ); - //the newly inserted datetime shoudl have bene associated to the new event for $other_db_event_props - $inserted_datetime_from_other_db = EEM_Datetime::instance()->get_one_by_ID( $datetime1_mapping ); - $this->assertEquals( $event1_mapping, $inserted_datetime_from_other_db->get('EVT_ID') ); - //there shoudl be a newly inserted ticket - $inserted_ticket_from_other_db = EEM_Ticket::instance()->get_one_by_ID( $ticket1_mapping ); - $this->assertNotNull( $inserted_ticket_from_other_db ); - //the newly inserted datetime-ticket should hae been associated with the newly inserted datetime and ticket - $inserted_datetime_ticket_from_other_db = EEM_Datetime_Ticket::instance()->get_one_by_ID( $datetime_ticket_mapping ); - $this->assertEquals( $ticket1_mapping, $inserted_datetime_ticket_from_other_db->get( 'TKT_ID' ) ); - $this->assertEquals( $datetime1_mapping, $inserted_datetime_ticket_from_other_db->get( 'DTT_ID' ) ); - //the original event shouldn't be affected, nor should it have more than the original datetime on it - $updated_event1 = EEM_Event::instance()->refresh_entity_map_from_db( $original_event1->ID() ); - $this->assertEEModelObjectsEquals( $original_event1, $updated_event1 ); - //the original datetime shoudln't be affected, nor shoudl it have more than the original ticket associagted with it - $updated_datetime1 = EEM_Datetime::instance()->refresh_entity_map_from_db( $original_datetime1->ID() ); - $this->assertEEModelObjectsEquals( $original_datetime1, $updated_datetime1 ); - } - - /** - * test we dont insert conflicting data (especially term-taxonomies) - */ - public function test_save_data_array_to_db__from_other_site__avoid_inserting_conflicting_data() { - $term_taxonomy = $this->new_model_obj_with_dependencies( 'Term_Taxonomy', array( 'taxonomy' => 'category', 'description' => 'original term-taxonomy' ) ); - $this->assertEquals( 'original term-taxonomy', $term_taxonomy->get( 'description' ) ); - $term_taxonomy_from_other_db = $this->new_model_obj_with_dependencies( 'Term_Taxonomy', - array( - 'term_id' => $term_taxonomy->get('term_id'), - 'taxonomy' => 'category', - 'description' => 'in other db' ), false ); - $country_usa = EEM_Country::instance()->get_one_by_ID( 'US' ); - $this->assertEquals( false, $country_usa->get( 'CNT_is_EU' ) ); - - //have the contry be slightly modified in the exporting site - $country_usa_props = $country_usa->model_field_array(); - $country_usa_props[ 'CNT_is_EU' ] = true; - $csv_data_rows = array( - 'Term_Taxonomy' => array( - $term_taxonomy_from_other_db->model_field_array() - ), - 'Country' => array( - $country_usa_props - ) - ); - $term_taxonomy_count = EEM_Term_Taxonomy::instance()->count(); - $country_count = EEM_Country::instance()->count(); - - //ok give it a whirl (keep the term-taxonomy's "term_id" the same by having it map to itself, obviously super unlikely but helps testing) - EE_Import::instance()->save_data_rows_to_db($csv_data_rows, true, array( 'Term' => array( $term_taxonomy->get( 'term_id' ) => $term_taxonomy->get( 'term_id' ) ) ) ); - - $this->assertEmpty( EE_Import::instance()->get_total_update_errors() ); - $this->assertEmpty( EE_Import::instance()->get_total_inserts() ); - $this->assertEmpty( EE_Import::instance()->get_total_insert_errors() ); - $this->assertEquals( 2, EE_Import::instance()->get_total_updates() ); - //there shouldn't be any new term taxonomies or countries - $this->assertEquals( $term_taxonomy_count, EEM_Term_Taxonomy::instance()->count() ); - $this->assertEquals( $country_count, EEM_Country::instance()->count() ); - //however, they should be updated - $updated_term_taxonomy = EEM_Term_Taxonomy::instance()->refresh_entity_map_from_db( $term_taxonomy->ID() ); - $this->assertEquals( 'in other db', $updated_term_taxonomy->get( 'description' ) ); - $updated_country = EEM_Country::instance()->refresh_entity_map_from_db( $country_usa->ID() ); - $this->assertEquals( true, $updated_country->get( 'CNT_is_EU' ) ); - } - /** - * test if an INT fk doesn't exist -> set it to NULL! - * if a STRING fk exists -> leave it alone - */ - public function test_save_data_array_to_db__from_other_site__fks_that_dont_exist() { - //model object with foreign key that's an INT (should be set to 0 or NULL) - $att = $this->new_model_obj_with_dependencies( 'Attendee', array( 'STA_ID' => 99999, 'CNT_ISO' => '77' ), false ); - $att_props = $att->model_field_array(); - $att_props[ 'ATT_ID' ] = 123; - $csv_data = array( - 'Attendee' => array( - $att_props - ) - ); - $att_count = EEM_Attendee::instance()->count(); - $mappings = EE_Import::instance()->save_data_rows_to_db($csv_data, true, array() ); - $this->assertEquals( $att_count + 1, EEM_Attendee::instance()->count() ); - //the STA_ID should ahve been set to 0, but teh CNT_ISO should have been left as-is - $att_id_in_db = $mappings[ 'Attendee' ][ 123 ]; - $att_in_db = EEM_Attendee::instance()->get_one_by_ID( $att_id_in_db ); - //model object with a foreign key that's a STRING (should be left as-is) - $this->assertEquals( 0, $att_in_db->get( 'STA_ID' ) ); - $this->assertEquals( '77', $att_in_db->get( 'CNT_ISO' ) ); - } - - /** - * @todo: if a foreign key can point to multiple models, only use mappings - * that apply - */ - public function test_save_data_array_to_db__from_other_site__fks_that_point_to_multiple_models() { - $this->markTestSkipped('addressed on ticket 7537.'); - //multiple types of fks that point ot multiple models: ones accompanied by a model name field and ones without - //using model name field: extra metas - //sans-model name field: term-relationships - $extra_meta_id = 1; - $extra_meta_id2 = 4; - $imaginary_txn_or_reg_id = 2; - - $an_event_id = 3; - - $csv_data = array( - 'Extra_Meta' => array( - //two extra meta rows, attached to different model objects - //but each coincidentally has the same ID - array( - 'EXM_ID' => $extra_meta_id, - 'OBJ_ID' => $imaginary_txn_or_reg_id, - 'EXM_type' => 'Transaction', - 'EXM_key' => 'foo', - 'EXM_value' => 'bar' - ), - array( - 'EXM_ID' => $extra_meta_id2, - 'OBJ_ID' => $imaginary_txn_or_reg_id, - 'EXM_type' => 'Registration', - 'EXM_key' => 'foo', - 'EXM_value' => 'bar' - ) - ), - 'Term_Relationship' => array( - array( - 'object_id' => $an_event_id,//an "event" - 'term_taxonomy_id' => 0, - 'term_order' => 1 - ) - ) - ); - - $mapped_txn_id = 4; - $mapped_reg_id = 124; - $mapped_event_id = 322; - $mappings = array( - 'Transaction' => array( - $imaginary_txn_or_reg_id => $mapped_txn_id - ), - 'Registration' => array( - $imaginary_txn_or_reg_id => $mapped_reg_id - ), - 'Event' => array( - $an_event_id => $mapped_event_id - ) - ); - //start test - $new_mappings = EE_Import::instance()->save_data_rows_to_db( $csv_data, true, $mappings ); - //ok, so we should have inserted 3 things, - $this->assertEquals( 2, count( $new_mappings[ 'Extra_Meta' ] ) ); - $this->assertEquals( 1, count( $new_mappings[ 'Term_Relationship' ] ) ); - //check that they correctly used the mappings that previously existed - $inserted_extra_meta_1_id = $new_mappings[ 'Extra_Meta' ][ $extra_meta_id ]; - $inserted_extra_meta_1 = EEM_Extra_Meta::instance()->get_one_by_ID( $inserted_extra_meta_1_id ); - $this->assertEquals( 'Transaction', $inserted_extra_meta_1->get( 'EXM_type' ) ); - $this->assertEquals( $mapped_txn_id, $inserted_extra_meta_1->get( 'OBJ_ID' ) ); - $inserted_extra_meta_2_id = $new_mappings[ 'Extra_Meta' ][ $extra_meta_id2 ]; - $inserted_extra_meta_2 = EEM_Extra_Meta::instance()->get_one_by_ID( $inserted_extra_meta_2_id ); - $this->assertEquals( 'Registration', $inserted_extra_meta_2->get( 'EXM_type' ) ); - $this->assertEquals( $mapped_reg_id, $inserted_extra_meta_2->get( 'OBJ_ID' ) ); - $inserted_term_r_id = $new_mappings[ 'Term_Relationship' ][ EEM_Term_Relationship::instance()->get_index_primary_key_string( $csv_data[ 'Term_Relationship' ][ 0 ])]; - $term_r = EEM_Term_Relationship::instance()->get_one_by_ID( $inserted_term_r_id ); - $this->assertInstanceOf( 'EE_Term_Relationship', $term_r); - $this->assertEquals( $mapped_event_id, $term_r->get('object_id' ) ); - - } - - /** - * test that term relationships are migrated ok if they would conflict with something already in the db - */ - function test_save_data_array_to_db__from_other_site__no_duplicate_term_relationships() { - /** - * @todo: unskip this once its working again - */ - $this->markTestSkipped('fixed on ticket 7537, https://events.codebasehq.com/projects/event-espresso/tickets/7537'); - $event_id_from_other_db = 122; - $term_tax_from_other_db = 32; - $old_term_r_order = 3; - $new_term_r_order = 123; - - $old_term_r_data = array( - 'object_id' => $event_id_from_other_db, - 'term_taxonomy_id' => $term_tax_from_other_db, - 'term_order' => $old_term_r_order - ); - - $a_real_event = $this->new_model_obj_with_dependencies( 'Event' ); - $a_real_term_taxonomy = $this->new_model_obj_with_dependencies( 'Term_Taxonomy' ); - $a_real_term_r = $this->new_model_obj_with_dependencies( 'Term_Relationship', array( 'object_id' => $a_real_event->ID(), 'term_taxonomy_id' => $a_real_term_taxonomy->ID(), 'term_order' => $new_term_r_order ) ); - - $csv_data = array( - 'Term_Relationship' => array( - $old_term_r_data - ) - ); - $mapping_data = array( - 'Event' => array( - $event_id_from_other_db => $a_real_event->ID() - ), - 'Term_Taxonomy' => array( - $term_tax_from_other_db => $a_real_term_taxonomy->ID() - ) - ); - $old_term_r_count = EEM_Term_Relationship::instance()->count(); - $new_mapping = EE_Import::instance()->save_data_rows_to_db( $csv_data, true, $mapping_data ); - $this->_assertNoImportErrors(); - //there should be NO new term relationships. it should have just been updated - $this->assertEquals( $old_term_r_count, EEM_Term_Relationship::instance()->count() ); - $this->assertEquals( 1, count( $new_mapping[ 'Term_Relationship' ] ) ); - $old_term_r_id = EEM_Term_Relationship::instance()->get_index_primary_key_string( $old_term_r_data ); - $new_term_r_id = $new_mapping[ 'Term_Relationship' ][ $old_term_r_id ]; - $new_term_r = EEM_Term_Relationship::instance()->get_one_by_ID( $new_term_r_id ); - $this->assertInstanceOf( 'EE_Term_Relationship', $new_term_r ); - $this->assertEquals( $old_term_r_order, $new_term_r->get('term_order' ) ); - - } - /** - * @todo: account for wp 4.2 term splitting (https://developer.wordpress.org/plugins/taxonomy/working-with-split-terms-in-wp-4-2/) - */ - function test_save_data_array_to_db__from_this_site__term_split(){ - //create term and term taxonomy - $term = $this->new_model_obj_with_dependencies( 'Term', array( 'name' => 'Jaguar', 'slug' => 'jag' ) ); - $ttcar = $this->new_model_obj_with_dependencies( 'Term_Taxonomy', array( 'term_id' => $term->ID(), 'taxonomy' => 'cars', 'description' => 'A fast car' ) ); - $ttcat = $this->new_model_obj_with_dependencies( 'Term_Taxonomy', array( 'term_id' => $term->ID(), 'taxonomy' => 'cats', 'description' => 'A large black cat that likes to swim' ) ); - //create "csv" data for it (pretend exported) - $csv_data = array( - 'Term' => array( - $term->model_field_array() - ), - 'Term_Taxonomy' => array( - $ttcar->model_field_array(), - $ttcat->model_field_array() - ) - ); - $this->assertEquals( $ttcat->get('term_id' ), $ttcar->get( 'term_id' ) ); - //split the term in the "wp" way. Our model objet $ttcar will NOT get updated on its own - $new_term_id_for_car = _split_shared_term( $term->ID(), $ttcar->ID() ); - $ttcar = EEM_Term_Taxonomy::instance()->refresh_entity_map_from_db( $ttcar->ID() ); -// echo "updated term taxonomy:";var_dump($ttcar->model_field_array()); - $this->assertNotEquals( $ttcat->get( 'term_id' ), $ttcar->get( 'term_id' ) ); - //import it - $new_mapping = EE_Import::instance()->save_data_rows_to_db( $csv_data, false, array() ); - - $ttcar = EEM_Term_Taxonomy::instance()->refresh_entity_map_from_db( $ttcar->ID() ); - - //when it's done importing, we should have saved a term-taxonomy for the new term, not re-inserted a term-taxonomy to the old term - //and because it used the models, the model objects we have in scope should already be up-to-date - $this->assertEquals( $new_term_id_for_car, $ttcar->get( 'term_id' ) ); - - } - /** - * in wp 4.1 there was no functions for term splitting. So let's add a filter - * to simulate that and mostly make sure there are no fatal errors - */ - function test_save_data_array_to_db__from_this_site__term_split__in_wp_41(){ - add_filter( 'FHEE__EE_Import__handle_split_term_ids__function_exists', '__return_false' ); - $term = $this->new_model_obj_with_dependencies( 'Term', array( 'name' => 'Jaguar', 'slug' => 'jag' ) ); - $ttcar = $this->new_model_obj_with_dependencies( 'Term_Taxonomy', array( 'term_id' => $term->ID(), 'taxonomy' => 'cars', 'description' => 'A fast car' ) ); - $ttcat = $this->new_model_obj_with_dependencies( 'Term_Taxonomy', array( 'term_id' => $term->ID(), 'taxonomy' => 'cats', 'description' => 'A large black cat that likes to swim' ) ); - //create "csv" data for it (pretend exported) - $csv_data = array( - 'Term' => array( - $term->model_field_array() - ), - 'Term_Taxonomy' => array( - $ttcar->model_field_array(), - $ttcat->model_field_array() - ) - ); - //now there should just not be any fatal errors when importing - EE_Import::instance()->save_data_rows_to_db( $csv_data, false, array() ); - $this->assertTrue( true ); - } - //@todo: test state which have int PKs, but should haev an unique index according to state abbrev and country - //@todo: test more regarding things with NO pks - //@todo: I suspect people will want to avoid duplicate states. This could be achieved by having the state abbrev and country ISO be a unique key - //@todo: add unit tests for inserting and updating models with no pks - -// public function test_save_data_array_to_db__from_other_site_second_time(){ -// //test that things in the mapping are remembered -// } -// -// public function test_save_data_array_to_db__from_same_site_first_time(){ -// //check for deleted things -// //should update old thing -// -// } -// public function test_save_data_array_to_db__from_same_site_second_time(){ -// //check -// } - - public function setUp(){ - parent::setUp(); - EE_Import::reset(); - } - protected function _assertNoImportErrors(){ - $notices = EE_Error::get_notices(false, false, true); - $this->assertEmpty( EE_Import::instance()->get_total_update_errors(), isset( $notices['errors'] ) ? $notices['errors'] : ''); - $this->assertEmpty( EE_Import::instance()->get_total_insert_errors(), isset( $notices['errors'] ) ? $notices['errors'] : '' ); - } -} -//in case this is run on WP 4.1, we'd still like to be able to test this WP 4.2 feature -if( ! function_exists( '_split_shared_term' ) ){ - /** - * Create a new term for a term_taxonomy item that currently shares its term with another term_taxonomy. - * - * @since 4.2.0 - * @access private - * - * @param int $term_id ID of the shared term. - * @param int $term_taxonomy_id ID of the term_taxonomy item to receive a new term. - * @return int|WP_Error When the current term does not need to be split (or cannot be split on the current database - * schema), `$term_id` is returned. When the term is successfully split, the new term_id is - * returned. A `WP_Error` is returned for miscellaneous errors. - */ - function _split_shared_term( $term_id, $term_taxonomy_id ) { - global $wpdb; - // Don't try to split terms if database schema does not support shared slugs. - $current_db_version = get_option( 'db_version' ); - if ( $current_db_version < 30133 ) { - return $term_id; - } - - // If there are no shared term_taxonomy rows, there's nothing to do here. - $shared_tt_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy tt WHERE tt.term_id = %d AND tt.term_taxonomy_id != %d", $term_id, $term_taxonomy_id ) ); - if ( ! $shared_tt_count ) { - return $term_id; - } - - // Pull up data about the currently shared slug, which we'll use to populate the new one. - $shared_term = $wpdb->get_row( $wpdb->prepare( "SELECT t.* FROM $wpdb->terms t WHERE t.term_id = %d", $term_id ) ); - - $new_term_data = array( - 'name' => $shared_term->name, - 'slug' => $shared_term->slug, - 'term_group' => $shared_term->term_group, - ); - - if ( false === $wpdb->insert( $wpdb->terms, $new_term_data ) ) { - return new WP_Error( 'db_insert_error', __( 'Could not split shared term.' ), $wpdb->last_error ); - } - - $new_term_id = (int) $wpdb->insert_id; - - // Update the existing term_taxonomy to point to the newly created term. - $wpdb->update( $wpdb->term_taxonomy, - array( 'term_id' => $new_term_id ), - array( 'term_taxonomy_id' => $term_taxonomy_id ) - ); - - // Reassign child terms to the new parent. - $term_taxonomy = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $term_taxonomy_id ) ); - $children_tt_ids = $wpdb->get_col( $wpdb->prepare( "SELECT term_taxonomy_id FROM $wpdb->term_taxonomy WHERE taxonomy = %s AND parent = %d", $term_taxonomy->taxonomy, $term_id ) ); - - if ( ! empty( $children_tt_ids ) ) { - foreach ( $children_tt_ids as $child_tt_id ) { - $wpdb->update( $wpdb->term_taxonomy, - array( 'parent' => $new_term_id ), - array( 'term_taxonomy_id' => $child_tt_id ) - ); - clean_term_cache( $term_id, $term_taxonomy->taxonomy ); - } - } else { - // If the term has no children, we must force its taxonomy cache to be rebuilt separately. - clean_term_cache( $new_term_id, $term_taxonomy->taxonomy ); - } - - // Clean the cache for term taxonomies formerly shared with the current term. - $shared_term_taxonomies = $wpdb->get_row( $wpdb->prepare( "SELECT taxonomy FROM $wpdb->term_taxonomy WHERE term_id = %d", $term_id ) ); - if ( $shared_term_taxonomies ) { - foreach ( $shared_term_taxonomies as $shared_term_taxonomy ) { - clean_term_cache( $term_id, $shared_term_taxonomy ); - } - } - - // Keep a record of term_ids that have been split, keyed by old term_id. See {@see wp_get_split_term()}. - $split_term_data = get_option( '_split_terms', array() ); - if ( ! isset( $split_term_data[ $term_id ] ) ) { - $split_term_data[ $term_id ] = array(); - } - - $split_term_data[ $term_id ][ $term_taxonomy->taxonomy ] = $new_term_id; - - update_option( '_split_terms', $split_term_data ); - - /** - * Fires after a previously shared taxonomy term is split into two separate terms. - * - * @since 4.2.0 - * - * @param int $term_id ID of the formerly shared term. - * @param int $new_term_id ID of the new term created for the $term_taxonomy_id. - * @param int $term_taxonomy_id ID for the term_taxonomy row affected by the split. - * @param string $taxonomy Taxonomy for the split term. - */ - do_action( 'split_shared_term', $term_id, $new_term_id, $term_taxonomy_id, $term_taxonomy->taxonomy ); - - return $new_term_id; - } -} -if( ! function_exists( 'wp_get_split_terms' ) ) { - /** - * - * @param type $old_term_id - * @return int - */ - function wp_get_split_terms( $old_term_id ) { - $split_terms = get_option( '_split_terms', array() ); - - $terms = array(); - if ( isset( $split_terms[ $old_term_id ] ) ) { - $terms = $split_terms[ $old_term_id ]; - } - - return $terms; - } -} -if( ! function_exists( 'wp_get_split_term' ) ){ - /** - * Get the new term ID corresponding to a previously split term. - * - * @since 4.2.0 - * - * @param int $old_term_id Term ID. This is the old, pre-split term ID. - * @param string $taxonomy Taxonomy that the term belongs to. - * @return bool|int If a previously split term is found corresponding to the old term_id and taxonomy, the new term_id - * will be returned. If no previously split term is found matching the parameters, returns false. - */ - function wp_get_split_term( $old_term_id, $taxonomy ) { - $split_terms = wp_get_split_terms( $old_term_id ); - - $term_id = false; - if ( isset( $split_terms[ $taxonomy ] ) ) { - $term_id = (int) $split_terms[ $taxonomy ]; - } - - return $term_id; -} -} - -// End of file EE_Import_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_classes/EE_Line_Item_Test.php b/tests/testcases/core/db_classes/EE_Line_Item_Test.php deleted file mode 100644 index 04bc43228f1..00000000000 --- a/tests/testcases/core/db_classes/EE_Line_Item_Test.php +++ /dev/null @@ -1,679 +0,0 @@ -save(); - $l = EE_Line_Item::new_instance(array('OBJ_type' => 'Transaction', 'OBJ_ID' => $t->ID())); - $this->assertNotNull($l->generate_code()); - } - - function test_get_nearest_descendant_of_type() - { - $txn = $this->new_typical_transaction(); - $line_item = $txn->total_line_item(); - $old_tax_subtotal = EEH_Line_Item::get_nearest_descendant_of_type($line_item, EEM_Line_Item::type_tax_sub_total); - $this->assertInstanceOf('EE_Line_Item', $old_tax_subtotal); - $this->assertEquals(EEM_Line_Item::type_tax_sub_total, $old_tax_subtotal->type()); - $old_tax = EEH_Line_Item::get_nearest_descendant_of_type($line_item, EEM_Line_Item::type_tax); - $this->assertInstanceOf('EE_Line_Item', $old_tax_subtotal); - $this->assertEquals(EEM_Line_Item::type_tax, $old_tax->type()); - - } - - /** - * test that if you call this on the grand total, that it doesn't REMOVE the taxes from it - * @group 7026 - */ - function test_recalculate_pre_tax_total__dont_change_grand_total() - { - $txn = $this->new_typical_transaction(); - $total_line_item = $txn->total_line_item(); - $total_including_taxes = $total_line_item->total(); - $total_line_item->recalculate_pre_tax_total(); - $this->assertNotEquals(0, $txn->tax_total()); - $this->assertEquals($total_including_taxes, $total_line_item->total()); - } - - - /** - * @group 10654 - * Verifies that when we recalculate an event's subtotal, we also update its unit price right away. - * Otherwise it can lead to issues like reported on 10654. - */ - public function test_recalculate_pre_tax_total__dont_miss_updating_subtotal_unit_prices() - { - $txn = $this->new_typical_transaction(); - $total_line_item = $txn->total_line_item(); - $event_subtotal_array = EEH_Line_Item::get_event_subtotals($total_line_item); - $event_subtotal = reset($event_subtotal_array); - $original_event_subtotal_amount = $event_subtotal->total(); - $original_event_subtotal_unit_price = $event_subtotal->unit_price(); - // EEH_Line_Item::visualize($total_line_item); - //ok now let's add a discount, under the event subtotal - EEH_Line_Item::add_percentage_based_item( - $event_subtotal, - 'Some discount', - -50, - 'should affect event subtotals unit price' - ); - // EEH_Line_Item::visualize($total_line_item); - $total_line_item->recalculate_pre_tax_total(); - // EEH_Line_Item::visualize($total_line_item); - //so that should have reduced the event subtotal's total by half, AND its unit price - $this->assertEquals($original_event_subtotal_amount / 2, $event_subtotal->total()); - $this->assertEquals($original_event_subtotal_unit_price / 2, $event_subtotal->unit_price()); - } - - /** - * @group 11126 - */ - public function testRecaculatePreTaxTotalUpdatesLineItemSubtotalQuantitiesToZeroForNextRequest() - { - //verify that if we decrement the total of a li, and its subtotal li becomes 0 - $txn = $this->new_typical_transaction(); - $total_li = $txn->total_line_item(); - $event_subtotals = EEH_Line_Item::get_event_subtotals($total_li); - $event_subtotal = reset($event_subtotals); - $line_items = $event_subtotal->children(); - $ticket_li = reset($line_items); - $this->assertEquals(1, $event_subtotal->quantity()); - $this->assertEquals(1, $ticket_li->quantity()); - EEH_Line_Item::decrement_quantity($ticket_li); - $total_li->recalculate_total_including_taxes(); - $this->assertEquals(0, $ticket_li->quantity()); - $this->assertEquals(0, $event_subtotal->quantity()); - //pretend it's the next request and double-check the changes stuck - EEM_Line_Item::reset(); - $event_subtotal_from_db = EEM_Line_Item::instance()->get_one_by_ID($event_subtotal->ID()); - $ticket_li_from_db = EEM_Line_Item::instance()->get_one_by_ID($ticket_li->ID()); - $this->assertEquals(0, $event_subtotal_from_db->quantity()); - $this->assertEquals(0, $ticket_li_from_db->quantity()); - } - - - /** - * @group 11126 - */ - public function testRecaculatePreTaxTotalUpdatesLineItemSubtotalQuantitiesFromZero() - { - //verify that if we decrement the total of a li, and its subtotal li becomes 0 - $txn = $this->new_typical_transaction(); - $total_li = $txn->total_line_item(); - $event_subtotals = EEH_Line_Item::get_event_subtotals($total_li); - $event_subtotal = reset($event_subtotals); - $line_items = $event_subtotal->children(); - $ticket_li = reset($line_items); - $this->assertEquals(1, $event_subtotal->quantity()); - $this->assertEquals(1, $ticket_li->quantity()); - EEH_Line_Item::decrement_quantity($ticket_li); - $total_li->recalculate_total_including_taxes(); - $this->assertEquals(0, $ticket_li->quantity()); - $this->assertEquals(0, $event_subtotal->quantity()); - //ok now re-increase the quantity - EEH_Line_Item::increment_quantity($ticket_li); - $total_li->recalculate_total_including_taxes(); - $this->assertEquals(1, $ticket_li->quantity()); - $this->assertEquals(1, $event_subtotal->quantity()); - //ok bump it up again. But only events' quantity should increase (that's the current behaviour so may as well keep it) - EEH_Line_Item::increment_quantity($ticket_li); - $total_li->recalculate_total_including_taxes(); - $this->assertEquals(2, $ticket_li->quantity()); - $this->assertEquals(1, $event_subtotal->quantity()); - - } - - /** - * Verifies that after we update a line item and recalculate the total, the tax subtotal also gets updated - * @group 11126 - */ - public function testRecalculatePreTaxTotalAndUpdateTaxesToo() - { - $txn = $this->new_typical_transaction(); - $old_grant_total = $txn->total_line_item()->total(); - //make sure it has a tax on it - $taxes_subtotal_li = EEH_Line_Item::get_taxes_subtotal($txn->total_line_item()); - $old_taxes_subtotal_total = $taxes_subtotal_li->total(); - $taxes = $taxes_subtotal_li->children(); - $this->assertCount(1, $taxes); - $tax_li = reset($taxes); - $old_tax_li_total = $tax_li->total(); - $this->assertGreaterThan(0, $taxes_subtotal_li->total()); - //take note of the current ticket price - $ticket_lis = EEH_Line_Item::get_ticket_line_items($txn->total_line_item()); - $this->assertCount(1, $ticket_lis); - $ticket_li = reset($ticket_lis); - $ticket_li->set_quantity(2); - $old_ticket_li_total = $ticket_li->total(); - //modify the ticket price and recalculate the total - $subitem_lis = $ticket_li->children(); - $this->assertCount(1, $subitem_lis); - $txn->total_line_item()->recalculate_total_including_taxes(); - //ok now pretend it's a new request - EEM_Line_Item::reset(); - $ticket_li_from_db = EEM_Line_Item::instance()->get_one_by_ID($ticket_li->ID()); - $total_li_from_db = EEM_Line_Item::instance()->get_one_by_ID($txn->total_line_item()->ID()); - $tax_li_from_db = EEM_Line_Item::instance()->get_one_by_ID($tax_li->ID()); - $tax_subtotal_li_from_db = EEM_Line_Item::instance()->get_one_by_ID($taxes_subtotal_li->ID()); - //verify the total was changed - $this->assertEquals($old_ticket_li_total * 2, $ticket_li_from_db->total()); - $this->assertEquals($old_grant_total * 2, $total_li_from_db->total()); - //lastly, verify the tax and tax subtotals got updated - $this->assertEquals($old_tax_li_total * 2, $tax_li_from_db->total()); - $this->assertEquals($old_taxes_subtotal_total * 2, $tax_subtotal_li_from_db->total()); - } - - - /** - * @group 8964 - * Uses a particular number and quantity that has been shown to cause rounding problems - * prior to the work on 8964 (specifically, if you had 2 transactions for 1 ticket purchase each - * the total for both transactions was NOT the same as 1 transaction for 2 ticket purchases) - */ - function test_recalculate_pre_tax_total__rounding_issues() - { - $flat_base_price_type_id = EEM_Price_Type::instance()->get_var(array(array('PRT_name' => 'Base Price'))); - $percent_surcharge_price_type_id = EEM_Price_Type::instance()->get_var(array(array('PRT_name' => 'Percent Surcharge'))); - $base_price = $this->new_model_obj_with_dependencies( - 'Price', - array( - 'PRT_ID' => $flat_base_price_type_id, - 'PRC_amount' => 21.67 - )); - $percent_surcharge = $this->new_model_obj_with_dependencies( - 'Price', - array( - 'PRT_ID' => $percent_surcharge_price_type_id, - 'PRC_amount' => 20 - )); - $ticket = $this->new_model_obj_with_dependencies( - 'Ticket', - array( - 'TKT_price' => $base_price->amount() + ($base_price->amount() * $percent_surcharge->amount() / 100), - 'TKT_taxable' => false - )); - $ticket->_add_relation_to($base_price, 'Price'); - $ticket->_add_relation_to($percent_surcharge, 'Price'); - $event = $this->new_model_obj_with_dependencies('Event'); - $datetime = $this->new_model_obj_with_dependencies('Datetime'); - $ticket->_add_relation_to($datetime, 'Datetime'); - - $quantity = 2; - $total_line_item = EEH_Line_Item::add_ticket_purchase(EEH_Line_Item::create_total_line_item(), $ticket, $quantity); - - $this->assertEquals($ticket->price() * $quantity, $total_line_item->total()); - - } - - /** - * * also test that if you call this in order to get the taxable total, that it doesn't update - * the totals to ONLY be taxable totals - * @group 7026 - */ - function test_recalculate_pre_tax_total__dont_save_if_ignoring_nontaxables() - { - //make a txn where NOTHING is taxable - $txn = $this->new_typical_transaction(array('ticket_types' => 2, 'taxable_tickets' => 1)); - $proper_line_items = EEM_Line_Item::instance()->get_all_of_type_for_transaction(EEM_Line_Item::type_line_item, $txn->ID()); - $this->assertEquals(2, count($proper_line_items)); - $taxable_one = FALSE; - $nontaxable_one = FALSE; - $taxable_line_item = NULL; - foreach ($proper_line_items as $line_item) { - if ($line_item->is_taxable()) { - $taxable_one = TRUE; - $taxable_line_item = $line_item; - } else { - $nontaxable_one = TRUE; - } - } - $this->assertTrue($taxable_one); - $this->assertTrue($nontaxable_one); - $this->assertNotEquals(0, $txn->tax_total()); - - $total_line_item = $txn->total_line_item(); - $old_total = $total_line_item->total(); - //when we calculate the pre-tax, including only taxable items (ie, we're wanting - //to know how much to apply taxes to) we don't change the grand or ticket totals - $pretax_total = $total_line_item->taxable_total(); - //because there is only one taxable line item, the taxable total should equals its total - $this->assertEquals($taxable_line_item->total(), $pretax_total); - //check we didn't assign the taxable total to be the grand total - $this->assertNotEquals($pretax_total, $total_line_item->total()); - $this->assertEquals($old_total, $total_line_item->total()); - //find tickets subtotal and make sure it hasn't been assigned to be the taxable total either - //temporarily commented out because this throws an error. - //$this->assertNotEquals( $pretax_total, $total_line_item->get_child_line_item('tickets')->total() ); - } - - /** - * Create a line item tree with an initially empty subtotal. We shouldn't - * have trouble calculating its total with a percent line item. - * Also, we shouldn't need to set any totals: the call to recalculate_total_including_taxes - * should take care of setting them all - * @group 8566 - */ - function test_recalculate_total_including_taxes__unknown_subtotals_initially() - { - $event_subtotal = EE_Line_Item::new_instance( - array( - 'LIN_code' => 'event1', - 'LIN_name' => 'EventA', - 'LIN_type' => EEM_Line_Item::type_sub_total, - 'OBJ_type' => 'Event', - 'LIN_total' => 0, - )); - $event_subtotal->save(); - $normal_line_item = EE_Line_Item::new_instance( - array( - 'LIN_code' => '12354', - 'LIN_name' => 'ticketA', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'OBJ_type' => 'Ticket', - 'LIN_unit_price' => 10, - 'LIN_quantity' => 2, - 'LIN_order' => 1, - 'LIN_parent' => $event_subtotal->ID() - )); - $normal_line_item->save(); - $percent_line_item = EE_Line_Item::new_instance( - array( - 'LIN_code' => 'dscntfry', - 'LIN_name' => 'Discounto', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'OBJ_type' => '', - 'LIN_unit_price' => null, - 'LIN_quantity' => null, - 'LIN_percent' => -25, - 'LIN_order' => 1000, - 'LIN_parent' => $event_subtotal->ID() - )); - $percent_line_item->save(); - $event_subtotal->recalculate_total_including_taxes(); -// EEH_Line_Item::visualize( $event_subtotal ); - $this->assertEquals(20, $normal_line_item->total()); - $this->assertEquals(15, $event_subtotal->total()); - $this->assertEquals(-5, $percent_line_item->total()); - - } - - /** - * Verifies that we fix sub line item quantities and line item unit prices - * @group 8566 - */ - function test_recalculate_total_including_taxes__fix_sub_line_item_quantities() - { - $line_item = EE_Line_Item::new_instance( - array( - 'LIN_name' => 'ticket', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_quantity' => 2 - )); - $line_item->save(); - $flat_sub_line_item = EE_Line_Item::new_instance( - array( - 'LIN_name' => 'flat', - 'LIN_type' => EEM_Line_Item::type_sub_line_item, - 'LIN_unit_price' => 10, - 'LIN_quantity' => 1,//it should match its parent, which is 2 - 'LIN_order' => 1, - 'LIN_parent' => $line_item->ID(), - )); - $flat_sub_line_item->save(); - $percent_sub_line_item = EE_Line_Item::new_instance( - array( - 'LIN_name' => 'percent', - 'LIN_type' => EEM_Line_Item::type_sub_line_item, - 'LIN_quantity' => 0, - 'LIN_percent' => -25, - 'LIN_order' => 100, - 'LIN_parent' => $line_item->ID() - )); - $percent_sub_line_item->save(); - $line_item->recalculate_pre_tax_total(); - $this->assertEquals(2, $flat_sub_line_item->quantity()); - $this->assertEquals(1, $percent_sub_line_item->quantity()); - $this->assertEquals(20, $flat_sub_line_item->total()); - $this->assertEquals(-5, $percent_sub_line_item->total()); - $this->assertEquals(15, $line_item->total()); - $this->assertEquals(7.5, $line_item->unit_price()); - } - - /** - * Create a line item tree which was originaly for 6 tickets and a discount, - * but 2 got cancelled and so shouldn't count towards the grand total, - * and so the ticket line item's quantity should be 4 - * @group 5580 - */ - function test_recalculate_total_including_taxes__with_cancellations() - { - $event_subtotal = EE_Line_Item::new_instance( - array( - 'LIN_code' => 'event1', - 'LIN_name' => 'EventA', - 'LIN_type' => EEM_Line_Item::type_sub_total, - 'OBJ_type' => 'Event', - 'LIN_total' => 0, - )); - $event_subtotal->save(); - $normal_line_item = EE_Line_Item::new_instance( - array( - 'LIN_code' => '12354', - 'LIN_name' => 'ticketA', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'OBJ_type' => 'Ticket', - 'LIN_unit_price' => 10, - 'LIN_quantity' => 4, - 'LIN_order' => 1, - 'LIN_parent' => $event_subtotal->ID() - )); - $normal_line_item->save(); - $cancellation_subitem = EE_Line_Item::new_instance( - array( - 'LIN_code' => 'cancellationoruny', - 'LIN_name' => 'cancellationOfA', - 'LIN_type' => EEM_Line_Item::type_cancellation, - 'OBJ_type' => '',//? - 'LIN_unit_price' => 10, - 'LIN_quantity' => 2, - 'LIN_order' => 1, - 'LIN_parent' => $normal_line_item->ID() - )); - $percent_line_item = EE_Line_Item::new_instance( - array( - 'LIN_code' => 'dscntfry', - 'LIN_name' => 'Discounto', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'OBJ_type' => '', - 'LIN_unit_price' => null, - 'LIN_quantity' => null, - 'LIN_percent' => -25, - 'LIN_order' => 1000, - 'LIN_parent' => $event_subtotal->ID() - )); - $percent_line_item->save(); - $event_subtotal->recalculate_total_including_taxes(); -// EEH_Line_Item::visualize( $event_subtotal ); - $this->assertEquals(40, $normal_line_item->total()); - $this->assertEquals(30, $event_subtotal->total()); - $this->assertEquals(-10, $percent_line_item->total()); - - } - - /** - * @group 9439 - */ - function test_recalculate_total_including_taxes__incorrect_total_with_specific_numbers_and_promotion() - { - $total_li = EE_Line_Item::new_instance( - array( - 'LIN_name' => 'total', - 'LIN_type' => EEM_Line_Item::type_total, - ) - ); - $total_li->save(); - - $pretax_subtotal = EE_Line_Item::new_instance( - array( - 'LIN_name' => 'pretax', - 'LIN_type' => EEM_Line_Item::type_sub_total, - 'LIN_code' => 'pre-tax-subtotal', - 'LIN_parent' => $total_li->ID(), - 'LIN_order' => 1 - ) - ); - $pretax_subtotal->save(); - $event_subtotal = EE_Line_Item::new_instance( - array( - 'LIN_name' => 'subtotal', - 'LIN_type' => EEM_Line_Item::type_sub_total, - 'LIN_parent' => $pretax_subtotal->ID(), - 'LIN_order' => 1 - - ) - ); - $event_subtotal->save(); - $line_item = EE_Line_Item::new_instance( - array( - 'LIN_name' => 'ticket', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_quantity' => 1, - 'LIN_is_taxable' => true, - 'LIN_parent' => $event_subtotal->ID(), - 'LIN_order' => 1, - )); - $line_item->save(); - $flat_sub_line_item = EE_Line_Item::new_instance( - array( - 'LIN_name' => 'flat', - 'LIN_type' => EEM_Line_Item::type_sub_line_item, - 'LIN_unit_price' => 21.01, - 'LIN_quantity' => 1, - 'LIN_order' => 1, - 'LIN_parent' => $line_item->ID(), - )); - $flat_sub_line_item->save(); - $percent_discount = EE_Line_Item::new_instance( - array( - 'LIN_name' => 'flat', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_percent' => -50, - 'LIN_quantity' => 1, - 'LIN_order' => 10, - 'LIN_is_taxable' => true, - 'LIN_parent' => $event_subtotal->ID(), - )); - $percent_discount->save(); - $tax_subtotal = EE_Line_Item::new_instance( - array( - 'LIN_name' => 'tax-sub-total', - 'LIN_code' => 'taxes', - 'LIN_type' => EEM_Line_Item::type_tax_sub_total, - 'LIN_order' => 100, - 'LIN_parent' => $total_li->ID(), - ) - ); - $tax_subtotal->save(); - $tax = EE_Line_Item::new_instance( - array( - 'LIN_name' => 'tax', - 'LIN_code' => 'a_tax', - 'LIN_type' => EEM_Line_Item::type_tax, - 'LIN_percent' => 19, - 'LIN_parent' => $tax_subtotal->ID(), - ) - ); - $tax->save(); - $total_li->recalculate_total_including_taxes(); - $this->assertEquals($line_item->total() + $percent_discount->total(), $event_subtotal->total()); - $this->assertEquals(12.50, $total_li->total()); - $this->assertEquals($pretax_subtotal->total(), $total_li->get_items_total()); - } - - /** - * @group 8464 - * Verifies that if the line item is for a relation that isn't currently defined - * (and in core there is no promotion model) that we don't get an exception or warning, just null - */ - public function test_get_object__non_existent_model_name() - { - $li = $this->new_model_obj_with_dependencies('Line_Item', array('OBJ_ID' => 123, 'OBJ_type' => 'Promotion')); - $this->assertNull($li->get_object()); - } - - /** - * @group 8464 - * Verifies that if the line item is for a relation that isn't currently RELATED but IS defined - */ - public function test_get_object__non_related_model_name() - { - $li = $this->new_model_obj_with_dependencies('Line_Item', array('OBJ_ID' => 123, 'OBJ_type' => 'Answer')); - $this->assertNull($li->get_object()); - } - - /** - * @group 8488 - */ - public function test_taxable_total__percent_items() - { - $parent_li = $this->new_model_obj_with_dependencies('Line_Item', - array( - 'LIN_name' => 'total', - 'LIN_type' => EEM_Line_Item::type_sub_total, - )); - //create 2 childline items, one taxable and one not - $taxable = $this->new_model_obj_with_dependencies('Line_Item', - array( - 'LIN_name' => 'taxable', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_total' => 10, - 'LIN_unit_price' => 10, - 'LIN_percent' => 0, - 'LIN_quantity' => 1, - 'LIN_is_taxable' => true, - 'LIN_parent' => $parent_li->ID() - )); - $nontaxable = $this->new_model_obj_with_dependencies('Line_Item', - array( - 'LIN_name' => 'nontaxable', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_total' => 10, - 'LIN_unit_price' => 10, - 'LIN_percent' => 0, - 'LIN_quantity' => 1, - 'LIN_is_taxable' => false, - 'LIN_parent' => $parent_li->ID() - )); - //and then a percent line item that is taxable - $discount = $this->new_model_obj_with_dependencies('Line_Item', - array( - 'LIN_name' => 'discount', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_total' => -10, - 'LIN_unit_price' => 0, - 'LIN_percent' => -50, - 'LIN_quantity' => 1, - 'LIN_is_taxable' => true, - 'LIN_parent' => $parent_li->ID() - )); - //so when we ask their parent for the taxable total, it should only - //factor in the taxable portion of the percent item - //only half of the 10 dollar discount (so 5) should be facotred into taxes - //so the taxable total should be the taxable ticket (10) minus half the discount (5) - //so it should equal 5 - $this->assertEquals(5, $parent_li->taxable_total()); - } - - /** - * @group 8488 - */ - public function test_taxable_total__negative_total() - { - $parent_li = $this->new_model_obj_with_dependencies('Line_Item', - array( - 'LIN_name' => 'total', - 'LIN_type' => EEM_Line_Item::type_sub_total, - )); - //create a child line item that's NOT taxable - $taxable = $this->new_model_obj_with_dependencies('Line_Item', - array( - 'LIN_name' => 'taxable', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_total' => 10, - 'LIN_unit_price' => 10, - 'LIN_percent' => 0, - 'LIN_quantity' => 1, - 'LIN_is_taxable' => false, - 'LIN_parent' => $parent_li->ID() - )); - //and then a flat discount that is "taxable" (ie, taxes take it into account) - $discount = $this->new_model_obj_with_dependencies('Line_Item', - array( - 'LIN_name' => 'discount', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_total' => -10, - 'LIN_unit_price' => -10, - 'LIN_percent' => 0, - 'LIN_quantity' => 1, - 'LIN_is_taxable' => true, - 'LIN_parent' => $parent_li->ID() - )); - //so when we ask their parent for the taxable total, it should only - //factor in the taxable portion of the percent item - //only half of the 10 dollar discount (so 5) should be facotred into taxes - //so the taxable total should be the taxable ticket (10) minus half the discount (5) - //so it should equal 5 - $this->assertEquals(0, $parent_li->taxable_total()); - } - - /** - * @group 8572 - */ - public function test_set_parent() - { - $li1 = $this->new_model_obj_with_dependencies('Line_Item', array('LIN_parent' => null), false); - - $li2 = $this->new_model_obj_with_dependencies('Line_Item', array('LIN_parent' => null), false); - $this->assertEquals(null, $li1->parent()); - $this->assertEquals(array(), $li1->children()); - - //add a cached relation - $li1->add_child_line_item($li2); - $this->assertEquals(array($li2->code() => $li2), $li1->children()); - $this->assertEquals($li1, $li2->parent()); - //and let's change the parent - $li3 = $this->new_model_obj_with_dependencies('Line_Item', array('LIN_parent' => null), false); - $li3->add_child_line_item($li2); - $this->assertEquals($li3, $li2->parent()); - //and let's see if the relations are preserved when we save them - $li3->save_this_and_descendants_to_txn(); - $this->assertNotEquals(0, $li3->ID()); - $this->assertNotEquals(0, $li2->ID()); - $this->assertEquals($li3, $li2->parent()); - } - - - public function test_line_item_serialization() - { - if (version_compare(PHP_VERSION, '5.5', '<')) { - $this->markTestSkipped(); - } - $line_item = $this->new_model_obj_with_dependencies( - 'Line_Item', - array('LIN_parent' => null), - false - ); - $line_item = serialize($line_item); - $line_item = unserialize($line_item); - $this->assertInstanceOf( - 'EE_Line_Item', - $line_item - ); - /** @var EE_Line_Item $line_item */ - $datetime = $line_item->get_DateTime_object('LIN_timestamp'); - $this->assertInstanceOf( - 'Datetime', - $datetime - ); - } -} -// End of file EE_Line_Item_Test.php -// Location: testcases/core/db_classes/EE_Line_Item_Test.php diff --git a/tests/testcases/core/db_classes/EE_Message_Template_Group_Test.php b/tests/testcases/core/db_classes/EE_Message_Template_Group_Test.php deleted file mode 100644 index a5f1ee8abb9..00000000000 --- a/tests/testcases/core/db_classes/EE_Message_Template_Group_Test.php +++ /dev/null @@ -1,99 +0,0 @@ -message_template_group = EEM_Message_Template_Group::instance()->get_one( - array( - array( - 'MTP_messenger' => 'email', - 'MTP_message_type' => 'registration' - ) - ) - ); - } - - - public function tearDown() - { - parent::tearDown(); - $this->message_template_group = null; - } - - - /** - * This tests that a valid context that should be active on a fresh install is. - */ - public function testValidContextTemplateShouldBeActive() - { - $this->assertTrue( - $this->message_template_group->is_context_active( - 'admin' - ) - ); - } - - - /** - * @expectedException EventEspresso\core\exceptions\InvalidIdentifierException - */ - public function testInvalidContextTemplateForIsContextActive() - { - $this->message_template_group->is_context_active('bogus'); - } - - - - - public function testDeactivatingAndReactivatingValidContext() - { - //deactivate - $this->message_template_group->deactivate_context('admin'); - $this->assertFalse( - $this->message_template_group->is_context_active('admin') - ); - - //activate again - $this->message_template_group->activate_context('admin'); - $this->assertTrue( - $this->message_template_group->is_context_active('admin') - ); - } - - - /** - * @expectedException EventEspresso\core\exceptions\InvalidIdentifierException - */ - public function testActivatingInvalidContext() - { - $this->message_template_group->deactivate_context('bogus'); - } - - - /** - * @expectedException EventEspresso\core\exceptions\InvalidIdentifierException - */ - public function testDeactivatingInvalidContext() - { - $this->message_template_group->activate_context('bogus'); - } -} diff --git a/tests/testcases/core/db_classes/EE_Payment_Test.php b/tests/testcases/core/db_classes/EE_Payment_Test.php deleted file mode 100644 index 7ff89a98ac1..00000000000 --- a/tests/testcases/core/db_classes/EE_Payment_Test.php +++ /dev/null @@ -1,121 +0,0 @@ -assertFalse( $p1->just_approved() ); - $p1->set_status( EEM_Payment::status_id_approved ); - $this->assertTrue( $p1->just_approved() ); - $id = $p1->save(); - $this->assertTrue( $p1->just_approved() ); - - EEM_Payment::reset(); - //now try with a payment that began as approved - //note that we've reset EEM_payment so this is just like - //it had been created on a previous request - $p2 = EEM_Payment::instance()->get_one_by_ID( $id ); - $this->assertFalse( $p2->just_approved() ); - $p2->set_status( EEM_Payment::status_id_pending ); - $p2->save(); - - EEM_Payment::reset(); - //again, pretend this next part is a subsequent request - $p3 = EEM_Payment::instance()->get_one_by_ID( $id ); - $this->assertFalse( $p3->just_approved() ); - $p3->set_status( EEM_Payment::status_id_approved ); - $this->assertTrue( $p3->just_approved() ); - } - - /** - * @group 7653 - */ - function test_set_details(){ - $p = $this->new_model_obj_with_dependencies( 'Payment' ); - $cookie = new WP_Http_Cookie( array( - 'name' => 'something', - 'value' => 'somethingelse' - )); - $details_to_set = array( - 'headers' => array( - 'header1' => 'headervalue1', - 'header2' => 'headervalue2', - ), - 'body' => 'hello', - 'cookies' => array( - $cookie - ) - ); - //set the details with that object in there - $p->set_details( $details_to_set ); - //ok now verify that it's been converted into an array a-ok - $details_to_set['cookies'][0] = (array)$cookie; - //and we should have actually removed tags like we set out to do in that method - $details_to_set['body'] = 'hello'; - $this->assertEquals( $details_to_set, $p->details() ); - } - - - /** - * @group 9245 - */ - function test_redirect_form__with_redirect_args() { - $redirect_url = 'http://somesite.com'; - $redirect_args = array( 'arg1' => 'a', 'arg2' => 'b' ); - $p = $this->new_model_obj_with_dependencies( 'Payment', array( 'PAY_redirect_url' => $redirect_url, 'PAY_redirect_args' => $redirect_args ) ); - $html_form = $p->redirect_form(); - $this->assertContains( - '
    ', - $html_form - ); - foreach( $redirect_args as $name => $value ) { - $this->assertContains( - '', - $html_form - ); - } - } - - /** - * @group 9245 - */ - function test_redirect_form__with_redirect_NO_args() { - $redirect_url = 'http://somesite.com'; - $redirect_args = array( 'arg1' => 'a', 'arg2' => 'b' ); - $redirect_url_combined = $redirect_url .'?' . http_build_query( $redirect_args ); - $p = $this->new_model_obj_with_dependencies( 'Payment', - array( - 'PAY_redirect_url' => $redirect_url_combined, - 'PAY_redirect_args' => false //we want it to be a GET request, so leave this blank - ) - ); - $html_form = $p->redirect_form(); - $this->assertContains( - '', - $html_form ); - foreach( $redirect_args as $name => $value ) { - $this->assertContains( - '', - $html_form); - } - } -} - -// End of file EE_Payment_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_classes/EE_Price_Test.php b/tests/testcases/core/db_classes/EE_Price_Test.php deleted file mode 100644 index 7639627fa39..00000000000 --- a/tests/testcases/core/db_classes/EE_Price_Test.php +++ /dev/null @@ -1,25 +0,0 @@ -'let hte wookie win')); - $this->assertEquals('let hte wookie win',$p->desc()); - } -} - -// End of file EE_Price_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_classes/EE_Registration_Test.php b/tests/testcases/core/db_classes/EE_Registration_Test.php deleted file mode 100644 index 58595c96e64..00000000000 --- a/tests/testcases/core/db_classes/EE_Registration_Test.php +++ /dev/null @@ -1,201 +0,0 @@ - EEM_Transaction::complete_status_code)); - $t->save(); - $e = EE_Event::new_instance(); - $e->save(); - $tkt = EE_Ticket::new_instance(); - $tkt->save(); - $d = EE_Datetime::new_instance(array('EVT_ID'=>$e->ID())); - $d->save(); - $tkt->_add_relation_to($d, 'Datetime'); - /** @type EE_Registration_Processor $registration_processor */ - $registration_processor = EE_Registry::instance()->load_class( 'Registration_Processor' ); - $REG_url_link = new EventEspresso\core\domain\entities\RegUrlLink( - 1, - EE_Line_Item::new_instance( - array( - 'LIN_name' => $tkt->name(), - 'LIN_desc' => $tkt->description(), - 'LIN_unit_price' => $tkt->price(), - 'LIN_quantity' => 1, - 'LIN_is_taxable' => $tkt->taxable(), - 'LIN_order' => 0, - 'LIN_total' => $tkt->price(), - 'LIN_type' => EEM_Line_Item::type_line_item, - 'OBJ_ID' => $tkt->ID(), - 'OBJ_type' => 'Ticket' - ) - ) - ); - $r = EE_Registration::new_instance( - array( - 'EVT_ID' => $e->ID(), - 'TXN_ID' => $t->ID(), - 'TKT_ID' => $tkt->ID(), - 'STS_ID' => EEM_Registration::status_id_pending_payment, - 'REG_url_link' => $REG_url_link - ) - ); - - $r->set_reg_code( - new EventEspresso\core\domain\entities\RegCode( - $REG_url_link, - $r->transaction(), - $r->ticket() - ) - ); - $registration_processor->update_registration_after_checkout_or_payment( $r ); - $this->assertNotNull($r->reg_code()); - $this->assertEquals(EEM_Registration::status_id_approved,$r->status_ID()); - } - - function test_answer_value_to_question() { - /** @var EE_Registration $r */ - $r = $this->new_model_obj_with_dependencies( 'Registration' ); - $q1 = $this->new_model_obj_with_dependencies( 'Question' ); - //also grab the default first name question - $q2 = EEM_Question::instance()->get_Question_ID_from_system_string(EEM_Attendee::system_question_fname); - $this->assertNotNull($q2); - /** @var EE_Answer $a1 */ - $a1 = $this->new_model_obj_with_dependencies( 'Answer', array('REG_ID' =>$r->ID(), 'QST_ID' =>$q1->ID())); - $this->assertEquals( $a1->value(), $r->answer_value_to_question( $q1, false ) ); - $this->assertEquals($r->attendee()->fname(),$r->answer_value_to_question($q2,false)); - } - - - - /** - * This verifies the can_checkin() method in EE_registration - * - * @since 4.5.0 - * - * @return void - */ - function test_can_checkin() { - //setup a registration - $r = $this->new_model_obj_with_dependencies( 'Registration' ); - - $t = $this->new_ticket(); - - //let's assign the above ticket to our registration - $r->_add_relation_to( $t, 'Ticket' ); - $r->save(); - - $d = EEM_Datetime_Ticket::instance()->get_one( array( array( 'TKT_ID' => $r->get('TKT_ID') ) ) ); - $this->assertInstanceOf( 'EE_Datetime_Ticket', $d ); - $valid_DTT_ID = $d->get('DTT_ID'); - $invalid_DTT_ID = 99999; - - //k let's test the possible expected responses of can_checkin; - //IGNORING status - //test one: valid DTT and unapproved reg - $r->set_status( EEM_Registration::status_id_not_approved ); - $this->assertTrue( $r->can_checkin( $valid_DTT_ID, false ) ); - - //test two: invalid DTT and approved reg - $r->set_status( EEM_Registration::status_id_approved ); - $this->assertFalse( $r->can_checkin( $invalid_DTT_ID, false ) ); - - //including status - //test one: valid DTT and approved reg - $this->assertTrue( $r->can_checkin( $valid_DTT_ID ) ); - - //test two: invalid DTT and approved reg - $this->assertFalse( $r->can_checkin( $invalid_DTT_ID ) ); - - //test three: valid DTT and not approved reg - $r->set_status( EEM_Registration::status_id_not_approved ); - $this->assertFalse( $r->can_checkin( $valid_DTT_ID ) ); - - //test four: valid DTT and incomplete reg - $r->set_status( EEM_Registration::status_id_incomplete ); - $this->assertFalse( $r->can_checkin( $valid_DTT_ID ) ); - - //test five: invalid DTT and incomplete reg - $this->assertFalse( $r->can_checkin( $invalid_DTT_ID ) ); - } - - /** - * @since 4.10.0.p - * @throws EE_Error - */ - public function testQuestionGroupsPrimaryReg() - { - $r = $this->new_model_obj_with_dependencies( - 'Registration', - [ - 'REG_count' => 1, - ] - ); - // Associate both question groups for primary registrants, but only personal for additional registrants - $r->event_obj()->add_question_group(EEM_Question_Group::system_personal, true); - $r->event_obj()->add_question_group(EEM_Question_Group::system_personal, false); - $r->event_obj()->add_question_group(EEM_Question_Group::system_address, true); - $qgs = $r->question_groups(); - $this->assertEquals(2, count($qgs)); - } - - /** - * @since 4.10.0.p - * @throws EE_Error - */ - public function testQuestionGroupsAdditionalReg() - { - $r = $this->new_model_obj_with_dependencies( - 'Registration', - [ - 'REG_count' => 2, - 'REG_group_size' => 2, - ] - ); - // Associate both question groups for primary registrants, but only personal for additional registrants - $r->event_obj()->add_question_group(EEM_Question_Group::system_personal, true); - $r->event_obj()->add_question_group(EEM_Question_Group::system_personal, false); - $r->event_obj()->add_question_group(EEM_Question_Group::system_address, true); - $qgs = $r->question_groups(); - $this->assertEquals(1, count($qgs)); - $qg = reset($qgs); - $this->assertEquals(1, $qg->ID()); - } - - /** - * @since 4.10.0.p - * @throws EE_Error - */ - public function testCountQuestionGroups() - { - $r = $this->new_model_obj_with_dependencies( - 'Registration', - [ - 'REG_count' => 2, - 'REG_group_size' => 2, - ] - ); - // Associate both question groups for primary registrants, but only personal for additional registrants - $r->event_obj()->add_question_group(EEM_Question_Group::system_personal, true); - $r->event_obj()->add_question_group(EEM_Question_Group::system_personal, false); - $r->event_obj()->add_question_group(EEM_Question_Group::system_address, true); - $this->assertEquals(1, $r->count_question_groups()); - } -} - -// End of file EE_Registration_Test.php -// Location: /tests/testcases/core/db_classes/EE_Registration_Test.php diff --git a/tests/testcases/core/db_classes/EE_Ticket_Test.php b/tests/testcases/core/db_classes/EE_Ticket_Test.php deleted file mode 100644 index 5dacb9acf4b..00000000000 --- a/tests/testcases/core/db_classes/EE_Ticket_Test.php +++ /dev/null @@ -1,149 +0,0 @@ - time() - 100, - 'TKT_end_date' => time() + 200, - )); - $this->assertTrue($t->is_on_sale()); - $t->set('TKT_start_date', time() + 100); - $this->assertFalse($t->is_on_sale()); - } - - public function test_is_pending() - { - $t = EE_Ticket::new_instance(array( - 'TKT_start_date' => time() + 100, - 'TKT_end_date' => time() + 200, - )); - $this->assertTrue($t->is_pending()); - $t->set('TKT_start_date', time() - 100); - $this->assertFalse($t->is_pending()); - } - - public function test_is_expired() - { - $t = EE_Ticket::new_instance(array( - 'TKT_start_date' => time() - 200, - 'TKT_end_date' => time() - 100, - )); - $this->assertTrue($t->is_expired()); - $t->set('TKT_end_date', time() + 100); - $this->assertFalse($t->is_expired()); - } - - public function test_available() - { - $t = EE_Ticket::new_instance(array( - 'TKT_start_date' => time(), - 'TKT_end_date' => time(), - 'TKT_qty' => 10, - 'TKT_sold' => 0, - )); - $this->assertTrue($t->available()); - $t->set('TKT_sold', 10); - $t->save(); - $this->assertFalse($t->available()); - } - - public function test_remaining() - { - $t = EE_Ticket::new_instance(array( - 'TKT_start_date' => time(), - 'TKT_end_date' => time(), - 'TKT_qty' => 10, - 'TKT_sold' => 0, - )); - $t->save(); - $d = EE_Datetime::new_instance(); - $d->save(); - $t->_add_relation_to($d, 'Datetime'); - $this->assertEquals(10, $t->remaining()); - // simulate 5 ticket sales - $this->simulate_x_number_ticket_sales($t, 5); - $this->assertEquals(5, $t->remaining()); - } - - - public function test_ticket_status() - { - $t = EE_Ticket::new_instance(array( - 'TKT_start_date' => time() - 100, - 'TKT_end_date' => time() + 100, - 'TKT_qty' => 10, - 'TKT_sold' => 0, - 'TKT_deleted' => true, - )); - $t->save(); - $d = EE_Datetime::new_instance(); - $d->save(); - $t->_add_relation_to($d, 'Datetime'); - - $this->assertEquals(EE_Ticket::archived, $t->ticket_status()); - $t->set('TKT_deleted', false); - $this->assertEquals(EE_Ticket::onsale, $t->ticket_status()); - // simulate 10 ticket sales - $this->simulate_x_number_ticket_sales($t, 10); - $this->assertEquals(EE_Ticket::sold_out, $t->ticket_status()); - $this->reverse_x_number_ticket_sales($t, 10); - $d->set_reg_limit(10); - $d->save(); - $t->set('TKT_start_date', time() + 50); - $this->assertEquals(EE_Ticket::pending, $t->ticket_status()); - $t->set('TKT_start_date', time() - 100); - $t->set('TKT_end_date', time() - 50); - $this->assertEquals(EE_Ticket::expired, $t->ticket_status()); - } - - public function test_increase_and_decrease_sold() - { - $t = EE_Ticket::new_instance(array( - 'TKT_start_date' => time() - 100, - 'TKT_end_date' => time() + 100, - 'TKT_qty' => 10, - 'TKT_sold' => 0, - )); - $this->assertEquals(0, $t->sold()); - $t->increaseSold(); - $this->assertEquals(1, $t->sold()); - $t->increaseSold(2); - $this->assertEquals(3, $t->sold()); - //now try decreasing - $t->decreaseSold(); - $this->assertEquals(2, $t->sold()); - $t->decreaseSold(2); - $this->assertEquals(0, $t->sold()); - } - - - /** - * @group 10283 - * @expectedException \EventEspresso\core\exceptions\UnexpectedEntityException - */ - public function test_get_related_event_exception() - { - //create a ticket (it won't have any datetime). - /** @var EE_Ticket $ticket */ - $ticket = $this->factory->ticket->create(); - //the following should throw the exception - $ticket->get_related_event(); - } -} - -// End of file EE_Ticket_Test.php -// Location: tests/testcases/core/db_classes/EE_Ticket_Test.php diff --git a/tests/testcases/core/db_classes/EE_Transaction_Test.php b/tests/testcases/core/db_classes/EE_Transaction_Test.php deleted file mode 100644 index f9c8822fc00..00000000000 --- a/tests/testcases/core/db_classes/EE_Transaction_Test.php +++ /dev/null @@ -1,222 +0,0 @@ -new_model_obj_with_dependencies( 'Transaction', null, false ); - $this->assertEquals( 0, $t->ID() ); - /** @type EE_Registration $r */ - $r = $this->new_model_obj_with_dependencies( 'Registration', array( 'REG_count' => 1 ), false ); - $this->assertEquals( 0, $r->ID() ); - $t->_add_relation_to( $r, 'Registration' ); - $this->assertEquals( $r, $t->primary_registration() ); - $r->save(); - $this->assertNotEquals( 0, $r->ID() ); - $in_map = EE_Registry::instance()->load_model( 'Registration' )->get_from_entity_map( $r->ID() ); - $this->assertEquals( $r, $in_map ); - $this->assertEquals( $r, $t->primary_registration() ); - $this->assertEquals( 1, $r->count() ); - $r_in_db = EE_Registry::instance()->load_model( 'Registration' )->get_one_by_ID( $r->ID() ); - $this->assertEquals( $r, $r_in_db ); - $t->save(); - $this->assertEquals( $r, $t->primary_registration() ); - //why does the above fail? because we forgot to set the registration's TXN_ID! - //so it makes sense, but it sure would have been considerate of the transaction if, - //when it was saved, it would have set the ID on all foreign keys pointing to it - //on things it had cached on itself - } - - - - public function test_payment_method() { - /** @type EE_Transaction $t */ - $t = $this->new_model_obj_with_dependencies( 'Transaction' ); - $this->assertNotEquals( 0, $t->payment_method_ID() ); - $pm = $t->payment_method(); - $this->assertInstanceOf( 'EE_Payment_Method', $pm ); - //now if there is no explicit payment method on the transaction, use the first payment - $t->set( 'PMD_ID', 0 ); - $p = $this->new_model_obj_with_dependencies( 'Payment' ); - $t->_add_relation_to( $p, 'Payment' ); - $pm = $t->payment_method(); - $this->assertInstanceOf( 'EE_Payment_Method', $pm ); - } - - - - /** - * This tests the datetime method on EE_Transaction - * - * @since 4.6 - * @throws \EE_Error - */ - public function test_datetime() { - $now = new DateTime( "now", new DateTimeZone( 'America/Vancouver' ) ); - $DateTimeZoneAbbr = $now->format( 'T' ); - // Now get the transaction's time - $format_to_use = get_option( 'date_format' ) . ' ' . 'H:i:s'; - /** @type EE_Transaction $t */ - $t = $this->factory->transaction->create(); - $t->set_timezone( 'America/Vancouver' ); - /** - * just to standardize the two times because Unix timestamps are so precise, we'll use our expected - * time to set the time on the transaction. This still verifies the functionality of the class. - * Because time comparisons will be based on seconds (Unix timestamp), let's ensure we use a - * format with seconds as well - */ - $t->set_time_format( 'H:i:s' ); - $t->set( 'TXN_timestamp', $now->format( $t->get_format( $format_to_use ) ) ); - //test getting pretty (should return formatted item in the correct timezone) - $this->assertEquals( - $now->format( $format_to_use ) . ' (' . $DateTimeZoneAbbr . ')', - $t->datetime( true ), - 'datetime( true ) test' - ); - //test getting pretty with no_html - $this->assertEquals( - $now->format( $format_to_use ) . ' (' . $DateTimeZoneAbbr . ')', - $t->get_pretty( 'TXN_timestamp', 'no_html' ), - 'get_pretty, no_html test' - ); - //test getting raw Unix timestamp - $this->assertEquals( - $now->format( 'U' ), - $t->datetime( false, true ), - 'datetime( false, true) test' - ); - //test get() (time string with offset) - $this->assertEquals( $now->format( $format_to_use ), $t->datetime(), 'datetime() test' ); - } - - - - /** - * @throws \EE_Error - */ - public function test_is_locked() { - /** @type EE_Transaction $transaction */ - $transaction = $this->factory->transaction->create(); - // initial state should be unlocked - $locked = $transaction->get_extra_meta( 'lock', true, 0 ); - $this->assertEquals( 0, $locked ); - // is_locked() should equal $locked - $this->assertEquals( $locked, $transaction->is_locked() ); - // set a lock - $transaction->add_extra_meta( 'lock', time(), true ); - // now is_locked() should NOT equal $locked - $this->assertNotEquals( $locked, $transaction->is_locked() ); - // delete existing lock - $transaction->delete_extra_meta( 'lock' ); - // now set another lock, but with an expired timestamp - $transaction->add_extra_meta( 'lock', time() - HOUR_IN_SECONDS , true ); - // is_locked() should remove that lock and once again equal $locked - $this->assertEquals( $locked, $transaction->is_locked() ); - } - - - - public function test_lock() { - /** @type EE_Transaction $transaction */ - $transaction = $this->factory->transaction->create(); - // initial state should be unlocked - $locked = $transaction->get_extra_meta( 'lock', true, 0 ); - $this->assertEquals( 0, $locked ); - // now lock it - $transaction->lock(); - $locked = $transaction->get_extra_meta( 'lock', true, 0 ); - $this->assertNotEquals( 0, $locked ); - // delete existing lock - $transaction->delete_extra_meta( 'lock' ); - // now set another lock, but with an expired timestamp - $expired_timestamp = time() - HOUR_IN_SECONDS; - $transaction->add_extra_meta( 'lock', $expired_timestamp, true ); - // this time, lock() should remove the expired lock, and set a new one with a current timestamp - $transaction->lock(); - $locked = $transaction->get_extra_meta( 'lock', true, 0 ); - $this->assertNotEquals( 0, $locked ); - $this->assertGreaterThan( $expired_timestamp, $locked ); - } - - - - /** - * @throws \EE_Error - */ - public function test_unlock() { - /** @type EE_Transaction $transaction */ - $transaction = $this->factory->transaction->create(); - // initial state should be unlocked - $locked = $transaction->get_extra_meta( 'lock', true, 0 ); - $this->assertEquals( 0, $locked ); - // set a lock - $transaction->add_extra_meta( 'lock', time(), true ); - // unlock() should remove the above lock and return a value of 1 - $this->assertEquals( 1, $transaction->unlock() ); - } - - - - /** - * @see https://events.codebasehq.com/projects/event-espresso/tickets/10920 - * @group 10920 - */ - public function testTrashedRegistrationLoading() - { - /** @type EE_Transaction $transaction */ - $transaction = $this->new_model_obj_with_dependencies('Transaction', null); - /** @type EE_Registration[] $registrations */ - $registrations = array(); - for($x = 1; $x < 5; $x++) { - $registrations[$x] = $this->new_model_obj_with_dependencies( - 'Registration', - array( - 'REG_count' => $x, - 'STS_ID' => $x > 2 // true for registrations 3 && 4 - ? EEM_Registration::status_id_cancelled - : EEM_Registration::status_id_pending_payment, - 'REG_deleted' => $x > 2 // true for registrations 3 && 4 - ) - ); - $transaction->_add_relation_to($registrations[$x], 'Registration'); - } - // confirm setup worked correctly - for ($x = 1; $x < 5; $x++) { - $this->assertEquals( - $registrations[$x]->is_cancelled(), - $x > 2 // true for registrations 3 && 4 - ); - $this->assertEquals( - $registrations[$x]->deleted(), - $x > 2 // true for registrations 3 && 4 - ); - } - $this->assertCount(4, $registrations); - // should NOT return trashed registrations - $this->assertCount( - 2, - $transaction->registrations(array(array('REG_deleted' => false))), - 'There should only be two registrations returned' - ); - } - - -} -// End of file EE_Transaction_Test.php -// Location:/tests/testcases/core/db_classes/EE_Transaction_Test.php diff --git a/tests/testcases/core/db_classes/EE_Venue_Test.php b/tests/testcases/core/db_classes/EE_Venue_Test.php deleted file mode 100644 index fbc3ec00cde..00000000000 --- a/tests/testcases/core/db_classes/EE_Venue_Test.php +++ /dev/null @@ -1,72 +0,0 @@ - $this->factory->datetime->create( array( 'DTT_EVT_start' => $past_start_date->format( $full_format ), 'DTT_EVT_end' => $past_start_date->format( $full_format), 'timezone' => 'America/Toronto', 'formats' => $formats ) ), - 'upcoming_datetime' => $this->factory->datetime->create( array( 'DTT_EVT_start' => $upcoming_start_date->format( $full_format ), 'DTT_EVT_end' => $upcoming_start_date->format( $full_format), 'timezone' => 'America/Toronto', 'formats' => $formats ) ), - 'active_datetime' => $this->factory->datetime->create( array( 'DTT_EVT_start' => $current->format( $full_format ), 'DTT_EVT_end' => $current_end_date->format( $full_format), 'timezone' => 'America/Toronto', 'formats' => $formats ) ), - 'sold_out_datetime' => $this->factory->datetime->create( array( 'DTT_EVT_start' => $upcoming_start_date->format( $full_format ), 'DTT_EVT_end' => $upcoming_start_date->format( $full_format), 'DTT_reg_limit' => 10, 'DTT_sold' => 10, 'timezone' => 'America/Toronto', 'formats' => $formats ) ) - ); - - - $venue = $this->factory->venue->create(); - //assign events to the datetimes and then the events to the venue. - foreach ( $datetimes as $type => $datetime ) { - $event = $this->factory->event->create(); - $event->set_timezone( 'America/Toronto' ); - $event->set('status', 'publish'); - $event->_add_relation_to( $datetime, 'Datetime' ); - $event->save(); - $venue->_add_relation_to($event, 'Event'); - $venue->save(); - } - - //test with upcoming as false. Should return 4 events. - $events = $venue->events(); - $this->assertEquals( 4, count($events) ); - $this->assertInstanceOf( 'EE_Event', reset($events) ); - - //test with upcoming as true. Should return 2 events. - $events = $venue->events(array(), true); - $this->assertEquals( 2, count($events) ); - $this->assertInstanceOf( 'EE_Event', reset($events) ); - - } - - - -}// end class EE_Venue_Test diff --git a/tests/testcases/core/db_models/EEM_Answer_Test.php b/tests/testcases/core/db_models/EEM_Answer_Test.php deleted file mode 100644 index 6b7b3b9624e..00000000000 --- a/tests/testcases/core/db_models/EEM_Answer_Test.php +++ /dev/null @@ -1,113 +0,0 @@ -model = EEM_Answer::instance(); - } - - function test_get_registration_question_answer_object(){ - $r = $this->new_model_obj_with_dependencies('Registration'); - $a = $this->new_model_obj_with_dependencies('Answer',array('REG_ID'=>$r->ID())); - $q = EEM_Question::instance()->get_one_by_ID($a->question_ID()); - $this->assertNotNull($q); - $this->assertEquals( $a, EEM_Answer::instance()->get_registration_question_answer_object( $r, $a->question_ID() ) ); - } - function test_get_attendee_property_answer_value(){ - $r = $this->new_model_obj_with_dependencies( 'Registration' ); - global $wpdb; - $att = EEM_Attendee::reset()->get_one_by_ID( $r->attendee_ID() ); - $this->assertEquals( $r->attendee()->fname(), EEM_Answer::instance()->get_attendee_property_answer_value( $r, EEM_Attendee::system_question_fname ) ); - } - public function test_get_answer_value_to_question(){ - $r = $this->new_model_obj_with_dependencies('Registration'); - $a = $this->new_model_obj_with_dependencies('Answer',array('REG_ID'=>$r->ID())); - $this->assertEquals($a->value(),EEM_Answer::instance()->get_answer_value_to_question($r,$a->question_ID(),false)); - $this->assertEquals($r->attendee()->fname(),EEM_Answer::instance()->get_answer_value_to_question($r, EEM_Question::instance()->get_Question_ID_from_system_string( EEM_Attendee::system_question_fname ) ) ); - } - /** - * @group 8237 - */ - public function test_set_ANS_value__with_unsafe_html(){ - $a = $this->new_model_obj_with_dependencies( 'Answer', array( 'ANS_value' => '') ); - $this->assertEquals( '', $a->get_raw( 'ANS_value' ) ); - } - - /** - * @group 8237 - */ - public function test_get_ANS_value__with_unsafe_html_in_db() { - $a = $this->new_model_obj_with_dependencies( 'Answer' ); - global $wpdb; - //manually insert bad stuff into the answer - $success = $wpdb->update( - EEM_Answer::instance()->table(), - array( - 'ANS_value' => '' - ), - array( - 'ANS_ID' => $a->ID() - ), - array( - '%s',//ANS_value - ), - array( - '%s',//ANS_ID - ) - ); - $this->assertEquals( 1, $success ); - $this->assertEquals( - '', - EEM_Answer::instance()->get_var( - array( - array( - 'ANS_ID' => $a->ID() - ) - ), - 'ANS_value' )); - //ok so it's definetely got dangerous stuff in the db, but when we fetch it using the models it should be safe again - $a->refresh_from_db(); - $this->assertEquals( '', $a->get_raw( 'ANS_value' ) ); - } - - /** - * @since 4.9.74.p - * @group private-1 - */ - public function testRestrictedbyRelatedModelPassword() - { - $this->assertFalse($this->model->restrictedByRelatedModelPassword()); - } -} - -// End of file EEM_Answer_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_models/EEM_Attendee_Caps_Test.php b/tests/testcases/core/db_models/EEM_Attendee_Caps_Test.php deleted file mode 100644 index 79995341d6a..00000000000 --- a/tests/testcases/core/db_models/EEM_Attendee_Caps_Test.php +++ /dev/null @@ -1,44 +0,0 @@ -factory->user->create_and_get(); - $att = $this->new_model_obj_with_dependencies( 'Attendee' ); - $this->assertEquals( 0, EEM_Attendee::instance()->count( array( 'caps' => EEM_Base::caps_read ) ) ); - - //ok now log the user in - $current_user = $user; - - //and they still shouldn't be able to view the attendee - $this->assertEquals( 0, EEM_Attendee::instance()->count( array( 'caps' => EEM_Base::caps_read ) ) ); - - //ok now give them access to contacts - $current_user->add_cap( 'ee_read_contacts' ); - //and now they should be able to see it - $this->assertEquals( 1, EEM_Attendee::instance()->count( array( 'caps' => EEM_Base::caps_read ) ) ); - } -} - -// End of file EEM_Attendee_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_models/EEM_Base_Test.php b/tests/testcases/core/db_models/EEM_Base_Test.php deleted file mode 100644 index 10d0ea79f81..00000000000 --- a/tests/testcases/core/db_models/EEM_Base_Test.php +++ /dev/null @@ -1,1226 +0,0 @@ -markTestSkipped('If a multi-byte character gets chopped in half, EEM_Base::insert and update simply dont work. Avoid it by using mb_strcut instead of substr'); - $string_of_multibyte_chracters = 'eventโ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™โ€™'; - $string_with_a_chopped_multibyte_character = substr($string_of_multibyte_chracters,0,127); - $id = EEM_Change_Log::instance()->insert( - array( - 'LOG_message' => $string_with_a_chopped_multibyte_character - ) - ); - $this->assertNotFalse($id); - } - public function test_models_defined_ok() - { - foreach (EE_Registry::instance()->non_abstract_db_models as $model) { - $model_instance = EE_Registry::instance()->load_model($model); - $this->assertInstanceOf('EEM_Base', $model_instance); - //checks their relations - foreach ($model_instance->relation_settings() as $relation_name => $relation_obj) { - //verify that each relation is named according to an existing model - $related_model_instance = EE_Registry::instance()->load_model($relation_name); - $this->assertInstanceOf('EE_Model_Relation_Base', $relation_obj); - } - foreach ($model_instance->field_settings(true) as $field_name => $field_obj) { - $this->assertInstanceOf('EE_Model_Field_Base', $field_obj); - } - } - } - - - - /** - * Verifies that for each model, the tables it claims to require have been installed - * @doesNotPerformAssertions - */ - public function test_model_tables_exist() - { - foreach (EE_Registry::instance()->non_abstract_db_models as $model) { - $model_instance = EE_Registry::instance()->load_model($model); - foreach ($model_instance->get_tables() as $table_alias => $table_obj) { - $this->assertTableExists($table_obj->get_table_name(), $model); - } - } - } -// public function test_models_can_insert(){ -// foreach(EE_Registry::instance()->non_abstract_db_models as $model){ -// $model_instance = EE_Registry::instance()->load_model($model); -// $id = $model_instance->insert(array()); -// $this->assertNotEmpty($id); -// } -// } - /** - * checks that EEM_Base::has_field works properly - */ - public function test_has_field() - { - $this->assertTrue(EEM_Question::instance()->has_field('QST_ID')); - $this->assertTrue(EEM_QUestion::instance()->has_field('QST_admin_only')); - $this->assertFalse(EEM_Question::instance()->has_field('monkey brains')); - } - - - - /** - * checks that adding a LIKE in teh WHERE clauses works ok - */ - public function test_where_like() - { - $attendees_before = EEM_Attendee::instance()->get_all(); - $this->assertEmpty($attendees_before); - $a = EE_Attendee::new_instance(array('ATT_email' => 'monkey123@hotmail.com')); - $a->save(); - $attendees_after_insert = EEM_Attendee::instance()->get_all(); - $this->assertEquals(1, count($attendees_after_insert)); - $attendee_found = EEM_Attendee::instance()->get_one(array(array('ATT_email' => array('LIKE', '%key12%')))); - $this->assertInstanceOf('EE_Attendee', $attendee_found); - $this->assertEquals($a->ID(), $attendee_found->ID()); - } - - - - public function test_delete() - { - $e1 = EE_Event::new_instance(); - $e1->save(); - $e2 = EE_Event::new_instance(); - $e2->save(); - $e3 = EE_Event::new_instance(); - $e3->save(); - //now assert things are as they should be: the items are in teh Db and the entity map - $this->assertEquals(EEM_Event::instance()->get_one_by_ID($e1->ID()), $e1); - $this->assertEquals(EEM_Event::instance()->get_one_by_ID($e2->ID()), $e2); - $this->assertEquals(EEM_Event::instance()->get_one_by_ID($e3->ID()), $e3); - $this->assertEquals(EEM_Event::instance()->get_from_entity_map($e1->ID()), $e1); - $this->assertEquals(EEM_Event::instance()->get_from_entity_map($e2->ID()), $e2); - $this->assertEquals(EEM_Event::instance()->get_from_entity_map($e3->ID()), $e3); - //now run a delete query that should have deleted $e1 and $e2 - EEM_Event::instance()->delete_permanently(array(array('EVT_ID' => array('<=', $e2->ID())))); - //check $e1 and $e2 don't exist in the DB anymore - $this->assertEmpty(EEM_Event::instance()->get_one_by_ID($e1->ID())); - $this->assertEmpty(EEM_Event::instance()->get_one_by_ID($e2->ID())); - $this->assertEquals(EEM_Event::instance()->get_one_by_ID($e3->ID()), $e3); - //and now chekc $e1 and $e2 don't exist in the entity map either - $this->assertEmpty(EEM_Event::instance()->get_from_entity_map($e1->ID())); - $this->assertEmpty(EEM_Event::instance()->get_from_entity_map($e2->ID())); - $this->assertEquals(EEM_Event::instance()->get_from_entity_map($e3->ID()), $e3); - } - - - /** - * Verifies deletes still work properly, even when deleting a model object whose data is shared between two tables - */ - public function test_delete__across_multiple_tables() - { - $event_to_delete = $this->new_model_obj_with_dependencies('Event'); - $event_shouldnt_be_harmed = $this->new_model_obj_with_dependencies('Event'); - global $wpdb; - $post_table_entries = $wpdb->get_var('SELECT COUNT(*) FROM ' . EEM_Event::instance()->table()); - $event_meta_table_entries = $wpdb->get_var('SELECT COUNT(*) FROM ' . EEM_Event::instance()->second_table()); - //make sure when we delete this event, both the record from the posts table and the event meta table get deleted - $success = $event_to_delete->delete_permanently(); - $this->assertEquals(2, $success); - $this->assertEquals( - $post_table_entries - 1, - $wpdb->get_var('SELECT COUNT(*) FROM ' . EEM_Event::instance()->table()) - ); - $this->assertEquals( - $event_meta_table_entries - 1, - $wpdb->get_var('SELECT COUNT(*) FROM ' . EEM_Event::instance()->second_table()) - ); - } - - - /** - * Verifies permanent deletes will also remove any extra meta that might be present in the database for items - * deleted. - */ - public function test_delete_with_extra_meta() - { - /** @var EE_Registration $registration_to_delete */ - $registration_to_delete = $this->factory->registration->create(); - //add extrameta - $registration_to_delete->update_extra_meta('test_registration_meta', 'value'); - - //get the extra meta so we have its ID for checking later. - $extra_meta = EEM_Extra_Meta::instance()->get_one(array( - array( - 'OBJ_ID' => $registration_to_delete->ID(), - 'EXM_type' => 'Registration', - 'EXM_key' => 'test_registration_meta' - ) - )); - $this->assertInstanceOf('EE_Extra_Meta', $extra_meta); - - //delete the registration - $success = $registration_to_delete->delete_permanently(); - $this->assertEquals(1, $success); - - //assert the meta no longer exists in the db. - $extra_meta = EEM_Extra_Meta::instance()->get_one_by_ID($extra_meta->ID()); - $this->assertNotInstanceOf('EE_Extra_Meta', $extra_meta); - } - - - - /** - * @throws EE_Error - */ - public function test_distanced_HABTM_join() - { - try { - EEM_Line_Item::instance()->get_all(array(array('Ticket.Datetime.EVT_ID' => 1, 'TXN_ID' => 1))); - $this->assertTrue(true); - } catch (EE_Error $e) { - throw $e; - } - } - - - - public function test_get_col() - { - $att1 = EEM_Attendee::instance()->insert(array('ATT_fname' => 'one')); - $att2 = EEM_Attendee::instance()->insert(array('ATT_fname' => 'two')); - $att3 = EEM_Attendee::instance()->insert(array('ATT_fname' => 'three')); - $att4 = EEM_Attendee::instance()->insert(array('ATT_fname' => 'four')); - $all = EEM_Attendee::instance()->get_col(); - $this->assertArrayContains((string)$att1, $all); - $this->assertArrayContains((string)$att2, $all); - $this->assertArrayContains((string)$att3, $all); - $this->assertArrayContains((string)$att4, $all); - $just_two_and_threes_names = EEM_Attendee::instance()->get_col(array( - array( - 'ATT_fname' => array( - 'IN', - array( - 'two', - 'three', - ), - ), - ), - ), 'ATT_fname'); - $this->assertArrayDoesNotContain('one', $just_two_and_threes_names); - $this->assertArrayContains('two', $just_two_and_threes_names); - $this->assertArrayContains('three', $just_two_and_threes_names); - $this->assertArrayDoesNotContain('four', $just_two_and_threes_names); - } - - - - /** - * - */ - public function test_update__keeps_model_objs_in_sync() - { - $att1 = EE_Attendee::new_instance(array('ATT_fname' => 'one')); - $att2 = EE_Attendee::new_instance(array('ATT_fname' => 'two')); - $att3 = EE_Attendee::new_instance(array('ATT_fname' => 'three')); - $att1->save(); - $att2->save(); - $att3->save(); - //test taht when do perform an update, the model objects are updated also - $attm = EE_Registry::instance()->load_model('EEM_Attendee'); - $attm->update(array('ATT_fname' => 'win'), array(array('ATT_fname' => 'two'))); - $this->assertEquals('one', $att1->fname()); - $this->assertEquals('win', $att2->fname()); - $this->assertEquals('three', $att3->fname()); - //now test doing an update that should be more efficient wehre we DON'T update - //model objects - $attm->update(array('ATT_fname' => 'win_again'), array(array('ATT_fname' => 'one')), false); - $this->assertEquals('one', $att1->fname()); - $this->assertEquals('win', $att2->fname()); - $this->assertEquals('three', $att3->fname()); - global $wpdb; - $name_in_db = $wpdb->get_var("select ATT_fname FROM " - . $wpdb->prefix - . "esp_attendee_meta WHERE ATT_ID = " - . $att1->ID()); - $this->assertEquals('win_again', $name_in_db); - //also test to make sure there are no errors when there was nothing to update in the entity map - $att4 = EEM_Attendee::instance()->insert(array('ATT_fname' => 'four')); - $wpdb->last_error = null; - EEM_Attendee::instance()->update(array('ATT_fname' => 'lose'), array(array('ATT_fname' => 'four'))); - $this->assertEmpty($wpdb->last_error); - //and that there are no errors when nothing at all is updated - EEM_Attendee::instance() - ->update(array('ATT_fname' => 'lose_again'), array(array('ATT_fname' => 'nonexistent'))); - $this->assertEmpty($wpdb->last_error); - } - - - - /** - * @group 6767 - */ - public function test_two_joins() - { - EEM_Attendee::instance()->get_all(array(array('Registration.Event.EVT_name' => 'bob'))); - $this->assertTrue(true, 'No exception thrown'); - } - - - - /** - * @group 7151 - */ - public function test_refresh_entity_map_from_db() - { - //get an object purposefully out-of-sync with the DB - //call this and make sure it's wiped clean and - $p = $this->new_model_obj_with_dependencies('Payment', array('PAY_amount' => 25)); - $p->save(); - $this->assertEquals($p, EEM_Payment::instance()->get_from_entity_map($p->ID())); - //now manually update it in teh DB, but not the model object - global $wpdb; - $affected = $wpdb->query($wpdb->prepare("update {$wpdb->prefix}esp_payment SET PAY_amount = 100, TXN_ID = 0 WHERE PAY_ID = %d", - $p->ID())); - $this->assertEquals(1, $affected); - //and when it's refreshed, its PAY_amount should be updated too and it should no longer have any transaction cached or evenfindable - EEM_Payment::instance()->refresh_entity_map_from_db($p->ID()); - $this->assertEquals(100, $p->get('PAY_amount')); - $this->assertEquals(0, $p->get('TXN_ID')); - $this->assertEquals(array(), $p->get_all_from_cache('Transaction')); - $this->assertEquals(null, $p->transaction()); - } - - - - /** - * @group 7151 - */ - public function test_refresh_entity_map_from_db__serialized_object() - { - //get an object purposefully out-of-sync with the DB - //call this and make sure it's wiped clean and - $p = $this->new_model_obj_with_dependencies('Payment', array('PAY_amount' => 25)); - $p->save(); - $this->assertEquals($p, EEM_Payment::instance()->get_from_entity_map($p->ID())); - //ok now remember that ID, serialize the payment, and otherwise remove the object - $p_id = $p->ID(); - $p_serialized = serialize($p); - unset($p); - EEM_Payment::reset(); - //now manually update it in teh DB, but not the model object - global $wpdb; - $affected = $wpdb->query($wpdb->prepare("update {$wpdb->prefix}esp_payment SET PAY_amount = 100, TXN_ID = 0 WHERE PAY_ID = %d", - $p_id)); - $this->assertEquals(1, $affected); - //now unserialize it and verify it's what we thought it was - $p_unserialized = unserialize($p_serialized); - $this->assertEquals($p_id, $p_unserialized->ID()); - $this->assertEquals(25, $p_unserialized->get('PAY_amount')); - //and when it's refreshed, its PAY_amount should be updated too and it should no longer have any transaction cached or even findable - $p_unserialized = EEM_Payment::instance()->refresh_entity_map_from_db($p_unserialized->ID()); - $this->assertEquals(100, $p_unserialized->get('PAY_amount')); - $this->assertEquals(0, $p_unserialized->get('TXN_ID')); - $this->assertEquals(array(), $p_unserialized->get_all_from_cache('Transaction')); - $this->assertEquals(null, $p_unserialized->transaction()); - } - - - - /** - * @group 7151 - */ - public function test_fresh_entity_map_with() - { - $p = $this->new_model_obj_with_dependencies('Payment', array('PAY_amount' => 25)); - $p->save(); - $this->assertEquals($p, EEM_Payment::instance()->get_from_entity_map($p->ID())); - //now purposefully make a naughty payment which isn't in the entity map - $p2 = clone $p; - $this->assertFalse($p2->in_entity_map()); - //make the two EE_Payments diverge - $p2->set('PAY_amount', 99); - $t = EE_Transaction::new_instance(); - $p2->cache('Transaction', $t); - $this->assertEquals(25, $p->get('PAY_amount')); - $this->assertEquals(99, $p2->get('PAY_amount')); - $this->assertNotEquals($p->get_all_from_cache('Transaction'), $p2->get_all_from_cache('Transaction')); - //now update the payment in the entity map with the other - EEM_Payment::instance()->refresh_entity_map_with($p->ID(), $p2); - $this->assertEquals(99, $p->get('PAY_amount')); - //make sure p hasn't changed into p2. that's not what we wanted to do... - $this->assertFalse($p2 === $p); - //We wanted to just UPDATE p with p2's values - $this->assertEquals($p, EEM_Payment::instance()->get_from_entity_map($p->ID())); - //and make sure p's cache was updated to be the same as p2's - $this->assertEquals($p2->get_all_from_cache('Transaction'), $p->get_all_from_cache('Transaction')); - } - - - - /** - * This tests the get_formats_for method with exception - * - * @since 4.6.x - */ - public function test_get_formats_for_with_exception() - { - EEM_Datetime::reset(); - //test expected exception for invalid field - $this->setExpectedException('EE_Error'); - EEM_Datetime::instance()->get_formats_for('Bogus_Field'); - } - - - - /** - * This tests the get_formats_for method with valid field - * - * @since 4.6.x - */ - public function test_get_formats_for_with_valid_field() - { - EEM_Datetime::reset(); - //first test default field setup - $formats = EEM_Datetime::instance()->get_formats_for('DTT_EVT_start'); - $this->assertContains('F j, Y', $formats); - $this->assertContains('g:i a', $formats); - //test values on EE_Datetime_Field after EE_Datetime instantiation. - $this->factory->datetime->create(array('formats' => array('Y-m-d', 'H:i:s'))); - $test_formats = EEM_Datetime::instance()->get_formats_for('DTT_EVT_start'); - $this->assertContains('Y-m-d', $test_formats); - $this->assertContains('H:i:s', $test_formats); - } - - - - /** - * @since 4.6.x - */ - public function test_current_time_for_query() - { - EEM_Datetime::reset(); - //baseline DateTime object for testing - $now = new DateTime("now"); - $DateTimeZone = new DateTimeZone('America/Vancouver'); - $timezoneTest = new DateTime("now", $DateTimeZone); - //just in case some other test has messed up the default date format string in WordPress unit tests. - $expected_format = get_option('date_format') . ' ' . get_option('time_format'); - //test getting default formatted string and default formatted unix timestamp. - $formatted_string = EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'); - $this->assertEquals($now->format($expected_format), $formatted_string); - $timestamp_with_offset = EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start', true); - $this->assertEquals($now->format('U'), $timestamp_with_offset); - //test values when timezone and formats modified on EE_Datetime instantiation - $this->factory->datetime->create(array( - 'formats' => array('Y-m-d', 'H:i:s'), - 'timezone' => 'America/Vancouver', - )); - $formatted_string = EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'); - $this->assertDateWithinOneMinute($timezoneTest->format('Y-m-d H:i:s'), $formatted_string, 'Y-m-d H:i:s'); - $unix_timestamp = EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start', true); - $this->assertDateWithinOneMinute($timezoneTest->format('U'), $unix_timestamp, 'U'); - } - - - - /** - * If the site time format doesn't include seconds (which it doesn't, by default) - * then EEM_Base::current_time_for_query() truncates them - * @group 10869 - */ - public function test_current_time_for_query__ignore_minutes(){ - $formats = EE_Registry::instance()->load_model('Datetime')->get_formats_for('DTT_EVT_start'); - $this->assertEquals( - Datetime::createFromFormat( - 'Y-m-d H:i', - gmdate( 'Y-m-d H:i' ) - ), - DateTime::createFromFormat( - implode(' ', $formats - ), - EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start') - ) - ); - } - - /** - * If the site time format doesn't include seconds (which it doesn't, by default) - * then EEM_Base::current_time_for_query() truncates them - * @group 10869 - */ - public function test_current_time_for_query__timestamp(){ - $formats = EE_Registry::instance()->load_model('Datetime')->get_formats_for('DTT_EVT_start'); - $datetime = new DateTime(); - $datetime->setTimestamp( - EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start', true) - ); - $this->assertDateWithinOneMinute( - time(), - $datetime->format('U'), - 'U' - ); - } - - - - /** - * @group 341 - * @since 4.6.x - */ - public function test_convert_datetime_for_query() - { - EEM_Datetime::reset(); - //baselines for testing with - //baseline DateTime object for testing - $now = new DateTime("now"); - $timezoneTest = new DateTime("now", new DateTimeZone('America/Vancouver')); - $timezones_to_test = array( - 'Asia/Singapore', - 'America/Denver', - ); - $original_timezone = get_option('timezone_string'); - $original_offset = get_option('gmt_offset'); - foreach ($timezones_to_test as $timezone) { - //change the timezone set in wp options to something that has a positive offset - update_option('timezone_string', $timezone); - //initialize EEM_Datetime and EE_Datetime_Field settings for caches - $this->factory->datetime->create(array('formats' => array('F j, Y', 'g:i a'), 'timezone' => 'UTC')); - //test getting correctly formatted string for matching incoming format with defaults in WP - //options - $converted = EEM_Datetime::instance() - ->convert_datetime_for_query('DTT_EVT_start', $now->format('F j, Y g:i a'), - 'F j, Y g:i a', 'UTC'); - $this->assertDateWithinOneMinute( - $now->format('F j, Y g:i a'), - $converted->format('F j, Y g:i a'), - 'F j, Y g:i a', - sprintf('Dates not within one minute for timezone: %s', $timezone) - ); - //test getting correctly formatted string for different incoming format in same timezone. - $converted = EEM_Datetime::instance() - ->convert_datetime_for_query('DTT_EVT_start', $now->format('Y-m-d H:i:s'), - 'Y-m-d H:i:s', 'UTC'); - $this->assertDateWithinOneMinute( - $now->format('F j, Y g:i a'), - $converted->format('F j, Y g:i a'), - 'F j, Y g:i a', - sprintf('Dates not within one minute for timezone tested: %s', $timezone) - ); - //test getting correctly formatted string for different incoming format in different incoming timezone. - $converted = EEM_Datetime::instance() - ->convert_datetime_for_query('DTT_EVT_start', $timezoneTest->format('Y-m-d H:i:s'), - 'Y-m-d H:i:s', 'America/Vancouver'); - $this->assertDateWithinOneMinute( - $now->format('F j, Y g:i a'), - $converted->format('F j, Y g:i a'), - 'F j, Y g:i a', - sprintf('Dates not within one minute for timezone: %s', $timezone)); - //test getting correctly formatted string for unix_timestamp format. - $converted = EEM_Datetime::instance()->convert_datetime_for_query('DTT_EVT_start', time(), 'U'); - $this->assertDateWithinOneMinute( - $now->format('F j, Y g:i a'), - $converted->format('F j, Y g:i a'), - 'F j, Y g:i a', - sprintf('Timezone tested: %s', $timezone) - ); - //test getting correctly formatted string for current_time('mysql') format. - $converted = EEM_Datetime::instance() - ->convert_datetime_for_query('DTT_EVT_start', current_time('mysql'), - 'Y-m-d H:i:s'); - $this->assertDateWithinOneMinute( - $now->format('F j, Y g:i a'), - $converted->format('F j, Y g:i a'), - 'F j, Y g:i a', - sprintf('Dates not within one minute for timezone: %s', $timezone) - ); - //repeat above tests when internals on EE_Datetime_Field have been modified by new - //datetime creation. - $this->factory->datetime->create(array( - 'formats' => array('d/m/Y', 'h:i a'), - 'timezone' => 'America/Vancouver', - )); - //test getting correctly formatted string for matching incoming format with what is currently - //set - $converted = EEM_Datetime::instance() - ->convert_datetime_for_query('DTT_EVT_start', $timezoneTest->format('U'), 'U', - 'America/Vancouver'); - $this->assertDateWithinOneMinute( - $timezoneTest->format('d/m/Y h:i a'), - $converted->format('d/m/Y h:i a'), - 'd/m/Y h:i a', - sprintf('Dates not within one minute for timezone: %s', $timezone) - ); - //test getting correctly formatted string for different incoming format in same timezone. - $converted = EEM_Datetime::instance() - ->convert_datetime_for_query('DTT_EVT_start', $timezoneTest->format('Y-m-d H:i:s'), - 'Y-m-d H:i:s', 'America/Vancouver'); - $this->assertDateWithinOneMinute( - $timezoneTest->format('d/m/Y h:i a'), - $converted->format('d/m/Y h:i a'), - 'd/m/Y h:i a', - sprintf('Dates not within one minute for timezone tested: %s', $timezone) - ); - //test getting correctly formatted string for different incoming format in different incoming timezone. - $converted = EEM_Datetime::instance() - ->convert_datetime_for_query('DTT_EVT_start', $now->format('U'), 'U', 'UTC'); - $this->assertDateWithinOneMinute( - $timezoneTest->format('d/m/Y h:i a'), - $converted->format('d/m/Y h:i a'), - 'd/m/Y h:i a', - sprintf('Dates not within one minute for timezone tested: %s', $timezone) - ); - //test getting correctly formatted string for time() format. - $converted = EEM_Datetime::instance()->convert_datetime_for_query('DTT_EVT_start', time(), 'U'); - $this->assertDateWithinOneMinute( - $timezoneTest->format('d/m/Y h:i a'), - $converted->format('d/m/Y h:i a'), - 'd/m/Y h:i a', - sprintf('Dates not within one minute for timezone tested: %s', $timezone) - ); - //test getting correctly formatted string for current_time('mysql') format. - $converted = EEM_Datetime::instance() - ->convert_datetime_for_query('DTT_EVT_start', current_time('mysql'), - 'Y-m-d H:i:s'); - $this->assertDateWithinOneMinute( - $timezoneTest->format('d/m/Y h:i a'), - $converted->format('d/m/Y h:i a'), - 'd/m/Y h:i a', - sprintf('Dates not within one minute for timezone tested: %s', $timezone) - ); - } - update_option('timezone_string', $original_timezone); - update_option('gmt_offset', $original_offset); - } - - - - public function test_alter_query_params_to_only_include_mine__logged_in() - { - global $current_user; - //setup our user and set as current user. - $user = $this->factory->user->create_and_get(); - $this->assertInstanceOf('WP_User', $user); - $user->add_role('administrator'); - $current_user = $user; - $this->assertTrue(is_user_logged_in()); - $this->assertEquals( - array( - array( - 'QST_wp_user' => get_current_user_id(), - ), - ), - EEM_Question::instance()->alter_query_params_to_only_include_mine()); - } - - - - public function test_alter_query_params_to_only_include_mine__not_logged_in() - { - $this->assertFalse(is_user_logged_in()); - $this->assertEquals( - array( - array( - 'QST_wp_user' => get_current_user_id(), - ), - ), - EEM_Question::instance()->alter_query_params_to_only_include_mine()); - } - - - - public function test_alter_query_params_to_only_include_mine__across_model_chain_once() - { - $this->assertFalse(is_user_logged_in()); - $this->assertEquals( - array( - array( - 'Event.EVT_wp_user' => get_current_user_id(), - ), - ), - EEM_Registration::instance()->alter_query_params_to_only_include_mine()); - } - - - - public function test_alter_query_params_to_only_include_mine__across_model_chain_twice() - { - $this->assertFalse(is_user_logged_in()); - $this->assertEquals( - array( - array( - 'Registration.Event.EVT_wp_user' => get_current_user_id(), - ), - ), - EEM_Transaction::instance()->alter_query_params_to_only_include_mine()); - } - - - - /** - * @group 10083 - */ - public function test_alter_query_params_to_restrict_by_ID__simple_id() - { - $e = $this->new_model_obj_with_dependencies('Event'); - $query_params = EEM_Event::instance()->alter_query_params_to_restrict_by_ID($e->ID()); - $e_found = EEM_Event::instance()->get_one($query_params); - $this->assertEquals($e, $e_found); - } - - - - /** - * @group 10083 - */ - public function test_alter_query_params_to_restrict_by_ID__get_index_primary_key_string() - { - $e = $this->new_model_obj_with_dependencies('Event'); - $query_params = EEM_Event::instance()->alter_query_params_to_restrict_by_ID( - EEM_Event::instance()->get_index_primary_key_string( - $e->model_field_array() - ) - ); - $e_found = EEM_Event::instance()->get_one($query_params); - $this->assertEquals($e, $e_found); - } - - - - /** - * Checks that we can correctly apply backend read caps where there is only - * one cap controlling access to the model - * - * @group model_caps - */ - public function test_get_all__caps_admin_read__basic() - { - $this->assertEquals(0, EEM_Transaction::instance()->count()); - $this->new_typical_transaction(); - $current_user = $this->_ensure_current_user_set(); - //let's test first on transactions, which just have a single cap controlling access - //which the current user doesn't have so nothing should be found - $this->assertEquals(0, EEM_Transaction::instance()->count(array('caps' => EEM_Base::caps_read_admin))); - //now give the user permission to access transactions and make sure he can - $current_user->add_cap('ee_read_transactions'); - $this->assertEquals(EEM_Transaction::instance()->count(), - EEM_Transaction::instance()->count(array('caps' => EEM_Base::caps_read_admin))); - } - - - - /** - * Checks that we can correctly apply backend read caps where there are two - * caps controlling access to the model: the basic cap (eg 'ee_read_registrations') - * and the 'others' cap (eg 'ee_read_others_registrations' ) - * - * @group model_caps - */ - public function test_get_all__caps_admin_read__basic_and_others() - { - $current_user = $this->_ensure_current_user_set(); - $mtg_mine = $this->new_model_obj_with_dependencies('Message_Template_Group', - array('MTP_user_id' => $current_user->ID, 'MTP_is_global' => false)); - $mtg_others = $this->new_model_obj_with_dependencies('Message_Template_Group', - array('MTP_user_id' => $current_user->ID + 1, 'MTP_is_global' => false)); - //current user can't access messages - $this->assertEquals(0, - EEM_Message_Template_Group::instance()->count(array('caps' => EEM_Base::caps_read_admin))); - //ok now allow them to see their own messages - $current_user->add_cap('ee_read_messages'); - $mtgs_i_can_see_now = EEM_Message_Template_Group::instance() - ->get_all(array('caps' => EEM_Base::caps_read_admin)); - $this->assertEquals(1, count($mtgs_i_can_see_now)); - $first_mtg_i_can_see_now = reset($mtgs_i_can_see_now); - $this->assertEquals($mtg_mine, $first_mtg_i_can_see_now); - //ok now allowthem to see others non-global messages (tesing global-related-caps should happen on EEM_Message_template_Group_Test) - $current_user->add_cap('ee_read_others_messages'); - $mtgs_i_can_see_now = EEM_Message_Template_Group::instance()->get_all(array( - 'caps' => EEM_Base::caps_read_admin, - array('MTP_is_global' => false), - )); - $this->assertEquals(2, count($mtgs_i_can_see_now)); - $first_mtg_i_can_see_now = reset($mtgs_i_can_see_now); - $this->assertEquals($mtg_mine, $first_mtg_i_can_see_now); - $last_mtg_i_can_see_now = end($mtgs_i_can_see_now); - $this->assertEquals($mtg_others, $last_mtg_i_can_see_now); - } - - - - /** - * Checks that we can correctly apply backend read caps where there are three - * caps controlling access to the model: the basic cap (eg 'ee_read_events') - * and the 'others' cap (eg 'ee_read_others_events' ) and the - * 'private' cap (eg 'ee_read_private_events') - * - * @group model_caps - */ - public function test_get_all__caps_admin_read__basic_others_and_private() - { - $current_user = $this->_ensure_current_user_set(); - $my_e = $this->new_model_obj_with_dependencies('Event', - array('EVT_wp_user' => $current_user->ID, 'status' => 'publish')); - $others_public_e = $this->new_model_obj_with_dependencies('Event', - array('EVT_wp_user' => $current_user->ID + 1, 'status' => 'publish')); - $others_private_e = $this->new_model_obj_with_dependencies('Event', - array('EVT_wp_user' => $current_user->ID + 1, 'status' => 'private')); - //although there are 3 events, the current user shouldn't have permission to see any in the admin - $this->assertEquals(3, EEM_Event::instance()->count()); - $this->assertEquals(0, EEM_Event::instance()->count(array('caps' => EEM_Base::caps_read_admin))); - //ok give them the cap to view their own - $current_user->add_cap('ee_read_events'); - $events_i_can_see = EEM_Event::instance()->get_all(array('caps' => EEM_Base::caps_read_admin)); - $this->assertEquals(1, count($events_i_can_see)); - $first_event_i_can_see = reset($events_i_can_see); - $this->assertEquals($my_e, $first_event_i_can_see); - //ok now allowthem to see others, but not others private events - $current_user->add_cap('ee_read_others_events'); - $events_i_can_see = EEM_Event::instance()->get_all(array('caps' => EEM_Base::caps_read_admin)); - $this->assertEquals(2, count($events_i_can_see)); - $first_event_i_can_see = reset($events_i_can_see); - $this->assertEquals($my_e, $first_event_i_can_see); - $second_event_i_can_see = next($events_i_can_see); - $this->assertEquals($others_public_e, $second_event_i_can_see); - //ok now allowthem to see others private events - $current_user->add_cap('ee_read_private_events'); - $events_i_can_see = EEM_Event::instance()->get_all(array( - 'caps' => EEM_Base::caps_read_admin, - 'order_by' => array('EVT_ID' => 'ASC'), - )); - $this->assertEquals(3, count($events_i_can_see)); - $first_event_i_can_see = reset($events_i_can_see); - $this->assertEquals($my_e, $first_event_i_can_see); - $second_event_i_can_see = next($events_i_can_see); - $this->assertEquals($others_public_e, $second_event_i_can_see); - $second_event_i_can_see = next($events_i_can_see); - $this->assertEquals($others_private_e, $second_event_i_can_see); - } - - - - /** - * Checks that we can correctly apply FRONTEND read caps where there are three - * caps controlling access to the model: the basic cap (eg 'ee_read_events') - * and the 'others' cap (eg 'ee_read_others_events' ) and the - * 'private' cap (eg 'ee_read_private_events') - * - * @group model_caps - */ - public function test_get_all__caps_read_read__basic_others_and_private() - { - $others_public_e = $this->new_model_obj_with_dependencies('Event', - array('EVT_wp_user' => 45678, 'status' => 'publish')); - $others_private_e = $this->new_model_obj_with_dependencies('Event', - array('EVT_wp_user' => 3456, 'status' => 'private')); - $others_draft_e = $this->new_model_obj_with_dependencies('Event', - array('EVT_wp_user' => 1234, 'status' => 'draft')); - //although there are 3 events, the current user shouldn't have permission to see any in the admin - $this->assertEquals(3, EEM_Event::instance()->count()); - $events_i_can_see = EEM_Event::instance()->get_all(array('caps' => EEM_Base::caps_read)); - $this->assertEquals(1, count($events_i_can_see)); - $first_event_i_can_see = reset($events_i_can_see); - $this->assertEquals($others_public_e, $first_event_i_can_see); - //ok great. now let's authenticate and create some events for the authenticated user - $current_user = $this->_ensure_current_user_set(); - //ok give them the cap to view their own - $current_user->add_cap('ee_read_events'); - $my_e = $this->new_model_obj_with_dependencies('Event', - array('EVT_wp_user' => $current_user->ID, 'status' => 'publish')); - $my_private_e = $this->new_model_obj_with_dependencies('Event', - array('EVT_wp_user' => $current_user->ID, 'status' => 'private')); - $this->assertEquals(5, EEM_Event::instance()->count()); - $events_i_can_see = EEM_Event::instance()->get_all(array( - 'caps' => EEM_Base::caps_read, - 'order_by' => array('EVT_ID' => 'ASC'), - )); - $this->assertEquals(3, count($events_i_can_see)); - $first_event_i_can_see = reset($events_i_can_see); - $this->assertEquals($others_public_e, $first_event_i_can_see); - $second_event_i_can_see = next($events_i_can_see); - $this->assertEquals($my_e, $second_event_i_can_see); - $third_event_i_can_see = next($events_i_can_see); - $this->assertEquals($my_private_e, $third_event_i_can_see); - //ok great. give them the cap to view others - $current_user->add_cap('ee_read_others_events'); - $events_i_can_see = EEM_Event::instance()->get_all(array( - 'caps' => EEM_Base::caps_read, - 'order_by' => array('EVT_ID' => 'ASC'), - )); - $this->assertEquals(4, count($events_i_can_see)); - $first_event_i_can_see = reset($events_i_can_see); - $this->assertEquals($others_public_e, $first_event_i_can_see); - $second_event_i_can_see = next($events_i_can_see); - $this->assertEquals($others_draft_e, $second_event_i_can_see); - $third_event_i_can_see = next($events_i_can_see); - $this->assertEquals($my_e, $third_event_i_can_see); - $fourth_event_i_can_see = next($events_i_can_see); - $this->assertEquals($my_private_e, $fourth_event_i_can_see); - //ok now allowthem to see others, but not others private events - $current_user->add_cap('ee_read_others_events'); - $events_i_can_see = EEM_Event::instance()->get_all(array( - 'caps' => EEM_Base::caps_read, - 'order_by' => array('EVT_ID' => 'ASC'), - )); - $this->assertEquals(4, count($events_i_can_see)); - $first_event_i_can_see = reset($events_i_can_see); - $this->assertEquals($others_public_e, $first_event_i_can_see); - $second_event_i_can_see = next($events_i_can_see); - $this->assertEquals($others_draft_e, $second_event_i_can_see); - $third_event_i_can_see = next($events_i_can_see); - $this->assertEquals($my_e, $third_event_i_can_see); - $fourth_event_i_can_see = next($events_i_can_see); - $this->assertEquals($my_private_e, $fourth_event_i_can_see); - //ok now allowthem to see others private events - $current_user->add_cap('ee_read_private_events'); - $events_i_can_see = EEM_Event::instance()->get_all(array( - 'caps' => EEM_Base::caps_read, - 'order_by' => array('EVT_ID' => 'ASC'), - )); - $this->assertEquals(5, count($events_i_can_see)); - $first_event_i_can_see = reset($events_i_can_see); - $this->assertEquals($others_public_e, $first_event_i_can_see); - $second_event_i_can_see = next($events_i_can_see); - $this->assertEquals($others_private_e, $second_event_i_can_see); - $third_event_i_can_see = next($events_i_can_see); - $this->assertEquals($others_draft_e, $third_event_i_can_see); - $fourth_event_i_can_see = next($events_i_can_see); - $this->assertEquals($my_e, $fourth_event_i_can_see); - $fifth_event_i_can_see = next($events_i_can_see); - $this->assertEquals($my_private_e, $fifth_event_i_can_see); - } - - - - /** - * Makes sure the current user global is set and returns whoever that is - * - * @global WP_User $current_user - * @return WP_User - */ - protected function _ensure_current_user_set() - { - global $current_user; - if ( ! $current_user instanceof WP_User || ($current_user instanceof WP_User && $current_user->ID == 0)) { - $current_user = $this->factory->user->create_and_get(); - } - return $current_user; - } - - - - /** - * Tests that when we get rows from the database and a secondary table has no row, - * but the primary one does, that the fields for the secondary table are given - * DEFAULT values instead of NULLs - * - * @group 7634 - */ - public function test_if_no_meta_row_use_defaults_not_nulls() - { - $e = $this->new_model_obj_with_dependencies('Event'); - //now use wpdb to directly delete its meta row - global $wpdb; - $deletions = $wpdb->delete(EEM_Event::instance()->second_table(), array('EVT_ID' => $e->ID()), array('%d')); - $this->assertEquals(1, $deletions); - //now forget about the old event object we had, we want to see what happens when we fetch it again - EEM_Event::reset(); - $incomplete_e = EEM_Event::instance()->get_one_by_ID($e->ID()); - $actual_row = EEM_Event::instance()->get_all_wpdb_results(array(array('EVT_ID' => $e->ID()))); - $a_field_from_meta_table = EEM_Event::instance()->field_settings_for('EVT_display_ticket_selector'); - $another_field_from_meta_table = EEM_Event::instance()->field_settings_for('EVT_additional_limit'); - $this->assertEquals($a_field_from_meta_table->get_default_value(), - $incomplete_e->get('EVT_display_ticket_selector')); - $this->assertTrue(null !== $incomplete_e->get('EVT_display_ticket_selector')); - $this->assertEquals($another_field_from_meta_table->get_default_value(), - $incomplete_e->get('EVT_additional_limit')); - } - - - - /** - * Tests that if we are joining to a table that has no entries matching the query, - * but the primary table does that we don't create model objects for the non-existent - * row, but we do still create model objects for the row that did exist. - * - * @group 7634 - */ - public function test_get_all_if_related_model_blank_use_nulls() - { - $price_sans_price_type = EE_Price::new_instance(array( - 'PRC_name' => 'original', - 'PRT_ID' => EEM_Price_Type::instance()->count() + 1, - )); - $price_sans_price_type->save(); - $fetched_price = EEM_Price::reset()->get_one(array( - array('PRC_ID' => $price_sans_price_type->ID()), - 'force_join' => array('Price_Type'), - )); - $this->assertInstanceOf('EE_Price', $fetched_price); - $this->assertEquals(null, $fetched_price->type_obj()); - } - - - - /** - * Should reproduce issue 7791 - * - * @group 7791 - */ - public function test_create_question_options() - { - foreach (EE_Registry::instance()->non_abstract_db_models as $model_name => $model_classname) { - $model = EE_Registry::instance()->load_model($model_name); - $question_option = $this->new_model_obj_with_dependencies($model_name); - $this->assertInstanceOf('EE_' . $model_name, $question_option); - //make sure this model is queryable and when we fetch its items that there's no errors - $model->get_all(); - } - } - - - - /** - * @since 4.6.x - */ - public function test_next_x() - { - //create 5 events for testing with. - $events = $this->factory->event->create_many(5); - //grab the first event in the list as the reference - $event = reset($events); - $this->assertInstanceOf('EE_Event', $event); - //test method retrieving objects - $next_events = EEM_Event::instance()->next_x($event->ID(), 'EVT_ID', 4); - $this->assertEquals(4, count($next_events)); - $this->assertInstanceOf('EE_Event', reset($next_events)); - //test retrieving just ids - $next_events = EEM_Event::instance()->next_x($event->ID(), 'EVT_ID', 4, array(), 'EVT_ID'); - $this->assertEquals(4, count($next_events)); - $this->assertTrue(array_key_exists('EVT_ID', $next_events[0])); - } - - - - /** - * @since 4.6.x - */ - public function test_previous_x() - { - //create 5 events for testing with. - $events = $this->factory->event->create_many(5); - //grab the last event in the list as the reference - $event = end($events); - $this->assertInstanceOf('EE_Event', $event); - //test method retrieving objects - $previous_events = EEM_Event::instance()->previous_x($event->ID(), 'EVT_ID', 4); - $this->assertEquals(4, count($previous_events)); - $this->assertInstanceOf('EE_Event', reset($previous_events)); - //test retrieving just ids - $previous_events = EEM_Event::instance()->previous_x($event->ID(), 'EVT_ID', 4, array(), 'EVT_ID'); - $this->assertEquals(4, count($previous_events)); - $this->assertTrue(array_key_exists('EVT_ID', $previous_events[3])); - } - - - - /** - * @since 4.6.x - */ - public function test_next() - { - //create 5 events for testing with. - $events = $this->factory->event->create_many(5); - //grab the first event in the list as the reference - $event = reset($events); - $this->assertInstanceOf('EE_Event', $event); - //test method retrieving object - $next_event = EEM_Event::instance()->next($event->ID()); - $this->assertInstanceOf('EE_Event', $next_event); - $this->assertEquals($event->ID() + 1, $next_event->ID()); - //test retrieving just ids - $next_event = EEM_Event::instance()->next($event->ID(), 'EVT_ID', array(), 'EVT_ID'); - $this->assertTrue(array_key_exists('EVT_ID', $next_event)); - $this->assertEquals($event->ID() + 1, $next_event['EVT_ID']); - } - - - - /** - * @since 4.6.x - */ - public function test_previous() - { - //create 5 events for testing with. - $events = $this->factory->event->create_many(5); - //grab the last event in the list as the reference - $event = end($events); - $this->assertInstanceOf('EE_Event', $event); - //test method retrieving object - $previous_event = EEM_Event::instance()->previous($event->ID()); - $this->assertInstanceOf('EE_Event', $previous_event); - $this->assertEquals($event->ID() - 1, $previous_event->ID()); - //test retrieving just ids - $previous_event = EEM_Event::instance()->previous($event->ID(), 'EVT_ID', array(), 'EVT_ID'); - $this->assertTrue(array_key_exists('EVT_ID', $previous_event)); - $this->assertEquals($event->ID() - 1, $previous_event['EVT_ID']); - } - - - - /** - * checks that the BETWEEN operator works ok - * - * @group 8187 - */ - public function test_get_all__between() - { - EEM_Event::instance()->get_all(array( - array( - 'Datetime.DTT_EVT_start' => array('BETWEEN', array('2015-03-02 00:00:00', '2016-03-04 00:00:00')), - ), - )); - $this->assertTrue(true); - } - - - - /** - * @group 8241 - */ - public function test_get_IDs__empty_ID() - { - $e1 = $this->new_model_obj_with_dependencies('Event', array(), false); - $e2 = $this->new_model_obj_with_dependencies('Event', array(), false); - $this->assertEquals(array(), EEM_Event::instance()->get_IDs(array($e1, $e2), true)); - } - - - - /** - * @group 8241 - */ - public function test_get_IDS() - { - $e1 = $this->new_model_obj_with_dependencies('Event', array()); - $e2 = $this->new_model_obj_with_dependencies('Event', array()); - $this->assertEquals(array($e1->ID(), $e2->ID()), EEM_Event::instance()->get_IDs(array($e1, $e2), true)); - } - - - - /** - * @group 9389 - */ - public function test_get_all__automatic_group_by() - { - $this->assertEquals(2, EEM_Question_Group::instance()->count()); - $qsgs = EEM_Question_Group::instance()->get_all( - array( - 'force_join' => array('Question'), - 'limit' => array(2, 2),//grab 2 but offset by 2 - ) - ); - //so there are only 2 question groups, and we offset by 2. - //so we shouldn't see any right? - $this->assertEmpty($qsgs); - } - - - - /** - * Verifies that the EEM_Base::$_model_query_blog_id is not set until any model is instantiated and that if the - * blog id is explicitly changed after instantiation (via the setter), future models instantiated will still retain - * the blog id changed to. - * - * @group 9743 - */ - public function test_model_query_blog_id_set_on_instantiation() - { - //instantiate a model and verify that sets to current_blog_id(); - $attendee = EEM_Attendee::instance(); - $this->assertEquals(EEM_Base::get_model_query_blog_id(), get_current_blog_id()); - //verify blog_id changes - EEM_Base::set_model_query_blog_id(2); - $this->assertEquals(EEM_Base::get_model_query_blog_id(), 2); - //verify that any NEW models instantiated retain that change. - $question = EEM_Question::reset(); - $this->assertEquals(EEM_Base::get_model_query_blog_id(), 2); - //make sure we restore the models to blog 1 for future tests. - EEM_Base::set_model_query_blog_id(1); - } - - - - /** - * @group 9566 - */ - public function test_is_logic_query_param_key() - { - $this->assertTrue( EEM_Answer::instance()->is_logic_query_param_key( 'OR' ) ); - $this->assertTrue( EEM_Answer::instance()->is_logic_query_param_key( 'NOT*' ) ); - $this->assertTrue( EEM_Answer::instance()->is_logic_query_param_key( 'AND*other-condition' ) ); - $this->assertFalse( EEM_Answer::instance()->is_logic_query_param_key( 'ATT_fname' ) ); - $this->assertFalse( EEM_Answer::instance()->is_logic_query_param_key( 'Registration.REG_date' ) ); - $this->assertFalse( EEM_Answer::instance()->is_logic_query_param_key( 'ORG_name' ) ); - - } - - - /** - * @group customselects - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws Exception - */ - public function testExtraSelects() - { - //setup some data in the db - $attendee = $this->factory->attendee->create(); - $this->factory->registration->create_many(3, array('ATT_ID' => $attendee->ID())); - EEM_Attendee::reset(); - EEM_Registration::reset(); - $attendees = EEM_Attendee::instance()->get_all( - array( - 'extra_selects' => array( - 'registration_count' => array('Registration.REG_ID', 'count', '%d') - ) - ) - ); - $this->assertCount(1, $attendees); - $attendee = reset($attendees); - $this->assertInstanceOf('EE_Attendee', $attendee); - $this->assertEquals(3, $attendee->getCustomSelect('registration_count')); - } -} - -// End of file EEM_Base_Test.php -// Location: testcases/core/db_models/EEM_Base_Test.php diff --git a/tests/testcases/core/db_models/EEM_Base_Using_Mock_Model_Test.php b/tests/testcases/core/db_models/EEM_Base_Using_Mock_Model_Test.php deleted file mode 100644 index ab33963d4aa..00000000000 --- a/tests/testcases/core/db_models/EEM_Base_Using_Mock_Model_Test.php +++ /dev/null @@ -1,166 +0,0 @@ -_stop_pretending_addon_hook_time(); - $this->_pretend_addon_hook_time(); - $this->assertArrayDoesNotContain('EEM_Mock', EE_Registry::instance()->non_abstract_db_models); - $this->assertArrayDoesNotContain('EEM_Mock', EE_Registry::instance()->models); - //register it for realz - EE_Register_Model::register( - 'Mock', - array( - 'model_paths' => array(EE_MOCKS_DIR . 'core/db_models/'), - 'class_paths' => array(EE_MOCKS_DIR . 'core/db_classes/'), - ) - ); - //whitelist the table we're about to add - add_filter('FHEE__EEH_Activation__create_table__short_circuit', array($this, 'dont_short_circuit_mock_table'), 25, 3); - //add table from related DMS - EEH_Activation::create_table('esp_mock', ' - MCK_ID int(10) unsigned NOT NULL AUTO_INCREMENT, - MCK_value varchar(100), - MCK_datetime DATETIME NOT NULL DEFAULT "0000-00-00 00:00:00", - PRIMARY KEY (MCK_ID)' - ); - $this->assertTableExists('esp_mock'); - EE_System::instance()->load_core_configuration(); - $this->assertArrayContains('EEM_Mock', EE_Registry::instance()->non_abstract_db_models); - $this->assertArrayContains('EEM_Mock', EE_Registry::instance()->models); - } - - - - /** - * OK's the creation of the esp_new_addon table, because this hooks in AFTER EE_UNitTestCase's callback on this same hook - * - * @param bool $short_circuit - * @param string $table_name - * @param string $create_sql - * @return array - */ - public function dont_short_circuit_mock_table($short_circuit = false, $table_name = '', $create_sql = '') - { - $table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true); - if ($table_name == 'esp_mock' && ! $table_analysis->tableExists($table_name)) { - // echo "\r\n\r\nDONT short circuit $sql"; - //it's not altering. it's ok to allow this - return false; - } else { - // echo "3\r\n\r\n short circuit:$sql"; - return $short_circuit; - } - } - - - - /** - */ - public function test_get_all() - { - //there should be nothing in here - $this->assertFalse(EEM_Mock::instance()->exists(array())); - $mock_thing = EE_Mock::new_instance( - array( - 'MCK_value' => 'foobar', - ) - ); - $id = $mock_thing->save(); - $found_mock_thing = EEM_Mock::instance()->get_one(); - $this->assertEquals($mock_thing, $found_mock_thing); - } - - - - /** - */ - public function test_get_qualified_columns_for_all_fields__as_string() - { - $this->assertEquals( - 'Mock.MCK_ID, Mock.MCK_value, Mock.MCK_datetime', - EEM_Mock::instance()->get_qualified_columns_for_all_fields() - ); - } - - - - /** - */ - public function test_get_qualified_columns_for_all_fields__as_array() - { - $this->assertEquals( - array( - 'Mock.MCK_ID', - 'Mock.MCK_value', - 'Mock.MCK_datetime', - ), - EEM_Mock::instance()->get_qualified_columns_for_all_fields('', false) - ); - } - - - - /** - */ - public function test_get_qualified_columns_for_all_fields__with_prefix() - { - $this->assertEquals( - array( - 'Extra_Meta__Mock.MCK_ID', - 'Extra_Meta__Mock.MCK_value', - 'Extra_Meta__Mock.MCK_datetime', - ), - EEM_Mock::instance()->get_qualified_columns_for_all_fields('Extra_Meta', false) - ); - } - - - - /** - * Make up a really long model chain. It doesn't need to be actual model names (at least right now; if that - * ever becomes a requirement then we'll need to hae EEM_Mock actually related to some more mock models) - */ - public function test_get_qualified_columns_for_all_fields__with_big_prefix() - { - $this->assertEquals( - array( - 'Some__Model__Chain__Mock.MCK_ID', - 'Some__Model__Chain__Mock.MCK_value', - 'Some__Model__Chain__Mock.MCK_datetime', - ), - EEM_Mock::instance()->get_qualified_columns_for_all_fields('Some.Model.Chain', false) - ); - } - - - - public function tearDown() - { - EE_Register_Model::deregister('Mock'); - EE_System::instance()->load_core_configuration(); - $this->assertArrayDoesNotContain('EEM_Mock', EE_Registry::instance()->non_abstract_db_models); - $this->assertArrayDoesNotContain('EEM_Mock', EE_Registry::instance()->models); - $this->_stop_pretending_addon_hook_time(); - parent::tearDown(); - } - - -} -// End of file EEM_Base_Using_Mock_Model_Test.php -// Location: tests\testcases\core\db_models/EEM_Base_Using_Mock_Model_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_models/EEM_CPT_Base_Test.php b/tests/testcases/core/db_models/EEM_CPT_Base_Test.php deleted file mode 100644 index 3a21b033a86..00000000000 --- a/tests/testcases/core/db_models/EEM_CPT_Base_Test.php +++ /dev/null @@ -1,89 +0,0 @@ -assertEquals(0, EEM_Event::instance()->count(array('default_where_conditions' => 'none'))); - $e_normal = $this->new_model_obj_with_dependencies('Event', - array('status' => EEM_CPT_Base::post_status_publish)); - $e_trashed = $this->new_model_obj_with_dependencies('Event', - array('status' => EEM_CPT_Base::post_status_trashed)); - $normal_post = $this->factory->post->create_and_get(array('post_type' => 'monkey')); - //verify the regular post got added correctly - $this->assertNotEquals( 0, $normal_post->ID ); - //now verify we get what we wanted: the normal and trashed event, but not - //the normal post - $events_found = EEM_Event::instance()->get_all(array('default_where_conditions' => 'minimum')); - $this->assertArrayContains($e_normal, $events_found); - $this->assertArrayContains($e_trashed, $events_found); - $this->assertCount(2, $events_found); - //incidentally, lets show the problem of using the 'default_where_conditions' => 'none' - //it WOULD count the normal post. Which is obviously NOT an event! - $this->assertEquals(3, EEM_Event::instance()->count(array('default_where_conditions' => 'none'))); - } - - /** - * Test that when we set the minimum_others where conditions, we don't find trashed cpt items - * for the current model (because we use normal default where conditions for main model), but not for related - * trashed models (because they only use their minimum where conditions) - * -*@group 10260 - */ - public function test_get_minimum_others_where_conditions_during_query() - { - $this->assertEquals(0, EEM_Event::instance()->count(array('default_where_conditions' => 'none'))); - $e_normal = $this->new_model_obj_with_dependencies('Event', - array('status' => EEM_CPT_Base::post_status_publish)); - $e_normal_but_with_trashed_v = $this->new_model_obj_with_dependencies('Event', - array('status' => EEM_CPT_Base::post_status_publish)); - $e_trashed = $this->new_model_obj_with_dependencies('Event', - array('status' => EEM_CPT_Base::post_status_trashed)); - $v_normal = $this->new_model_obj_with_dependencies('Venue', - array('status' => EEM_CPT_Base::post_status_publish)); - $v_trashed = $this->new_model_obj_with_dependencies('Venue', - array('status' => EEM_CPT_Base::post_status_trashed)); - //associate them - $e_normal->_add_relation_to($v_normal, 'Venue'); - $e_normal_but_with_trashed_v->_add_relation_to($v_trashed, 'Venue'); - $e_trashed->_add_relation_to($v_normal, 'Venue'); - //now verify we get what we wanted... - $events_found = EEM_Event::instance()->get_all( - array( - 'force_join' => array( 'Venue' ), - 'default_where_conditions' => \EEM_Base::default_where_conditions_minimum_others - ) - ); - //we should find the normal one because it's not trashed, nor is its venue - $this->assertArrayContains($e_normal, $events_found); - //we should NOT find the trashed event - $this->assertArrayDoesNotContain($e_trashed, $events_found); - //we should find the event that's related to a trashed venue, because - //we should only be applying the MINIMUM where conditions for venues, which don't include their status - $this->assertArrayContains($e_normal_but_with_trashed_v, $events_found); - //and that's it - $this->assertCount(2, $events_found); - } -} diff --git a/tests/testcases/core/db_models/EEM_Change_Log_Test.php b/tests/testcases/core/db_models/EEM_Change_Log_Test.php deleted file mode 100644 index 57cf8b0d9f1..00000000000 --- a/tests/testcases/core/db_models/EEM_Change_Log_Test.php +++ /dev/null @@ -1,50 +0,0 @@ -new_model_obj_with_dependencies( - 'Change_Log', - array( - 'LOG_time' => new DateTime('-2 weeks'), - 'LOG_type' => EEM_Change_Log::type_gateway - ) - ); - $wrong_type = $this->new_model_obj_with_dependencies( - 'Change_Log', - array( - 'LOG_time' => new DateTime('-2 weeks'), - 'LOG_type' => EEM_Change_Log::type_create - ) - ); - $too_new = $this->new_model_obj_with_dependencies( - 'Change_Log', - array( - 'LOG_time' => new DateTime('-1 days'), - 'LOG_type' => EEM_Change_Log::type_gateway - ) - ); - - $result = EEM_Change_Log::instance()->delete_gateway_logs_older_than(new DateTime('-1 weeks')); - $this->assertTrue(EEM_Change_Log::instance()->exists_by_ID( $wrong_type->ID())); - $this->assertTrue(EEM_Change_Log::instance()->exists_by_ID($too_new->ID())); - $this->assertFalse(EEM_Change_Log::instance()->exists_by_ID($delete_me->ID())); - $this->assertEquals( '1', $result ); - - } - - -} -// End of file EEM_Change_Log_Test.php -// Location: ${NAMESPACE}/EEM_Change_Log_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_models/EEM_Country_Test.php b/tests/testcases/core/db_models/EEM_Country_Test.php deleted file mode 100644 index f02bb057778..00000000000 --- a/tests/testcases/core/db_models/EEM_Country_Test.php +++ /dev/null @@ -1,24 +0,0 @@ -assertFalse( EEM_Country::instance()->exists_by_ID( 'ZZZ' ) ); - $c = $this->new_model_obj_with_dependencies( 'Country' ); - $this->assertEquals( '', EEM_Country::instance()->get_country_name_by_ISO( 'ZZZ' ) ); - $this->assertEquals( $c->name(), EEM_Country::instance()->get_country_name_by_ISO( $c->ID() ) ); - } -} - -// End of file EEM_Country_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_models/EEM_Datetime_Test.php b/tests/testcases/core/db_models/EEM_Datetime_Test.php deleted file mode 100644 index d8fd9493810..00000000000 --- a/tests/testcases/core/db_models/EEM_Datetime_Test.php +++ /dev/null @@ -1,536 +0,0 @@ -factory->event->create( array( 'EVT_timezone_string' => 'Australia/Sydney' ) ); - - //for test we want a datetime begining one hour before now and ending now (-1min), and a datetime starting now and ending one hour from now. - $dtt1_start = time() - 60*60*24; - $dtt1_end = time() - 60*60; - $dtt2_start = $dtt1_start + 60*60; - $dtt2_end = $dtt1_end + 60*60*24; - - - $dtt1 = $this->factory->datetime->create( array( 'DTT_EVT_start' => $dtt1_start, 'DTT_EVT_end' => $dtt1_end ) ); - $dtt2 = $this->factory->datetime->create( array( 'DTT_EVT_start' => $dtt2_start, 'DTT_EVT_end' => $dtt2_end ) ); - - //verify - $this->assertInstanceOf( 'EE_Event', $event ); - $this->assertInstanceOf( 'EE_Datetime', $dtt1 ); - $this->assertInstanceOf( 'EE_Datetime', $dtt2 ); - - //attach dtt to event and save - $event->_add_relation_to( $dtt1, 'Datetime' ); - $event->_add_relation_to( $dtt2, 'Datetime' ); - $event->save(); - - //now let's run the method we're checking. - //first NO expiry flag. - $datetimes_on_event = EEM_Datetime::instance()->get_datetimes_for_event_ordered_by_DTT_order( $event->ID() ); - - //we should have all the datetimes returned - $dtt_checked = reset( $datetimes_on_event ); - - $this->assertEquals( 2, count( $datetimes_on_event ) ); - $this->assertInstanceOf( 'EE_Datetime', $dtt_checked ); - $this->assertEquals( $dtt_checked->ID(), $dtt1->ID() ); - - //now let's run the method excluding expired dtts - $datetimes_on_event = EEM_Datetime::instance()->get_datetimes_for_event_ordered_by_DTT_order( $event->ID(), false ); - $second_dtt_chk = reset( $datetimes_on_event ); - - //only one datetime should be returned - $this->assertEquals( 1, count( $datetimes_on_event ) ); - - //we should have the SECOND datetime returned because its the non-expired one. - $this->assertInstanceOf( 'EE_Datetime', $second_dtt_chk ); - $this->assertEquals( $second_dtt_chk->ID(), $dtt2->ID() ); - } - - - - - /** - * Test for get_datetimes_for_event_ordered_by_start_time method - * - * @since 4.5.0 - * - */ - public function test_get_datetimes_for_event_ordered_by_start_time() { - //create an event we'll use - $event = $this->factory->event->create(); - - //let's create three datetimes ( one that started one hour ago and ended now(-1min), one that starts now and ends one hour from now, and one that starts one hour from now and ends two hours from now) - $dtt1start = time() - 60*60; - $dtt1end = time() - 60; - - $dtt2start = $dtt1start + 60*60; - $dtt2end = $dtt1end + 60*60; - $dtt3start = $dtt2start + 60*60; - $dtt3end = $dtt2end + 60*60; - - $dtt1 = $this->factory->datetime->create( array( 'DTT_EVT_start' => $dtt1start, 'DTT_EVT_end' => $dtt1end ) ); - $dtt2 = $this->factory->datetime->create( array( 'DTT_EVT_start' => $dtt2start, 'DTT_EVT_end' => $dtt2end ) ); - $dtt3 = $this->factory->datetime->create( array( 'DTT_EVT_start' => $dtt3start, 'DTT_EVT_end' => $dtt3end ) ); - - //verify - $this->assertInstanceOf( 'EE_Event', $event ); - $this->assertInstanceOf( 'EE_Datetime', $dtt1 ); - $this->assertInstanceOf( 'EE_Datetime', $dtt2 ); - $this->assertInstanceOf( 'EE_Datetime', $dtt3 ); - - //add dtts to event - $event->_add_relation_to( $dtt1, 'Datetime' ); - $event->_add_relation_to( $dtt2, 'Datetime' ); - $event->_add_relation_to( $dtt3, 'Datetime' ); - $event->save(); - - //run the method we are checking with NO expiry flag set (so means we are including expired dtts). - $datetimes_on_event = EEM_Datetime::instance()->get_datetimes_for_event_ordered_by_start_time( $event->ID() ); - - //now let's verify that there are two datetimes returned - $this->assertEquals( 3, count( $datetimes_on_event) ); - - //verify the first datetime = dtt1 (because orderby is supposed to be DTT_EVT_start => ASC ); - $first_dtt = reset( $datetimes_on_event ); - $this->assertInstanceOf( 'EE_Datetime', $first_dtt ); - $this->assertEquals( $first_dtt->ID(), $dtt1->ID() ); - - //k now let's do the same thing as above but this time we DONT' return expired dtts. - //run the method we are checking with NO expiry flag set (so means we are including expired dtts). - $datetimes_on_event = EEM_Datetime::instance()->get_datetimes_for_event_ordered_by_start_time( $event->ID(), false ); - - //now let's verify that there are two datetimes returned (because the dtts should NOT have expired!) - $this->assertEquals( 2, count( $datetimes_on_event) ); - - //verify the first datetime = dtt2 (because orderby is supposed to be DTT_EVT_start => ASC ) AND the datetimes have NOT expired.; - $first_dtt = reset( $datetimes_on_event ); - $this->assertInstanceOf( 'EE_Datetime', $first_dtt ); - $this->assertEquals( $first_dtt->ID(), $dtt2->ID() ); - } - - - - - - /** - * Test the get_datetimes_for_ticket_ordered_by_start_time() method - * @since 4.5.0 - */ - public function test_get_datetimes_for_ticket_ordered_by_start_time() { - //now create a TICKET we'll use. - $ticket = $this->factory->ticket->create(); - - //let's create three datetimes ( one that started one hour ago and ended now (-1min), one that starts now and ends one hour from now, and one that starts one hour from now and ends two hours from now) - $dtt1start = time() - 60*60; - $dtt1end = time() - 60; - - $dtt2start = $dtt1start + 60*60; - $dtt2end = $dtt1end + 60*60; - $dtt3start = $dtt2start + 60*60; - $dtt3end = $dtt2end + 60*60; - - $dtt1 = $this->factory->datetime->create( array( 'DTT_EVT_start' => $dtt1start, 'DTT_EVT_end' => $dtt1end ) ); - $dtt2 = $this->factory->datetime->create( array( 'DTT_EVT_start' => $dtt2start, 'DTT_EVT_end' => $dtt2end ) ); - $dtt3 = $this->factory->datetime->create( array( 'DTT_EVT_start' => $dtt3start, 'DTT_EVT_end' => $dtt3end ) ); - - //verify - $this->assertInstanceOf( 'EE_Datetime', $dtt1 ); - $this->assertInstanceOf( 'EE_Datetime', $dtt2 ); - $this->assertInstanceOf( 'EE_Datetime', $dtt3 ); - $this->assertInstanceOf( 'EE_Ticket', $ticket ); - - //add dtts to ticket - $ticket->_add_relation_to( $dtt1, 'Datetime' ); - $ticket->_add_relation_to( $dtt2, 'Datetime' ); - $ticket->_add_relation_to( $dtt3, 'Datetime' ); - $ticket->save(); - - - //run the method we are checking with NO expiry flag set (so means we are including expired dtts). - $datetimes_on_ticket = EEM_Datetime::instance()->get_datetimes_for_ticket_ordered_by_start_time( $ticket->ID() ); - - //now let's verify that there are three datetimes returned - $this->assertEquals( 3, count( $datetimes_on_ticket) ); - - //verify the first datetime = dtt1 (because orderby is supposed to be DTT_EVT_start => ASC ); - $first_dtt = reset( $datetimes_on_ticket ); - $this->assertInstanceOf( 'EE_Datetime', $first_dtt ); - $this->assertEquals( $first_dtt->ID(), $dtt1->ID() ); - - //k now let's do the same thing as above but this time we DONT' return expired dtts. - //run the method we are checking with NO expiry flag set (so means we are including expired dtts). - $datetimes_on_ticket = EEM_Datetime::instance()->get_datetimes_for_ticket_ordered_by_start_time( $ticket->ID(), false ); - - //now let's verify that there are two datetimes returned (because only 2 of the dtts should NOT have expired!) - $this->assertEquals( 2, count( $datetimes_on_ticket) ); - - //verify the first datetime = dtt2 (because orderby is supposed to be DTT_EVT_start => ASC ) AND the second datetime is the first one that has NOT expired.; - $first_dtt = reset( $datetimes_on_ticket ); - $this->assertInstanceOf( 'EE_Datetime', $first_dtt ); - $this->assertEquals( $first_dtt->ID(), $dtt2->ID() ); - } - - - - - /** - * Test the get_datetimes_for_ticket_ordered_by_DTT_order() method - * @since 4.5.0 - */ - public function test_get_datetimes_for_ticket_ordered_by_DTT_order() { - //create an event and datetime - $ticket = $this->factory->ticket->create(); - - //for test we want a datetime begining one hour before now and ending now (-1min), and a datetime starting now and ending one hour from now. - $dtt1_start = time() - 60*60; - $dtt1_end = time() - 60; - $dtt2_start = $dtt1_start + 60*60; - $dtt2_end = $dtt1_end + 60*60; - - - $dtt1 = $this->factory->datetime->create( array( 'DTT_EVT_start' => $dtt1_start, 'DTT_EVT_end' => $dtt1_end ) ); - $dtt2 = $this->factory->datetime->create( array( 'DTT_EVT_start' => $dtt2_start, 'DTT_EVT_end' => $dtt2_end ) ); - - //verify - $this->assertInstanceOf( 'EE_Ticket', $ticket ); - $this->assertInstanceOf( 'EE_Datetime', $dtt1 ); - $this->assertInstanceOf( 'EE_Datetime', $dtt2 ); - - //attach dtt to ticket and save - $ticket->_add_relation_to( $dtt1, 'Datetime' ); - $ticket->_add_relation_to( $dtt2, 'Datetime' ); - $ticket->save(); - - //now let's run the method we're checking. - //first NO expiry flag. - $datetimes_on_ticket = EEM_Datetime::instance()->get_datetimes_for_ticket_ordered_by_DTT_order( $ticket->ID() ); - - //we should have the datetime returned - $dtt_checked = reset( $datetimes_on_ticket ); - - //check count, it should be two datetimes because expiry ignored. - $this->assertEquals( 2, count( $datetimes_on_ticket ) ); - - //shoudl be first datetime because expiry ignored. - $this->assertInstanceOf( 'EE_Datetime', $dtt_checked ); - $this->assertEquals( $dtt_checked->ID(), $dtt1->ID() ); - - //now let's run the method excluding expired dtts - $datetimes_on_ticket = EEM_Datetime::instance()->get_datetimes_for_ticket_ordered_by_DTT_order( $ticket->ID(), false ); - $second_dtt_chk = reset( $datetimes_on_ticket ); - - //count should be one because expiry considered. - $this->assertEquals( 1, count( $datetimes_on_ticket ) ); - - //first datetime returned should be dtt2 because dtt1 is expired. - $this->assertInstanceOf( 'EE_Datetime', $second_dtt_chk ); - $this->assertEquals( $second_dtt_chk->ID(), $dtt2->ID() ); - } - - - - - /** - * @since 4.6.x - */ - public function test_create_new_blank_datetime() { - //if timezone is empty string then the setUp didn't work correctly. For the purpose of this test - //we want a high positive timezone, so let's force that if necessary - if ( get_option( 'timezone_string' ) != 'Australia/Sydney' ) { - update_option( 'timezone_string', 'Australia/Sydney' ); - EEM_Datetime::reset(); - EEM_Datetime::instance(); - } - - //make sure now is in the timezone we want to test with. - $now = new DateTime( '@' . ( time() + ( DAY_IN_SECONDS * 30 ) ) ); - $now->setTimeZone( new DateTimeZone( EEH_DTT_Helper::get_timezone() ) ); - $now->setTime( '8', '0', '0' ); - $now->setTimeZone( new DateTimeZone( 'America/Toronto' ) ); - - //get the default datetime - $default_date = EEM_Datetime::instance()->create_new_blank_datetime(); - $default_date = reset( $default_date ); - - //assert instance - $this->assertInstanceOf( 'EE_Datetime', $default_date ); - - //set its timezone to match our expected timezone - $default_date->set_timezone( 'America/Toronto' ); - $actual = $default_date->get_DateTime_object( 'DTT_EVT_start'); - - $this->assertInstanceOf( 'DateTime', $actual ); - - //assert timezones are the same - $this->assertEquals( $now->getTimezone(), $actual->getTimeZone() ); - - //assert that we have the correct values on the date... we'll do each part separately to verify. - $this->assertEquals( $now->format('Y'), $actual->format('Y' ) ); - $this->assertEquals( $now->format('m'), $actual->format( 'm' ) ); - $this->assertEquals( $now->format('d'), $actual->format( 'd' ) ); - $this->assertEquals( $now->format('H'), $actual->format( 'H' ) ); - $this->assertEquals( $now->format('i'), $actual->format('i' ) ); - } - - - /** - * @since 4.9.80.p - */ - public function testCreateNewBlankDatetimeWithFilters() { - $start_date = new DateTime('@' . strtotime('2012-10-12')); - $end_date = new DateTime('@' . strtotime('2012-10-31')); - add_filter( - 'FHEE__EEM_Datetime__create_new_blank_datetime__start_date', - function () use ($start_date) { - return $start_date->format('U'); - } - ); - add_filter( - 'FHEE__EEM_Datetime__create_new_blank_datetime__end_date', - function () use ($end_date) { - return $end_date->format('U'); - } - ); - add_filter( - 'FHEE__EEM_Datetime__create_new_blank_datetime__start_time', - function () { - return ['10am', 'ga']; - } - ); - add_filter( - 'FHEE__EEM_Datetime__create_new_blank_datetime__end_time', - function () { - return ['8pm', 'ga']; - } - ); - $blank_date = EEM_Datetime::instance()->create_new_blank_datetime()[0]; - $actual_start = $blank_date->get_DateTime_object('DTT_EVT_start'); - $actual_end = $blank_date->get_DateTime_object('DTT_EVT_end'); - - $start_date->setTime('10', '0', '0'); - $end_date->setTime('20', '0', '0'); - $formats = [ 'Y', 'm', 'd', 'H', 'i' ]; - // test each format to ensure it matches expectation - foreach( $formats as $format ) { - $message = 'For format ' . $format; - $this->assertEquals($actual_start->format($format), $start_date->format($format), $message); - $this->assertEquals($actual_end->format($format), $end_date->format($format), $message ); - } - } - - - - public function test_get_dtt_months_and_years() { - //setup some dates we'll use for testing with. - $timezone = new DateTimeZone( 'America/Toronto' ); - $upcoming_start_date = new DateTime( "now +2hours", $timezone ); - $past_start_date = new DateTime( "now -2days", $timezone ); - $current_end_date = new DateTime( "now +2days", $timezone ); - $current = new DateTime( "now", $timezone ); - $formats = array( 'Y-d-m', 'h:i a' ); - $full_format = implode( ' ', $formats ); - - //setup some datetimes to attach to events. - $datetimes = array( - 'expired_datetime' => $this->factory->datetime->create( array( 'DTT_EVT_start' => $past_start_date->format( $full_format ), 'DTT_EVT_end' => $past_start_date->format( $full_format), 'timezone' => 'America/Toronto', 'formats' => $formats ) ), - 'upcoming_datetime' => $this->factory->datetime->create( array( 'DTT_EVT_start' => $upcoming_start_date->format( $full_format ), 'DTT_EVT_end' => $upcoming_start_date->format( $full_format), 'timezone' => 'America/Toronto', 'formats' => $formats ) ), - 'active_datetime' => $this->factory->datetime->create( array( 'DTT_EVT_start' => $current->sub( new DateInterval( "PT2H") )->format( $full_format ), 'DTT_EVT_end' => $current_end_date->add( new DateInterval( "PT2H" ) )->format( $full_format), 'timezone' => 'America/Toronto', 'formats' => $formats ) ), - 'sold_out_datetime' => $this->factory->datetime->create( array( 'DTT_EVT_start' => $upcoming_start_date->format( $full_format ), 'DTT_EVT_end' => $upcoming_start_date->format( $full_format), 'DTT_reg_limit' => 10, 'DTT_sold' => 10, 'timezone' => 'America/Toronto', 'formats' => $formats ) ), - 'inactive_datetime' => $this->factory->datetime->create( array( 'DTT_EVT_start' => $current->format( $full_format ), 'DTT_EVT_end' => $current_end_date->format( $full_format), 'timezone' => 'America/Toronto', 'formats' => $formats ) ) - ); - - - $events = $this->factory->event->create_many(5); - - //add datetimes to the events. - $events[0]->_add_relation_to( $datetimes['expired_datetime'], 'Datetime' ); - $events[0]->save(); - $events[1]->_add_relation_to( $datetimes['upcoming_datetime'], 'Datetime' ); - $events[1]->save(); - $events[2]->_add_relation_to( $datetimes['active_datetime'], 'Datetime' ); - $events[2]->save(); - $events[3]->_add_relation_to( $datetimes['sold_out_datetime'], 'Datetime' ); - $events[3]->save(); - $events[4]->_add_relation_to( $datetimes['inactive_datetime'], 'Datetime' ); - $events[4]->save(); - - foreach ( $events as $index => $event ) { - if ( $index !== 4 ) { - $event->set('status', 'publish' ); - $event->save(); - } - } - - //run tests for various scenarios. - foreach ( $datetimes as $type => $datetime ) { - switch ( $type ) { - case 'expired_datetime' : - $dtts = EEM_Datetime::instance()->get_dtt_months_and_years( array(), 'expired' ); - $dtt = reset( $dtts ); - $this->assertEquals( 1, count( $dtts ) ); - $this->assertEquals( $past_start_date->format('Y'), $dtt->dtt_year ); - $this->assertEquals( $past_start_date->format('F'), $dtt->dtt_month ); - break; - case 'upcoming_datetime' : - $dtts = EEM_Datetime::instance()->get_dtt_months_and_years( array(), 'upcoming' ); - $dtt = reset( $dtts ); - $this->assertEquals( 1, count( $dtts ) ); - $this->assertEquals( $upcoming_start_date->format('Y'), $dtt->dtt_year ); - $this->assertEquals( $upcoming_start_date->format('F'), $dtt->dtt_month ); - break; - case 'active_datetime' : - $dtts = EEM_Datetime::instance()->get_dtt_months_and_years( array(), 'active' ); - $dtt = reset( $dtts ); - $this->assertEquals( 1, count( $dtts ) ); - $this->assertEquals( $current->format('Y'), $dtt->dtt_year ); - $this->assertEquals( $current->format('F'), $dtt->dtt_month ); - break; - case 'sold_out_datetime' : - $dtts = EEM_Datetime::instance()->get_dtt_months_and_years( array(), 'upcoming' ); - $dtt = reset( $dtts ); - $this->assertEquals( 1, count( $dtts ) ); - $this->assertEquals( $upcoming_start_date->format('Y'), $dtt->dtt_year ); - $this->assertEquals( $upcoming_start_date->format('F'), $dtt->dtt_month ); - break; - case 'inactive_datetime' : - $dtts = EEM_Datetime::instance()->get_dtt_months_and_years( array(), 'inactive' ); - $dtt = reset( $dtts ); - $this->assertEquals( 1, count( $dtts ) ); - $this->assertEquals( $current->format('Y'), $dtt->dtt_year ); - $this->assertEquals( $current->format('F'), $dtt->dtt_month ); - break; - } - } - } - - - /** - * @since 4.8.27.rc.005 - */ - public function test_get_datetime_counts_by_status_and_get_datetime_count_for_status() { - - $existing_datetimes = EEM_Datetime::instance()->get_all(); - $this->assertInternalType('array', $existing_datetimes); - $this->assertCount(0, $existing_datetimes); - //setup some datetimes for testing with - $upcoming_datetimes = $this->factory->datetime->create_many(5); - //set upcoming datetimes to actually be upcoming! - foreach( $upcoming_datetimes as $datetime ) { - $datetime->set('DTT_EVT_start', time() + MONTH_IN_SECONDS ); - $datetime->set('DTT_EVT_end', time() + (MONTH_IN_SECONDS + DAY_IN_SECONDS) ); - $datetime->save(); - } - - //setup some expired datetimes - $expired_datetimes = $this->factory->datetime->create_many(2); - //set expired - foreach( $expired_datetimes as $datetime ) { - $datetime->set( 'DTT_EVT_start', time() - (MONTH_IN_SECONDS + DAY_IN_SECONDS) ); - $datetime->set( 'DTT_EVT_end', time() - MONTH_IN_SECONDS ); - $datetime->save(); - } - - //active datetimes - $active_datetime = $this->factory->datetime->create( - array( 'DTT_EVT_start' => time() - DAY_IN_SECONDS, 'DTT_EVT_end' => time() + DAY_IN_SECONDS ) - ); - - //now get the results from the method being tested - $datetimes_count = EEM_Datetime::instance()->get_datetime_counts_by_status(); - - $this->assertTrue( is_array( $datetimes_count ) ); - $this->assertEquals( 1, $datetimes_count[ EE_Datetime::active ] ); - $this->assertEquals( 5, $datetimes_count[ EE_Datetime::upcoming ] ); - $this->assertEquals( 2, $datetimes_count[ EE_Datetime::expired ] ); - - //test just getting a specific status via get_datetime_count_for_status - $this->assertEquals( 5, EEM_Datetime::instance()->get_datetime_count_for_status( EE_Datetime::upcoming ) ); - $this->assertEquals( 1, EEM_Datetime::instance()->get_datetime_count_for_status() ); - $this->assertEquals( 2, EEM_Datetime::instance()->get_datetime_count_for_status( EE_Datetime::expired ) ); - } - - /** - * @since 4.9.74.p - * @group private-1 - */ - public function testGetAllExcludeProtected() - { - // create two events, one is password-protected - $e_password = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'status' => EEM_Event::post_status_publish, - 'password' => 'foobar' - ) - ); - $e_no_password = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'status' => EEM_Event::post_status_publish, - 'password' => '' - ) - ); - - // create related data - $d_password = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $e_password->ID() - ) - ); - $d_no_password = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $e_no_password->ID() - ) - ); - - // fetch related data. Those for password-protected events should be excluded - $datetime_ids = EEM_Datetime::instance()->get_col(array('exclude_protected'=>true)); - $this->assertArrayContains((string) $d_no_password->ID(),$datetime_ids); - $this->assertArrayDoesNotContain((string) $d_password, $datetime_ids); - } -} diff --git a/tests/testcases/core/db_models/EEM_Event_Test.php b/tests/testcases/core/db_models/EEM_Event_Test.php deleted file mode 100644 index aacdfe14fcd..00000000000 --- a/tests/testcases/core/db_models/EEM_Event_Test.php +++ /dev/null @@ -1,192 +0,0 @@ - $this->factory->datetime->create( array( 'DTT_EVT_start' => $past_start_date->format( $full_format ), 'DTT_EVT_end' => $past_start_date->format( $full_format), 'timezone' => 'America/Toronto', 'formats' => $formats ) ), - 'upcoming_datetime' => $this->factory->datetime->create( array( 'DTT_EVT_start' => $upcoming_start_date->format( $full_format ), 'DTT_EVT_end' => $upcoming_start_date->format( $full_format), 'timezone' => 'America/Toronto', 'formats' => $formats ) ), - 'active_datetime' => $this->factory->datetime->create( array( 'DTT_EVT_start' => $current->sub( new DateInterval( "PT2H") )->format( $full_format ), 'DTT_EVT_end' => $current_end_date->add( new DateInterval( "PT2H" ) )->format( $full_format), 'timezone' => 'America/Toronto', 'formats' => $formats ) ), - 'sold_out_datetime' => $this->factory->datetime->create( array( 'DTT_EVT_start' => $upcoming_start_date->format( $full_format ), 'DTT_EVT_end' => $upcoming_start_date->format( $full_format), 'DTT_reg_limit' => 10, 'DTT_sold' => 10, 'timezone' => 'America/Toronto', 'formats' => $formats ) ), - 'inactive_datetime' => $this->factory->datetime->create( array( 'DTT_EVT_start' => $current->sub( new DateInterval( "PT2H") )->format( $full_format ), 'DTT_EVT_end' => $current_end_date->add( new DateInterval( "PT2H" ) )->format( $full_format), 'timezone' => 'America/Toronto', 'formats' => $formats ) ) - ); - - //setup some events - /** @var EE_Event[] $events */ - $events = $this->factory->event->create_many( '4' ); - - //add datetimes to the events. - $events[0]->_add_relation_to( $datetimes['expired_datetime'], 'Datetime' ); - $events[0]->save(); - $events[1]->_add_relation_to( $datetimes['upcoming_datetime'], 'Datetime' ); - $events[1]->save(); - $events[2]->_add_relation_to( $datetimes['active_datetime'], 'Datetime' ); - $events[2]->save(); - $events[3]->_add_relation_to( $datetimes['sold_out_datetime'], 'Datetime' ); - $events[3]->save(); - - foreach( $events as $event ) { - $event->set('status', 'publish'); - $event->save(); - } - - //one more event that is just going to be inactive - /** @var EE_Event $final_event */ - $final_event = $this->factory->event->create(); - $final_event->_add_relation_to( $datetimes['inactive_datetime'], 'Datetime' ); - $final_event->save(); - - } - - - - /** - * This tests getting active events. - * @since 4.6.x - */ - public function test_get_active_events() { - $this->_setup_events(); - //now do our tests - $this->assertEquals( 1, EEM_Event::instance()->get_active_events( array(), true ) ); - } - - - public function test_get_upcoming_events() { - $this->_setup_events(); - //now do our tests - $this->assertEquals( 2, EEM_Event::instance()->get_upcoming_events( array(), true ) ); - } - - - public function test_get_expired_events() { - $this->_setup_events(); - //now do our tests - $this->assertEquals( 1, EEM_Event::instance()->get_expired_events( array(), true ) ); - } - - public function test_get_inactive_events() { - $this->_setup_events(); - //now do our tests - $this->assertEquals( 1, EEM_Event::instance()->get_inactive_events( array(), true ) ); - } - - public function test_get_active_and_upcoming_events() { - $this->_setup_events(); - //now do our tests - $this->assertEquals( 3, EEM_Event::instance()->get_active_and_upcoming_events( array(), true ) ); - } - - - /** - * @see https://events.codebasehq.com/projects/event-espresso/tickets/8799 - * @group 8799 - * @since 4.8.8.rc.019 - */ - public function test_default_reg_status() { - //first verify the default reg status on config is pending payment - $this->assertEquals( EEM_Registration::status_id_pending_payment, EE_Registry::instance()->CFG->registration->default_STS_ID ); - - //verify creating default event from the model has that default reg status - /** @type EE_Event $event */ - $event = EEM_Event::instance()->create_default_object(); - $this->assertEquals( EEM_Registration::status_id_pending_payment, $event->default_registration_status() ); - - //let's update config in the db to have default reg status of approved - EE_Registry::instance()->CFG->registration->default_STS_ID = EEM_Registration::status_id_approved; - EE_Registry::instance()->CFG->update_espresso_config(); - - //let's reset for new test - EEM_Event::reset(); - EE_Registry::reset(); - - //k NOW the default reg status in config should be approved - $this->assertEquals( EEM_Registration::status_id_approved, EE_Registry::instance()->CFG->registration->default_STS_ID ); - - //new default event should have approved as the default reg status - $event = EEM_Event::instance()->create_default_object(); - $this->assertEquals( EEM_Registration::status_id_approved, $event->default_registration_status() ); - } - - /** - * @since 4.10.0.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - */ - public function testGetQuestionGroupsForEvent() - { - $r = $this->new_model_obj_with_dependencies( - 'Registration', - [ - 'REG_count' => 1 - ] - ); - $r->event_obj()->add_question_group(EEM_Question_Group::system_personal, true); - $r->event_obj()->add_question_group(EEM_Question_Group::system_address, true); - // Just add another question group, but it will only be for additional attendees. - $additional_qg = $this->new_model_obj_with_dependencies('Question_Group'); - $r->event_obj()->add_question_group($additional_qg, false); - $qgs = EEM_Event::instance()->get_question_groups_for_event($r->event_ID(), $r); - $this->assertEquals(2, count($qgs)); - $this->assertArrayContains( - EEM_Question_Group::instance()->get_one_by_ID(EEM_Question_Group::system_personal), - $qgs - ); - $this->assertArrayContains( - EEM_Question_Group::instance()->get_one_by_ID(EEM_Question_Group::system_address), - $qgs - ); - } - -} -// Location: testcases/core/db_models/EEM_Event_Test.php diff --git a/tests/testcases/core/db_models/EEM_Extra_Join_Test.php b/tests/testcases/core/db_models/EEM_Extra_Join_Test.php deleted file mode 100644 index 992e7e6206d..00000000000 --- a/tests/testcases/core/db_models/EEM_Extra_Join_Test.php +++ /dev/null @@ -1,117 +0,0 @@ -new_model_obj_with_dependencies('Event'); - $pm = $this->new_model_obj_with_dependencies('Payment_Method', array('PMD_type' => 'Invoice')); - //add a few extra events and payment methods, just to make sure we are - //only relating the things we intended - $this->new_model_obj_with_dependencies('Event'); - $this->new_model_obj_with_dependencies('Payment_Method', array('PMD_type' => 'Invoice')); - $this->new_model_obj_with_dependencies( - 'Extra_Join', - array( - 'EXJ_first_model_ID' => $e->ID(), - 'EXJ_first_model_name' => 'Event', - 'EXJ_second_model_ID' => $pm->ID(), - 'EXJ_second_model_name' => 'Payment_Method', - ) - ); - $this->assertEquals(array($pm->ID() => $pm), $e->get_many_related('Payment_Method')); - $this->assertEquals(array($e->ID() => $e), $pm->get_many_related('Event')); - } - - - /** - * @group 9113 - */ - public function test_add() - { - $e = $this->new_model_obj_with_dependencies('Event'); - $pm = $this->new_model_obj_with_dependencies('Payment_Method', array('PMD_type' => 'Invoice')); - $e->_add_relation_to($pm, 'Payment_Method'); - $this->assertEquals(array($pm->ID() => $pm), $e->get_many_related('Payment_Method')); - } - - - - /** - * @group 9113 - */ - public function test_delete() - { - $e = $this->new_model_obj_with_dependencies('Event'); - $pm = $this->new_model_obj_with_dependencies('Payment_Method', array('PMD_type' => 'Invoice')); - $e->_add_relation_to($pm, 'Payment_Method'); - $this->assertEquals(array($pm->ID() => $pm), $e->get_many_related('Payment_Method')); - $e->_remove_relation_to($pm, 'Payment_Method'); - $this->assertEquals(array(), $e->get_many_related('Payment_Method')); - } - -} - -// Location: testcases/core/db_models/EEM_Extra_Join_Test.php diff --git a/tests/testcases/core/db_models/EEM_Line_Item_Test.php b/tests/testcases/core/db_models/EEM_Line_Item_Test.php deleted file mode 100644 index 33a24002780..00000000000 --- a/tests/testcases/core/db_models/EEM_Line_Item_Test.php +++ /dev/null @@ -1,76 +0,0 @@ -new_model_obj_with_dependencies('Transaction'); - $ticket = $this->new_model_obj_with_dependencies( 'Ticket' ); - $tax = $this->new_model_obj_with_dependencies( 'Price' ); - $line_item_for_ticket = $this->new_model_obj_with_dependencies( 'Line_Item', - array( - 'TXN_ID' => $txn->ID(), - 'LIN_type' => EEM_Line_Item::type_line_item, - 'OBJ_type' => 'Ticket', - 'OBJ_ID' => $ticket->ID() - ) ); - $line_item_for_tax = $this->new_model_obj_with_dependencies( 'Line_Item', - array( - 'TXN_ID' => $txn->ID(), - 'LIN_type' => EEM_Line_Item::type_tax, - 'OBJ_type' => 'Price', - 'OBJ_ID' => $tax->ID() - )); - $line_item_for_nothing = $this->new_model_obj_with_dependencies( 'Line_Item', - array( - 'TXN_ID' => $txn->ID(), - 'LIN_type' => EEM_Line_Item::type_line_item, - 'OBJ_type' => NULL, - 'OBJ_ID' => 0 - ) - ); - $line_item_for_venue = $this->new_model_obj_with_dependencies( 'Line_Item', - array( - 'TXN_ID' => $txn->ID(), - 'LIN_type' => EEM_Line_Item::type_line_item, - 'OBJ_type' => 'Venue', - 'OBJ_ID' => 0 - ) - ); - $non_ticket_line_items = EEM_Line_Item::instance()->get_all_non_ticket_line_items_for_transaction( $txn ); - $this->assertEquals( 2, count( $non_ticket_line_items ) ); - $this->assertTrue( in_array( $line_item_for_nothing, $non_ticket_line_items ) ); - $this->assertTrue( in_array( $line_item_for_venue, $non_ticket_line_items ) ); - } - - /** - * @group 7965 - */ - function test_delete_registrations_with_no_transaction(){ - $deletable_count = 5; - $safe_count = 8; - for( $i = 0; $i < $deletable_count; $i++ ) { - $this->new_model_obj_with_dependencies( 'Line_Item', array( 'TXN_ID' => 0, 'LIN_timestamp' => time() - WEEK_IN_SECONDS * 2 ) ); - } - for( $i=0;$i< $safe_count; $i++ ){ - $this->new_model_obj_with_dependencies( 'Line_Item' ); - } - $deleted = EEM_Line_Item::instance()->delete_line_items_with_no_transaction(); - $this->assertEquals( $deletable_count, $deleted ); - } -} - -// End of file EEM_Line_Item_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_models/EEM_Message_Template_Caps_Test.php b/tests/testcases/core/db_models/EEM_Message_Template_Caps_Test.php deleted file mode 100644 index d766c1c2c04..00000000000 --- a/tests/testcases/core/db_models/EEM_Message_Template_Caps_Test.php +++ /dev/null @@ -1,70 +0,0 @@ -delete( array(), false ); - $this->assertEquals( 0, EEM_Message_Template::instance()->count() ); - EEM_Message_Template_Group::instance()->delete_permanently( EEM_Message_Template_Group::instance()->alter_query_params_so_deleted_and_undeleted_items_included(), false ); - $this->assertEquals( 0, EEM_Message_Template_Group::instance()->count() ); - - global $current_user; - $user = $this->factory->user->create_and_get(); - $this->assertEquals( 0, EEM_Question::instance()->count( array( 'caps' => EEM_Base::caps_read_admin ) ) ); - - //now log in and see I can edit my own - $current_user = $user; - $user->add_cap( 'ee_read_messages'); - $mtg1 = $this->new_model_obj_with_dependencies( 'Message_Template_Group', array( 'MTP_is_global' => false, 'MTP_user_id' => $user->ID ) ); - $mt1 = $this->new_model_obj_with_dependencies( 'Message_Template', array( 'GRP_ID' => $mtg1->ID() ) ); - - $mtg2_others = $this->new_model_obj_with_dependencies( 'Message_Template_Group', array( 'MTP_is_global' => false, 'MTP_user_id' => 9999 ) ); - $mt2_others = $this->new_model_obj_with_dependencies( 'Message_Template', array( 'GRP_ID' => $mtg2_others->ID() ) ); - - $mtg3_global = $this->new_model_obj_with_dependencies( 'Message_Template_Group', array( 'MTP_is_global' => true, 'MTP_user_id' => 9999 ) ); - $mt3_global = $this->new_model_obj_with_dependencies( 'Message_Template', array( 'GRP_ID' => $mtg3_global->ID() ) ); - - $i_can_edit = EEM_Message_Template::instance()->get_all( array( 'caps' => EEM_Base::caps_read_admin ) ); - $this->assertEquals( $mt1, reset( $i_can_edit ) ); - $this->assertEquals( 1, count( $i_can_edit ) ); - - //now give them the ability to read others messages - $user->add_cap( 'ee_read_others_messages' ); - $i_can_edit = EEM_Message_Template::instance()->get_all( array( 'caps' => EEM_Base::caps_read_admin ) ); - $this->assertEquals( $mt1, reset( $i_can_edit ) ); - $this->assertEquals( $mt2_others, next( $i_can_edit ) ); - $this->assertEquals( 2, count( $i_can_edit ) ); - - //now let them read global message - $user->add_cap( 'ee_read_global_messages' ); - $i_can_edit = EEM_Message_Template::instance()->get_all( array( 'caps' => EEM_Base::caps_read_admin, 'order_by' => array( 'MTP_ID' => 'ASC' ) ) ); - $this->assertEquals( $mt1, reset( $i_can_edit ) ); - $this->assertEquals( $mt2_others, next( $i_can_edit ) ); - $this->assertEquals( $mt3_global, next( $i_can_edit ) ); - $this->assertEquals( 3, count( $i_can_edit ) ); - } -} - -// End of file EEM_Message_Template_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_models/EEM_Message_Test.php b/tests/testcases/core/db_models/EEM_Message_Test.php deleted file mode 100644 index a4af60a450d..00000000000 --- a/tests/testcases/core/db_models/EEM_Message_Test.php +++ /dev/null @@ -1,41 +0,0 @@ -fail( __METHOD__ . ' cannot be tested because the EE_DEBUG_MESSAGES constant has been set somewhere. Please ensure this constant isn\'t set for unit tests' ); - } - - //set constant and ensure it defaults to true. - define( 'EE_DEBUG_MESSAGES', true ); - $this->assertTrue( EEM_Message::debug() ); - - //ensure it continues to return true - $this->assertTrue( EEM_Message::debug() ); - - //set false and ensure it continues to return false - EEM_Message::debug( false ); - $this->assertFalse( EEM_Message::debug() ); - - //set true and ensure it continues to return true - EEM_Message::debug( true ); - $this->assertTrue( EEM_Message::debug() ); - - //filter so it always returns true. - add_filter( 'FHEE__EEM_Message__debug', '__return_true' ); - EEM_Message::debug( false ); - $this->assertTrue( EEM_Message::debug() ); - - //remove filter and restore to default. - remove_filter( 'FHEE__EEM_Message__debug', '__return_true' ); - EEM_Message::debug( false ); - } -} diff --git a/tests/testcases/core/db_models/EEM_Payment_Method_Test.php b/tests/testcases/core/db_models/EEM_Payment_Method_Test.php deleted file mode 100644 index 1245c15d075..00000000000 --- a/tests/testcases/core/db_models/EEM_Payment_Method_Test.php +++ /dev/null @@ -1,38 +0,0 @@ -new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Invoice' ) ); - $this->assertNotEmpty( $pm->ID() ); - $this->assertEquals( $pm, EEM_Payment_Method::instance()->ensure_is_obj( $pm ) ); - $this->assertEquals( $pm, EEM_Payment_Method::instance()->ensure_is_obj( $pm->ID() ) ); - $this->assertEquals( $pm, EEM_Payment_Method::instance()->ensure_is_obj( $pm->slug() ) ); - } - - /** - * @group 7201 - */ - function test_get_one_by_slug(){ - $pm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Invoice' ) ); - $this->assertNotEmpty( $pm->ID() ); - $this->assertEquals( $pm, EEM_Payment_Method::instance()->get_one_by_ID( $pm->ID() ) ); - $this->assertEquals( $pm, EEM_Payment_Method::instance()->get_one_by_slug( $pm->slug() ) ); - } -} - -// End of file EEM_Payment_Method_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_models/EEM_Payment_Test.php b/tests/testcases/core/db_models/EEM_Payment_Test.php deleted file mode 100644 index e67503cf884..00000000000 --- a/tests/testcases/core/db_models/EEM_Payment_Test.php +++ /dev/null @@ -1,147 +0,0 @@ -sub(new DateInterval('P2D')); - $one_hour_from_now = $one_hour_from_now->add(new DateInterval('PT1H')); - $two_hours_ago = $two_hours_ago->sub(new DateInterval('PT2H')); - $two_days_from_now = $two_days_from_now->add(new DateInterval('P2D')); - // grab format settings - $formats = array(\EE_Datetime_Field::mysql_date_format, \EE_Datetime_Field::mysql_time_format); - // let's setup the args for our payments in an array, - // then we can just loop through to grab them and set things up. - $payment_args = array( - array( - 'PAY_timestamp' => $two_days_ago->format(\EE_Datetime_Field::mysql_timestamp_format), - 'timezone' => 'America/Toronto', - 'formats' => $formats, - ), - array( - 'PAY_timestamp' => $one_hour_from_now->format(\EE_Datetime_Field::mysql_timestamp_format), - 'timezone' => 'America/Toronto', - 'formats' => $formats, - ), - array( - 'PAY_timestamp' => $two_hours_ago->format(\EE_Datetime_Field::mysql_timestamp_format), - 'timezone' => 'America/Toronto', - 'formats' => $formats, - ), - array( - 'PAY_timestamp' => $two_days_from_now->format(\EE_Datetime_Field::mysql_timestamp_format), - 'timezone' => 'America/Toronto', - 'formats' => $formats, - ), - array( - 'PAY_timestamp' => $two_days_ago->format(\EE_Datetime_Field::mysql_timestamp_format), - 'timezone' => 'America/Toronto', - 'formats' => $formats, - ), - ); - foreach ($payment_args as $payment_arg) { - $this->factory->payment->create($payment_arg); - } - $this->assertEquals(5, EEM_Payment::instance()->count()); - } - - - - /** - * @since 4.6.0 - */ - public function test_get_payments_between_dates() - { - $timezone = new DateTimeZone('America/Toronto'); - // set $test_time in the timezone being tested. - $test_time = new DateTime('now', $timezone); - $test_time->setTime(14, 00); - $this->_setup_payments($test_time, $timezone); - //test defaults - $payments = EEM_Payment::instance()->get_payments_made_between_dates(); - $this->assertCount(2, $payments); - //test including a date from past date for start date. - $payments = EEM_Payment::instance()->get_payments_made_between_dates( - $test_time->sub(new DateInterval('P2D'))->format('d/m/Y'), - '', - 'd/m/Y', - 'America/Toronto' - ); - $this->assertCount(4, $payments); - //test including a date from past date for end date. - $payments = EEM_Payment::instance()->get_payments_made_between_dates( - '', - $test_time->format('d/m/Y'), - 'd/m/Y', - 'America/Toronto' - ); - $this->assertCount(4, $payments); - //test including a date from upcoming date for start date - $payments = EEM_Payment::instance()->get_payments_made_between_dates( - $test_time->add(new DateInterval('P4D'))->format('d/m/Y'), - '', - 'd/m/Y', - 'America/Toronto' - ); - $this->assertCount(3, $payments); - //test including a date from upcoming date for end date - $payments = EEM_Payment::instance()->get_payments_made_between_dates( - '', - $test_time->format('d/m/Y'), - 'd/m/Y', - 'America/Toronto' - ); - $this->assertCount(3, $payments); - //test exception - $this->setExpectedException('EE_Error'); - EEM_Payment::instance()->get_payments_made_between_dates('trigger_exception'); - } - - -} -//end class EEM_Payment_Test -// Location: tests/testcases/core/db_models/EEM_Payment_Test.php diff --git a/tests/testcases/core/db_models/EEM_Price_Caps_Test.php b/tests/testcases/core/db_models/EEM_Price_Caps_Test.php deleted file mode 100644 index fb33b1aeb95..00000000000 --- a/tests/testcases/core/db_models/EEM_Price_Caps_Test.php +++ /dev/null @@ -1,201 +0,0 @@ -user - * @var EE_Price - */ - public $p_mine; - - /** - * Non-default ticket owned by another user - * @var EE_Price - */ - public $p_others; - - /** - * Event though tickets can't be "private", the event they are for can be - * @var EE_Price - */ - public $p_private; - - /** - * Default ticket owned by $this->user - * @var EE_Price - */ - public $p_mine_default; - - /** - * Default ticket owned by another user - * @var EE_Price - */ - public $p_others_default; - - /** - * Non-default ticket owned by the $this->user - * @var EE_Ticket - */ - public $t_mine; - - /** - * Non-default ticket owned by another user - * @var EE_Ticket - */ - public $t_others; - - /** - * Event though tickets can't be "private", the event they are for can be - * @var EE_Ticket - */ - public $t_private; - - /** - * My Event - * @var EE_Event - */ - public $e_mine; - - /** - * Another users event - * @var EE_Event - */ - public $e_others; - - /** - * Another users private event - * @var EE_Event - */ - public $e_private; - public function setUp(){ - parent::setUp(); - //let's make sure we start off with NO tickets in the DB - EEM_Price::instance()->delete_permanently( EEM_Price::instance()->alter_query_params_so_deleted_and_undeleted_items_included(), false ); - $this->assertEquals( 0, EEM_Price::instance()->count( EEM_Price::instance()->alter_query_params_so_deleted_and_undeleted_items_included() ) ); - - $this->user = $this->factory->user->create_and_get(); - $this->e_mine = $this->new_model_obj_with_dependencies( 'Event', array( 'EVT_wp_user' => $this->user->ID, 'status' => 'publish' ) ); - $this->e_others = $this->new_model_obj_with_dependencies( 'Event', array( 'EVT_wp_user' => 99999, 'status' => 'publish' ) ); - $this->e_private = $this->new_model_obj_with_dependencies( 'Event', array( 'EVT_wp_user' => 99999, 'status' => 'private' ) ); - $this->t_mine = $this->new_model_obj_with_dependencies('Ticket', array( 'TKT_is_default' => false, 'TKT_wp_user' => $this->user->ID ) ); - $this->t_others = $this->new_model_obj_with_dependencies('Ticket', array( 'TKT_is_default' => false, 'TKT_wp_user' => 9999 ) ); - $this->t_private = $this->new_model_obj_with_dependencies('Ticket', array( 'TKT_is_default' => false, 'TKT_wp_user' => 9999 ) ); - $dtt_to_mine = $this->new_model_obj_with_dependencies( 'Datetime', array( 'EVT_ID' => $this->e_mine->ID() ) ); - $dtt_to_mine->_add_relation_to( $this->t_mine, 'Ticket' ); - $dtt_to_others = $this->new_model_obj_with_dependencies( 'Datetime', array( 'EVT_ID' => $this->e_others->ID() ) ); - $dtt_to_others->_add_relation_to( $this->t_others, 'Ticket' ); - $dtt_to_private = $this->new_model_obj_with_dependencies( 'Datetime', array( 'EVT_ID' => $this->e_private->ID() ) ); - $dtt_to_private->_add_relation_to( $this->t_private, 'Ticket'); - - $this->p_mine = $this->new_model_obj_with_dependencies('Price', array( 'PRC_is_default' => false, 'PRC_wp_user' => $this->user->ID ) ); - $this->p_others = $this->new_model_obj_with_dependencies('Price', array( 'PRC_is_default' => false, 'PRC_wp_user' => 9999 ) ); - $this->p_private = $this->new_model_obj_with_dependencies('Price', array( 'PRC_is_default' => false, 'PRC_wp_user' => 9999 ) ); - $this->p_mine_default = $this->new_model_obj_with_dependencies('Price', array( 'PRC_is_default' => true, 'PRC_wp_user' => $this->user->ID ) ); - $this->p_others_default = $this->new_model_obj_with_dependencies('Price', array( 'PRC_is_default' => true, 'PRC_wp_user' =>999999 ) ); - $this->p_mine->_add_relation_to( $this->t_mine, 'Ticket' ); - $this->p_others->_add_relation_to( $this->t_others, 'Ticket' ); - $this->p_private->_add_relation_to( $this->t_private, 'Ticket' ); - } - - /** - * Make sure we are getting back the right things when we apply the read-context - * restrictions - */ - public function test_get_all__caps__read__not_logged_in() { - //when we have no caps we should find all the non-global ones - $results = EEM_Price::instance()->get_all( array( 'caps' => EEM_Base::caps_read, 'order_by' => array ('PRC_ID' => 'ASC' ) ) ); - - $first_result = reset( $results ); - $this->assertEEModelObjectsEquals($this->p_mine, $first_result ); - $next_result = next( $results ); - $this->assertEEModelObjectsEquals( $this->p_others, $next_result ); - $this->assertEquals( 2, count( $results ) ); - } - - public function test_get_all__caps__read__logged_in_with_read_default_prices_cap(){ - //now if we are a real user with read default tickets, we should also be able to see our own - global $current_user; - $current_user = $this->user; - $this->user->add_cap( 'ee_read_default_prices' ); - $results = EEM_Price::instance()->get_all( array( 'caps' => EEM_Base::caps_read, 'order_by' => array ('PRC_ID' => 'ASC' ) ) ); - $this->assertEEModelObjectsEquals($this->p_mine, reset( $results ) ); - $this->assertEEModelObjectsEquals( $this->p_others, next( $results ) ); - $this->assertEEModelObjectsEquals( $this->p_mine_default, next( $results ) ); - $this->assertEEModelObjectsEquals( $this->p_others_default, next( $results ) ); - $this->assertEquals( 4, count( $results ) ); - } - - - public function test_get_all__caps__read_admin__not_logged_in(){ - //when we have no caps we should none - $results = EEM_Price::instance()->get_all( array( 'caps' => EEM_Base::caps_read_admin, 'order_by' => array ('PRC_ID' => 'ASC' ) ) ); - $this->assertEquals( 0, count( $results ) ); - } - - /** - * If a user can read events, they should be able to read their own prices - */ - public function test_get_all__caps__read_admin__logged_in_with_read_events(){ - global $current_user; - $current_user = $this->user; - $current_user->add_cap( 'ee_read_events' ); - $results = EEM_Price::instance()->get_all( array( 'caps' => EEM_Base::caps_read_admin, 'order_by' => array ('PRC_ID' => 'ASC' ) ) ); - //I should be able to read prices for my own events - $this->assertEEModelObjectsEquals( $this->p_mine, reset( $results ) ); - $this->assertEquals( 1, count( $results ) ); - } - - /** - * If a user can read others' events, they should be able to read prices for others' events - */ - public function test_get_all__caps__read_admin__logged_in_with_read_others_events(){ - global $current_user; - $current_user = $this->user; - $current_user->add_cap( 'ee_read_events' ); - $current_user->add_cap( 'ee_read_others_events' ); - $results = EEM_Price::instance()->get_all( array( 'caps' => EEM_Base::caps_read_admin, 'order_by' => array ('PRC_ID' => 'ASC' ) ) ); - //I should be able to read tickets for my own events, and for others' that aren't private - $this->assertEEModelObjectsEquals( $this->p_mine, reset( $results ) ); - $this->assertEEModelObjectsEquals($this->p_others, next( $results ) ); - $this->assertEquals( 2, count( $results ) ); - } - - /** - * If a user can read private events, they should be able to read others private events' prices - */ - public function test_get_all__caps__read_admin__logged_in_with_read_private_events(){ - global $current_user; - $current_user = $this->user; - $current_user->add_cap( 'ee_read_events' ); - $current_user->add_cap( 'ee_read_others_events' ); - $current_user->add_cap( 'ee_read_private_events' ); - $results = EEM_Price::instance()->get_all( array( 'caps' => EEM_Base::caps_read_admin, 'order_by' => array ('PRC_ID' => 'ASC' ) ) ); - //I should be able to read prices for my own events, and for others' that aren't private - $this->assertEEModelObjectsEquals( $this->p_mine, reset( $results ) ); - $this->assertEEModelObjectsEquals($this->p_others, next( $results ) ); - $this->assertEEModelObjectsEquals($this->p_private, next( $results ) ); - $this->assertEquals( 3, count( $results ) ); - } -} - -// End of file EEM_Price_Caps_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_models/EEM_Question_Caps_Test.php b/tests/testcases/core/db_models/EEM_Question_Caps_Test.php deleted file mode 100644 index 0f554aaaadb..00000000000 --- a/tests/testcases/core/db_models/EEM_Question_Caps_Test.php +++ /dev/null @@ -1,64 +0,0 @@ -assertEquals( EEM_Question::instance()->count(), EEM_Question::instance()->count( array( 'caps' => EEM_Base::caps_read ) ) ); - } - /** - * test that questions aren't editable until you're logged in, - * then you can only edit your own non-system questions, - * and then you can edit others if you have that cap, - * and then you can edit others if you have that cap - */ - function test_get_all__caps__edit() { - //remove all questions currently existing - EEM_Question::instance()->delete_permanently( EEM_Question::instance()->alter_query_params_so_deleted_and_undeleted_items_included(), false ); - $this->assertEquals( 0, EEM_Question::instance()->count( EEM_Question::instance()->alter_query_params_so_deleted_and_undeleted_items_included() ) ); - global $current_user; - $user = $this->factory->user->create_and_get(); - $this->assertEquals( 0, EEM_Question::instance()->count( array( 'caps' => EEM_Base::caps_edit ) ) ); - - //now log in and see I can edit my own - $current_user = $user; - $user->add_cap( 'ee_edit_questions'); - $q1 = $this->new_model_obj_with_dependencies( 'Question', array( 'QST_system' => '', 'QST_wp_user' => $user->ID ) ); - $q2_system = $this->new_model_obj_with_dependencies( 'Question', array( 'QST_system' => 'something', 'QST_wp_user' => $user->ID ) ); - $q3_others = $this->new_model_obj_with_dependencies( 'Question', array( 'QST_system' => '', 'QST_wp_user' => 9999 ) ); - $q4_others_system = $this->new_model_obj_with_dependencies( 'Question', array( 'QST_system' => 'somethingelse', 'QST_wp_user' => 9999 ) ); - $i_can_edit = EEM_Question::instance()->get_all( array( 'caps' => EEM_Base::caps_edit ) ); - $this->assertEquals( $q1, reset( $i_can_edit ) ); - $this->assertEquals( $q3_others, next( $i_can_edit ) ); - $this->assertEquals( 2, count( $i_can_edit ) ); - - //now give them the ability to edit system questions - $user->add_cap( 'ee_edit_system_questions' ); - $i_can_edit = EEM_Question::instance()->get_all( array( 'caps' => EEM_Base::caps_edit ) ); - $this->assertEquals( $q1, reset( $i_can_edit ) ); - $this->assertEquals( $q2_system, next( $i_can_edit ) ); - $this->assertEquals( $q3_others, next( $i_can_edit ) ); - $this->assertEquals( $q4_others_system, next( $i_can_edit ) ); - $this->assertEquals( 4, count( $i_can_edit ) ); - } -} - -// End of file EEM_Question_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_models/EEM_Question_Group_Question_Caps_Test.php b/tests/testcases/core/db_models/EEM_Question_Group_Question_Caps_Test.php deleted file mode 100644 index e076b9c83f2..00000000000 --- a/tests/testcases/core/db_models/EEM_Question_Group_Question_Caps_Test.php +++ /dev/null @@ -1,70 +0,0 @@ -delete_permanently( EEM_Question_Group::instance()->alter_query_params_so_deleted_and_undeleted_items_included(), false ); - $this->assertEquals( 0, EEM_Question_Group::instance()->count( EEM_Question_Group::instance()->alter_query_params_so_deleted_and_undeleted_items_included() ) ); - EEM_Question_Group_Question::instance()->delete( array(), false ); - $this->assertEquals( 0, EEM_Question_Group_Question::instance()->count() ); - global $current_user; - $user = $this->factory->user->create_and_get(); - - - - $qg1 = $this->new_model_obj_with_dependencies( 'Question_Group', array( 'QSG_system' => 0, 'QSG_wp_user' => $user->ID ) ); - $qg2_system = $this->new_model_obj_with_dependencies( 'Question_Group', array( 'QSG_system' => 3, 'QSG_wp_user' => $user->ID ) ); - $qg3_others = $this->new_model_obj_with_dependencies( 'Question_Group', array( 'QSG_system' => 0, 'QSG_wp_user' => 9999 ) ); - $qg4_others_system = $this->new_model_obj_with_dependencies( 'Question_Group', array( 'QSG_system' => 4, 'QSG_wp_user' => 9999 ) ); - $q = $this->new_model_obj_with_dependencies( 'Question' ); - $qgq1 = $this->new_model_obj_with_dependencies( 'Question_Group_Question', array( 'QST_ID' => $q->ID(), 'QSG_ID' => $qg1->ID() ) ); - $qgq2 = $this->new_model_obj_with_dependencies( 'Question_Group_Question', array( 'QST_ID' => $q->ID(), 'QSG_ID' => $qg2_system->ID() ) ); - $qgq3 = $this->new_model_obj_with_dependencies( 'Question_Group_Question', array( 'QST_ID' => $q->ID(), 'QSG_ID' => $qg3_others->ID() ) ); - $qgq4 = $this->new_model_obj_with_dependencies( 'Question_Group_Question', array( 'QST_ID' => $q->ID(), 'QSG_ID' => $qg4_others_system->ID() ) ); - - //I am not yet logged in, so I shouldnt be able to edit any - $this->assertEquals( 0, EEM_Question_Group_Question::instance()->count( array( 'caps' => EEM_Base::caps_edit ) ) ); - - //now log in and see I can edit my own - $current_user = $user; - $user->add_cap( 'ee_edit_question_groups'); - $i_can_edit = EEM_Question_Group_Question::instance()->get_all( array( 'caps' => EEM_Base::caps_edit ) ); - $this->assertEquals( $qgq1, reset( $i_can_edit ) ); - $this->assertEquals( $qgq3, next( $i_can_edit ) ); - $this->assertEquals( 2, count( $i_can_edit ) ); - - //now give them the ability to edit system questions - $user->add_cap( 'ee_edit_system_question_groups' ); - $i_can_edit = EEM_Question_Group_Question::instance()->get_all( array( 'caps' => EEM_Base::caps_edit ) ); - $this->assertEquals( $qgq1, reset( $i_can_edit ) ); - $this->assertEquals( $qgq2, next( $i_can_edit ) ); - $this->assertEquals( $qgq3, next( $i_can_edit ) ); - $this->assertEquals( $qgq4, next( $i_can_edit ) ); - $this->assertEquals( 4, count( $i_can_edit ) ); - } -} - -// End of file EEM_Question_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_models/EEM_Registration_Test.php b/tests/testcases/core/db_models/EEM_Registration_Test.php deleted file mode 100644 index 185f8f6c82b..00000000000 --- a/tests/testcases/core/db_models/EEM_Registration_Test.php +++ /dev/null @@ -1,157 +0,0 @@ -factory->transaction->create(); - //them and set things up. - $registration_args = array( - array( - 'REG_date' => $past_start_date->format( $full_format ), - 'timezone' => 'America/Toronto', - 'formats' => $formats, - 'TXN_ID' => $transaction->ID(), - ), - array( - 'REG_date' => $future_end_date->format( $full_format ), - 'timezone' => 'America/Toronto', - 'formats' => $formats, - 'TXN_ID' => $transaction->ID(), - ), - array( - 'REG_date' => $current->sub( new DateInterval( "PT2H" ) )->format( $full_format ), - 'timezone' => 'America/Toronto', - 'formats' => $formats, - 'TXN_ID' => $transaction->ID(), - ), - array( - 'REG_date' => $current->add( new DateInterval( "P1M" ) )->format( $full_format ), - 'timezone' => 'America/Toronto', - 'formats' => $formats, - 'TXN_ID' => $transaction->ID(), - ), - array( - 'REG_date' => $past_start_date->format( $full_format ), - 'timezone' => 'America/Toronto', - 'formats' => $formats, - 'TXN_ID' => $transaction->ID(), - ), - ); - //need to create an event to add all these registrations to because of the capability checks - $events = $this->factory->event->create_many( 4, array( 'EVT_wp_user' => 0 ) ); - - foreach ( $events as $event ) { - foreach( $registration_args as $registration_arg ) { - /** @var EE_Registration $reg */ - $reg = $this->factory->registration->create( $registration_arg ); - //set registrations to pending so we can test - $reg->set_status( EEM_Registration::status_id_pending_payment ); - $reg->_add_relation_to( $event, 'Event' ); - $reg->save(); - } - } - - $this->assertEquals( 20, EEM_Registration::instance()->count() ); - } - - - - /** - * @since 4.6.0 - */ - public function test_get_registrations_per_day_report() { - $this->_setup_registrations(); - - $regs_per_day = EEM_Registration::instance()->get_registrations_per_day_report(); - - //first assert count of results - $this->assertEquals( 3, count( $regs_per_day ) ); - - //next there should be a total = 1 for each result - foreach ( $regs_per_day as $registration ) { - $this->assertEquals( 4, $registration->total ); - } - } - - - - - public function test_get_registrations_per_event_report() { - $this->_setup_registrations(); - $regs_per_event = EEM_Registration::instance()->get_registrations_per_event_report(); - - //first assert total count of results - $this->assertEquals( 4, count( $regs_per_event ) ); - - //next there should be a total = 1 for each result - foreach ( $regs_per_event as $registration ) { - $this->assertEquals( 3, $registration->total ); - } - } - - - - /** - * @group 7965 - */ - function test_delete_registrations_with_no_transaction(){ - $deletable_count = 5; - $safe_count = 8; - $this->factory->registration->create_many( $deletable_count, array( 'TXN_ID' => 0 ) ); - for( $i=0;$i< $safe_count; $i++ ){ - $this->new_model_obj_with_dependencies( 'Registration' ); - } - $deleted = EEM_Registration::instance()->delete_registrations_with_no_transaction(); - $this->assertEquals( $deletable_count, $deleted ); - } - - - -} -// End of file EEM_Registration_Test.php -// Location: testcases/core/db_models/EEM_Registration_Test.php diff --git a/tests/testcases/core/db_models/EEM_Soft_Delete_Base_Test.php b/tests/testcases/core/db_models/EEM_Soft_Delete_Base_Test.php deleted file mode 100644 index d108363d891..00000000000 --- a/tests/testcases/core/db_models/EEM_Soft_Delete_Base_Test.php +++ /dev/null @@ -1,127 +0,0 @@ - 'tim', 'ATT_lname' => 'bob', 'ATT_email' => 'few@ew.efds' ) ); - $a1->save(); - - - $a2 = EE_Attendee::new_instance( array( 'ATT_fname' => 'update-me', 'ATT_lname' => 'man', 'ATT_email' => 'few@ew.efds' ) ); - $a2->save(); - - //and isnert another attendee NOT using the models system - $new_attendee_id = wp_insert_post( array( 'post_name' => 'update-me-abnormal-man', 'post_content' => 'the man', 'post_status' => 'publish', 'post_type' => 'espresso_attendees' ), TRUE ); - $this->assertNotEmpty( $new_attendee_id ); - $this->assertFalse( is_array( $new_attendee_id ) ); - global $wpdb; - $wpdb->insert( $wpdb->prefix."esp_attendee_meta", array( - 'ATT_ID' => $new_attendee_id, - 'ATT_fname' => 'update-me-abnormal', - 'ATT_lname' => 'man', - 'ATT_email' => 'few@fewd.v4', - ), array( - '%d', //ATT_ID' - '%s', //ATT_fname - '%s', //ATT_lname - '%s', //ATT_email - ) - ); - $this->assertNotEmpty( $wpdb->insert_id ); - - - //soft delete 'update-me' and 'update-me-abnormal' - $att_model = EE_Registry::instance()->load_model( 'Attendee' ); - $att_model->delete( array( array( 'ATT_lname' => 'man' ) ) ); - $this->assertNotEquals( EEM_CPT_Base::post_status_trashed, $a1->status() ); - $this->assertEquals( EEM_CPT_Base::post_status_trashed, $a2->status() ); - - $abnormal_attendee = $att_model->get_one_by_ID( $new_attendee_id ); - $this->assertInstanceOf( 'EE_Attendee', $abnormal_attendee ); - $this->assertEquals( EEM_CPT_Base::post_status_trashed, $abnormal_attendee->status()); - } - - - - /** - * This tests a soft delete trash and restore of a cpt model item. - * Test prompted by https://events.codebasehq.com/projects/event-espresso/tickets/6625 - * - * @since 4.4.0 - * - * @return void - */ - public function test_soft_trash_restore_cpt_from_model_context() { - //create attendee model object and dependencies. - $attendee = $this->new_model_obj_with_dependencies( 'Attendee' ); - - //verify have an attendeee object - $this->assertInstanceOf( 'EE_Attendee', $attendee ); - - //use this attendee_id for every model request. - $att_id = $attendee->ID(); - - //reset model - EEM_Attendee::instance()->reset(); - - //verify not trashed. - $status = $attendee->status(); - $this->assertFalse( $status == 'trash' ); - - //k now let's trash it - EEM_Attendee::instance()->delete_by_ID( $att_id ); - - //verify - $trash_attendee = EEM_Attendee::instance()->get_one_by_ID( $att_id ); - $this->assertInstanceOf( 'EE_Attendee', $trash_attendee ); - $status = $trash_attendee->status(); - $this->assertTrue( $status == 'trash' ); - - //reset model again - EEM_Attendee::instance()->reset(); - - //now let's try to restore. - EEM_Attendee::instance()->restore_by_ID( $att_id ); - $restore_attendee = EEM_Attendee::instance()->get_one_by_ID( $att_id ); - $this->assertInstanceOf( 'EE_Attendee', $restore_attendee ); - $status = $restore_attendee->status(); - $this->assertFalse( $status == 'trash' ); - } - - /** - * @group 9179 - */ - public function test_get_minimum_where_conditions_during_query() { - $this->new_model_obj_with_dependencies( 'Registration', array( 'REG_deleted' => true ) ); - $this->new_model_obj_with_dependencies( 'Registration', array( 'REG_deleted' => false ) ); - //count using the default where conditions, which excludes the deleted one - $this->assertEquals( - 1, - EEM_Registration::instance()->count() - ); - //count using the MINIMUM where conditions, which INCLUDES the deleted one - $this->assertEquals( - 2, - EEM_Registration::instance()->count( - array( - 'default_where_conditions' => 'minimum' - )) - ); - } - - -} - -// End of file EEM_Soft_Delete_Base_Test.php diff --git a/tests/testcases/core/db_models/EEM_State_Test.php b/tests/testcases/core/db_models/EEM_State_Test.php deleted file mode 100644 index 8b7313d5016..00000000000 --- a/tests/testcases/core/db_models/EEM_State_Test.php +++ /dev/null @@ -1,25 +0,0 @@ -assertFalse( EEM_State::instance()->exists_by_ID( 99999 ) ); - $s = $this->new_model_obj_with_dependencies( 'State' ); - $this->assertEquals( '', EEM_State::instance()->get_state_name_by_ID( 99999 ) ); - $this->assertEquals( $s->name(), EEM_State::instance()->get_state_name_by_ID( $s->ID() ) ); - } -} - -// End of file EEM_State_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_models/EEM_Term_Caps_Test.php b/tests/testcases/core/db_models/EEM_Term_Caps_Test.php deleted file mode 100644 index b5be0b6d752..00000000000 --- a/tests/testcases/core/db_models/EEM_Term_Caps_Test.php +++ /dev/null @@ -1,185 +0,0 @@ -event_term = $this->new_model_obj_with_dependencies('Term' ); - $this->new_model_obj_with_dependencies( 'Term_Taxonomy', array( - 'term_id' => $this->event_term->ID(), - 'taxonomy' => 'espresso_event_categories' )); - $this->venue_term = $this->new_model_obj_with_dependencies( 'Term' ); - $this->new_model_obj_with_dependencies( 'Term_Taxonomy', array( - 'term_id' => $this->venue_term->ID(), - 'taxonomy' => 'espresso_venue_categories' )); - } - - /** - * anyone should be able to read term-taxonomies - */ - function test_get_all__caps__read__not_logged_in() { - $venue_and_event_cats = EEM_Term::instance()->get_all( array( - 'caps' => EEM_Base::caps_read, - 'order_by' => array( 'term_id' => 'ASC' ), - array( 'Term_Taxonomy.taxonomy' => array( 'IN', array( 'espresso_event_categories', 'espresso_venue_categories'))) - )); - $this->assertEEModelObjectsEquals( $this->event_term, reset( $venue_and_event_cats ) ); - $this->assertEEModelObjectsEquals($this->venue_term, next( $venue_and_event_cats ) ); - $this->assertEquals( 2, count( $venue_and_event_cats ) ); - } - - function test_get_all__caps__read_admin__not_logged_in() { - $venue_and_event_cats = EEM_Term::instance()->get_all( array( - 'caps' => EEM_Base::caps_read_admin, - 'order_by' => array( 'term_id' => 'ASC' ), - array( 'Term_Taxonomy.taxonomy' => array( 'IN', array( 'espresso_event_categories', 'espresso_venue_categories'))) - )); - $this->assertEquals( 0, count( $venue_and_event_cats ) ); - } - - function test_get_all__caps__read_admin__read_event_cats() { - global $current_user; - $current_user = $this->factory->user->create_and_get(); - $current_user->add_cap( 'ee_manage_event_categories'); - $venue_and_event_cats = EEM_Term::instance()->get_all( array( - 'caps' => EEM_Base::caps_read_admin, - 'order_by' => array( 'term_id' => 'ASC' ), - array( 'Term_Taxonomy.taxonomy' => array( 'IN', array( 'espresso_event_categories', 'espresso_venue_categories'))) - )); - $this->assertEEModelObjectsEquals( $this->event_term, reset( $venue_and_event_cats ) ); - $this->assertEquals( 1, count( $venue_and_event_cats ) ); - } - - function test_get_all__caps__read_admin__read_venue_cats() { - global $current_user; - $current_user = $this->factory->user->create_and_get(); - $current_user->add_cap( 'ee_manage_venue_categories'); - $venue_and_event_cats = EEM_Term::instance()->get_all( array( - 'caps' => EEM_Base::caps_read_admin, - 'order_by' => array( 'term_id' => 'ASC' ), - array( 'Term_Taxonomy.taxonomy' => array( 'IN', array( 'espresso_event_categories', 'espresso_venue_categories'))) - )); - $this->assertEEModelObjectsEquals( $this->venue_term, reset( $venue_and_event_cats ) ); - $this->assertEquals( 1, count( $venue_and_event_cats ) ); - } - - function test_get_all__caps__read_admin__read_event_and_venue_cats() { - global $current_user; - $current_user = $this->factory->user->create_and_get(); - $current_user->add_cap( 'ee_manage_event_categories'); - $current_user->add_cap( 'ee_manage_venue_categories'); - $venue_and_event_cats = EEM_Term::instance()->get_all( array( - 'caps' => EEM_Base::caps_read_admin, - 'order_by' => array( 'term_id' => 'ASC' ), - array( 'Term_Taxonomy.taxonomy' => array( 'IN', array( 'espresso_event_categories', 'espresso_venue_categories'))) - )); - $this->assertEEModelObjectsEquals( $this->event_term, reset( $venue_and_event_cats ) ); - $this->assertEEModelObjectsEquals($this->venue_term, next( $venue_and_event_cats ) ); - $this->assertEquals( 2, count( $venue_and_event_cats ) ); - } - - function test_get_all__caps__edit__no_caps() { - $venue_and_event_cats = EEM_Term::instance()->get_all( array( - 'caps' => EEM_Base::caps_edit, - 'order_by' => array( 'term_id' => 'ASC' ), - array( 'Term_Taxonomy.taxonomy' => array( 'IN', array( 'espresso_event_categories', 'espresso_venue_categories'))) - )); - $this->assertEquals( 0, count( $venue_and_event_cats ) ); - } - - function test_get_all__caps__edit__event_caps() { - global $current_user; - $current_user = $this->factory->user->create_and_get(); - $current_user->add_cap( 'ee_edit_event_category'); - $venue_and_event_cats = EEM_Term::instance()->get_all( array( - 'caps' => EEM_Base::caps_edit, - 'order_by' => array( 'term_id' => 'ASC' ), - array( 'Term_Taxonomy.taxonomy' => array( 'IN', array( 'espresso_event_categories', 'espresso_venue_categories'))) - )); - $this->assertEEModelObjectsEquals( $this->event_term, reset( $venue_and_event_cats ) ); - $this->assertEquals( 1, count( $venue_and_event_cats ) ); - } - - function test_get_all__caps__edit__venue__caps() { - global $current_user; - $current_user = $this->factory->user->create_and_get(); - $current_user->add_cap( 'ee_edit_venue_category'); - $venue_and_event_cats = EEM_Term::instance()->get_all( array( - 'caps' => EEM_Base::caps_edit, - 'order_by' => array( 'term_id' => 'ASC' ), - array( 'Term_Taxonomy.taxonomy' => array( 'IN', array( 'espresso_event_categories', 'espresso_venue_categories'))) - )); - $this->assertEEModelObjectsEquals( $this->venue_term, reset( $venue_and_event_cats ) ); - $this->assertEquals( 1, count( $venue_and_event_cats ) ); - } - - function test_get_all__caps__delete__no_caps() { - $venue_and_event_cats = EEM_Term::instance()->get_all( array( - 'caps' => EEM_Base::caps_delete, - 'order_by' => array( 'term_id' => 'ASC' ), - array( 'Term_Taxonomy.taxonomy' => array( 'IN', array( 'espresso_event_categories', 'espresso_venue_categories'))) - )); - $this->assertEquals( 0, count( $venue_and_event_cats ) ); - } - - function test_get_all__caps__delete__event_caps() { - global $current_user; - $current_user = $this->factory->user->create_and_get(); - $current_user->add_cap( 'ee_delete_event_category'); - $venue_and_event_cats = EEM_Term::instance()->get_all( array( - 'caps' => EEM_Base::caps_delete, - 'order_by' => array( 'term_id' => 'ASC' ), - array( 'Term_Taxonomy.taxonomy' => array( 'IN', array( 'espresso_event_categories', 'espresso_venue_categories'))) - )); - $this->assertEEModelObjectsEquals( $this->event_term, reset( $venue_and_event_cats ) ); - $this->assertEquals( 1, count( $venue_and_event_cats ) ); - } - - function test_get_all__caps__delete__venue_and_event_caps() { - global $current_user; - $current_user = $this->factory->user->create_and_get(); - $current_user->add_cap( 'ee_delete_venue_category'); - $current_user->add_cap( 'ee_delete_event_category'); - $venue_and_event_cats = EEM_Term::instance()->get_all( array( - 'caps' => EEM_Base::caps_delete, - 'order_by' => array( 'term_id' => 'ASC' ), - array( 'Term_Taxonomy.taxonomy' => array( 'IN', array( 'espresso_event_categories', 'espresso_venue_categories'))) - )); - $this->assertEEModelObjectsEquals( $this->event_term, reset( $venue_and_event_cats ) ); - $this->assertEEModelObjectsEquals( $this->venue_term, next( $venue_and_event_cats ) ); - $this->assertEquals( 2, count( $venue_and_event_cats ) ); - } - - - - -} - -// End of file EE_Term_Relationship_Caps_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_models/EEM_Term_Relationship_Caps_Test.php b/tests/testcases/core/db_models/EEM_Term_Relationship_Caps_Test.php deleted file mode 100644 index 4278e6076d8..00000000000 --- a/tests/testcases/core/db_models/EEM_Term_Relationship_Caps_Test.php +++ /dev/null @@ -1,238 +0,0 @@ -user = $this->factory->user->create_and_get(); - $this->my_event = $this->new_model_obj_with_dependencies( 'Event', array( 'EVT_wp_user' => $this->user->ID ) ); - $term_id_and_taxonomy_id = wp_insert_term('term_r_for_my_event', 'espresso_event_categories' ); - $result = wp_set_object_terms( $this->my_event->ID(), $term_id_and_taxonomy_id['term_id'], 'espresso_event_categories' ); - $this->term_r_for_my_event = EEM_Term_Relationship::instance()->get_one( - array( - array( - 'object_id' => $this->my_event->ID(), - 'term_taxonomy_id' => reset( $result ) - ) - ) - ); - - $this->others_event = $this->new_model_obj_with_dependencies( 'Event', array( 'EVT_wp_user' => $this->user->ID + 1 ) ); - $term_id_and_taxonomy_id = wp_insert_term('term_r_for_others_event', 'espresso_event_categories' ); - $result = wp_set_object_terms( $this->others_event->ID(), $term_id_and_taxonomy_id['term_id'], 'espresso_event_categories' ); - $this->term_r_for_others_event = EEM_Term_Relationship::instance()->get_one( - array( - array( - 'object_id' => $this->others_event->ID(), - 'term_taxonomy_id' => reset( $result ) - ) - ) - ); - - - } - - public function test_get_all__caps__read(){ - $term_rs = EEM_Term_Relationship::instance()->get_all( - array( - array( - 'object_id' => array( 'IN', array( $this->my_event->ID(), $this->others_event->ID() ) ) - ), - 'order_by' => array( 'object_id' => 'ASC' ), - ) - ); - $this->assertEEModelObjectsEquals( $this->term_r_for_my_event, reset( $term_rs ) ); - $this->assertEEModelObjectsEquals( $this->term_r_for_others_event, next( $term_rs ) ); - $this->assertEquals( 2, count( $term_rs ) ); - } - - /** - * if you're not logged in, you shouldn't be able to see any of this in the admin context - */ - public function test_get_all_read_admin__no_caps() { - $term_rs = EEM_Term_Relationship::instance()->get_all( - array( - array( - 'object_id' => array( 'IN', array( $this->my_event->ID(), $this->others_event->ID() ) ) - ), - 'order_by' => array( 'object_id' => 'ASC' ), - 'caps' => EEM_Base::caps_read_admin - ) - ); - $this->assertEquals( 0, count( $term_rs ) ); - } - - /** - * currently, you don't need "ee_assign_event_categories" to READ term relationships in the admin - */ - public function test_get_all__caps__read_admin__my_own(){ - //log the user in - global $current_user; - $current_user = $this->user; - $current_user->add_cap( 'ee_read_events' ); - - //now check they can only see the term relationship for their own event - $term_rs = EEM_Term_Relationship::instance()->get_all( - array( - array( - 'object_id' => array( 'IN', array( $this->my_event->ID(), $this->others_event->ID() ) ) - ), - 'order_by' => array( 'object_id' => 'ASC' ), - 'caps' => EEM_Base::caps_read_admin - ) - ); - $this->assertEEModelObjectsEquals( $this->term_r_for_my_event, reset( $term_rs ) ); - $this->assertEquals( 1, count( $term_rs ) ); - } - - public function test_get_all__caps__read_admin__others(){ - //log the user in - global $current_user; - $current_user = $this->user; - $current_user->add_cap( 'ee_read_events' ); - $current_user->add_cap( 'ee_read_others_events' ); - - //now check they can only see the term relationship for their own event - $term_rs = EEM_Term_Relationship::instance()->get_all( - array( - array( - 'object_id' => array( 'IN', array( $this->my_event->ID(), $this->others_event->ID() ) ) - ), - 'order_by' => array( 'object_id' => 'ASC' ), - 'caps' => EEM_Base::caps_read_admin - ) - ); - $this->assertEEModelObjectsEquals( $this->term_r_for_my_event, reset( $term_rs ) ); - $this->assertEEModelObjectsEquals( $this->term_r_for_others_event, next( $term_rs ) ); - $this->assertEquals( 2, count( $term_rs ) ); - } - - /** - * you need the "ee_assign_event_categories" too, in order to edit any event categories - */ - public function test_get_all__caps__edit__no_assign_event_category(){ - //log the user in - global $current_user; - $current_user = $this->user; - $current_user->add_cap( 'ee_edit_events' ); - - //now check they can only see the term relationship for their own event - $term_rs = EEM_Term_Relationship::instance()->get_all( - array( - array( - 'object_id' => array( 'IN', array( $this->my_event->ID(), $this->others_event->ID() ) ) - ), - 'order_by' => array( 'object_id' => 'ASC' ), - 'caps' => EEM_Base::caps_edit - ) - ); - $this->assertEquals( 0, count( $term_rs ) ); - } - - public function test_get_all__caps__edit__with_assign_event_category(){ - //log the user in - global $current_user; - $current_user = $this->user; - $current_user->add_cap( 'ee_edit_events' ); - $current_user->add_cap( 'ee_assign_event_category' ); - $term_rs = EEM_Term_Relationship::instance()->get_all( - array( - array( - 'object_id' => array( 'IN', array( $this->my_event->ID(), $this->others_event->ID() ) ) - ), - 'order_by' => array( 'object_id' => 'ASC' ), - 'caps' => EEM_Base::caps_edit - ) - ); - $this->assertEEModelObjectsEquals( $this->term_r_for_my_event, reset( $term_rs ) ); - $this->assertEquals( 1, count( $term_rs ) ); - } - - - - /** - * you need the "ee_assign_event_categories" too, in order to edit any event categories - */ - public function test_get_all__caps__delete__no_assign_event_category(){ - //log the user in - global $current_user; - $current_user = $this->user; - $current_user->add_cap( 'ee_edit_events' ); - - //now check they can only see the term relationship for their own event - $term_rs = EEM_Term_Relationship::instance()->get_all( - array( - array( - 'object_id' => array( 'IN', array( $this->my_event->ID(), $this->others_event->ID() ) ) - ), - 'order_by' => array( 'object_id' => 'ASC' ), - 'caps' => EEM_Base::caps_delete - ) - ); - $this->assertEquals( 0, count( $term_rs ) ); - } - - public function test_get_all__caps__delete__with_assign_event_category(){ - //log the user in - global $current_user; - $current_user = $this->user; - $current_user->add_cap( 'ee_edit_events' ); - $current_user->add_cap( 'ee_assign_event_category' ); - - //now check they can only see the term relationship for their own event - $term_rs = EEM_Term_Relationship::instance()->get_all( - array( - array( - 'object_id' => array( 'IN', array( $this->my_event->ID(), $this->others_event->ID() ) ) - ), - 'order_by' => array( 'object_id' => 'ASC' ), - 'caps' => EEM_Base::caps_delete - ) - ); - $this->assertEEModelObjectsEquals( $this->term_r_for_my_event, reset( $term_rs ) ); - $this->assertEquals( 1, count( $term_rs ) ); - } - - - - -} - -// End of file EEM_Term_Relationship_Caps_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_models/EEM_Term_Relationship_Test.php b/tests/testcases/core/db_models/EEM_Term_Relationship_Test.php deleted file mode 100644 index 554ae708a08..00000000000 --- a/tests/testcases/core/db_models/EEM_Term_Relationship_Test.php +++ /dev/null @@ -1,143 +0,0 @@ - 'monkey1', 'slug' => 'monkey1' ) ); - $term2 = EE_Term::new_instance( array( 'name' => 'monkey2', 'slug'=> 'monkey2' ) ); - $term1->save(); - $term2->save(); - $tt_1 = EE_Term_Taxonomy::new_instance( array( 'taxonomy' => 'whatever', 'term_id' => $term1->ID() ) ); - $tt_1->save(); - $tt_2 = EE_Term_Taxonomy::new_instance( array( 'taxonomy' => 'whatever', 'term_id' => $term2->ID() ) ); - $tt_2->save(); - $e = EE_Event::new_instance( array( 'EVT_name' => 'for_term_1' ) ); - $e->save(); - //ok done setup - //test INSERT - $this->assertEquals(0,$tt_1->count()); - $new_tr_id = EEM_Term_Relationship::instance()->insert( array( 'term_taxonomy_id'=>$tt_1->ID(), 'object_id' => $e->ID() ) ); - $this->assertNotNull( $new_tr_id ); - //refresh out term_taxonomy objects, as the database has changed - $tt_1 = EEM_Term_Taxonomy::reset()->get_one_by_ID( $tt_1->ID() ); - $tt_2 = EEM_Term_Taxonomy::instance()->get_one_by_ID($tt_2->ID() ); - $this->assertEquals( 1, $tt_1->count() ); - $this->assertEquals(0,$tt_2->count() ); - - //test UPDATE... except we can't update term_relationship because there's no Primary Key - //on it. This should be fixed at some point - //@todo: fix this test -// $updated = EEM_Term_Relationship::instance()->update_by_ID(array('term_taxonomy_id'=>$tt_2->ID() ), $new_tr_id ); -// //refresh out term_taxonomy objects, as the database has changed -// $tt_1 = EEM_Term_Taxonomy::reset()->get_one_by_ID( $tt_1->ID() ); -// $tt_2 = EEM_Term_Taxonomy::instance()->get_one_by_ID($tt_2->ID() ); -// $this->assertEquals( 0, $tt_1->count() ); -// $this->assertEquals(1,$tt_2->count() ); - - //test DELETE - //@todo: fix this test too. see above -// $count_deleted = EEM_Term_Relationship::instance()->delete_by_ID($new_tr_id); -// $this->assertNotEmpty( $count_deleted ); -// //refresh out term_taxonomy objects, as the database has changed -// $tt_1 = EEM_Term_Taxonomy::reset()->get_one_by_ID( $tt_1->ID() ); -// $tt_2 = EEM_Term_Taxonomy::instance()->get_one_by_ID($tt_2->ID() ); -// $this->assertEquals( 0, $tt_1->count() ); -// $this->assertEquals(0,$tt_2->count() ); - } - - - /** - * Verifies that when EEM_Term_Relationship::update_term_taxonomy_counts is called with no arguments, - * the counts are correct - */ - public function testUpdateTermTaxonomyCountsPassNull() - { - $terms = $this->setupTerms(); - //verify that when we update the counts, they aren't set to zero - EEM_Term_Relationship::instance()->update_term_taxonomy_counts(); - $this->assertTermCountsCorrect($terms); - } - - - /** - * Verifies that when EEM_Term_Relationship::update_term_taxonomy_counts is called with a term ID, that - * the term counts are afterwards correct still. - */ - public function testUpdateTermTaxonomyCountsPassInt() - { - $terms = $this->setupTerms(); - $term2 = $terms[1]; - //verify that when we update the counts, they aren't set to zero - EEM_Term_Relationship::instance()->update_term_taxonomy_counts($term2->term_id); - $this->assertTermCountsCorrect($terms); - } - - - /** - * Sets up 3 terms, and some related posts, and associates them so that the term counts are :1, 2, 1, respectively. - * Returns a numerically-indexed array of these WP_Term objects - * @return WP_Term[] - */ - protected function setupTerms() - { - //create a few term taxonomies - $term1 = $this->factory()->term->create_and_get(); - $term2 = $this->factory()->term->create_and_get(); - $term3 = $this->factory()->term->create_and_get(); - //add them to some posts - $post1 = $this->factory()->post->create_and_get(); - $post2 = $this->factory()->post->create_and_get(); - wp_set_post_terms($post1->ID, array($term1->term_id, $term2->term_id)); - wp_set_post_terms($post2->ID,array($term2->term_id, $term3->term_id)); - wp_cache_flush(); - $term1 = get_term($term1->term_id); - $term2 = get_term($term2->term_id); - $term3 = get_term($term3->term_id); - - $this->assertEquals(1, $term1->count); - $this->assertEquals(2, $term2->count); - $this->assertEquals(1, $term3->count); - return array( - $term1, - $term2, - $term3 - ); - } - - - /** - * Asserts that the terms received were from setupTerms() and have the correct counts - * @param WP_Term[] $terms - */ - protected function assertTermCountsCorrect(array $terms) - { - $term1 = $terms[0]; - $term2 = $terms[1]; - $term3 = $terms[2]; - wp_cache_flush(); - $term1 = get_term($term1->term_id); - $term2 = get_term($term2->term_id); - $term3 = get_term($term3->term_id); - $this->assertEquals(1, $term1->count); - $this->assertEquals(2, $term2->count); - $this->assertEquals(1, $term3->count); - } -} - -// End of file EEM_Term_Relationship_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_models/EEM_Ticket_Caps_Test.php b/tests/testcases/core/db_models/EEM_Ticket_Caps_Test.php deleted file mode 100644 index cf29bda41fa..00000000000 --- a/tests/testcases/core/db_models/EEM_Ticket_Caps_Test.php +++ /dev/null @@ -1,198 +0,0 @@ -user - * @var EE_Ticket - */ - public $t_mine; - - /** - * Non-default ticket owned by another user - * @var EE_Ticket - */ - public $t_others; - - /** - * Event though tickets can't be "private", the event they are for can be - * @var EE_Ticket - */ - public $t_private; - - /** - * Default ticket owned by $this->user - * @var EE_Ticket - */ - public $t_mine_default; - - /** - * Default ticket owned by another user - * @var EE_Ticket - */ - public $t_others_default; - - /** - * My Event - * @var EE_Event - */ - public $e_mine; - - /** - * Another users event - * @var EE_Event - */ - public $e_others; - - /** - * Another users private event - * @var EE_Event - */ - public $e_private; - public function setUp(){ - parent::setUp(); - //let's make sure we start off with NO tickets in the DB - EEM_Ticket::instance()->delete_permanently( EEM_Ticket::instance()->alter_query_params_so_deleted_and_undeleted_items_included(), false ); - $this->assertEquals( 0, EEM_Ticket::instance()->count( EEM_Ticket::instance()->alter_query_params_so_deleted_and_undeleted_items_included() ) ); - - $this->user = $this->factory->user->create_and_get(); - $this->e_mine = $this->new_model_obj_with_dependencies( 'Event', array( 'EVT_wp_user' => $this->user->ID, 'status' => 'publish' ) ); - $this->e_others = $this->new_model_obj_with_dependencies( 'Event', array( 'EVT_wp_user' => 99999, 'status' => 'publish' ) ); - $this->e_private = $this->new_model_obj_with_dependencies( 'Event', array( 'EVT_wp_user' => 99999, 'status' => 'private' ) ); - $this->t_mine = $this->new_model_obj_with_dependencies('Ticket', array( 'TKT_is_default' => false, 'TKT_wp_user' => $this->user->ID ) ); - $this->t_others = $this->new_model_obj_with_dependencies('Ticket', array( 'TKT_is_default' => false, 'TKT_wp_user' => 9999 ) ); - $this->t_private = $this->new_model_obj_with_dependencies('Ticket', array( 'TKT_is_default' => false, 'TKT_wp_user' => 9999 ) ); - $this->t_mine_default = $this->new_model_obj_with_dependencies('Ticket', array( 'TKT_is_default' => true, 'TKT_wp_user' => $this->user->ID ) ); - $this->t_others_default = $this->new_model_obj_with_dependencies('Ticket', array( 'TKT_is_default' => true, 'TKT_wp_user' => 9999 ) ); - $dtt_to_mine = $this->new_model_obj_with_dependencies( 'Datetime', array( 'EVT_ID' => $this->e_mine->ID() ) ); - $dtt_to_mine->_add_relation_to( $this->t_mine, 'Ticket' ); - $dtt_to_others = $this->new_model_obj_with_dependencies( 'Datetime', array( 'EVT_ID' => $this->e_others->ID() ) ); - $dtt_to_others->_add_relation_to( $this->t_others, 'Ticket' ); - $dtt_to_private = $this->new_model_obj_with_dependencies( 'Datetime', array( 'EVT_ID' => $this->e_private->ID() ) ); - $dtt_to_private->_add_relation_to( $this->t_private, 'Ticket'); - } - - /** - * Make sure we are getting back the right things when we apply the read-context - * restrictions - */ - public function test_get_all__caps__read__not_logged_in() { - //when we have no caps we should find all the non-global ones - $results = EEM_Ticket::instance()->get_all( array( 'caps' => EEM_Base::caps_read, 'order_by' => array( 'TKT_ID' => 'ASC' ) ) ); - - $first_result = reset( $results ); - $this->assertEEModelObjectsEquals($this->t_mine, $first_result ); - $next_result = next( $results ); - $this->assertEEModelObjectsEquals( $this->t_others, $next_result ); - $this->assertEquals( 2, count( $results ) ); - } - - public function test_get_all__caps__read__logged_in_with_read_default_tickets_cap(){ - //now if we are a real user with read default tickets, we should also be able to see our own - global $current_user; - $current_user = $this->user; - $this->user->add_cap( 'ee_read_default_tickets' ); - $results = EEM_Ticket::instance()->get_all( array( 'caps' => EEM_Base::caps_read, 'order_by' => array( 'TKT_ID' => 'ASC' ) ) ); - $first_result = reset( $results ); - $this->assertEEModelObjectsEquals($this->t_mine, $first_result ); - $next_result = next( $results ); - $this->assertEEModelObjectsEquals( $this->t_others, $next_result ); - $next_result = next( $results ); - $this->assertEEModelObjectsEquals( $this->t_mine_default, $next_result ); - $this->assertEquals( 3, count( $results ) ); - } - - public function test_get_all__caps__read__logged_in_with_read_others_default_tickets_cap(){//now if we are a real user with read default tickets, we should also be able to see our own - //and lastly, if we are a real user who can read others default tickets... - global $current_user; - $current_user = $this->user; - $this->user->add_cap( 'ee_read_default_tickets' ); - $this->user->add_cap( 'ee_read_others_default_tickets' ); - $results = EEM_Ticket::instance()->get_all( array( 'caps' => EEM_Base::caps_read, 'order_by' => array( 'TKT_ID' => 'ASC' ) ) ); - $first_result = reset( $results ); - $this->assertEEModelObjectsEquals($this->t_mine, $first_result ); - $next_result = next( $results ); - $this->assertEEModelObjectsEquals( $this->t_others, $next_result ); - $next_result = next( $results ); - $this->assertEEModelObjectsEquals( $this->t_mine_default, $next_result ); - $next_result = next( $results ); - $this->assertEEModelObjectsEquals( $this->t_others_default, $next_result ); - $this->assertEquals( 4, count( $results ) ); - } - - - public function test_get_all__caps__read_admin__not_logged_in(){ - //when we have no caps we should none - $results = EEM_Ticket::instance()->get_all( array( 'caps' => EEM_Base::caps_read_admin, 'order_by' => array( 'TKT_ID' => 'ASC' ) ) ); - $this->assertEquals( 0, count( $results ) ); - } - - /** - * If a user can read events, they should be able to read their own tickets - */ - public function test_get_all__caps__read_admin__logged_in_with_read_events(){ - global $current_user; - $current_user = $this->user; - $current_user->add_cap( 'ee_read_events' ); - $results = EEM_Ticket::instance()->get_all( array( 'caps' => EEM_Base::caps_read_admin, 'order_by' => array( 'TKT_ID' => 'ASC' ) ) ); - //I should be able to read tickets for my own events - $this->assertEEModelObjectsEquals( $this->t_mine, reset( $results ) ); - $this->assertEquals( 1, count( $results ) ); - } - - /** - * If a user can read others' events, they should be able to read tickets for others' events - */ - public function test_get_all__caps__read_admin__logged_in_with_read_others_events(){ - global $current_user; - $current_user = $this->user; - $current_user->add_cap( 'ee_read_events' ); - $current_user->add_cap( 'ee_read_others_events' ); - $results = EEM_Ticket::instance()->get_all( array( 'caps' => EEM_Base::caps_read_admin, 'order_by' => array( 'TKT_ID' => 'ASC' ) ) ); - //I should be able to read tickets for my own events, and for others' that aren't private - $this->assertEEModelObjectsEquals( $this->t_mine, reset( $results ) ); - $this->assertEEModelObjectsEquals($this->t_others, next( $results ) ); - $this->assertEquals( 2, count( $results ) ); - } - - /** - * If a user can read private events, they should be able to read others private events' tickets - */ - public function test_get_all__caps__read_admin__logged_in_with_read_private_events(){ - global $current_user; - $current_user = $this->user; - $current_user->add_cap( 'ee_read_events' ); - $current_user->add_cap( 'ee_read_others_events' ); - $current_user->add_cap( 'ee_read_private_events' ); - $results = EEM_Ticket::instance()->get_all( array( 'caps' => EEM_Base::caps_read_admin, 'order_by' => array( 'TKT_ID' => 'ASC' ) ) ); - //I should be able to read tickets for my own events, and for others' that aren't private - $this->assertEEModelObjectsEquals( $this->t_mine, reset( $results ) ); - $this->assertEEModelObjectsEquals($this->t_others, next( $results ) ); - $this->assertEEModelObjectsEquals($this->t_private, next( $results ) ); - $this->assertEquals( 3, count( $results ) ); - } - - -} - -// End of file EEM_Ticket_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_models/EEM_Ticket_Test.php b/tests/testcases/core/db_models/EEM_Ticket_Test.php deleted file mode 100644 index 9526dc8c134..00000000000 --- a/tests/testcases/core/db_models/EEM_Ticket_Test.php +++ /dev/null @@ -1,95 +0,0 @@ -loadTestScenarios(); - $scenarios = $this->scenarios->get_scenarios_by_type( 'datetime' ); - foreach ( $scenarios as $scenario ) { - //echo "\n\nTesting" . $scenario->name; - if ( $scenario->get_expected( 'sum_tickets_currently_available_at_datetime' ) !== false ) { - //echo "\n scenario->get_scenario_object()->ID(): " . $scenario->get_scenario_object()->ID(); - $actual = EEM_Ticket::instance()->sum_tickets_currently_available_at_datetime( $scenario->get_scenario_object()->ID() ); - $this->assertEquals( $scenario->get_expected( 'sum_tickets_currently_available_at_datetime' ), $actual ); - } - } - } - - /** - * @since 4.9.74.p - * @group private-1 - */ - public function testGetAllExcludeProtected() - { - // create two events, one is password-protected - $e_password = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'status' => EEM_Event::post_status_publish, - 'password' => 'foobar' - ) - ); - $e_no_password = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'status' => EEM_Event::post_status_publish, - 'password' => '' - ) - ); - - // create related data - $d_password = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $e_password->ID() - ) - ); - $d_no_password = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $e_no_password->ID() - ) - ); - - $t_password = $this->new_model_obj_with_dependencies('Ticket'); - $t_password->_add_relation_to($d_password->ID(),'Datetime'); - - $t_no_password = $this->new_model_obj_with_dependencies('Ticket'); - $t_no_password->_add_relation_to($d_no_password->ID(),'Datetime'); - - // and a general ticket too! - - $t_default = $this->new_model_obj_with_dependencies( - 'Ticket', - array( - 'TKT_is_default' => true - ) - ); - - // fetch related data. Those for password-protected events should be excluded - $ticket_ids = EEM_Ticket::instance()->get_col(array('exclude_protected'=>true)); - $this->assertArrayContains((string) $t_no_password->ID(),$ticket_ids); - $this->assertArrayContains((string) $t_default->ID(), $ticket_ids); - $this->assertArrayDoesNotContain((string) $t_password->ID(), $ticket_ids); - } -} -// Location: tests/testcases/core/db_models/EEM_Ticket_Test.php diff --git a/tests/testcases/core/db_models/EEM_Transaction_Test.php b/tests/testcases/core/db_models/EEM_Transaction_Test.php deleted file mode 100644 index 8edbe8b22a4..00000000000 --- a/tests/testcases/core/db_models/EEM_Transaction_Test.php +++ /dev/null @@ -1,68 +0,0 @@ -factory->transaction->create_many( - $pretend_bot_creations, - array('TXN_timestamp' => time() - WEEK_IN_SECONDS * 2, 'STS_ID' => EEM_Transaction::failed_status_code) - ); - $this->factory->transaction->create_many( - $pretend_real_recent_txns, - array( - 'TXN_timestamp' => time() - EE_Session_Mock::instance()->lifespan() + MINUTE_IN_SECONDS, - 'STS_ID' => EEM_Transaction::failed_status_code, - ) - ); - $this->factory->transaction->create_many( - $pretend_real_good_txns, - array('STS_ID' => EEM_Transaction::abandoned_status_code) - ); - $failed_transaction_with_real_payment = $this->factory->transaction->create( - array( - 'TXN_timestamp' => time() - WEEK_IN_SECONDS * 2, - 'STS_ID' => EEM_Transaction::failed_status_code - ) - ); - $transaction_count = EEM_Transaction::instance()->count(); - - $this->assertEquals( - $pretend_bot_creations + $pretend_real_recent_txns + $pretend_real_good_txns + 1, - $transaction_count - ); - $failed_transaction_count = EEM_Transaction::instance()->count( - array( - array('STS_ID' => EEM_Transaction::failed_status_code) - ) - ); - $this->assertEquals( - $pretend_bot_creations + $pretend_real_recent_txns + 1, - $failed_transaction_count - ); - $this->factory->payment->create(array('TXN_ID' => $failed_transaction_with_real_payment->ID())); - $num_deleted = EEM_Transaction::instance()->delete_junk_transactions(); - $this->assertEquals($pretend_bot_creations, $num_deleted); - } - - -} diff --git a/tests/testcases/core/db_models/EEM_WP_User_Caps_Test.php b/tests/testcases/core/db_models/EEM_WP_User_Caps_Test.php deleted file mode 100644 index 4f78e9cb577..00000000000 --- a/tests/testcases/core/db_models/EEM_WP_User_Caps_Test.php +++ /dev/null @@ -1,64 +0,0 @@ -delete( array(), false ); - $this->me = $this->factory->user->create_and_get(); - $this->somebody_else = $this->factory->user->create_and_get(); - } - - function test_get_all__caps__not_logged_in() { - $this->assertEquals( 0, EEM_WP_User::instance()->count( array( 'caps' => EEM_Base::caps_read ) ) ); - } - - function test_get_all__caps__logged_in(){ - global $current_user; - $current_user = $this->me; - $results = EEM_WP_User::instance()->get_all( array( 'caps' => EEM_Base::caps_read ) ); - $this->assertEEModelObjectsEquals( EEM_WP_User::instance()->get_one_by_ID( $this->me->ID ), reset( $results ) ); - $this->assertEquals( 1, count( $results ) ); - } - - function test_get_all__caps__list_users(){ - global $current_user; - $current_user = $this->me; - $current_user->add_cap( 'list_users' ); - $results = EEM_WP_User::instance()->get_all( array( 'caps' => EEM_Base::caps_read ) ); - $this->assertEEModelObjectsEquals( EEM_WP_User::instance()->get_one_by_ID( $this->me->ID ), reset( $results ) ); - $this->assertEEModelObjectsEquals( EEM_WP_User::instance()->get_one_by_ID( $this->somebody_else->ID ), next( $results ) ); - $this->assertEquals( 2, count( $results ) ); - } -} - -// End of file EEM_WP_User_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_models/EEM_WP_User_Test.php b/tests/testcases/core/db_models/EEM_WP_User_Test.php deleted file mode 100644 index f6d7f1645b9..00000000000 --- a/tests/testcases/core/db_models/EEM_WP_User_Test.php +++ /dev/null @@ -1,27 +0,0 @@ -assertEquals( 1, EEM_WP_User::instance()->count() ); - } -} - -// End of file EEM_WP_User_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_models/EemDatetimeTicketTest.php b/tests/testcases/core/db_models/EemDatetimeTicketTest.php deleted file mode 100644 index e44d7bc1b95..00000000000 --- a/tests/testcases/core/db_models/EemDatetimeTicketTest.php +++ /dev/null @@ -1,43 +0,0 @@ -model = EEM_Datetime_Ticket::instance(); - } - - /** - * @since 4.9.74.p - * @group private-1 - */ - public function testRestrictedbyRelatedModelPassword() - { - $this->assertTrue($this->model->restrictedByRelatedModelPassword()); - } -} -// End of file EemDatetimeTicketTest.php -// Location: ${NAMESPACE}/EemDatetimeTicketTest.php diff --git a/tests/testcases/core/db_models/EemEventVenueTest.php b/tests/testcases/core/db_models/EemEventVenueTest.php deleted file mode 100644 index 73513527b1f..00000000000 --- a/tests/testcases/core/db_models/EemEventVenueTest.php +++ /dev/null @@ -1,45 +0,0 @@ -model = EEM_Event_Venue::instance(); - } - - /** - * @since 4.9.74.p - * @group private-1 - */ - public function testRestrictedbyRelatedModelPassword() - { - $this->assertTrue($this->model->restrictedByRelatedModelPassword()); - } - - -} -// End of file EemDatetimeTicketTest.php -// Location: ${NAMESPACE}/EemDatetimeTicketTest.php diff --git a/tests/testcases/core/db_models/fields/EE_All_Caps_Text_Field_Test.php b/tests/testcases/core/db_models/fields/EE_All_Caps_Text_Field_Test.php deleted file mode 100644 index 07db3b74abb..00000000000 --- a/tests/testcases/core/db_models/fields/EE_All_Caps_Text_Field_Test.php +++ /dev/null @@ -1,47 +0,0 @@ -_field = EEM_Payment::instance()->field_settings_for('PAY_source'); - $this->assertInstanceOf('EE_All_Caps_Text_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals('string', $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%s', $this->_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_Any_Foreign_Model_Name_Field_Test.php b/tests/testcases/core/db_models/fields/EE_Any_Foreign_Model_Name_Field_Test.php deleted file mode 100644 index 39179c71015..00000000000 --- a/tests/testcases/core/db_models/fields/EE_Any_Foreign_Model_Name_Field_Test.php +++ /dev/null @@ -1,47 +0,0 @@ -_field = EEM_Extra_Meta::instance()->field_settings_for('EXM_type'); - $this->assertInstanceOf('EE_Any_Foreign_Model_Name_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals('string', $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%s', $this->_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_Boolean_Field_Test.php b/tests/testcases/core/db_models/fields/EE_Boolean_Field_Test.php deleted file mode 100644 index ab8bfe80f3f..00000000000 --- a/tests/testcases/core/db_models/fields/EE_Boolean_Field_Test.php +++ /dev/null @@ -1,55 +0,0 @@ -_field = EEM_Checkin::instance()->field_settings_for('CHK_in'); - $this->assertInstanceOf('EE_Boolean_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals('boolean', $this->_field->getSchemaType()); - } - - - public function test_prepare_for_pretty_echoing() - { - $this->assertEquals(__('Yes', 'event_espresso'), $this->_field->prepare_for_pretty_echoing(true)); - $this->assertEquals(__('No', 'event_espresso'), $this->_field->prepare_for_pretty_echoing(false)); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%d', $this->_field->get_wpdb_data_type()); - } -} diff --git a/tests/testcases/core/db_models/fields/EE_DB_Only_Float_Field_Test.php b/tests/testcases/core/db_models/fields/EE_DB_Only_Float_Field_Test.php deleted file mode 100644 index ce0b55e9474..00000000000 --- a/tests/testcases/core/db_models/fields/EE_DB_Only_Float_Field_Test.php +++ /dev/null @@ -1,47 +0,0 @@ -_field = EEM_Event::instance()->field_settings_for('EVTM_ID'); - $this->assertInstanceOf('EE_DB_Only_Float_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals('number', $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%f', $this->_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_DB_Only_Int_Field_Test.php b/tests/testcases/core/db_models/fields/EE_DB_Only_Int_Field_Test.php deleted file mode 100644 index 0f0abcc3317..00000000000 --- a/tests/testcases/core/db_models/fields/EE_DB_Only_Int_Field_Test.php +++ /dev/null @@ -1,47 +0,0 @@ -_field = EEM_Attendee::instance()->field_settings_for('ATT_parent'); - $this->assertInstanceOf('EE_DB_Only_Int_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals('integer', $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%d', $this->_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_DB_Only_Text_Field_Test.php b/tests/testcases/core/db_models/fields/EE_DB_Only_Text_Field_Test.php deleted file mode 100644 index e84e612e9ed..00000000000 --- a/tests/testcases/core/db_models/fields/EE_DB_Only_Text_Field_Test.php +++ /dev/null @@ -1,47 +0,0 @@ -_field = new EE_DB_Only_Text_Field('post_type', __("Post Type", 'event_espresso'), false, 'espresso_events'); - $this->assertInstanceOf('EE_DB_Only_Text_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals('string', $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%s', $this->_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_Datetime_Field_Test.php b/tests/testcases/core/db_models/fields/EE_Datetime_Field_Test.php deleted file mode 100644 index 2de314434bc..00000000000 --- a/tests/testcases/core/db_models/fields/EE_Datetime_Field_Test.php +++ /dev/null @@ -1,439 +0,0 @@ -loadModelFieldMocks(array('EE_Datetime_Field')); - } - - - /** - * Used to set the _datetime_field property for tests with the provided params and set with defaults - * if none provided. - * - * @see EE_Datetime_Field for docs on params - * @param string $table_column - * @param string $nice_name - * @param bool $nullable - * @param string $default_value - * @param null $timezone - * @param null $date_format - * @param null $time_format - * @param null $pretty_date_format - * @param null $pretty_time_format - */ - protected function _set_dtt_field_object( - $table_column = 'DTT_EVT_start', - $nice_name = 'Start Date', - $nullable = false, - $default_value = '', - $timezone = null, - $date_format = null, - $time_format = null, - $pretty_date_format = null, - $pretty_time_format = null - ) { - $this->_datetime_field = new EE_Datetime_Field_Mock( - $table_column, - $nice_name, - $nullable, - $default_value, - $timezone, - $date_format, - $time_format, - $pretty_date_format, - $pretty_time_format - ); - } - - - /** - * This returns a common set of time strings for testing indexed by format. - * - * @return array - */ - protected function _get_time_strings_for_testing() - { - //set our expected properties - //setup some baselines to get expected values (the date/time strings match what is returned from _get_time_strings_for_testing ); - $datetimeZoneVC = new DateTimeZone('America/Vancouver'); - $datetimeZoneUTC = new DateTimeZone('UTC'); - $this->_defaultDTT = new DateTime('2015-02-20 11:38', $datetimeZoneVC); - - //formats we want to test - $date_formats = $this->date_formats_to_test(); - - //set the timezone to be America/Vancouver (UTC-8h Daylight UTC-7h) - $this->_datetime_field->set_timezone('America/Vancouver'); - - //set the expected Unix timestamp - $expectedDTT = clone $this->_defaultDTT; - $expectedDTT->setTimezone($datetimeZoneUTC); - $this->_expected_unixtimestamp = $expectedDTT->format('U'); - $this->_expected_mysqltimestamp = $expectedDTT->format('Y-m-d H:i:s'); - return $date_formats; - } - - - /** - * This ensures that when constructed the datetime field object is setup correctly - * - * @since 4.6 - */ - public function test_construct() - { - //instantiate a _datetime_field object for tests. - $this->_set_dtt_field_object(); - - //verify date_format - $this->assertEquals($this->_datetime_field->get_property('_date_format'), 'F j, Y'); - $this->assertEquals($this->_datetime_field->get_property('_time_format'), 'g:i a'); - $this->assertEquals($this->_datetime_field->get_property('_pretty_date_format'), 'F j, Y'); - $this->assertEquals($this->_datetime_field->get_property('_pretty_time_format'), 'g:i a'); - - //verify timezone. By default wp has the gmt_offset set to 0. So this means we convert that to UTC. - $this->assertEquals($this->_datetime_field->get_timezone(), 'UTC'); - } - - - /** - * Test getting a DateTimeZone object that has the UTC timezone set. - * - * @since 4.6 - */ - public function test_get_UTC_DateTimeZone() - { - $this->_set_dtt_field_object(); - $utcTz = $this->_datetime_field->get_UTC_DateTimeZone(); - $this->assertInstanceOf('DateTimeZone', $utcTz); - //should be in utc! - $this->assertEquals('UTC', $utcTz->getName()); - } - - - /** - * Test prepare_for_set method. - * - * @since 4.6 - */ - public function test_prepare_for_set() - { - //instantiate a _datetime_field object. Set timezone - $this->_set_dtt_field_object(); - - //grab our time strings - $timestrings = $this->_get_time_strings_for_testing(); - - //loop through timestrings and run tests - foreach ($timestrings['date'] as $format) { - $datetime = $this->_defaultDTT->format($format); - $this->_datetime_field->set_date_format($format); - foreach ($timestrings['time'] as $time_format) { - $dtt = $datetime . ' ' . $this->_defaultDTT->format($time_format); - $this->_datetime_field->set_time_format($time_format); - $dateobject = $this->_datetime_field->prepare_for_set($dtt); - $this->assertInstanceOf('DateTime', $dateobject); - //test expected value - $this->assertEquals($this->_expected_unixtimestamp, $dateobject->format('U')); - } - } - } - - - /** - * This tests the prepare_for_set_with_new_time method in EE_Datetime_Field - * - * @since 4.6 - */ - public function test_prepare_for_set_with_new_time() - { - $this->_set_dtt_field_object(); - $timestrings = $this->_get_time_strings_for_testing(); - - //clone defaultDTT to setup what our expected time offset unixtimestamp will be. - $DTToffset = clone $this->_defaultDTT; - $DTToffset->add(new DateInterval('PT2H')); - $expected = $DTToffset->format('U'); - - //loop through timestrings and run tests - foreach ($timestrings['time'] as $format) { - $this->_datetime_field->set_time_format($format); - $new_time_string = $this->_datetime_field->prepare_for_set_with_new_time($DTToffset->format($format), - $this->_defaultDTT); - $this->assertEquals($expected, $new_time_string->format('U'), - sprintf('Time Format is %s. Date format is %s.', $format, $this->_datetime_field->get_date_format())); - } - - //loop again except this time just send in the DateTime object. - foreach ($timestrings['time'] as $format) { - $this->_datetime_field->set_time_format($format); - $new_time_string = $this->_datetime_field->prepare_for_set_with_new_time($DTToffset, $this->_defaultDTT); - $this->assertEquals($expected, $new_time_string->format('U'), - sprintf('Time Format is %s. Date format is %s.', $format, $this->_datetime_field->get_date_format())); - } - } - - - /** - * This tests the prepare_for_set_with_new_date method in EE_Datetime_Field - * - * @since 4.6 - */ - public function test_prepare_for_set_with_new_date() - { - $this->_set_dtt_field_object(); - $timestrings = $this->_get_time_strings_for_testing(); - - //clone defaultDTT to setup what our expected time offset unixtimestamp will be. - $DTToffset = clone $this->_defaultDTT; - $DTToffset->add(new DateInterval('P2D')); - $expected = $DTToffset->format('U'); - - - //loop through timestrings and run tests - foreach ($timestrings['date'] as $format) { - $this->_datetime_field->set_date_format($format); - $new_time_string = $this->_datetime_field->prepare_for_set_with_new_date($DTToffset->format($format), - $this->_defaultDTT); - $this->assertEquals($expected, $new_time_string->format('U'), sprintf('Format is %s', $format)); - } - - - //loop again except this time just send in the DateTime object. - foreach ($timestrings['date'] as $format) { - $this->_datetime_field->set_date_format($format); - $new_time_string = $this->_datetime_field->prepare_for_set_with_new_date($DTToffset, $this->_defaultDTT); - $this->assertEquals($expected, $new_time_string->format('U'), sprintf('Format is %s.', $format)); - } - } - - - /** - * This tests the prepare_for_get method in EE_Datetime_Field - * - * @since 4.6 - */ - public function test_prepare_for_get() - { - $this->_set_dtt_field_object(); - $timestrings = $this->_get_time_strings_for_testing(); - - foreach ($timestrings['date'] as $dateformat) { - $this->_datetime_field->set_date_format($dateformat); - foreach ($timestrings['time'] as $timeformat) { - $this->_datetime_field->set_time_format($timeformat); - - //test date_time_output as time. - $this->_datetime_field->set_date_time_output('time'); - $output = $this->_datetime_field->prepare_for_get($this->_defaultDTT); - $this->assertEquals($output, $this->_defaultDTT->format($timeformat), - sprintf('Date Format: %s Time Format: %s', $dateformat, $timeformat)); - - //test date_time_output as date. - $this->_datetime_field->set_date_time_output('date'); - $output = $this->_datetime_field->prepare_for_get($this->_defaultDTT); - $this->assertEquals($output, $this->_defaultDTT->format($dateformat), - sprintf('Date Format: %s Time Format: %s', $dateformat, $timeformat)); - - //test date_time_output as date and time. - $this->_datetime_field->set_date_time_output('all'); - $output = $this->_datetime_field->prepare_for_get($this->_defaultDTT); - $this->assertEquals($output, $this->_defaultDTT->format($dateformat . ' ' . $timeformat), - sprintf('Date Format: %s Time Format: %s', $dateformat, $timeformat)); - } - } - } - - - /** - * Tests EE_Datetime_Field prepare_for_display method when it receives a - * invalid DateTime object on a non-nullable field and WP_DEBUG is true. - * - * @since 4.7.0 - * @expectedException EE_Error - * @expectedExceptionMessage EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value - * for the $DateTime argument because the Start Date field is not nullable. - */ - public function test_prepare_for_display_with_exception() - { - $this->_set_dtt_field_object(); - if (defined('WP_DEBUG') && ! WP_DEBUG) { - $this->markTestSkipped('Unable to complete test because WP_DEBUG is already defined and is set to false'); - } else { - if (! defined('WP_DEBUG')) { - define('WP_DEBUG', true); - } - } - - $this->_datetime_field->prepare_for_display(null); - } - - - /** - * Tests EE_Datetime_Field prepare_for_display method when it receives an invalid DateTime object on a - * non-nullable field and WP_DEBUG is false. - * - * @since 4.7.0 - */ - public function test_prepare_for_display_with_EE_Error() - { - if (defined('WP_DEBUG') && WP_DEBUG) { - $this->markTestSkipped('Unable to complete test because WP_DEBUG is already defined and is set to true'); - } - $this->_set_dtt_field_object(); - $this->_datetime_field->prepare_for_display(null); - //have error notice? - $notice = EE_Error::get_notices(false); - $notice = $notice['errors']; - $expected = 'An error has occurred:
    EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the Start Date field is not nullable. When WP_DEBUG is false, the value is set to "now" instead of throwing an exception.'; - $this->assertEquals($expected, $notice); - EE_Error::reset_notices(); - } - - /** - * @since 4.7.0 - */ - public function test_prepare_for_display() - { - $this->_set_dtt_field_object(); - - //set nullable allowed (non nullable allowed are in other tests). - $this->_datetime_field->set_nullable(); - - //test null value. - $this->assertEmpty($this->_datetime_field->prepare_for_display(null)); - - //non null values are tested by prepare_for_get_test - } - - - /** - * This tests the prepare_for_use_in_db method on EE_Datetime_Field - * - * @since 4.6 - */ - public function test_prepare_for_use_in_db() - { - $this->_set_dtt_field_object(); - $this->_get_time_strings_for_testing(); - - //test if not nullable and datestring is empty, then we should get back current_time in utc in mysql timestamp. - $this->assertEquals(date('Y-m-d H:i:s'), $this->_datetime_field->prepare_for_use_in_db(null)); - - //test if nullable and datestring is empty, then we should get null. - $this->_datetime_field->set_nullable(); - $this->assertNull($this->_datetime_field->prepare_for_use_in_db('')); - - //test getting the correct value for the set UTC timestamp - $this->assertEquals($this->_expected_mysqltimestamp, - $this->_datetime_field->prepare_for_use_in_db($this->_defaultDTT)); - } - - - /** - * This tests the prepare_for_set_from_db method in EE_Datetime_Field - * - * @since 4.6 - */ - public function test_prepare_for_set_from_db() - { - $this->_set_dtt_field_object(); - $this->_get_time_strings_for_testing(); - - //test if not nullable and datestring is empty, then we should get back datetime object. - $this->assertInstanceOf('DateTime', $this->_datetime_field->prepare_for_set_from_db('')); - - //test if nullable and datestring is empty, then we should get null. - $this->_datetime_field->set_nullable(); - $this->assertNull($this->_datetime_field->prepare_for_set_from_db('')); - - //test getting the correct value for the set UTC mysql timestamp - $this->assertEquals( - $this->_expected_unixtimestamp, - $this->_datetime_field->prepare_for_set_from_db($this->_expected_mysqltimestamp)->format('U') - ); - } - - - public function test_datetime_field_serialization() - { - if (version_compare(PHP_VERSION, '5.5', '<')) { - $this->markTestSkipped(); - } - $this->_set_dtt_field_object('LIN_timestamp', 'LIN_timestamp', false, EE_Datetime_Field::now); - $this->_get_time_strings_for_testing(); - $datetime_field = $this->_datetime_field; - $datetime_field = serialize($datetime_field); - $datetime_field = unserialize($datetime_field); - /** @var DateTime $datetime */ - $datetime = $datetime_field->get_date_object(''); - $this->assertInstanceOf('EventEspresso\core\domain\entities\DbSafeDateTime', $datetime); - // now serialize and unserialize - $datetime = serialize($datetime); - // ensure that a DateTime object was not serialized - $this->assertFalse(strpos($datetime, 'O:8:"DateTime"')); - $datetime = unserialize($datetime); - $this->assertInstanceOf('EventEspresso\core\domain\entities\DbSafeDateTime', $datetime); - } - - - public function test_getSchemaType() - { - $this->_set_dtt_field_object('LIN_timestamp', 'LIN_timestamp', false, EE_Datetime_Field::now); - $this->assertEquals('string', $this->_datetime_field->getSchemaType()); - } - - - public function test_get_wpdb_data_type() - { - $this->_set_dtt_field_object('LIN_timestamp', 'LIN_timestamp', false, EE_Datetime_Field::now); - $this->assertEquals('%s', $this->_datetime_field->get_wpdb_data_type()); - } -} -// end class EE_Datetime_Field_Test -// Location: tests/testcases/core/db_models/fields/EE_Datetime_Field_Test.php diff --git a/tests/testcases/core/db_models/fields/EE_Email_Field_Test.php b/tests/testcases/core/db_models/fields/EE_Email_Field_Test.php deleted file mode 100644 index 0f61cb67199..00000000000 --- a/tests/testcases/core/db_models/fields/EE_Email_Field_Test.php +++ /dev/null @@ -1,106 +0,0 @@ -_field = EEM_Attendee::instance()->field_settings_for('ATT_email'); - $this->assertInstanceOf('EE_Email_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals(array('string','null'), $this->_field->getSchemaType()); - } - - public function test_prepare_for_set() - { - $email_validation_levels = array( - 'basic' => true, - 'wp_default' => false, - 'i18n' => true, - ); - //only add `i18n_dns` validation check if mailcatcher isn't detected. Mailcatcher hijacks that dns checks. - if (strpos(ini_get('sendmail_path'), 'catchmail') === false) { - $email_validation_levels['i18n_dns'] = true; - } - foreach ($email_validation_levels as $email_validation_level => $test_should_pass) { - EE_Registry::instance()->CFG->registration->email_validation_level = $email_validation_level; - $this->set_email_field_value($email_validation_level, $test_should_pass); - } - } - - - /** - * @param bool $test_should_pass - * @throws \EE_Error - */ - public function set_email_field_value($validation_being_tested, $test_should_pass = true) - { - $international_email_address = 'jรคgerjรผrgen@deutschland.com'; - /** @var \EE_Email_Field $email_field */ - $email_field = $this->_field; - $actual_email_address = $email_field->prepare_for_set($international_email_address); - if ($test_should_pass) { - $this->assertEquals( - $international_email_address, - $actual_email_address, - sprintf( - 'Was ist das? Die E-Mail-Adresse des Teilnehmers sollte "%1$s", nicht "%2$s" sein (Validation Level: %3$s)!', - $international_email_address, - $actual_email_address, - $validation_being_tested - ) - // translation: - // What is this? The attendee's email address should be "jรคgerjรผrgen@deutschland.com", not "{actual result}" - ); - } else { - $this->assertNotEquals( - $international_email_address, - $actual_email_address, - sprintf( - 'Was ist das? Die E-Mail-Adresse des Teilnehmers sollte "", nicht "%1$s" sein (Validation Level: %2$s!', - $actual_email_address, - $validation_being_tested - ) - // translation: - // What is this? The attendee's email address should be "", not "{actual result}" - ); - } - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%s', $this->_field->get_wpdb_data_type()); - } - -} -// End of file EE_Email_Field_Test.php -// Location: tests/testcases/core/db_models/fields/EE_Email_Field_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_Enum_Integer_Field_Test.php b/tests/testcases/core/db_models/fields/EE_Enum_Integer_Field_Test.php deleted file mode 100644 index c46ac521ef8..00000000000 --- a/tests/testcases/core/db_models/fields/EE_Enum_Integer_Field_Test.php +++ /dev/null @@ -1,47 +0,0 @@ -_field = EEM_Message::instance()->field_settings_for('MSG_priority'); - $this->assertInstanceOf('EE_Enum_Integer_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals('object', $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%d', $this->_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_Enum_Text_Field_Test.php b/tests/testcases/core/db_models/fields/EE_Enum_Text_Field_Test.php deleted file mode 100644 index 2089f80025e..00000000000 --- a/tests/testcases/core/db_models/fields/EE_Enum_Text_Field_Test.php +++ /dev/null @@ -1,114 +0,0 @@ -_an_enum_field = new EE_Enum_Text_Field( - 'A_field', - 'some field', - true, - 'b', - array( - 'a' => 'A', - 'b' => 'B', - 'c' => 'C' - ) - ); - } - - /** - * ensures that when valid input is provided, its left as-is - */ - public function test_prepare_for_set__valid() - { - $this->assertEquals('a',$this->_an_enum_field->prepare_for_set('a')); - $this->assertEquals('b',$this->_an_enum_field->prepare_for_set('b')); - } - - /** - * verifies that when invalid input is provided, it's replaced with the default - */ - public function test_prepare_for_set__invalid() - { - $this->assertEquals('b', $this->_an_enum_field->prepare_for_set('invalid')); - $this->assertEquals('b', $this->_an_enum_field->prepare_for_set('borked')); - //verify an error was issued if WP_DEBUG is on - $this->assertTrue( WP_DEBUG && EE_Error::has_error()); - EE_Error::reset_notices(); - } - - - - /** - * Verify that when retrieving from the DB, we're accepting of invalid input. - * That's because data might have gotten into the db via models - * when the filter FHEE__EE_Enum_Text_Field___allowed_enum_options - * was used, but then the filter callback got removed. In that case, - * we don't really want to change that existing data - * in the DB, and we certainly don't want to have errors because of it. - */ - public function test_prepare_for_set_from_db() - { - $this->assertEquals( - 'invalid-data-from-db', - $this->_an_enum_field->prepare_for_set_from_db('invalid-data-from-db') - ); - } - - - - /** - * Verify that when something borked got into the model - * (eg from prepare_for_set_from_db()) then it should actually - * stay that way, even inserting it into the DB. - * This way, if someone retrieves something borked from the DB and - * it gets set on the model, if they switch some other field - * on that model object and re-save it, this enum's "invalid" - * data won't get overridden. - * So if we want to enforce switching data back into a valid form, - * we need to explicitly do that, it won't happen - * automatically. - */ - public function test_prepare_for_use_in_db() - { - $this->assertEquals( - 'invalid-data-on-model-object', - $this->_an_enum_field->prepare_for_use_in_db('invalid-data-on-model-object') - ); - } - - - public function test_getSchemaType() - { - $this->assertEquals(array('object','null'), $this->_an_enum_field->getSchemaType()); - } - - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%s', $this->_an_enum_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_Float_Field_Test.php b/tests/testcases/core/db_models/fields/EE_Float_Field_Test.php deleted file mode 100644 index 0ad0266eb71..00000000000 --- a/tests/testcases/core/db_models/fields/EE_Float_Field_Test.php +++ /dev/null @@ -1,47 +0,0 @@ -_field = EEM_Line_Item::instance()->field_settings_for('LIN_percent'); - $this->assertInstanceOf('EE_Float_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals('number', $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%f', $this->_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_Foreign_Key_Int_Field_Test.php b/tests/testcases/core/db_models/fields/EE_Foreign_Key_Int_Field_Test.php deleted file mode 100644 index 6c3421badbb..00000000000 --- a/tests/testcases/core/db_models/fields/EE_Foreign_Key_Int_Field_Test.php +++ /dev/null @@ -1,47 +0,0 @@ -_field = EEM_Checkin::instance()->field_settings_for('REG_ID'); - $this->assertInstanceOf('EE_Foreign_Key_Int_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals('integer', $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%d', $this->_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_Foreign_Key_String_Field_Test.php b/tests/testcases/core/db_models/fields/EE_Foreign_Key_String_Field_Test.php deleted file mode 100644 index cd3ecc70e8b..00000000000 --- a/tests/testcases/core/db_models/fields/EE_Foreign_Key_String_Field_Test.php +++ /dev/null @@ -1,47 +0,0 @@ -_field = EEM_Attendee::instance()->field_settings_for('CNT_ISO'); - $this->assertInstanceOf('EE_Foreign_Key_String_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals(array('string','null'), $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%s', $this->_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_Full_HTML_Field_Test.php b/tests/testcases/core/db_models/fields/EE_Full_HTML_Field_Test.php deleted file mode 100644 index 7726dd48996..00000000000 --- a/tests/testcases/core/db_models/fields/EE_Full_HTML_Field_Test.php +++ /dev/null @@ -1,48 +0,0 @@ -_field = EEM_Line_Item::instance()->field_settings_for('LIN_name'); - $this->assertInstanceOf('EE_Full_HTML_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals('object', $this->_field->getSchemaType()); - } - - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%s', $this->_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_Infinite_Integer_Field_Test.php b/tests/testcases/core/db_models/fields/EE_Infinite_Integer_Field_Test.php deleted file mode 100644 index c2c072ccda2..00000000000 --- a/tests/testcases/core/db_models/fields/EE_Infinite_Integer_Field_Test.php +++ /dev/null @@ -1,47 +0,0 @@ -_field = EEM_Ticket::instance()->field_settings_for('TKT_qty'); - $this->assertInstanceOf('EE_Infinite_Integer_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals(array('integer', 'null'), $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%d', $this->_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_Integer_Field_Test.php b/tests/testcases/core/db_models/fields/EE_Integer_Field_Test.php deleted file mode 100644 index 208df2055db..00000000000 --- a/tests/testcases/core/db_models/fields/EE_Integer_Field_Test.php +++ /dev/null @@ -1,47 +0,0 @@ -_field = EEM_Datetime::instance()->field_settings_for('DTT_sold'); - $this->assertInstanceOf('EE_Integer_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals(array('integer','null'), $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%d', $this->_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_Maybe_Serialized_Simple_HTML_Field_Test.php b/tests/testcases/core/db_models/fields/EE_Maybe_Serialized_Simple_HTML_Field_Test.php deleted file mode 100644 index 045463cd056..00000000000 --- a/tests/testcases/core/db_models/fields/EE_Maybe_Serialized_Simple_HTML_Field_Test.php +++ /dev/null @@ -1,47 +0,0 @@ -_field = EEM_Answer::instance()->field_settings_for('ANS_value'); - $this->assertInstanceOf('EE_Maybe_Serialized_Simple_HTML_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals(array('object','string'), $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%s', $this->_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_Maybe_Serialized_Text_Field_Test.php b/tests/testcases/core/db_models/fields/EE_Maybe_Serialized_Text_Field_Test.php deleted file mode 100644 index 62f77141ed4..00000000000 --- a/tests/testcases/core/db_models/fields/EE_Maybe_Serialized_Text_Field_Test.php +++ /dev/null @@ -1,47 +0,0 @@ -_field = EEM_Message::instance()->field_settings_for('MSG_content'); - $this->assertInstanceOf('EE_Maybe_Serialized_Text_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals(array('object','string','null'), $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%s', $this->_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_Money_Field_Test.php b/tests/testcases/core/db_models/fields/EE_Money_Field_Test.php deleted file mode 100644 index 70c66685bb2..00000000000 --- a/tests/testcases/core/db_models/fields/EE_Money_Field_Test.php +++ /dev/null @@ -1,47 +0,0 @@ -_field = EEM_Price::instance()->field_settings_for('PRC_amount'); - $this->assertInstanceOf('EE_Money_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals('object', $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%f', $this->_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_Plain_Text_Field_Test.php b/tests/testcases/core/db_models/fields/EE_Plain_Text_Field_Test.php deleted file mode 100644 index cfa3a36a4af..00000000000 --- a/tests/testcases/core/db_models/fields/EE_Plain_Text_Field_Test.php +++ /dev/null @@ -1,47 +0,0 @@ -_field = EEM_Message::instance()->field_settings_for('MSG_token'); - $this->assertInstanceOf('EE_Plain_Text_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals('string', $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%s', $this->_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_Post_Content_Field_Test.php b/tests/testcases/core/db_models/fields/EE_Post_Content_Field_Test.php deleted file mode 100644 index 13d23b56fba..00000000000 --- a/tests/testcases/core/db_models/fields/EE_Post_Content_Field_Test.php +++ /dev/null @@ -1,112 +0,0 @@ -_field = EEM_Event::instance()->field_settings_for('EVT_desc'); - $this->assertInstanceOf('EE_Post_Content_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals('object', $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%s', $this->_field->get_wpdb_data_type()); - } - - - /** - * @group 8405 - */ - public function test_prepare_for_pretty_echoing() - { - //use a simple mock shortcode to verify it gets replaced - add_shortcode( - 'mock', - function () { - return 'replacement'; - } - ); - $this->assertTrue( - strpos( - $this->_field->prepare_for_pretty_echoing('This is the shortcode: [mock]'), - 'This is the shortcode: replacement' - ) !== false - ); - } - - /** - * @group 8405 - */ - public function test_prepare_for_get() - { - //use a simple mock shortcode to verify it DOESN'T get replaced - add_shortcode( - 'mock', - function () { - return 'replacement'; - } - ); - $this->assertTrue( - strpos( - $this->_field->prepare_for_get('This is the shortcode: [mock]'), - 'This is the shortcode: replacement' - ) === false - ); - } - - public function test_prepare_for_set_with_valid_html() - { - $valid_html = 'Hey! This should stay.'; - $this->assertEquals($valid_html, $this->_field->prepare_for_set($valid_html)); - } - - - public function test_prepare_for_set_with_invalid_partial_html_tag() - { - $invalid_html = 'Hey! assertEquals($expected_result, $this->_field->prepare_for_set($invalid_html)); - } - - - public function test_prepare_for_set_with_invalid_full_html_tag() - { - $invalid_html = 'Hey! '; - $expected_result = 'Hey! '; - $this->assertEquals($expected_result, $this->_field->prepare_for_set($invalid_html)); - } - -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_Primary_Key_Int_Field_Test.php b/tests/testcases/core/db_models/fields/EE_Primary_Key_Int_Field_Test.php deleted file mode 100644 index beed488f337..00000000000 --- a/tests/testcases/core/db_models/fields/EE_Primary_Key_Int_Field_Test.php +++ /dev/null @@ -1,47 +0,0 @@ -_field = EEM_Message::instance()->field_settings_for('MSG_ID'); - $this->assertInstanceOf('EE_Primary_Key_Int_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals('integer', $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%d', $this->_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_Primary_Key_String_Field_Test.php b/tests/testcases/core/db_models/fields/EE_Primary_Key_String_Field_Test.php deleted file mode 100644 index ef81716e072..00000000000 --- a/tests/testcases/core/db_models/fields/EE_Primary_Key_String_Field_Test.php +++ /dev/null @@ -1,47 +0,0 @@ -_field = EEM_Country::instance()->field_settings_for('CNT_ISO'); - $this->assertInstanceOf('EE_Primary_Key_String_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals('string', $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%s', $this->_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_Serialized_Text_Field_Test.php b/tests/testcases/core/db_models/fields/EE_Serialized_Text_Field_Test.php deleted file mode 100644 index 9f24ec1ba36..00000000000 --- a/tests/testcases/core/db_models/fields/EE_Serialized_Text_Field_Test.php +++ /dev/null @@ -1,47 +0,0 @@ -_field = EEM_Transaction::instance()->field_settings_for('TXN_session_data'); - $this->assertInstanceOf('EE_Serialized_Text_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals(array('object','string','null'), $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%s', $this->_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_Simple_HTML_Field_Test.php b/tests/testcases/core/db_models/fields/EE_Simple_HTML_Field_Test.php deleted file mode 100644 index 92d0daebb8b..00000000000 --- a/tests/testcases/core/db_models/fields/EE_Simple_HTML_Field_Test.php +++ /dev/null @@ -1,69 +0,0 @@ -_field = EEM_Event::instance()->field_settings_for('EVT_short_desc'); - $this->assertInstanceOf('EE_Simple_HTML_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals('string', $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%s', $this->_field->get_wpdb_data_type()); - } - - public function test_prepare_for_set_with_valid_html() - { - $valid_html = 'Hey! This should stay.'; - $this->assertEquals($valid_html, $this->_field->prepare_for_set($valid_html)); - } - - - public function test_prepare_for_set_with_invalid_partial_html_tag() - { - $invalid_html = 'Hey! assertEquals($expected_result, $this->_field->prepare_for_set($invalid_html)); - } - - - public function test_prepare_for_set_with_invalid_full_html_tag() - { - $invalid_html = 'Hey! '; - $expected_result = 'Hey! '; - $this->assertEquals($expected_result, $this->_field->prepare_for_set($invalid_html)); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_Slug_Field_Test.php b/tests/testcases/core/db_models/fields/EE_Slug_Field_Test.php deleted file mode 100644 index c3bccbe5fa4..00000000000 --- a/tests/testcases/core/db_models/fields/EE_Slug_Field_Test.php +++ /dev/null @@ -1,47 +0,0 @@ -_field = EEM_Event::instance()->field_settings_for('EVT_slug'); - $this->assertInstanceOf('EE_Slug_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals('string', $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%s', $this->_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_Trashed_Flag_Field_Test.php b/tests/testcases/core/db_models/fields/EE_Trashed_Flag_Field_Test.php deleted file mode 100644 index c77f2ff18db..00000000000 --- a/tests/testcases/core/db_models/fields/EE_Trashed_Flag_Field_Test.php +++ /dev/null @@ -1,47 +0,0 @@ -_field = EEM_Registration::instance()->field_settings_for('REG_deleted'); - $this->assertInstanceOf('EE_Trashed_Flag_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals('boolean', $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%d', $this->_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_WP_Post_Status_Field_Test.php b/tests/testcases/core/db_models/fields/EE_WP_Post_Status_Field_Test.php deleted file mode 100644 index d522b6f26f0..00000000000 --- a/tests/testcases/core/db_models/fields/EE_WP_Post_Status_Field_Test.php +++ /dev/null @@ -1,47 +0,0 @@ -_field = EEM_Event::instance()->field_settings_for('status'); - $this->assertInstanceOf('EE_WP_Post_Status_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals('object', $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%s', $this->_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_WP_Post_Type_Field_Test.php b/tests/testcases/core/db_models/fields/EE_WP_Post_Type_Field_Test.php deleted file mode 100644 index 7d6bd751a8a..00000000000 --- a/tests/testcases/core/db_models/fields/EE_WP_Post_Type_Field_Test.php +++ /dev/null @@ -1,47 +0,0 @@ -_field = EEM_Event::instance()->field_settings_for('post_type'); - $this->assertInstanceOf('EE_WP_Post_Type_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals('string', $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%s', $this->_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/fields/EE_WP_User_Field_Test.php b/tests/testcases/core/db_models/fields/EE_WP_User_Field_Test.php deleted file mode 100644 index abb49991cb9..00000000000 --- a/tests/testcases/core/db_models/fields/EE_WP_User_Field_Test.php +++ /dev/null @@ -1,47 +0,0 @@ -_field = EEM_Event::instance()->field_settings_for('EVT_wp_user'); - $this->assertInstanceOf('EE_WP_User_Field', $this->_field); - } - - - public function tearDown() - { - $this->_field = null; - parent::tearDown(); - } - - - public function test_getSchemaType() - { - $this->assertEquals('integer', $this->_field->getSchemaType()); - } - - public function test_get_wpdb_data_type() - { - $this->assertEquals('%d', $this->_field->get_wpdb_data_type()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/db_models/strategies/EE_Default_Where_Conditions_Test.php b/tests/testcases/core/db_models/strategies/EE_Default_Where_Conditions_Test.php deleted file mode 100644 index ed488767caf..00000000000 --- a/tests/testcases/core/db_models/strategies/EE_Default_Where_Conditions_Test.php +++ /dev/null @@ -1,58 +0,0 @@ -factory->user->create_and_get(); - $value1 = 12; - $value2 = 23; - $value3= array( 1,2,3); - $value4 = 'eee'; - $default_where_conditions = new EE_Default_Where_Conditions(); - $default_where_conditions->_finalize_construct( EEM_Event::instance() ); - $this->assertEquals( - array( 'OR*' => array( 'Event.EVT_ID' => $value1, 'Event.Datetime.DTT_ID' => $value2 ), 'AND' => array( 'Event.EVT_name' => array( 'IN', $value3 ), 'Event.Datetime.DTT_name' => $value4 ), 'Event.EVT_wp_user' => $current_user->ID ), - $default_where_conditions->prepare_where_conditions_for_querying( - array( 'OR*' => array( 'EVT_ID' => $value1, 'Datetime.DTT_ID' => $value2 ), 'AND' => array( 'EVT_name' => array( 'IN', $value3 ), 'Datetime.DTT_name' => $value4 ), EEM_Event::instance()->wp_user_field_name() => EE_Default_Where_Conditions::current_user_placeholder ), 'Event.' )); - } - function test_wp_user_field_name(){ - $this->assertEquals( 'EVT_wp_user', EEM_Event::instance()->wp_user_field_name() ); - $this->assertEquals( 'Registration.Event.EVT_wp_user', EEM_Transaction::instance()->wp_user_field_name() ); - $this->assertEquals( 'TKT_wp_user', EEM_Ticket::instance()->wp_user_field_name() ); - } - - /** - * tests teh odd case where we want to add a model relation chain that goes back on itself - */ -// function test_add_model_relation_chain_onto_where_conditions__reciprocal_relation(){ -// $value1 = 12; -// $default_where_conditions = new EE_Default_Where_Conditions( array( 'Event.EVT_wp_user' => $value1 ) ); -// $default_where_conditions->_finalize_construct( EEM_Registration::instance() ); -// //pretend we were querying events, and we joined to the registrations model, and so the -// //registration's model added a default where condition to only return registrations for events owned -// //by teh current user. eg EEM_Event::instance()->get_all( array( array( 'Registration.REG_ID' => 12 ) ); -// $this->assertEquals( -// array( -// 'EVT_wp_user' => $value1 -// //NOT Event.Event.EVT_wp_user -// ) -// , -// $default_where_conditions->add_model_relation_chain_onto_where_conditions( array( 'Event.EVT_wp_user' => $value1 ), 'Registration.' )); -// } -} - -// End of file EE_Default_Where_Conditions_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_models/strategies/EE_Restriciton_Generator_Protected_Test.php b/tests/testcases/core/db_models/strategies/EE_Restriciton_Generator_Protected_Test.php deleted file mode 100644 index b04705706fd..00000000000 --- a/tests/testcases/core/db_models/strategies/EE_Restriciton_Generator_Protected_Test.php +++ /dev/null @@ -1,80 +0,0 @@ -_construct_finalize( EEM_Transaction::instance(), EEM_Base::caps_read ); - $restrictions = $generator->generate_restrictions(); - foreach ( $restrictions as $default_where_conditions ) { - $default_where_conditions->_finalize_construct( EEM_Registration::instance() ); - } - $this->assertArrayHasKey( 'ee_read_transactions', $restrictions ); - $this->assertInstanceOf( 'EE_Return_None_Where_Conditions', $restrictions[ 'ee_read_transactions' ] ); - $this->assertEquals( 1, count( $restrictions ) ); - } - - function test_generate_restrictions__basic_and_others() { - global $current_user; - $current_user = $this->factory->user->create_and_get(); - //currently registrations have the 'ee_read_registrations' and 'ee_read_others_registrations' permissions - //if that changes, this will need to be updated - $generator = new EE_Restriction_Generator_Protected(); - $generator->_construct_finalize( EEM_Registration::instance(), EEM_Base::caps_read ); - $restrictions = $generator->generate_restrictions(); - foreach ( $restrictions as $default_where_conditions ) { - $default_where_conditions->_finalize_construct( EEM_Registration::instance() ); - } - $this->assertArrayHasKey( 'ee_read_registrations', $restrictions ); - $this->assertInstanceOf( 'EE_Return_None_Where_Conditions', $restrictions[ 'ee_read_registrations' ] ); - $this->assertArrayHasKey( 'ee_read_others_registrations', $restrictions ); - $this->assertInstanceOf( 'EE_Default_Where_Conditions', $restrictions[ 'ee_read_others_registrations' ] ); - $this->assertEquals( array( EEM_Registration::instance()->wp_user_field_name() => get_current_user_id() ), $restrictions[ 'ee_read_others_registrations' ]->get_default_where_conditions() ); - $this->assertEquals( 2, count( $restrictions ) ); - } - - function test_generate_restrictions__basic_and_others_and_private() { - //currently events have the 'ee_read_events', 'ee_read_others_events', and 'ee_read_others_private_events' caps - //if that changes, this will need to be updated - $generator = new EE_Restriction_Generator_Protected(); - $generator->_construct_finalize( EEM_Event::instance(), EEM_Base::caps_read ); - $restrictions = $generator->generate_restrictions(); - foreach ( $restrictions as $default_where_conditions ) { - $default_where_conditions->_finalize_construct( EEM_Event::instance() ); - } - $this->assertArrayHasKey( 'ee_read_events', $restrictions ); - $this->assertInstanceOf( 'EE_Return_None_Where_Conditions', $restrictions[ 'ee_read_events' ] ); - - $this->assertArrayHasKey( 'ee_read_others_events', $restrictions ); - $this->assertInstanceOf( 'EE_Default_Where_Conditions', $restrictions[ 'ee_read_others_events' ] ); - $this->assertEquals( - array( EEM_Event::instance()->wp_user_field_name() => get_current_user_id() ), $restrictions[ 'ee_read_others_events' ]->get_default_where_conditions() ); - - $this->assertArrayHasKey( 'ee_read_private_events', $restrictions ); - $this->assertInstanceOf( 'EE_Default_Where_Conditions', $restrictions[ 'ee_read_private_events' ] ); - $this->assertEquals( array( - 'OR*no_' . EE_Restriction_Generator_Base::get_cap_name( EEM_Event::instance(), 'read_private' ) => array( - EEM_Event::instance()->wp_user_field_name() => get_current_user_id(), - 'status' => array( '!=', 'private' ) ) ), $restrictions[ 'ee_read_private_events' ]->get_default_where_conditions() ); - $this->assertEquals( 3, count( $restrictions ) ); - } - -} - -// End of file EE_Restriciton_Generator_Protected_Test.php \ No newline at end of file diff --git a/tests/testcases/core/db_models/strategies/EE_Restriction_Generator_Base_Test.php b/tests/testcases/core/db_models/strategies/EE_Restriction_Generator_Base_Test.php deleted file mode 100644 index 52de7a6a5fa..00000000000 --- a/tests/testcases/core/db_models/strategies/EE_Restriction_Generator_Base_Test.php +++ /dev/null @@ -1,29 +0,0 @@ -assertEquals( 'ee_edit_events', EE_Restriction_Generator_Base::get_cap_name(EEM_Event::instance(), 'edit' ) ); - $this->assertEquals( 'ee_read_private_venues', EE_Restriction_Generator_Base::get_cap_name( EEM_Venue::instance(), 'read_private' ) ); - } - - function test_is_cap(){ - $this->assertTrue( EE_Restriction_Generator_Base::is_cap( EEM_Event::instance(), 'edit' ) ); - $this->assertTrue( EE_Restriction_Generator_Base::is_cap( EEM_Event::instance(), 'edit_others' ) ); - $this->assertFalse( EE_Restriction_Generator_Base::is_cap( EEM_Event::instance(), 'rock' ) ); - } -} - -// End of file EE_Restriction_Generator_Base.php \ No newline at end of file diff --git a/tests/testcases/core/db_models/strategies/EE_Restriction_Generator_Meta_Test.php b/tests/testcases/core/db_models/strategies/EE_Restriction_Generator_Meta_Test.php deleted file mode 100644 index 612b768c134..00000000000 --- a/tests/testcases/core/db_models/strategies/EE_Restriction_Generator_Meta_Test.php +++ /dev/null @@ -1,67 +0,0 @@ -_construct_finalize( EEM_Post_Meta::instance(), EEM_Base::caps_read ); - $restrictions = $generator->generate_restrictions(); - $this->assertArrayHasKey( EE_Restriction_Generator_Base::get_default_restrictions_cap(), $restrictions ); - $this->assertArrayHasKey( 'apply-to-all-queries-using-caps', $restrictions ); - $this->assertInstanceOf( 'EE_Return_None_Where_Conditions', $restrictions[ EE_Restriction_Generator_Base::get_default_restrictions_cap() ] ); - $restrictions_for_all_cap_contexts = $restrictions[ 'apply-to-all-queries-using-caps' ]; - $this->assertInstanceOf( 'EE_Default_Where_Conditions', $restrictions_for_all_cap_contexts ); - $this->assertEquals( - array( - 'meta_key' => array( 'NOT_LIKE', "\\\\_%" ), - 'meta_value' => array( 'NOT_REGEXP', '^[aOs]:[\d]:.*$') - ), - $restrictions_for_all_cap_contexts->get_default_where_conditions() - ); - } - - public function test_no_caps__whitelisted_and_blacklisted() { - add_filter( 'FHEE__EE_Restriction_Generator_Meta___generate_restrictions__whitelisted_meta_keys', array( $this, '_whitelist_metas' ) ); - add_filter( 'FHEE__EE_Restriction_Generator_Meta___generate_restrictions__blacklisted_meta_keys', array( $this, '_blacklist_metas' ) ); - $generator = new EE_Restriction_Generator_Meta( 'meta_key', 'meta_value' ); - $generator->_construct_finalize( EEM_Post_Meta::instance(), EEM_Base::caps_read ); - $restrictions = $generator->generate_restrictions(); - $this->assertArrayHasKey( EE_Restriction_Generator_Base::get_default_restrictions_cap(), $restrictions ); - $this->assertArrayHasKey( 'apply-to-all-queries-using-caps', $restrictions ); - $this->assertInstanceOf( 'EE_Return_None_Where_Conditions', $restrictions[ EE_Restriction_Generator_Base::get_default_restrictions_cap() ] ); - $restrictions_for_all_cap_contexts = $restrictions[ 'apply-to-all-queries-using-caps' ]; - $this->assertInstanceOf( 'EE_Default_Where_Conditions', $restrictions_for_all_cap_contexts ); - $this->assertEquals( - array( - 'OR*whitelisted-or-normal' => array( - 'meta_key*whitelisted' => array( 'IN', array( 'white' ) ), - 'AND' => array( - 'meta_key' => array( 'NOT_LIKE', "\\\\_%" ), - 'meta_value' => array( 'NOT_REGEXP', '^[aOs]:[\d]:.*$'), - 'meta_key*blacklisted' => array( 'NOT_IN', array( 'black' ) ), - ), - ), - ), - $restrictions_for_all_cap_contexts->get_default_where_conditions() - ); - } - - public function _whitelist_metas( $whitelisted_metas ) { - return array( 'white' ); - } - - public function _blacklist_metas( $blacklisted_metas ) { - return array( 'black' ); - } -} diff --git a/tests/testcases/core/db_models/strategies/EE_Return_None_Where_Conditions_Test.php b/tests/testcases/core/db_models/strategies/EE_Return_None_Where_Conditions_Test.php deleted file mode 100644 index 6a6c2d1ca5b..00000000000 --- a/tests/testcases/core/db_models/strategies/EE_Return_None_Where_Conditions_Test.php +++ /dev/null @@ -1,30 +0,0 @@ -_finalize_construct( EEM_Registration::instance() ); - $this->assertEquals( - array( - 'Event.Registration.REG_ID' => array('<', 0 ) - ) - , - $default_where_conditions->get_default_where_conditions( 'Event.Registration' )); - } -} - -// End of file EE_Return_None_Where_Conditions_Test.php \ No newline at end of file diff --git a/tests/testcases/core/domain/DomainFactoryTest.php b/tests/testcases/core/domain/DomainFactoryTest.php deleted file mode 100644 index 9e07bfb353a..00000000000 --- a/tests/testcases/core/domain/DomainFactoryTest.php +++ /dev/null @@ -1,91 +0,0 @@ -assertInstanceOf('EventEspresso\tests\mocks\core\domain\DomainMock', $domain_mock); - $this->assertInstanceOf('EventEspresso\core\domain\DomainBase', $domain_mock); - $this->assertEquals($file_path, $domain_mock->pluginFile()); - $this->assertEquals(plugin_basename($file_path), $domain_mock->pluginBasename()); - $this->assertEquals(plugin_dir_path($file_path),$domain_mock->pluginPath()); - $this->assertEquals(plugin_dir_url($file_path),$domain_mock->pluginUrl()); - $this->assertEquals(plugin_dir_url($file_path),$domain_mock->pluginUrl()); - $this->assertEquals($version, $domain_mock->version()); - $this->assertEquals('Oh Yeah', $domain_mock->returnOhYeah()); - } - - - public function test_constructor_with_invalid_arguments() - { - $this->setExceptionExpected('InvalidArgumentException'); - DomainFactory::getShared( - new FullyQualifiedName( - 'EventEspresso\tests\mocks\core\domain\DomainMock' - ), - array() - ); - } - - - public function test_constructor_with_invalid_arguments_2() - { - $this->setExceptionExpected('InvalidArgumentException'); - DomainFactory::getShared( - new FullyQualifiedName( - 'EventEspresso\tests\mocks\core\domain\DomainMock' - ), - array(new FilePath(EE_TESTS_DIR . 'mocks/core/domain/DomainMock.php')) - ); - } - - - public function test_constructor_with_invalid_arguments_3() - { - $this->setExceptionExpected('DomainException'); - DomainFactory::getShared( - new FullyQualifiedName( - 'EventEspresso\core\domain\values\FilePath' - ), - array( - EE_TESTS_DIR . 'mocks/core/domain/DomainMock.php', - '1.2.3.p' - ) - ); - } - -} -// Location: DomainFactoryTest.php diff --git a/tests/testcases/core/domain/entities/DbSafeDateTimeTest.php b/tests/testcases/core/domain/entities/DbSafeDateTimeTest.php deleted file mode 100644 index 9ad38fd4543..00000000000 --- a/tests/testcases/core/domain/entities/DbSafeDateTimeTest.php +++ /dev/null @@ -1,69 +0,0 @@ -assertEquals( - $original_datetime->format('Y-m-d H:m:i'), - $test_datetime->format('Y-m-d H:m:i'), - sprintf('The timezone string: %s isn\'t working', $timezone_string) - ); - } - } - - - - public function test_serialization_and_unserialization_with_empty_datetime_string() - { - $utc = new DateTimeZone('UTC'); - $empty_datetime = new DateTime('0000-00-00 00:00:00.000000', $utc); - $db_safe_datetime = new DbSafeDateTime($empty_datetime->format('Y-m-d H:i:s.u'), $utc); - // serializing the above will write to the PHP error log, - // so we are going to set that path to something else, so that we can grab that error - $log_file = EVENT_ESPRESSO_UPLOAD_DIR . 'logs/espresso_unit_tests_errors.log'; - EEH_File::ensure_file_exists_and_is_writable($log_file); - $db_safe_datetime->setErrorLogDir($log_file); - // now perform the serialization - $serialized_datetime = serialize($db_safe_datetime); - // and grab the error log file - $errors = file_get_contents($log_file); - if ($errors) { - $this->assertNotFalse(strpos($errors, 'A valid DateTime could not be generated')); - } - unlink($log_file); - $db_safe_datetime = unserialize($serialized_datetime); - $this->assertInstanceOf('DateTime', $db_safe_datetime); - // ensures date has been coerced to something more valid. - $this->assertEquals( - '0000-01-03 00:00:00.000000', - $db_safe_datetime->format('Y-m-d H:i:s.u') - ); - } -} diff --git a/tests/testcases/core/domain/entities/route_match/DoesNotMatchRouteSpecificationTest.php b/tests/testcases/core/domain/entities/route_match/DoesNotMatchRouteSpecificationTest.php deleted file mode 100644 index d6d37bcf757..00000000000 --- a/tests/testcases/core/domain/entities/route_match/DoesNotMatchRouteSpecificationTest.php +++ /dev/null @@ -1,72 +0,0 @@ -getRouteMatchSpecification(); - return new DoesNotMatchRouteSpecification($route_match_specification); - } - - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\Exception - */ - public function test__construct() - { - // useless test but need to override parent constructor - $this->assertInstanceOf( - 'EventEspresso\core\domain\entities\route_match\DoesNotMatchRouteSpecification', - $this->getDecorator() - ); - - } - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\AssertionFailedError - */ - public function testIsMatchingRoute() - { - // not testing 1-2-1-2 request - $route_match_specification = $this->getRouteMatchSpecification(array('another' => 'request')); - $route_match_specification->setParam('testing'); - $route_match_specification->setValue('one-two-one-two'); - $decorator = $this->getDecorator($route_match_specification); - // IT'S OPPOSITE DAY!!! - $this->assertTrue($decorator->isMatchingRoute()); - // testing 1-2-1-2 request but checking for other route - $route_match_specification = $this->getRouteMatchSpecification(array('testing' => 'one-two-one-two')); - $route_match_specification->setParam('testing'); - $route_match_specification->setValue('one-two-three'); - $decorator = $this->getDecorator($route_match_specification); - // IT'S OPPOSITE DAY!!! - $this->assertTrue($decorator->isMatchingRoute()); - // testing 1-2-1-2 request and route - $route_match_specification = $this->getRouteMatchSpecification(array('testing' => 'one-two-one-two')); - $route_match_specification->setParam('testing'); - $route_match_specification->setValue('one-two-one-two'); - $decorator = $this->getDecorator($route_match_specification); - // IT'S OPPOSITE DAY!!! - $this->assertFalse($decorator->isMatchingRoute()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/domain/entities/route_match/MatchAllRouteSpecificationsTest.php b/tests/testcases/core/domain/entities/route_match/MatchAllRouteSpecificationsTest.php deleted file mode 100644 index 34c341e66bc..00000000000 --- a/tests/testcases/core/domain/entities/route_match/MatchAllRouteSpecificationsTest.php +++ /dev/null @@ -1,54 +0,0 @@ -getRequest($this->request_params) - ); - } - - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\AssertionFailedError - * @throws \EventEspresso\core\exceptions\InvalidEntityException - */ - public function testIsMatchingRoute() - { - $route_match_specification = $this->getMultiRouteSpecification( - array( - $this->getRouteMatchOne(), - $this->getRouteMatchTwo(), - ) - ); - $this->assertTrue($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array( - $this->getRouteMatchOne(), - $this->getRouteMatchTwo(), - // will not match - $this->getRouteMatchThree(), - ) - ); - $this->assertFalse($route_match_specification->isMatchingRoute()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/domain/entities/route_match/MatchAnyRouteSpecificationTest.php b/tests/testcases/core/domain/entities/route_match/MatchAnyRouteSpecificationTest.php deleted file mode 100644 index 38c1f2e6a77..00000000000 --- a/tests/testcases/core/domain/entities/route_match/MatchAnyRouteSpecificationTest.php +++ /dev/null @@ -1,55 +0,0 @@ -getRequest($this->request_params) - ); - } - - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\AssertionFailedError - * @throws \EventEspresso\core\exceptions\InvalidEntityException - */ - public function testIsMatchingRoute() - { - $route_match_specification = $this->getMultiRouteSpecification( - array( - $this->getRouteMatchOne(), - $this->getRouteMatchTwo(), - ) - ); - $this->assertTrue($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array( - // will not match but test will pass after hitting the next spec - $this->getRouteMatchThree(), - $this->getRouteMatchOne(), - $this->getRouteMatchTwo(), - ) - ); - $this->assertTrue($route_match_specification->isMatchingRoute()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/domain/entities/route_match/MultiRouteSpecificationTest.php b/tests/testcases/core/domain/entities/route_match/MultiRouteSpecificationTest.php deleted file mode 100644 index bc8281b96ad..00000000000 --- a/tests/testcases/core/domain/entities/route_match/MultiRouteSpecificationTest.php +++ /dev/null @@ -1,103 +0,0 @@ -getRequest($this->request_params) - ); - } - - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\Exception - * @throws \EventEspresso\core\exceptions\InvalidEntityException - */ - public function test__construct() - { - $this->assertInstanceOf( - 'EventEspresso\tests\mocks\core\domain\entities\route_match\MultiRouteSpecificationMock', - $this->getMultiRouteSpecification( - array( - $this->getRouteMatchOne(), - $this->getRouteMatchTwo(), - ) - ) - ); - } - - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\Exception - * @throws \EventEspresso\core\exceptions\InvalidEntityException - */ - public function test__constructWithBadParameters() - { - $exception = 'EventEspresso\core\exceptions\InvalidEntityException'; - if (method_exists($this, 'expectException')) { - $this->expectException($exception); - } elseif (method_exists($this, 'setExpectedException')) { - $this->setExpectedException($exception); - } - $this->assertInstanceOf( - 'EventEspresso\tests\mocks\core\domain\entities\route_match\MultiRouteSpecificationMock', - $this->getMultiRouteSpecification( - array( - new stdClass(), - "what the heck... I'm not even an object!?!?!?" - ) - ) - ); - } - - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\AssertionFailedError - * @throws \EventEspresso\core\exceptions\InvalidEntityException - */ - public function testIsMatchingRoute() - { - $route_match_specification = $this->getMultiRouteSpecification( - array( - $this->getRouteMatchOne(), - $this->getRouteMatchTwo(), - ) - ); - $route_match_specification->addResults(true); - $route_match_specification->addResults(true); - $this->assertTrue($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array( - $this->getRouteMatchOne(), - $this->getRouteMatchTwo(), - // should return false - $this->getRouteMatchThree(), - ) - ); - $route_match_specification->addResults(true); - $route_match_specification->addResults(true); - $route_match_specification->addResults(false); - $this->assertTrue($route_match_specification->isMatchingRoute()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/domain/entities/route_match/MultiRouteSpecificationTestBase.php b/tests/testcases/core/domain/entities/route_match/MultiRouteSpecificationTestBase.php deleted file mode 100644 index dec361c0553..00000000000 --- a/tests/testcases/core/domain/entities/route_match/MultiRouteSpecificationTestBase.php +++ /dev/null @@ -1,76 +0,0 @@ - '1', - 'two' => '2', - ); - - /** - * @since 4.9.71.p - * @return \EventEspresso\tests\mocks\core\domain\entities\route_match\RouteMatchSpecificationMock - */ - public function getRouteMatchOne() - { - $route_match_specification = $this->getRouteMatchSpecification($this->request_params); - $route_match_specification->setParam('one'); - $route_match_specification->setValue('1'); - return $route_match_specification; - } - - /** - * @since 4.9.71.p - * @return \EventEspresso\tests\mocks\core\domain\entities\route_match\RouteMatchSpecificationMock - */ - public function getRouteMatchTwo() - { - $route_match_specification = $this->getRouteMatchSpecification($this->request_params); - $route_match_specification->setParam('two'); - $route_match_specification->setValue('2'); - return $route_match_specification; - } - - /** - * @since 4.9.71.p - * @return \EventEspresso\tests\mocks\core\domain\entities\route_match\RouteMatchSpecificationMock - */ - public function getRouteMatchThree() - { - $route_match_specification = $this->getRouteMatchSpecification($this->request_params); - $route_match_specification->setParam('three'); - $route_match_specification->setValue('3'); - return $route_match_specification; - } - - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\Exception - * @throws \EventEspresso\core\exceptions\InvalidEntityException - */ - public function testRouteConstructors() - { - $this->assertInstanceOf( - 'EventEspresso\tests\mocks\core\domain\entities\route_match\RouteMatchSpecificationMock', - $this->getRouteMatchOne() - ); - $this->assertInstanceOf( - 'EventEspresso\tests\mocks\core\domain\entities\route_match\RouteMatchSpecificationMock', - $this->getRouteMatchTwo() - ); - $this->assertInstanceOf( - 'EventEspresso\tests\mocks\core\domain\entities\route_match\RouteMatchSpecificationMock', - $this->getRouteMatchThree() - ); - } -} \ No newline at end of file diff --git a/tests/testcases/core/domain/entities/route_match/RouteMatchSpecificationDecoratorTest.php b/tests/testcases/core/domain/entities/route_match/RouteMatchSpecificationDecoratorTest.php deleted file mode 100644 index 2af5869f078..00000000000 --- a/tests/testcases/core/domain/entities/route_match/RouteMatchSpecificationDecoratorTest.php +++ /dev/null @@ -1,69 +0,0 @@ -getRouteMatchSpecification(); - return new RouteMatchSpecificationDecoratorMock($route_match_specification); - } - - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\Exception - */ - public function test__construct() - { - $this->assertInstanceOf( - 'EventEspresso\tests\mocks\core\domain\entities\route_match\RouteMatchSpecificationMock', - $this->getDecorator()->getSpecification() - ); - - } - - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\AssertionFailedError - */ - public function testIsMatchingRoute() - { - // not testing 1-2-1-2 request - $route_match_specification = $this->getRouteMatchSpecification(array('another' => 'request')); - $route_match_specification->setParam('testing'); - $route_match_specification->setValue('one-two-one-two'); - $decorator = $this->getDecorator($route_match_specification); - $this->assertFalse($decorator->isMatchingRoute()); - // testing 1-2-1-2 request but checking for other route - $route_match_specification = $this->getRouteMatchSpecification(array('testing' => 'one-two-one-two')); - $route_match_specification->setParam('testing'); - $route_match_specification->setValue('one-two-three'); - $decorator = $this->getDecorator($route_match_specification); - $this->assertFalse($decorator->isMatchingRoute()); - // testing 1-2-1-2 request and route - $route_match_specification = $this->getRouteMatchSpecification(array('testing' => 'one-two-one-two')); - $route_match_specification->setParam('testing'); - $route_match_specification->setValue('one-two-one-two'); - $decorator = $this->getDecorator($route_match_specification); - $this->assertTrue($decorator->isMatchingRoute()); - } -} diff --git a/tests/testcases/core/domain/entities/route_match/RouteMatchSpecificationTest.php b/tests/testcases/core/domain/entities/route_match/RouteMatchSpecificationTest.php deleted file mode 100644 index 73be65ea22b..00000000000 --- a/tests/testcases/core/domain/entities/route_match/RouteMatchSpecificationTest.php +++ /dev/null @@ -1,44 +0,0 @@ -getRouteMatchSpecification(array('another' => 'request')); - $route_match_specification->setParam('testing'); - $route_match_specification->setValue('one-two-one-two'); - $this->assertFalse( - $route_match_specification->isMatchingRoute() - ); - // testing 1-2-1-2 request but checking for other route - $route_match_specification = $this->getRouteMatchSpecification(array('testing' => 'one-two-one-two')); - $route_match_specification->setParam('testing'); - $route_match_specification->setValue('one-two-three'); - $this->assertFalse( - $route_match_specification->isMatchingRoute() - ); - // testing 1-2-1-2 request and route - $route_match_specification = $this->getRouteMatchSpecification(array('testing' => 'one-two-one-two')); - $route_match_specification->setParam('testing'); - $route_match_specification->setValue('one-two-one-two'); - $this->assertTrue( - $route_match_specification->isMatchingRoute() - ); - } -} - -// location: /testcases/core/domain/entities/route_match/RouteMatchSpecificationTest.php \ No newline at end of file diff --git a/tests/testcases/core/domain/entities/route_match/RouteMatchSpecificationTestBase.php b/tests/testcases/core/domain/entities/route_match/RouteMatchSpecificationTestBase.php deleted file mode 100644 index 73e1943f846..00000000000 --- a/tests/testcases/core/domain/entities/route_match/RouteMatchSpecificationTestBase.php +++ /dev/null @@ -1,59 +0,0 @@ -getRequest($get, $post, $cookie, $server, $files) - ); - } - - /** - * @since 4.9.71.p - * @return Request - */ - protected function getRequest( - array $get = array(), - array $post = array(), - array $cookie = array(), - array $server = array(), - array $files = array() - ) { - return new Request($get, $post, $cookie, $server, $files); - } - - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\Exception - */ - public function test__construct() - { - $this->assertInstanceOf( - 'EventEspresso\tests\mocks\core\domain\entities\route_match\RouteMatchSpecificationMock', - $this->getRouteMatchSpecification() - ); - } -} -// location: /testcases/core/domain/entities/route_match/RouteMatchSpecificationTest.php diff --git a/tests/testcases/core/domain/entities/route_match/admin/EspressoEventEditorAddNewTest.php b/tests/testcases/core/domain/entities/route_match/admin/EspressoEventEditorAddNewTest.php deleted file mode 100644 index cd63fd07b18..00000000000 --- a/tests/testcases/core/domain/entities/route_match/admin/EspressoEventEditorAddNewTest.php +++ /dev/null @@ -1,51 +0,0 @@ -getRequest($request_params)); - } - - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\AssertionFailedError - * @throws \EventEspresso\core\exceptions\InvalidEntityException - */ - public function testIsMatchingRoute() - { - $route_match_specification = $this->getMultiRouteSpecification( - array( - 'page' => 'espresso_events', - 'action' => 'create_new', - ) - ); - $this->assertTrue($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array( - 'page' => 'not_espresso_page', - 'action' => 'WSOD', - ) - ); - $this->assertFalse($route_match_specification->isMatchingRoute()); - } -} diff --git a/tests/testcases/core/domain/entities/route_match/admin/EspressoEventEditorEditTest.php b/tests/testcases/core/domain/entities/route_match/admin/EspressoEventEditorEditTest.php deleted file mode 100644 index 4d36621b90b..00000000000 --- a/tests/testcases/core/domain/entities/route_match/admin/EspressoEventEditorEditTest.php +++ /dev/null @@ -1,51 +0,0 @@ -getRequest($request_params)); - } - - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\AssertionFailedError - * @throws \EventEspresso\core\exceptions\InvalidEntityException - */ - public function testIsMatchingRoute() - { - $route_match_specification = $this->getMultiRouteSpecification( - array( - 'page' => 'espresso_events', - 'action' => 'edit', - ) - ); - $this->assertTrue($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array( - 'page' => 'not_espresso_page', - 'action' => 'WSOD', - ) - ); - $this->assertFalse($route_match_specification->isMatchingRoute()); - } -} diff --git a/tests/testcases/core/domain/entities/route_match/admin/EspressoEventEditorTest.php b/tests/testcases/core/domain/entities/route_match/admin/EspressoEventEditorTest.php deleted file mode 100644 index 15a5f71b9c4..00000000000 --- a/tests/testcases/core/domain/entities/route_match/admin/EspressoEventEditorTest.php +++ /dev/null @@ -1,65 +0,0 @@ -getRequest($request_params); - return new EspressoEventEditor( - new EspressoEventEditorEdit($request), - new EspressoEventEditorAddNew($request), - $request - ); - } - - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\AssertionFailedError - * @throws \EventEspresso\core\exceptions\InvalidEntityException - */ - public function testIsMatchingRoute() - { - $route_match_specification = $this->getMultiRouteSpecification( - array( - 'page' => 'espresso_events', - 'action'=> 'edit', - ) - ); - $this->assertTrue($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array( - 'page' => 'espresso_events', - 'action'=> 'create_new', - ) - ); - $this->assertTrue($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array( - 'page' => 'not_espresso_page', - 'action' => 'WSOD', - ) - ); - $this->assertFalse($route_match_specification->isMatchingRoute()); - } -} diff --git a/tests/testcases/core/domain/entities/route_match/admin/EspressoEventsListTableTest.php b/tests/testcases/core/domain/entities/route_match/admin/EspressoEventsListTableTest.php deleted file mode 100644 index 6ce2c437147..00000000000 --- a/tests/testcases/core/domain/entities/route_match/admin/EspressoEventsListTableTest.php +++ /dev/null @@ -1,55 +0,0 @@ -getRequest($request_params)); - } - - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\AssertionFailedError - * @throws \EventEspresso\core\exceptions\InvalidEntityException - */ - public function testIsMatchingRoute() - { - $route_match_specification = $this->getMultiRouteSpecification( - array('page' => 'espresso_events') - ); - $this->assertTrue($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array( - 'page' => 'espresso_events', - 'action' => 'default', - ) - ); - $this->assertTrue($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array( - 'page' => 'not_espresso_page', - 'action' => 'WSOD', - ) - ); - $this->assertFalse($route_match_specification->isMatchingRoute()); - } -} diff --git a/tests/testcases/core/domain/entities/route_match/admin/WordPressPostsEditorAddNewTest.php b/tests/testcases/core/domain/entities/route_match/admin/WordPressPostsEditorAddNewTest.php deleted file mode 100644 index eacaa9e117e..00000000000 --- a/tests/testcases/core/domain/entities/route_match/admin/WordPressPostsEditorAddNewTest.php +++ /dev/null @@ -1,65 +0,0 @@ -getRequest($request_params, array(), array(), $server) - ); - } - - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\AssertionFailedError - * @throws \EventEspresso\core\exceptions\InvalidEntityException - */ - public function testIsMatchingRoute() - { - $route_match_specification = $this->getMultiRouteSpecification( - array(), - array('REQUEST_URI' => 'wp-admin/post-new.php') - ); - $this->assertTrue($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array('post_type' => 'post'), - array('REQUEST_URI' => 'wp-admin/post-new.php') - ); - $this->assertTrue($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array('post_type' => 'post'), - array('REQUEST_URI' => 'wp-admin/post.php') - ); - $this->assertFalse($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array('post_type' => 'custom-post-type'), - array('REQUEST_URI' => 'wp-admin/post-new.php') - ); - $this->assertFalse($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array('post_type' => 'post'), - array('REQUEST_URI' => 'wp-admin/telephone-post.php') - ); - $this->assertFalse($route_match_specification->isMatchingRoute()); - } -} diff --git a/tests/testcases/core/domain/entities/route_match/admin/WordPressPostsEditorEditTest.php b/tests/testcases/core/domain/entities/route_match/admin/WordPressPostsEditorEditTest.php deleted file mode 100644 index 5e7ce728e32..00000000000 --- a/tests/testcases/core/domain/entities/route_match/admin/WordPressPostsEditorEditTest.php +++ /dev/null @@ -1,142 +0,0 @@ -getRequest($request_params, $post_params, array(), $server) - ); - } - - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\AssertionFailedError - * @throws \EventEspresso\core\exceptions\InvalidEntityException - */ - public function testIsMatchingRoute() - { - // with $_GET params - $route_match_specification = $this->getMultiRouteSpecification( - array( - 'post_type' => 'post', - 'action' => 'edit', - ), - array(), - array('REQUEST_URI' => 'wp-admin/post.php') - ); - $this->assertTrue($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array('post_type' => 'post'), - array(), - array('REQUEST_URI' => 'wp-admin/post.php') - ); - $this->assertFalse($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array('action' => 'edit'), - array(), - array('REQUEST_URI' => 'wp-admin/post-new.php') - ); - $this->assertFalse($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array( - 'post_type' => 'custom-post-type', - 'action' => 'edit', - ), - array(), - array('REQUEST_URI' => 'wp-admin/post.php') - ); - $this->assertFalse($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array( - 'post_type' => 'post', - 'action' => 'edit', - ), - array(), - array('REQUEST_URI' => 'wp-admin/telephone-post.php') - ); - $this->assertFalse($route_match_specification->isMatchingRoute()); - - // with $_POST params - $route_match_specification = $this->getMultiRouteSpecification( - array(), - array( - 'post_type' => 'post', - 'action' => 'edit', - ), - array('REQUEST_URI' => 'wp-admin/post.php') - ); - $this->assertTrue($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array(), - array('post_type' => 'post'), - array('REQUEST_URI' => 'wp-admin/post.php') - ); - $this->assertFalse($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array(), - array('action' => 'edit'), - array('REQUEST_URI' => 'wp-admin/post-new.php') - ); - $this->assertFalse($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array(), - array( - 'post_type' => 'custom-post-type', - 'action' => 'edit', - ), - array('REQUEST_URI' => 'wp-admin/post.php') - ); - $this->assertFalse($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array(), - array( - 'post_type' => 'post', - 'action' => 'edit', - ), - array('REQUEST_URI' => 'wp-admin/telephone-post.php') - ); - $this->assertFalse($route_match_specification->isMatchingRoute()); - - // with $_GET && $_POST params - $route_match_specification = $this->getMultiRouteSpecification( - array('action' => 'edit'), - array('post_type' => 'post'), - array('REQUEST_URI' => 'wp-admin/post.php') - ); - $this->assertTrue($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array('action' => 'edit'), - array('post_type' => 'custom-post-type'), - array('REQUEST_URI' => 'wp-admin/post.php') - ); - $this->assertFalse($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array('action' => 'edit'), - array('post_type' => 'post'), - array('REQUEST_URI' => 'wp-admin/telephone-post.php') - ); - $this->assertFalse($route_match_specification->isMatchingRoute()); - } -} -// location: testcases/core/domain/entities/route_match/admin/WordPressPostsEditorEditTest.php diff --git a/tests/testcases/core/domain/entities/route_match/admin/WordPressPostsEditorTest.php b/tests/testcases/core/domain/entities/route_match/admin/WordPressPostsEditorTest.php deleted file mode 100644 index affceff05f3..00000000000 --- a/tests/testcases/core/domain/entities/route_match/admin/WordPressPostsEditorTest.php +++ /dev/null @@ -1,78 +0,0 @@ -getRequest($request_params, array(), array(), $server); - return new WordPressPostsEditor( - new WordPressPostsEditorEdit($request), - new WordPressPostsEditorAddNew($request), - $request - ); - } - - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\AssertionFailedError - * @throws \EventEspresso\core\exceptions\InvalidEntityException - */ - public function testIsMatchingRoute() - { - $route_match_specification = $this->getMultiRouteSpecification( - array(), - array('REQUEST_URI' => 'wp-admin/post-new.php') - ); - $this->assertTrue($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array( - 'post_type' => 'post', - 'action' => 'edit', - ), - array('REQUEST_URI' => 'wp-admin/post.php') - ); - $this->assertTrue($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array('post_type' => 'post'), - array('REQUEST_URI' => 'wp-admin/post-new.php') - ); - $this->assertTrue($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array('post_type' => 'post'), - array('REQUEST_URI' => 'wp-admin/post.php') - ); - $this->assertFalse($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array('post_type' => 'custom-post-type'), - array('REQUEST_URI' => 'wp-admin/post-new.php') - ); - $this->assertFalse($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array('post_type' => 'post'), - array('REQUEST_URI' => 'wp-admin/telephone-post.php') - ); - $this->assertFalse($route_match_specification->isMatchingRoute()); - } -} diff --git a/tests/testcases/core/domain/entities/route_match/admin/WordPressPostsListTableTest.php b/tests/testcases/core/domain/entities/route_match/admin/WordPressPostsListTableTest.php deleted file mode 100644 index e3040819fd9..00000000000 --- a/tests/testcases/core/domain/entities/route_match/admin/WordPressPostsListTableTest.php +++ /dev/null @@ -1,54 +0,0 @@ -getRequest($request_params, array(), array(), $server) - ); - } - - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\AssertionFailedError - * @throws \EventEspresso\core\exceptions\InvalidEntityException - */ - public function testIsMatchingRoute() - { - $route_match_specification = $this->getMultiRouteSpecification( - array('post_type' => 'post'), - array('REQUEST_URI' => 'wp-admin/edit.php') - ); - $this->assertTrue($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array('post_type' => 'post'), - array('REQUEST_URI' => 'wp-admin/post.php') - ); - $this->assertFalse($route_match_specification->isMatchingRoute()); - $route_match_specification = $this->getMultiRouteSpecification( - array('post_type' => 'custom-post-type'), - array('REQUEST_URI' => 'wp-admin/edit.php') - ); - $this->assertFalse($route_match_specification->isMatchingRoute()); - } -} diff --git a/tests/testcases/core/domain/services/admin/registrations/list_table/QueryBuilderTest.php b/tests/testcases/core/domain/services/admin/registrations/list_table/QueryBuilderTest.php deleted file mode 100644 index c3bc51dfb51..00000000000 --- a/tests/testcases/core/domain/services/admin/registrations/list_table/QueryBuilderTest.php +++ /dev/null @@ -1,392 +0,0 @@ -'; - - /** - * @param array $get_params - * @return QueryBuilderMock - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @since 4.10.2.p - */ - private function getQueryBuilder(array $get_params) - { - return new QueryBuilderMock( - [], - new RequestMock($get_params, [], [], [], []), - EEM_Registration::instance() - ); - } - - - /** - * @param string $addIdMethod - * @param string $key - * @param array $get_params - * @param bool $exists - * @param int $expected - * @throws EE_Error - * @throws Exception - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - */ - private function addIdToWhereConditions($addIdMethod, $key, array $get_params, $exists, $expected) - { - $QB = $this->getQueryBuilder($get_params); - $QB->$addIdMethod(); - $where_params = $QB->getWhereParams(); - if ($exists) { - $this->assertArrayHasKey($key, $where_params); - $this->assertEquals($expected, $where_params[ $key ]); - } else { - $this->assertArrayNotHasKey($key, $where_params); - } - } - - - /** - * returns following parameters: - * $get_params array of simulated $_GET params - * $exists whether key should exist - * $expected value of $_GET param - * - * @return array - */ - public function attendeeIdProvider() - { - return [ - // empty array - [[], false, null], - // invalid keys - [['ATT-ID' => 123], false, null], - [['attendee-id' => 123], false, null], - // invalid values - [['ATT_ID' => '

    big honkin cabbage

    '], true, 0], - [['ATT_ID' => $this->xss], true, 0], - [['attendee_id' => '

    big honkin cabbage

    '], true, 0], - [['attendee_id' => $this->xss], true, 0], - // all good - [['ATT_ID' => 123], true, 123], - [['ATT_ID' => '123'], true, 123], - [['attendee_id' => 123], true, 123], - [['attendee_id' => '123'], true, 123], - ]; - } - - - /** - * @dataProvider attendeeIdProvider - * @param array $get_params - * @param bool $exists - * @param int $expected - * @throws EE_Error - * @throws Exception - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - */ - public function testAddAttendeeIdToWhereConditions(array $get_params, $exists, $expected) - { - $this->addIdToWhereConditions( - 'addAttendeeIdToWhereConditions', - 'ATT_ID', - $get_params, - $exists, - $expected - ); - } - - - /** - * returns following parameters: - * $get_params array of simulated $_GET params - * $exists whether key should exist - * $expected value of $_GET param - * - * @return array - */ - public function eventIdProvider() - { - return [ - // empty array - [[], false, null], - // invalid keys - [['EVT-ID' => 123], false, null], - [['event-id' => 123], false, null], - // invalid values - [['EVT_ID' => '

    big honkin cabbage

    '], true, 0], - [['EVT_ID' => $this->xss], true, 0], - [['event_id' => '

    big honkin cabbage

    '], true, 0], - [['event_id' => $this->xss], true, 0], - // all good - [['EVT_ID' => 123], true, 123], - [['EVT_ID' => '123'], true, 123], - [['event_id' => 123], true, 123], - [['event_id' => '123'], true, 123], - ]; - } - - - /** - * @dataProvider eventIdProvider - * @param array $get_params - * @param bool $exists - * @param int $expected - * @throws EE_Error - * @throws Exception - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - */ - public function testAddEventIdToWhereConditions(array $get_params, $exists, $expected) - { - $this->addIdToWhereConditions( - 'addEventIdToWhereConditions', - 'EVT_ID', - $get_params, - $exists, - $expected - ); - } - - - /** - * returns following parameters: - * $get_params array of simulated $_GET params - * $exists whether key should exist - * $expected value of $_GET param - * - * @return array - */ - public function categoryIdProvider() - { - return [ - // empty array - [[], false, null], - // invalid keys - [['EVT-CAT' => 123], false, null], - [['term_id' => 123], false, null], - [['Event.Term_Taxonomy.term_id' => 123], false, null], - // invalid values >>> PLZ NOTE: event category NOT added if value is not int > 0 !!! - [['EVT_CAT' => '

    big honkin cabbage

    '], false, 0], - [['EVT_CAT' => $this->xss], false, 0], - // all good - [['EVT_CAT' => 123], true, 123], - [['EVT_CAT' => '123'], true, 123], - ]; - } - - - /** - * @dataProvider categoryIdProvider - * @param array $get_params - * @param bool $exists - * @param int $expected - * @throws EE_Error - * @throws Exception - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - */ - public function testAddCategoryIdToWhereConditions(array $get_params, $exists, $expected) - { - $this->addIdToWhereConditions( - 'addCategoryIdToWhereConditions', - 'Event.Term_Taxonomy.term_id', - $get_params, - $exists, - $expected - ); - } - - - /** - * returns following parameters: - * $get_params array of simulated $_GET params - * $exists whether key should exist - * $expected value of $_GET param - * - * @return array - */ - public function datetimeIdProvider() - { - return [ - // empty array - [[], false, null], - // invalid keys - [['DTT-ID' => 123], false, null], - [['datetime-id' => 123], false, null], - [['Ticket.Datetime.DTT_ID' => 123], false, null], - // invalid values - [['DTT_ID' => '

    big honkin cabbage

    '], true, 0], - [['DTT_ID' => $this->xss], true, 0], - [['datetime_id' => '

    big honkin cabbage

    '], true, 0], - [['datetime_id' => $this->xss], true, 0], - // all good - [['DTT_ID' => 123], true, 123], - [['DTT_ID' => '123'], true, 123], - [['datetime_id' => 123], true, 123], - [['datetime_id' => '123'], true, 123], - ]; - } - - - /** - * @dataProvider datetimeIdProvider - * @param array $get_params - * @param bool $exists - * @param int $expected - * @throws EE_Error - * @throws Exception - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - */ - public function testAddDatetimeIdToWhereConditions(array $get_params, $exists, $expected) - { - $this->addIdToWhereConditions( - 'addDatetimeIdToWhereConditions', - 'Ticket.Datetime.DTT_ID', - $get_params, - $exists, - $expected - ); - } - - - /** - * returns following parameters: - * $get_params array of simulated $_GET params - * $exists whether key should exist - * $expected value of $_GET param - * - * @return array - */ - public function ticketIdProvider() - { - return [ - // empty array - [[], false, null], - // invalid keys - [['TKT-ID' => 123], false, null], - [['ticket-id' => 123], false, null], - // invalid values - [['TKT_ID' => '

    big honkin cabbage

    '], true, 0], - [['TKT_ID' => $this->xss], true, 0], - [['ticket_id' => '

    big honkin cabbage

    '], true, 0], - [['ticket_id' => $this->xss], true, 0], - // all good - [['TKT_ID' => 123], true, 123], - [['TKT_ID' => '123'], true, 123], - [['ticket_id' => 123], true, 123], - [['ticket_id' => '123'], true, 123], - ]; - } - - - /** - * @dataProvider ticketIdProvider - * @param array $get_params - * @param bool $exists - * @param int $expected - * @throws EE_Error - * @throws Exception - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - */ - public function testAddTicketIdToWhereConditions(array $get_params, $exists, $expected) - { - $this->addIdToWhereConditions( - 'addTicketIdToWhereConditions', - 'TKT_ID', - $get_params, - $exists, - $expected - ); - } - - - /** - * returns following parameters: - * $key the where parameter that was set - * $get_params array of simulated $_GET params - * $exists whether key should exist - * $expected value of $_GET param - * - * @return array - */ - public function registrationStatusProvider() - { - $default = ['!=', 'RIC']; - return [ - // no reg status set, but different views - ['STS_ID', [], true, $default], - ['STS_ID', ['status' => 'month'], true, $default], - ['STS_ID', ['status' => 'today'], true, $default], - ['STS_ID', ['status' => 'incomplete'], true, 'RIC'], - ['STS_ID', ['status' => 'trash'], false, $default], - ['REG_deleted', ['status' => 'trash'], true, true], - // invalid keys - ['STS_ID', ['STS_ID' => 'RIC'], true, $default], - ['STS_ID', ['reg-status' => 'RIC'], true, $default], - ['STS_ID', ['reg-status' => 'RIC'], true, $default], - // invalid values - ['STS_ID', ['_reg_status' => '

    big honkin cabbage

    '], true, 'big honkin cabbage'], - ['STS_ID', ['_reg_status' => $this->xss], true, '">'], - // // all good - ['STS_ID', ['_reg_status' => 'RIC'], true, 'RIC'], - ['STS_ID', ['_reg_status' => 'RNA'], true, 'RNA'], - ['STS_ID', ['_reg_status' => 'RPP'], true, 'RPP'], - ['STS_ID', ['_reg_status' => 'RWL'], true, 'RWL'], - ['STS_ID', ['_reg_status' => 'RAP'], true, 'RAP'], - ['STS_ID', ['_reg_status' => 'RCN'], true, 'RCN'], - ['STS_ID', ['_reg_status' => 'RDC'], true, 'RDC'], - ]; - } - - - /** - * @dataProvider registrationStatusProvider - * @param string $key - * @param array $get_params - * @param bool $exists - * @param int $expected - * @throws EE_Error - * @throws Exception - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - */ - public function testAddRegistrationStatusToWhereConditions($key, array $get_params, $exists, $expected) - { - $this->addIdToWhereConditions( - 'addRegistrationStatusToWhereConditions', - $key, - $get_params, - $exists, - $expected - ); - } -} diff --git a/tests/testcases/core/domain/services/admin/registrations/list_table/page_header/AttendeeFilterHeaderTest.php b/tests/testcases/core/domain/services/admin/registrations/list_table/page_header/AttendeeFilterHeaderTest.php deleted file mode 100644 index 8e4ed6beaab..00000000000 --- a/tests/testcases/core/domain/services/admin/registrations/list_table/page_header/AttendeeFilterHeaderTest.php +++ /dev/null @@ -1,182 +0,0 @@ -'; - - - public static function setUpBeforeClass() - { - require_once EE_ADMIN . 'EE_Admin_Page.core.php'; - if (! defined('REG_ADMIN_URL')) { - define('REG_ADMIN_URL', admin_url('admin.php?page=espresso_registrations')); - } - } - - - /** - * @throws EE_Error - * @throws Exception - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - * @since 4.10.2.p - */ - public function setUp() - { - $this->setUpAttendee(); - } - - /** - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - * @throws Exception - * @since 4.10.2.p - */ - public function setUpAttendee() - { - $this->attendee = EE_Attendee::new_instance([ - 'ATT_fname' => 'Shaggy', - 'ATT_lname' => 'Rogers', - 'ATT_email' => 'shaggy@mysterymachine.com' - ]); - $saved = $this->attendee->save(); - $this->assertTrue($saved > 0); - } - - - /** - * @param array $get_params - * @return AttendeeFilterHeader - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @since 4.10.2.p - */ - private function getAttendeeFilterHeader(array $get_params) - { - return new AttendeeFilterHeader( - new RequestMock($get_params, [], [], [], []), - EEM_Attendee::instance() - ); - } - - - /** - * generator function to replace phpunit's dataProvider - * because those run during initial phpunit setup - * and NOT when this actual test class is run, - * therefore making it impossible to create - * and save entities to the database in order to use - * their autoincrement IDs in this function - * and have those entities still exist when these - * testcases actually run. - * - * @return Generator - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - * @since 4.10.2.p - */ - public function testDataGenerator() - { - $ID = $this->attendee->ID(); - $site_admin_url = admin_url(); - $test_data = [ - // empty array - [[], ''], - // invalid keys - [['ATT-ID' => $ID], ''], - [['attendee-id' => $ID], ''], - // invalid values - [['ATT_ID' => '

    Ruh Oh

    '], ''], - [['ATT_ID' => $this->xss], ''], - [['attendee_id' => '

    Ruh Oh

    '], ''], - [['attendee_id' => $this->xss], ''], - // all good - [ - ['ATT_ID' => $ID], - '

    Viewing registrations for Shaggy Rogers

    ' - ], - [ - ['attendee_id' => $ID], - '

    Viewing registrations for Shaggy Rogers

    ' - ], - ]; - foreach ($test_data as $data) { - yield $data; - } - } - - - /** - * generator function to replace phpunit's dataProvider - * because those run during initial phpunit setup - * and NOT when this actual test class is run, - * therefore making it impossible to create - * and save entities to the database in order to use - * their autoincrement IDs in this function - * and have those entities still exist when these - * testcases actually run. - * - * @throws EE_Error - * @throws Exception - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - * @since 4.10.2.p - */ - public function testGetHeaderText() - { - foreach ($this->testDataGenerator() as list($get_params, $expected)) { - $this->assertInstanceOf('EE_Attendee', $this->attendee); - $attendee_filter_header = $this->getAttendeeFilterHeader($get_params); - $header_text = $attendee_filter_header->getHeaderText(); - // strip out nonce since it constantly changes - $header_text = preg_replace( - '/&edit_attendee_nonce=\S+"/', - '&edit_attendee_nonce="', - $header_text - ); - $this->assertEquals($expected, $header_text); - } - } -} diff --git a/tests/testcases/core/domain/services/admin/registrations/list_table/page_header/DateFilterHeaderTest.php b/tests/testcases/core/domain/services/admin/registrations/list_table/page_header/DateFilterHeaderTest.php deleted file mode 100644 index 81d88f48b61..00000000000 --- a/tests/testcases/core/domain/services/admin/registrations/list_table/page_header/DateFilterHeaderTest.php +++ /dev/null @@ -1,160 +0,0 @@ -'; - - - /** - * @throws EE_Error - * @throws Exception - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - * @since 4.10.2.p - */ - public function setUp() - { - $this->setUpDatetime(); - } - - /** - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - * @throws Exception - * @since 4.10.2.p - */ - public function setUpDatetime() - { - $this->datetime = EE_Datetime::new_instance([ - 'DTT_name' => 'Stephen Hawkingโ€™s Time Traveler Party', - ]); - $this->datetime->set_start_date('June 29, 2009'); - $this->datetime->set_end_date('June 29, 2009'); - $saved = $this->datetime->save(); - $this->assertTrue($saved > 0); - } - - - /** - * @param array $get_params - * @return DateFilterHeader - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws EE_Error - * @throws InvalidArgumentException - * @since 4.10.2.p - */ - private function getDateFilterHeader(array $get_params) - { - return new DateFilterHeader( - new RequestMock($get_params, [], [], [], []), - EEM_Datetime::instance() - ); - } - - - /** - * generator function to replace phpunit's dataProvider - * because those run during initial phpunit setup - * and NOT when this actual test class is run, - * therefore making it impossible to create - * and save entities to the database in order to use - * their autoincrement IDs in this function - * and have those entities still exist when these - * testcases actually run. - * - * @return Generator - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - * @since 4.10.2.p - */ - public function testDataGenerator() - { - $date = $this->datetime->start_date('F d, Y'); - $test_data = [ - // empty array - [[], '', ''], - // invalid keys - [['DTT-ID' => $this->datetime->ID()], '', ''], - [['datetime-id' => $this->datetime->ID()], '', ''], - // invalid values - [['DTT_ID' => '

    I am from the Future!!!

    '], '', ''], - [['DTT_ID' => $this->xss], '', ''], - [['datetime_id' => '

    I am from the Future!!!

    '], '', ''], - [['datetime_id' => $this->xss], '', ''], - [['DTT_ID' => '

    I am from the Future!!!

    '], 'Event Details', 'Event Details'], - [['DTT_ID' => $this->xss], 'Event Details', 'Event Details'], - [['datetime_id' => '

    I am from the Future!!!

    '], 'Event Details', 'Event Details'], - [['datetime_id' => $this->xss], 'Event Details', 'Event Details'], - // all good - [['DTT_ID' => $this->datetime->ID()], '', ''], - [ - ['DTT_ID' => $this->datetime->ID()], - 'Event Details', - 'Event Details    Stephen Hawkingโ€™s Time Traveler Party ( ' . $date . ' )' - ], - [['datetime_id' => $this->datetime->ID()], '', ''], - [ - ['datetime_id' => $this->datetime->ID()], - 'Event Details', - 'Event Details    Stephen Hawkingโ€™s Time Traveler Party ( ' . $date . ' )' - ], - ]; - foreach ($test_data as $data) { - yield $data; - } - } - - - /** - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @since 4.10.2.p - */ - public function testGetHeaderText() - { - foreach ($this->testDataGenerator() as list($get_params, $event_text, $expected)) { - $datetime_filter_header = $this->getDateFilterHeader($get_params); - $header_text = $datetime_filter_header->getHeaderText($event_text); - $this->assertEquals($expected, $header_text); - } - } -} diff --git a/tests/testcases/core/domain/services/admin/registrations/list_table/page_header/EventFilterHeaderTest.php b/tests/testcases/core/domain/services/admin/registrations/list_table/page_header/EventFilterHeaderTest.php deleted file mode 100644 index 0304b309741..00000000000 --- a/tests/testcases/core/domain/services/admin/registrations/list_table/page_header/EventFilterHeaderTest.php +++ /dev/null @@ -1,165 +0,0 @@ -'; - - - public static function setUpBeforeClass() - { - require_once EE_ADMIN . 'EE_Admin_Page.core.php'; - if (! defined('EVENTS_ADMIN_URL')) { - define('EVENTS_ADMIN_URL', admin_url('admin.php?page=espresso_events')); - } - } - - - /** - * @throws EE_Error - * @throws Exception - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - * @since 4.10.2.p - */ - public function setUp() - { - $this->setUpEvent(); - } - - /** - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - * @throws Exception - * @throws InvalidArgumentException - * @since 4.10.2.p - */ - public function setUpEvent() - { - $this->event = EE_Event::new_instance([ - 'EVT_name' => 'Stephen Hawkingโ€™s Time Traveler Party', - ]); - $saved = $this->event->save(); - $this->assertTrue($saved > 0); - } - - - /** - * @param array $get_params - * @return EventFilterHeader - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidArgumentException - * @since 4.10.2.p - */ - private function getEventFilterHeader(array $get_params) - { - return new EventFilterHeader( - new RequestMock($get_params, [], [], [], []), - EEM_Event::instance() - ); - } - - - /** - * generator function to replace phpunit's dataProvider - * because those run during initial phpunit setup - * and NOT when this actual test class is run, - * therefore making it impossible to create - * and save entities to the database in order to use - * their autoincrement IDs in this function - * and have those entities still exist when these - * testcases actually run. - * - * @return Generator - * @since 4.10.2.p - */ - public function testDataGenerator() - { - $ID = $this->event->ID(); - $site_admin_url = admin_url(); - $test_data = [ - // empty array - [[], ''], - // invalid keys - [['EVT-ID' => $ID], ''], - [['event-id' => $ID], ''], - // invalid values - [['EVT_ID' => '

    I am from the Future!!!

    '], ''], - [['EVT_ID' => $this->xss], ''], - [['event_id' => '

    I am from the Future!!!

    '], ''], - [['event_id' => $this->xss], ''], - // all good - [ - ['EVT_ID' => $ID], - '

    Viewing registrations for the event:  Stephen Hawkingโ€™s Time Traveler Party 

    ' - ], - [ - ['event_id' => $ID], - '

    Viewing registrations for the event:  Stephen Hawkingโ€™s Time Traveler Party 

    ' - ], - ]; - foreach ($test_data as $data) { - yield $data; - } - } - - - /** - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws EE_Error - * @throws ReflectionException - * @throws Exception - * @since 4.10.2.p - */ - public function testGetHeaderText() - { - foreach ($this->testDataGenerator() as list($get_params, $expected)) { - $this->assertInstanceOf('EE_Event', $this->event); - $event_filter_header = $this->getEventFilterHeader($get_params); - $header_text = $event_filter_header->getHeaderText(); - // strip out nonce since it constantly changes - $header_text = preg_replace('/&edit_nonce=\S+"/', '&edit_nonce="', $header_text); - $this->assertEquals($expected, $header_text); - } - } -} diff --git a/tests/testcases/core/domain/services/admin/registrations/list_table/page_header/TicketFilterHeaderTest.php b/tests/testcases/core/domain/services/admin/registrations/list_table/page_header/TicketFilterHeaderTest.php deleted file mode 100644 index 466772d1639..00000000000 --- a/tests/testcases/core/domain/services/admin/registrations/list_table/page_header/TicketFilterHeaderTest.php +++ /dev/null @@ -1,182 +0,0 @@ -'; - - - /** - * @throws AssertionFailedError - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - * @since 4.10.2.p - */ - public function setUp() - { - $this->setUpTickets(); - } - - /** - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - * @throws InvalidArgumentException - * @throws AssertionFailedError - * @since 4.10.2.p - */ - public function setUpTickets() - { - $price = EE_Price::new_instance( - [ - 'PRT_ID' => 1, - 'PRC_name' => 'Tree Fiddy', - 'PRC_amount' => 3.5, - ] - ); - $this->assertTrue($price->save() > 0); - $this->ticket = EE_Ticket::new_instance( - [ - 'TKT_name' => 'NO FREEBIE FOR YOU!!!', - 'TKT_price' => $price->amount(), - 'TKT_taxable' => false - ] - ); - $this->assertTrue($this->ticket->save() > 0); - $this->ticket->_add_relation_to($price, 'Price'); - $this->free_ticket = EE_Ticket::new_instance( - [ - 'TKT_name' => 'I am not Groot... I am Free!', - 'TKT_price' => 0, - 'TKT_taxable' => false - ] - ); - $this->assertTrue($this->free_ticket->save() > 0); - } - - - /** - * @param array $get_params - * @return TicketFilterHeader - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @since 4.10.2.p - */ - private function getTicketFilterHeader(array $get_params) - { - return new TicketFilterHeader( - new RequestMock($get_params, [], [], [], []), - EEM_Ticket::instance() - ); - } - - - /** - * generator function to replace phpunit's dataProvider - * because those run during initial phpunit setup - * and NOT when this actual test class is run, - * therefore making it impossible to create - * and save entities to the database in order to use - * their autoincrement IDs in this function - * and have those entities still exist when these - * testcases actually run. - * - * @return Generator - * @throws EE_Error - * @since 4.10.2.p - */ - public function testDataGenerator() - { - $test_data = [ - // empty array - [[], ''], - // invalid keys - [['TKT-ID' => $this->ticket->ID()], ''], - [['ticket-id' => $this->ticket->ID()], ''], - // invalid values - [['TKT_ID' => '

    I am from the Future!!!

    '], ''], - [['TKT_ID' => $this->xss], ''], - [['ticket_id' => '

    I am from the Future!!!

    '], ''], - [['ticket_id' => $this->xss], ''], - // all good - // [['TKT_ID' => $this->ticket->ID()], ''], - [ - ['TKT_ID' => $this->ticket->ID()], - '

    Viewing registrations for ticket:    NO FREEBIE FOR YOU!!! $3.50 (USD)

    ' - ], - [ - ['TKT_ID' => $this->free_ticket->ID()], - '

    Viewing registrations for ticket:    I am not Groot... I am Free! free

    ' - ], - [ - ['ticket_id' => $this->ticket->ID()], - '

    Viewing registrations for ticket:    NO FREEBIE FOR YOU!!! $3.50 (USD)

    ' - ], - [ - ['ticket_id' => $this->free_ticket->ID()], - '

    Viewing registrations for ticket:    I am not Groot... I am Free! free

    ' - ], - ]; - foreach ($test_data as $data) { - yield $data; - } - } - - - /** - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - * @throws InvalidArgumentException - * @since 4.10.2.p - */ - public function testGetHeaderText() - { - foreach ($this->testDataGenerator() as list($get_params, $expected)) { - $ticket_filter_header = $this->getTicketFilterHeader($get_params); - $header_text = $ticket_filter_header->getHeaderText(); - // strip out nonce since it constantly changes - $header_text = preg_replace('/&edit_nonce=\S+"/', '&edit_nonce="', $header_text); - $this->assertEquals($expected, $header_text); - } - } -} diff --git a/tests/testcases/core/domain/services/contexts/RequestTypeContextDetectorTest.php b/tests/testcases/core/domain/services/contexts/RequestTypeContextDetectorTest.php deleted file mode 100644 index e4a1ac6fa22..00000000000 --- a/tests/testcases/core/domain/services/contexts/RequestTypeContextDetectorTest.php +++ /dev/null @@ -1,215 +0,0 @@ -detectRequestTypeContext(); - $this->assertEquals($expected, $request_type->slug()); - } - - - /** - * @since 4.9.70.p - * @return array - */ - public function requestProvider() - { - $factory = new RequestTypeContextFactoryMock(); - return [ - 'Detect WP Scrape Request' => [ - new RequestTypeContextDetector( - new RequestMock( - array('wp_scrape_key' => '123', 'wp_scrape_nonce' => '456'), - array(), - array(), - array() - ), - $factory - ), - RequestTypeContext::WP_SCRAPE, - ], - 'Detect EE REST API Request' => [ - new RequestTypeContextDetector( - new RequestMock( - array(), - array(), - array(), - array('REQUEST_URI' => '/wp-json/' . Domain::API_NAMESPACE . '/') - ), - $factory - ), - RequestTypeContext::API, - ], - 'Detect WP REST API Request' => [ - new RequestTypeContextDetector( - new RequestMock( - array(), - array(), - array(), - array('REQUEST_URI' => '/wp-json/') - ), - $factory - ), - RequestTypeContext::WP_API, - ], - 'Detect Frontend AJAX Request' => [ - new RequestTypeContextDetector( - new RequestMock( - array(), - array('ee_front_ajax' => true), - array(), - array() - ), - $factory, - array('DOING_AJAX' => true) - ), - RequestTypeContext::AJAX_FRONT, - ], - 'Detect Admin AJAX Request' => [ - new RequestTypeContextDetector( - new RequestMock( - array(), - array('ee_admin_ajax' => true), - array(), - array() - ), - $factory, - array('DOING_AJAX' => true) - ), - RequestTypeContext::AJAX_ADMIN, - ], - 'Detect Other AJAX Request' => [ - new RequestTypeContextDetector( - new RequestMock( - array(), - array(), - array(), - array() - ), - $factory, - array('DOING_AJAX' => true) - ), - RequestTypeContext::AJAX_OTHER, - ], - 'Detect WP Cron Request' => [ - new RequestTypeContextDetector( - new RequestMock( - array(), - array(), - array(), - array('REQUEST_URI' => '/wp-cron.php') - ), - $factory - ), - RequestTypeContext::CRON, - ], - 'Detect WP CLI Request' => [ - new RequestTypeContextDetector( - new RequestMock( - array(), - array(), - array(), - array() - ), - $factory, - array('WP_CLI' => true) - ), - RequestTypeContext::CLI, - ], - 'Detect WP Admin Request' => [ - new RequestTypeContextDetector( - new RequestMock( - array(), - array(), - array(), - array() - ), - $factory, - array('is_admin' => true) - ), - RequestTypeContext::ADMIN, - ], - 'Detect Event List iFrame Request' => [ - new RequestTypeContextDetector( - new RequestMock( - array('event_list' => 'iframe'), - array(), - array(), - array() - ), - $factory - ), - RequestTypeContext::IFRAME, - ], - 'Detect Ticket Selector iFrame Request' => [ - new RequestTypeContextDetector( - new RequestMock( - array('ticket_selector' => 'iframe'), - array(), - array(), - array() - ), - $factory - ), - RequestTypeContext::IFRAME, - ], - 'Detect Calendar iFrame Request' => [ - new RequestTypeContextDetector( - new RequestMock( - array('calendar' => 'iframe'), - array(), - array(), - array() - ), - $factory - ), - RequestTypeContext::IFRAME, - ], - 'Detect Feed Request' => [ - new RequestTypeContextDetector( - new RequestMock( - array(), - array(), - array(), - array('REQUEST_URI' => '/feed/') - ), - $factory - ), - RequestTypeContext::FEED, - ], - 'Detect Frontend Request' => [ - new RequestTypeContextDetector( - new RequestMock( - array('param' => 'value'), - array(), - array(), - array() - ), - $factory - ), - RequestTypeContext::FRONTEND, - ], - ]; - } -} - -// location: /tests/testcases/core/domain/services/contexts/RequestTypeContextDetectorTest.php diff --git a/tests/testcases/core/domain/services/custom_post_types/RegisterCustomPostTypesTest.php b/tests/testcases/core/domain/services/custom_post_types/RegisterCustomPostTypesTest.php deleted file mode 100644 index b4a34fc288c..00000000000 --- a/tests/testcases/core/domain/services/custom_post_types/RegisterCustomPostTypesTest.php +++ /dev/null @@ -1,327 +0,0 @@ -custom_post_types = LoaderFactory::getLoader()->getShared( - 'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions' - ); - EE_Dependency_Map::register_dependencies( - 'EventEspresso\tests\mocks\core\domain\services\custom_post_types\RegisterCustomPostTypesMock', - array( - 'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions' => EE_Dependency_Map::load_from_cache, - ) - ); - $this->register_custom_post_types = LoaderFactory::getLoader()->getShared( - 'EventEspresso\tests\mocks\core\domain\services\custom_post_types\RegisterCustomPostTypesMock' - ); - } - - - /** - * @since 4.9.62.p - */ - public function testPrepareArguments() - { - $custom_post_types = $this->custom_post_types->getDefinitions(); - foreach ($custom_post_types as $custom_post_type => $CPT) { - $this->assertEquals( - $this->getExpected($custom_post_type), - $this->register_custom_post_types->prepareArguments( - $custom_post_type, - $CPT['singular_name'], - $CPT['plural_name'], - $CPT['singular_slug'], - $CPT['plural_slug'], - $CPT['args'] - ), - "The prepared arguments for {$custom_post_type} do not match what is expected." - ); - } - } - - - /** - * @since 4.9.62.p - * @param string $custom_post_type - * @return array|mixed - */ - public function getExpected($custom_post_type) - { - $custom_post_types = array( - 'espresso_events' => array( - 'labels' => array( - 'name' => 'Events', - 'singular_name' => 'Event', - 'singular_slug' => 'event', - 'plural_slug' => 'events', - 'add_new' => 'Add Event', - 'add_new_item' => 'Add New Event', - 'edit_item' => 'Edit Event', - 'new_item' => 'New Event', - 'all_items' => 'All Events', - 'view_item' => 'View Event', - 'view_items' => 'View Events', - 'archives' => 'Event Archives', - 'attributes' => 'Event Attributes', - 'insert_into_item' => 'Insert into this Event', - 'uploaded_to_this_item' => 'Uploaded to this Event', - 'filter_items_list' => 'Filter Events list', - 'items_list_navigation' => 'Events list navigation', - 'items_list' => 'Events list', - 'item_published' => 'Event published', - 'item_published_privately' => 'Event published privately', - 'item_reverted_to_draft' => 'Event reverted to draft', - 'item_scheduled' => 'Event scheduled', - 'item_updated' => 'Event updated', - 'search_items' => 'Search Events', - 'not_found' => 'No Events found', - 'not_found_in_trash' => 'No Events found in Trash', - 'parent_item_colon' => '', - 'menu_name' => 'Events', - ), - 'public' => true, - 'publicly_queryable' => true, - 'show_ui' => false, - 'show_ee_ui' => true, - 'show_in_menu' => false, - 'show_in_nav_menus' => true, - 'query_var' => true, - 'rewrite' => array( - 'slug' => 'events', - ), - 'capability_type' => 'event', - 'map_meta_cap' => true, - 'has_archive' => true, - 'hierarchical' => false, - 'menu_position' => - null, - 'supports' => array( - 0 => 'title', - 1 => 'editor', - 2 => 'author', - 3 => 'thumbnail', - 4 => 'excerpt', - 5 => 'custom-fields', - 6 => 'comments', - ), - 'capabilities' => array( - 'edit_post' => 'ee_edit_event', - 'read_post' => 'ee_read_event', - 'delete_post' => 'ee_delete_event', - 'edit_posts' => 'ee_edit_events', - 'edit_others_posts' => 'ee_edit_others_events', - 'publish_posts' => 'ee_publish_events', - 'read_private_posts' => 'ee_read_private_events', - 'delete_posts' => 'ee_delete_events', - 'delete_private_posts' => 'ee_delete_private_events', - 'delete_published_posts' => 'ee_delete_published_events', - 'delete_others_posts' => 'ee_delete_others_events', - 'edit_private_posts' => 'ee_edit_private_events', - 'edit_published_posts' => 'ee_edit_published_events', - ), - 'taxonomies' => array( - 0 => 'espresso_event_categories', - 1 => 'espresso_event_type', - 2 => 'post_tag', - ), - 'page_templates' => true, - ), - 'espresso_venues' => array( - 'labels' => array( - 'name' => 'Venues', - 'singular_name' => 'Venue', - 'singular_slug' => 'venue', - 'plural_slug' => 'venues', - 'add_new' => 'Add Venue', - 'add_new_item' => 'Add New Venue', - 'edit_item' => 'Edit Venue', - 'new_item' => 'New Venue', - 'all_items' => 'All Venues', - 'view_item' => 'View Venue', - 'view_items' => 'View Venues', - 'archives' => 'Venue Archives', - 'attributes' => 'Venue Attributes', - 'insert_into_item' => 'Insert into this Venue', - 'uploaded_to_this_item' => 'Uploaded to this Venue', - 'filter_items_list' => 'Filter Venues list', - 'items_list_navigation' => 'Venues list navigation', - 'items_list' => 'Venues list', - 'item_published' => 'Venue published', - 'item_published_privately' => 'Venue published privately', - 'item_reverted_to_draft' => 'Venue reverted to draft', - 'item_scheduled' => 'Venue scheduled', - 'item_updated' => 'Venue updated', - 'search_items' => 'Search Venues', - 'not_found' => 'No Venues found', - 'not_found_in_trash' => 'No Venues found in Trash', - 'parent_item_colon' => '', - 'menu_name' => 'Venues', - ), - 'public' => true, - 'publicly_queryable' => true, - 'show_ui' => false, - 'show_ee_ui' => true, - 'show_in_menu' => false, - 'show_in_nav_menus' => true, - 'query_var' => true, - 'rewrite' => array( - 'slug' => 'venues', - ), - 'capability_type' => 'venue', - 'map_meta_cap' => true, - 'has_archive' => true, - 'hierarchical' => false, - 'menu_position' => - null, - 'supports' => array( - 0 => 'title', - 1 => 'editor', - 2 => 'author', - 3 => 'thumbnail', - 4 => 'excerpt', - 5 => 'custom-fields', - 6 => 'comments', - ), - 'capabilities' => array( - 'edit_post' => 'ee_edit_venue', - 'read_post' => 'ee_read_venue', - 'delete_post' => 'ee_delete_venue', - 'edit_posts' => 'ee_edit_venues', - 'edit_others_posts' => 'ee_edit_others_venues', - 'publish_posts' => 'ee_publish_venues', - 'read_private_posts' => 'ee_read_private_venues', - 'delete_posts' => 'ee_delete_venues', - 'delete_private_posts' => 'ee_delete_private_venues', - 'delete_published_posts' => 'ee_delete_published_venues', - 'delete_others_posts' => 'ee_edit_others_venues', - 'edit_private_posts' => 'ee_edit_private_venues', - 'edit_published_posts' => 'ee_edit_published_venues', - ), - 'taxonomies' => array( - 0 => 'espresso_venue_categories', - 1 => 'post_tag', - ), - 'page_templates' => true, - ), - 'espresso_attendees' => array( - 'labels' => array( - 'name' => 'Contacts', - 'singular_name' => 'Contact', - 'singular_slug' => 'contact', - 'plural_slug' => 'contacts', - 'add_new' => 'Add Contact', - 'add_new_item' => 'Add New Contact', - 'edit_item' => 'Edit Contact', - 'new_item' => 'New Contact', - 'all_items' => 'All Contacts', - 'view_item' => 'View Contact', - 'view_items' => 'View Contacts', - 'archives' => 'Contact Archives', - 'attributes' => 'Contact Attributes', - 'insert_into_item' => 'Insert into this Contact', - 'uploaded_to_this_item' => 'Uploaded to this Contact', - 'filter_items_list' => 'Filter Contacts list', - 'items_list_navigation' => 'Contacts list navigation', - 'items_list' => 'Contacts list', - 'item_published' => 'Contact published', - 'item_published_privately' => 'Contact published privately', - 'item_reverted_to_draft' => 'Contact reverted to draft', - 'item_scheduled' => 'Contact scheduled', - 'item_updated' => 'Contact updated', - 'search_items' => 'Search Contacts', - 'not_found' => 'No Contacts found', - 'not_found_in_trash' => 'No Contacts found in Trash', - 'parent_item_colon' => '', - 'menu_name' => 'Contacts', - ), - 'public' => false, - 'publicly_queryable' => false, - 'show_ui' => false, - 'show_ee_ui' => true, - 'show_in_menu' => false, - 'show_in_nav_menus' => false, - 'query_var' => true, - 'rewrite' => array( - 'slug' => 'contacts', - ), - 'capability_type' => 'contact', - 'map_meta_cap' => true, - 'has_archive' => false, - 'hierarchical' => false, - 'menu_position' => - null, - 'supports' => array( - 0 => 'editor', - 1 => 'thumbnail', - 2 => 'excerpt', - 3 => 'custom-fields', - 4 => 'comments', - ), - 'taxonomies' => array( - 0 => 'post_tag', - ), - 'capabilities' => array( - 'edit_post' => 'ee_edit_contact', - 'read_post' => 'ee_read_contact', - 'delete_post' => 'ee_delete_contact', - 'edit_posts' => 'ee_edit_contacts', - 'edit_others_posts' => 'ee_edit_contacts', - 'publish_posts' => 'ee_edit_contacts', - 'read_private_posts' => 'ee_edit_contacts', - 'delete_posts' => 'ee_delete_contacts', - 'delete_private_posts' => 'ee_delete_contacts', - 'delete_published_posts' => 'ee_delete_contacts', - 'delete_others_posts' => 'ee_delete_contacts', - 'edit_private_posts' => 'ee_edit_contacts', - 'edit_published_posts' => 'ee_edit_contacts', - ), - ), - ); - return isset($custom_post_types[ $custom_post_type ]) ? $custom_post_types[ $custom_post_type ] : array(); - } -} -// location: tests/testcases/core/domain/services/custom_post_types/RegisterCustomPostTypesTest.php \ No newline at end of file diff --git a/tests/testcases/core/domain/services/custom_post_types/RegisterCustomTaxonomiesTest.php b/tests/testcases/core/domain/services/custom_post_types/RegisterCustomTaxonomiesTest.php deleted file mode 100644 index 658a72ddfaf..00000000000 --- a/tests/testcases/core/domain/services/custom_post_types/RegisterCustomTaxonomiesTest.php +++ /dev/null @@ -1,170 +0,0 @@ -custom_taxonomies = LoaderFactory::getLoader()->getShared( - 'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions' - ); - EE_Dependency_Map::register_dependencies( - 'EventEspresso\tests\mocks\core\domain\services\custom_post_types\RegisterCustomTaxonomiesMock', - array( - 'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions' => EE_Dependency_Map::load_from_cache, - ) - ); - $this->register_custom_taxonomies = LoaderFactory::getLoader()->getShared( - 'EventEspresso\tests\mocks\core\domain\services\custom_post_types\RegisterCustomTaxonomiesMock' - ); - } - - - /** - * @since 4.9.62.p - */ - public function testPrepareArguments() - { - $custom_taxonomies = $this->custom_taxonomies->getCustomTaxonomyDefinitions(); - foreach ($custom_taxonomies as $taxonomy => $tax) { - $this->assertEquals( - $this->getExpected($taxonomy), - $this->register_custom_taxonomies->prepareArguments( - $tax['singular_name'], - $tax['plural_name'], - $tax['args'] - ) - ); - } - } - - - /** - * @since 4.9.62.p - * @param string $taxonomy - * @return array|mixed - */ - public function getExpected($taxonomy) - { - $custom_taxonomies = array( - 'espresso_event_categories' => array( - 'hierarchical' => true, - 'labels' => array( - 'name' => 'Event Categories', - 'singular_name' => 'Event Category', - ), - 'show_ui' => true, - 'show_ee_ui' => true, - 'show_admin_column' => true, - 'query_var' => true, - 'show_in_nav_menus' => true, - 'map_meta_cap' => true, - 'public' => true, - 'show_in_rest' => true, - 'capabilities' => array( - 'manage_terms' => 'ee_manage_event_categories', - 'edit_terms' => 'ee_edit_event_category', - 'delete_terms' => 'ee_delete_event_category', - 'assign_terms' => 'ee_assign_event_category', - ), - 'rewrite' => array( - 'slug' => 'event-category', - ), - ), - 'espresso_venue_categories' => array( - 'hierarchical' => true, - 'labels' => array( - 'name' => 'Venue Categories', - 'singular_name' => 'Venue Category', - ), - 'show_ui' => true, - 'show_ee_ui' => true, - 'show_admin_column' => true, - 'query_var' => true, - 'show_in_nav_menus' => true, - 'map_meta_cap' => true, - 'public' => true, - 'show_in_rest' => true, - 'capabilities' => array( - 'manage_terms' => 'ee_manage_venue_categories', - 'edit_terms' => 'ee_edit_venue_category', - 'delete_terms' => 'ee_delete_venue_category', - 'assign_terms' => 'ee_assign_venue_category', - ), - 'rewrite' => array( - 'slug' => 'venue-category', - ), - ), - 'espresso_event_type' => array( - 'hierarchical' => true, - 'labels' => array( - 'name' => 'Event Types', - 'singular_name' => 'Event Type', - ), - 'show_ui' => false, - 'show_ee_ui' => true, - 'show_admin_column' => true, - 'query_var' => true, - 'show_in_nav_menus' => false, - 'map_meta_cap' => true, - 'public' => true, - 'show_in_rest' => true, - 'capabilities' => array( - 'manage_terms' => 'ee_read_event_type', - 'edit_terms' => 'ee_edit_event_type', - 'delete_terms' => 'ee_delete_event_type', - 'assign_terms' => 'ee_assign_event_type', - ), - 'rewrite' => array( - 'slug' => 'event-type', - ), - ), - ); - return isset($custom_taxonomies[$taxonomy]) ? $custom_taxonomies[ $taxonomy ] : array(); - } -} -// location: tests/testcases/core/domain/services/custom_post_types/RegisterCustomTaxonomiesTest.php - - - diff --git a/tests/testcases/core/domain/values/FilePathTest.php b/tests/testcases/core/domain/values/FilePathTest.php deleted file mode 100644 index 082e5e49c64..00000000000 --- a/tests/testcases/core/domain/values/FilePathTest.php +++ /dev/null @@ -1,58 +0,0 @@ -assertInstanceOf('EventEspresso\core\domain\values\FilePath', $filepath); - } - - - public function test_constructor_with_invalid_data_type() - { - $this->setExceptionExpected('EventEspresso\core\exceptions\InvalidDataTypeException'); - new FilePath(1234); - } - - - public function test_constructor_with_invalid_filepath() - { - $this->setExceptionExpected('EventEspresso\core\exceptions\InvalidFilePathException'); - new FilePath(__FILE__ . '.totallynotmalware'); - } - - - public function test_toString() - { - $filepath = new FilePath(__FILE__); - $this->assertEquals(__FILE__, (string) $filepath); - $this->assertEquals( - str_replace('\\', '/', EE_TESTS_DIR . 'testcases/core/domain/values/FilePathTest.php'), - str_replace('\\', '/', $filepath) - ); - } - - -} -// Location: FilePathTest.php diff --git a/tests/testcases/core/domain/values/FullyQualifiedNameTest.php b/tests/testcases/core/domain/values/FullyQualifiedNameTest.php deleted file mode 100644 index 15218d542ec..00000000000 --- a/tests/testcases/core/domain/values/FullyQualifiedNameTest.php +++ /dev/null @@ -1,63 +0,0 @@ -assertInstanceOf('EventEspresso\core\domain\values\FullyQualifiedName', $fqcn); - } - - public function test_constructor_with_invalid_data_type() - { - $this->setExceptionExpected('EventEspresso\core\exceptions\InvalidDataTypeException'); - new FullyQualifiedName(1234); - } - - - public function test_constructor_with_invalid_class_name() - { - $this->setExceptionExpected('EventEspresso\core\exceptions\InvalidClassException'); - new FullyQualifiedName('EventExpresso\tests\testcases\core\domain\values\FullyQualifiedNameTest'); - } - - - public function test_constructor_with_invalid_interface() - { - $this->setExceptionExpected('EventEspresso\core\exceptions\InvalidInterfaceException'); - new FullyQualifiedName('EventEspresso\tests\testcases\core\domain\values\FullyQualifiedNameInterface'); - } - - - public function test_toString() - { - $fqcn = new FullyQualifiedName(__CLASS__); - $this->assertEquals(__CLASS__, (string) $fqcn); - $this->assertEquals( - 'This test is part of the EventEspresso\tests\testcases\core\domain\values\FullyQualifiedNameTest class', - "This test is part of the {$fqcn} class" - ); - } - -} -// Location: FullyQualifiedNameTest.php diff --git a/tests/testcases/core/domain/values/UrlTest.php b/tests/testcases/core/domain/values/UrlTest.php deleted file mode 100644 index da2bb0b0272..00000000000 --- a/tests/testcases/core/domain/values/UrlTest.php +++ /dev/null @@ -1,301 +0,0 @@ -setExceptionExpected('InvalidArgumentException'); - } - $url = new Url($url_string); - $this->assertInstanceOf('EventEspresso\core\domain\values\Url', $url); - } - - - /** - * @return array - */ - public function schemeProvider() - { - return array( - array( - 'http://local.wordpress.dev', - 'http://', - ), - array( - 'https://local.wordpress.dev/wp-admin/admin.php', - 'https://', - ), - array( - 'abc://username:password@example.com:123/path/data?key=value#fragid1', - 'abc://', - ), - ); - } - - - /** - * @dataProvider schemeProvider - * @param string $url_string - * @param string $scheme - * @throws Exception - */ - public function testScheme($url_string, $scheme) - { - $url = new Url($url_string); - $this->assertInstanceOf('EventEspresso\core\domain\values\Url', $url); - $this->assertEquals($scheme, $url->scheme()); - } - - - /** - * @return array - */ - public function hostProvider() - { - return array( - array( - 'http://local.wordpress.dev', - 'local.wordpress.dev', - ), - array( - 'https://www.eventespresso.com/', - 'www.eventespresso.com', - ), - array( - 'abc://username:password@example.com:123/path/data?key=value#fragid1', - 'example.com', - ), - ); - } - - - /** - * @dataProvider hostProvider - * @param string $url_string - * @param string $host - * @throws Exception - */ - public function testHost($url_string, $host) - { - $url = new Url($url_string); - $this->assertInstanceOf('EventEspresso\core\domain\values\Url', $url); - $this->assertEquals($host, $url->host()); - } - - - /** - * @return array - */ - public function pathProvider() - { - return array( - array( - 'http://local.wordpress.dev', - '', - ), - array( - 'https://local.wordpress.dev/wp-admin/admin.php', - '/wp-admin/admin.php', - ), - array( - 'abc://username:password@example.com:123/path/data?key=value#fragid1', - '/path/data', - ), - ); - } - - - /** - * @dataProvider pathProvider - * @param string $url_string - * @param string $path - * @throws Exception - */ - public function testPath($url_string, $path) - { - $url = new Url($url_string); - $this->assertInstanceOf('EventEspresso\core\domain\values\Url', $url); - $this->assertEquals($path, $url->path()); - } - - - /** - * @return array - */ - public function queryProvider() - { - return array( - array( - 'http://local.wordpress.dev', - '', - array(), - ), - array( - 'http://local.wordpress.dev/wp-admin/admin.php?page=espresso_events&action=edit&post=39', - '?page=espresso_events&action=edit&post=39', - array( - 'page' => 'espresso_events', - 'action' => 'edit', - 'post' => '39', - ), - ), - array( - 'abc://username:password@example.com:123/path/data?key=value#fragid1', - '?key=value', - array('key' => 'value'), - ), - ); - } - - - /** - * @dataProvider queryProvider - * @param string $url_string - * @param string $query_string - * @param array $query_params - * @throws Exception - */ - public function testQueryStringAndQueryParams($url_string, $query_string, array $query_params) - { - $url = new Url($url_string); - $this->assertInstanceOf('EventEspresso\core\domain\values\Url', $url); - $this->assertEquals($query_string, $url->queryString()); - $this->assertEquals($query_params, $url->queryParams()); - } - - - /** - * @return array - */ - public function fragmentProvider() - { - return array( - array( - 'http://local.wordpress.dev', - '', - ), - array( - 'http://local.wordpress.dev/registration-checkout/?uts=1513717329#checkout', - '#checkout', - ), - array( - 'abc://username:password@example.com:123/path/data?key=value#fragid1', - '#fragid1', - ), - ); - } - - - /** - * @dataProvider fragmentProvider - * @param string $url_string - * @param string $fragment - * @throws Exception - */ - public function testFragment($url_string, $fragment) - { - $url = new Url($url_string); - $this->assertInstanceOf('EventEspresso\core\domain\values\Url', $url); - $this->assertEquals($fragment, $url->fragment()); - } - - - /** - * @return array - */ - public function fullUrlProvider() - { - return array( - array( - 'http://local.wordpress.dev', - 'http://local.wordpress.dev', - ), - array( - 'http://local.wordpress.dev/registration-checkout/?uts=1513717329#checkout', - 'http://local.wordpress.dev/registration-checkout/?uts=1513717329#checkout', - ), - array( - 'abc://username:password@example.com:123/path/data?key=value#fragid1', - 'abc://example.com/path/data?key=value#fragid1', - ), - ); - } - - - /** - * @dataProvider fullUrlProvider - * @param string $url_string - * @param string $full_url - * @throws Exception - */ - public function testGetFullUrl($url_string, $full_url) - { - $url = new Url($url_string); - $this->assertInstanceOf('EventEspresso\core\domain\values\Url', $url); - $this->assertEquals($full_url, $url->getFullUrl()); - ob_start(); - echo $url; - $this->assertEquals($full_url, ob_get_clean()); - } -} diff --git a/tests/testcases/core/domain/values/VersionTest.php b/tests/testcases/core/domain/values/VersionTest.php deleted file mode 100644 index 5250d82d602..00000000000 --- a/tests/testcases/core/domain/values/VersionTest.php +++ /dev/null @@ -1,369 +0,0 @@ -assertInstanceOf('EventEspresso\core\domain\values\Version', $version); - } - - - - /** - * @return array - */ - public function invalidMajorMinorPatchProvider() - { - return array( - array(1.1, 2, 3, 'rc', 4), - array(1, 2.1, 3, 'rc', 4), - array(1, 2, 'three', 'rc', 4), - array(1, 2, 3, 3.5, 4, 'InvalidArgumentException'), - array(1, 2, 3, 'release', 4, 'InvalidArgumentException'), - array(1, 2, 3, 'decaff', 4, 'InvalidArgumentException'), - array(1, 2, 3, 'rc', 4.1), - array(1, 2, 3, 'rc', '001'), - ); - } - - - /** - * @dataProvider invalidMajorMinorPatchProvider - * @param $major - * @param $minor - * @param $patch - * @param string $release - * @param int $build - * @param string $exception - * @throws Exception - */ - public function testConstructorWithInvalidParameters( - $major, - $minor, - $patch, - $release = Version::RELEASE_TYPE_PROD, - $build = 0, - $exception = 'EventEspresso\core\exceptions\InvalidDataTypeException' - ) { - $this->setExceptionExpected($exception); - new Version($major, $minor, $patch, $release, $build); - } - - - - /** - * @return array - */ - public function validVersionStringProvider() - { - return array( - array(espresso_version(), espresso_version()), - array('1.2.3.rc.4', '1.2.3.rc.004'), - array('1.2.3.beta', '1.2.3.beta.000'), - array('1.2.3.decaf.123', '1.2.3.decaf'), - array('1.2.3.decaf', '1.2.3.decaf'), - array('1.2.3.p.123', '1.2.3.p'), - array('1.2.3.p', '1.2.3.p'), - array('1.2.3', '1.2.3.p'), - ); - } - - - - /** - * @dataProvider validVersionStringProvider - * @param string $version_string - * @param string $expected - * @throws Exception - * @throws InvalidArgumentException - */ - public function testFromString($version_string, $expected) - { - // using EE version method - $version = Version::fromString($version_string); - $this->assertInstanceOf('EventEspresso\core\domain\values\Version', $version); - $this->assertEquals($expected, "{$version}"); - } - - - - /** - * @return array - */ - public function invalidVersionStringProvider() - { - return array( - array('1.2.3.alpha.4'), - array('moar.betterer.version.for.$5000'), - array('Oh come on!!! This isn\'t even a version string!!!'), - ); - } - - - /** - * @dataProvider invalidVersionStringProvider - * @param string $version_string - * @throws Exception - * @throws InvalidArgumentException - */ - public function testFromStringWithInvalidData($version_string) - { - $this->setExceptionExpected('InvalidArgumentException'); - Version::fromString($version_string); - } - - - /** - * @return array - */ - public function majorMinorPatchReleaseAndBuildProvider() - { - return array( - array(1, 2, 3, 'rc', 4), - array(1, 2, 3, 'beta', 4), - array(1, 2, 3, 'decaf', 4), - array(1, 2, 3, 'p', 4), - array(1, 2, 3, 'p'), - array(1, 2, 3), - ); - } - - - /** - * @dataProvider validMajorMinorPatchProvider - * @param $major - * @param $minor - * @param $patch - * @param string $release - * @param int $build - * @throws Exception - */ - public function testMajorMinorPatchReleaseAndBuild( - $major, - $minor, - $patch, - $release = Version::RELEASE_TYPE_PROD, - $build = 0 - ) { - $version = new Version($major, $minor, $patch, $release, $build); - $this->assertEquals($major, $version->major()); - $this->assertEquals($minor, $version->minor()); - $this->assertEquals($patch, $version->patch()); - $this->assertEquals($release, $version->release()); - $this->assertEquals($build, $version->build()); - } - - - - /** - * @return array - */ - public function versionCompareProvider() - { - return array( - 'major version compare' => array( - 'version' => new Version(2, 2, 3, 'p', 0), - 'older version' => new Version(1, 2, 3, 'p', 0), - 'same version' => new Version(2, 2, 3, 'p', 0), - 'newer version' => new Version(3, 2, 3, 'p', 0), - ), - 'minor version compare' => array( - 'version' => new Version(1, 2, 3, 'p', 0), - 'older version' => new Version(1, 1, 3, 'p', 0), - 'same version' => new Version(1, 2, 3, 'p', 0), - 'newer version' => new Version(1, 3, 3, 'p', 0), - ), - 'patch version compare' => array( - 'version' => new Version(1, 2, 3, 'p', 0), - 'older version' => new Version(1, 2, 2, 'p', 0), - 'same version' => new Version(1, 2, 3, 'p', 0), - 'newer version' => new Version(1, 2, 4, 'p', 0), - ), - 'release version compare' => array( - 'version' => new Version(1, 2, 3, 'rc', 0), - 'older version' => new Version(1, 2, 3, 'beta', 0), - 'same version' => new Version(1, 2, 3, 'rc', 0), - 'newer version' => new Version(1, 2, 3, 'p', 0), - ), - 'build version compare' => array( - 'version' => new Version(1, 2, 3, 'rc', 2), - 'older version' => new Version(1, 2, 3, 'rc', 1), - 'same version' => new Version(1, 2, 3, 'rc', 2), - 'newer version' => new Version(1, 2, 3, 'rc', 3), - ), - ); - } - - - - /** - * @dataProvider versionCompareProvider - * @param Version $version - * @param Version $older_version - * @param Version $same_version - * @param Version $newer_version - */ - public function testCompare( - Version $version, - Version $older_version, - Version $same_version, - Version $newer_version - ) { - // current version is newer so result == 1 - $this->assertEquals(1, $version->compare($older_version)); - // current version is same so result == 0 - $this->assertEquals(0, $version->compare($same_version)); - // current version is older so result == -1 - $this->assertEquals(-1, $version->compare($newer_version)); - } - - - /** - * @dataProvider versionCompareProvider - * @param Version $version - * @param Version $older_version - * @param Version $same_version - * @param Version $newer_version - */ - public function testEquals( - Version $version, - Version $older_version, - Version $same_version, - Version $newer_version - ) { - $this->assertFalse($version->equals($older_version)); - $this->assertFalse( $version->equals($newer_version)); - $this->assertTrue($version->equals($same_version)); - } - - - /** - * @dataProvider versionCompareProvider - * @param Version $version - * @param Version $older_version - * @param Version $same_version - * @param Version $newer_version - */ - public function testNewerThan( - Version $version, - Version $older_version, - Version $same_version, - Version $newer_version - ) { - $this->assertFalse( $version->newerThan($same_version)); - $this->assertFalse($version->newerThan($newer_version)); - $this->assertTrue($version->newerThan($older_version)); - } - - - /** - * @dataProvider versionCompareProvider - * @param Version $version - * @param Version $older_version - * @param Version $same_version - * @param Version $newer_version - */ - public function testOlderThan( - Version $version, - Version $older_version, - Version $same_version, - Version $newer_version - ) { - $this->assertFalse( $version->olderThan($same_version)); - $this->assertFalse($version->olderThan($older_version)); - $this->assertTrue($version->olderThan($newer_version)); - } - - - /** - * @return array - */ - public function toStringProvider() - { - return array( - array('1.2.3.rc.004', 1, 2, 3, 'rc', 4), - array('1.2.3.beta.004', 1, 2, 3, 'beta', 4), - array('1.2.3.decaf', 1, 2, 3, 'decaf', 4), - array('1.2.3.decaf', 1, 2, 3, 'decaf'), - array('1.2.3.p', 1, 2, 3, 'p', 4), - array('1.2.3.p', 1, 2, 3, 'p'), - array('1.2.3.p', 1, 2, 3), - ); - } - - - /** - * @dataProvider toStringProvider - * @param string $expected - * @param int $major - * @param int $minor - * @param int $patch - * @param string $release - * @param int $build - * @throws Exception - */ - public function testToString ( - $expected, - $major, - $minor, - $patch, - $release = Version::RELEASE_TYPE_PROD, - $build = 0 - ) { - $version = new Version($major, $minor, $patch, $release, $build); - $this->assertInstanceOf('EventEspresso\core\domain\values\Version', $version); - $this->assertEquals($expected, (string) $version); - $this->assertEquals($expected, "{$version}"); - } - - -} -// Location: VersionTest.php diff --git a/tests/testcases/core/domain/values/assets/JavascriptAssetTest.php b/tests/testcases/core/domain/values/assets/JavascriptAssetTest.php deleted file mode 100644 index ae0aea0292a..00000000000 --- a/tests/testcases/core/domain/values/assets/JavascriptAssetTest.php +++ /dev/null @@ -1,132 +0,0 @@ -domain_mock = new DomainMock(); - $this->js_asset = $this->getAsset(); - } - - - public function tearDown() - { - $this->domain_mock = null; - $this->js_asset = null; - } - - - private function getAsset( - $source = 'https://testurl.com/test.js', - $dependencies = array(), - $load_in_footer = true - ) { - return new JavascriptAsset( - 'test-handle', - $source, - $dependencies, - $load_in_footer, - $this->domain_mock - ); - } - - - public function testConstruct() - { - $this->assertEquals('test-handle', $this->js_asset->handle()); - $this->assertEquals('https://testurl.com/test.js', $this->js_asset->source()); - $this->assertEquals(array(), $this->js_asset->dependencies()); - $this->assertTrue($this->js_asset->loadInFooter()); - } - - - public function testRequiresTranslation() - { - $this->assertFalse($this->js_asset->requiresTranslation()); - $this->js_asset->setRequiresTranslation(); - $this->assertTrue($this->js_asset->requiresTranslation()); - } - - - public function testHasInlineData() - { - $this->assertFalse($this->js_asset->hasInlineData()); - $this->js_asset->setHasInlineData(); - $this->assertTrue($this->js_asset->hasInlineData()); - } - - - public function testInlineDataCallback() - { - $test_callback = function () { - return true; - }; - $this->assertFalse($this->js_asset->hasInlineDataCallback()); - $this->assertNull($this->js_asset->inlineDataCallback()); - $this->assertFalse($this->js_asset->hasInlineData()); - - $this->js_asset->setInlineDataCallback($test_callback); - $this->assertTrue($this->js_asset->hasInlineDataCallback()); - $this->assertEquals($test_callback, $this->js_asset->inlineDataCallback()); - $this->assertTrue($this->js_asset->hasInlineData()); - } - - - public function testIsBuiltDistributionSource() - { - $this->assertFalse($this->js_asset->isBuiltDistributionSource()); - - $asset = $this->getAsset('https://testurl.com/testjs.dist.js'); - $this->assertTrue($asset->isBuiltDistributionSource()); - } - - - public function testVersion() - { - // version for non built (or "dist") source with no set version - $this->assertEquals('1.2.3.p', $this->js_asset->version()); - - // version for explicitly set version - $this->js_asset->setVersion('4.5.6'); - $this->assertEquals('4.5.6', $this->js_asset->version()); - - // version for built ('.dist.js') source. - $asset = $this->getAsset('https://testurl.com/testjs.dist.js'); - $this->assertEquals('', $asset->version()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/domain/values/model/CustomSelectsTests.php b/tests/testcases/core/domain/values/model/CustomSelectsTests.php deleted file mode 100644 index 53a09772780..00000000000 --- a/tests/testcases/core/domain/values/model/CustomSelectsTests.php +++ /dev/null @@ -1,131 +0,0 @@ - '%s', 'REG_ID' => '%s', 'TXN_ID' => '%s') - ), - array( - CustomSelects::TYPE_COMPLEX, - array( - 'attendee_id' => array('ATT_ID', '%s'), - 'registration_count' => array('count(REG_ID)', '%d'), - 'transaction_total' => array('sum(TXN_total)', '%f') - ), - 'ATT_ID AS attendee_id, count(REG_ID) AS registration_count, sum(TXN_total) AS transaction_total', - array('attendee_id', 'registration_count', 'transaction_total'), - array('attendee_id' => '%s', 'registration_count' => '%d', 'transaction_total' => '%f') - ), - array( - CustomSelects::TYPE_STRUCTURED, - array( - 'attendee_id' => array('ATT_ID', '', '%s'), - 'registration_count' => array('REG_ID', 'count', '%d'), - 'transaction_total' => array('TXN_total', 'sum', '%f') - ), - 'ATT_ID AS attendee_id, COUNT(REG_ID) AS registration_count, SUM(TXN_total) AS transaction_total', - array('attendee_id', 'registration_count', 'transaction_total'), - array('attendee_id' => '%s', 'registration_count' => '%d', 'transaction_total' => '%f') - ) - ); - } - - - /** - * @return array - */ - public function typeSelectFailsProvider() - { - return array( - array( - array('ATT_ID', 'REG_ID' => 2) - ), - array( - array('attendee_id' => 'something') - ), - array( - array('attendee_id' => array('count(REG_ID)', '%d', 'count')) - ) - ); - } - - - /** - * @dataProvider typesSelectProvider - * @param string $type - * @param array $incoming_select_array - * @param string $expected__columns_to_select - * @param array $expected_column_aliases - * @param array $expected_data_types_for_aliases - * @throws InvalidArgumentException - */ - public function testTypes( - $type, - array $incoming_select_array, - $expected__columns_to_select, - array $expected_column_aliases, - array $expected_data_types_for_aliases - ) { - $select = new CustomSelects($incoming_select_array); - $this->assertEquals($incoming_select_array, $select->originalSelects()); - $this->assertEquals( - $expected__columns_to_select, - $select->columnsToSelectExpression() - ); - $this->assertEquals( - $expected_column_aliases, - $select->columnAliases() - ); - $this->assertEquals( - $type, - $select->type() - ); - //data types - foreach ($expected_data_types_for_aliases as $alias => $data_type) { - $this->assertEquals($data_type, $select->getDataTypeForAlias($alias)); - } - $this->assertEquals( - '%s', - $select->getDataTypeForAlias('ATT_ID') - ); - } - - - /** - * @dataProvider typeSelectFailsProvider - * @param array $incoming_select_array - * @throws InvalidArgumentException - * @throws Exception - */ - public function testTypeFails(array $incoming_select_array) - { - $this->setExceptionExpected('InvalidArgumentException'); - $select = new CustomSelects($incoming_select_array); - } -} diff --git a/tests/testcases/core/helpers/EEH_Activation_Test.php b/tests/testcases/core/helpers/EEH_Activation_Test.php deleted file mode 100644 index 39938f17b16..00000000000 --- a/tests/testcases/core/helpers/EEH_Activation_Test.php +++ /dev/null @@ -1,264 +0,0 @@ -load_lib( 'Message_Resource_Manager' ); - // messengers that have been activated and verified installed - $active_messengers = $message_resource_manager->active_messengers(); - // ALL installed messengers regardless of whether they are active or not - $installed_messengers = $message_resource_manager->installed_messengers(); - $should_be_installed = array(); - foreach( $active_messengers as $msgr ) { - $this->assertInstanceOf( 'EE_messenger', $msgr ); - if ( $msgr->activate_on_install ) { - $should_be_installed[] = $msgr->name; - } - } - //loop through $should_be_installed and verify that those that should be active ARE active. - foreach ( $should_be_installed as $msgr_name ) { - $this->assertTrue( - isset( $installed_messengers[ $msgr_name ] ), - sprintf( 'The messenger %s should be active on fresh install, but it is not.', $msgr_name ) - ); - } - - //now verify that the code doesn't run new message template generation etc. - $this->assertFalse( EEH_Activation::generate_default_message_templates() ); - - - // now we simulate someone who's deactivated a messenger - // and we simulate a migration that triggers generating default message templates again. - // The html messenger should STICK and NOT be activated. - $message_resource_manager->deactivate_messenger( 'html' ); - - //do the same for message type - $message_resource_manager->deactivate_message_type_for_messenger( 'not_approved', 'email' ); - - //Reset messages to test stickiness - EE_Registry::reset(); - - $activated_response = EEH_Activation::generate_default_message_templates(); - - //verify we got a response (html should not have templates generated) - $this->assertFalse( $activated_response ); - - // double check we still don't have html in the active messengers array - $active_messengers = $message_resource_manager->get_active_messengers_option( true ); - $this->assertFalse( isset( $active_messengers['html'] ) ); - $this->assertFalse( $message_resource_manager->is_message_type_active_for_messenger( 'email', 'not_approved' ) ); - } - - - - - - /** - * This tests the generate_default_message_templates method with using the - * FHEE__EE_messenger__get_default_message_types__default_types filter to add a - * bogus message_type string. No errors should be triggered, and the invalid default mt - * should NOT be added to the active array for the messenger. - * - * @since 4.6 - * @group 7595 - */ - public function test_filtered_default_message_types_on_activation() { - /** @type EE_Message_Resource_Manager $message_resource_manager */ - $message_resource_manager = EE_Registry::instance()->load_lib( 'Message_Resource_Manager' ); - //let's clear out all active messengers to get an accurate test of initial generation of message templates. - global $wpdb; - // delete message_template_group templates - $message_template_group_table = $wpdb->prefix . 'esp_message_template_group'; - $query = "DELETE FROM $message_template_group_table WHERE 'GRP_ID' > 0"; - $wpdb->query( $query ); - // delete message_template templates - $message_template_table = $wpdb->prefix . 'esp_message_template'; - $query = "DELETE FROM $message_template_table WHERE 'MTP_ID' > 0"; - $wpdb->query($query); - // delete event_message_template templates - $event_message_template_table = $wpdb->prefix . 'esp_event_message_template'; - $query = "DELETE FROM $event_message_template_table WHERE 'EMT_ID' > 0"; - $wpdb->query( $query ); - - $message_resource_manager->update_active_messengers_option( array() ); - //set a filter for the invalid message type - add_filter( - 'FHEE__EE_messenger__get_default_message_types__default_types', - function( $default_types ) { - $default_types[] = 'bogus_message_type'; - return $default_types; - }, 10, 2 - ); - - try { - //activate messages... if there's any problems then errors will trigger a fail. - EEH_Activation::generate_default_message_templates(); - } catch( EE_Error $e ){ - $this->assertInstanceOf( 'EE_Error', $e ); - } - - //all went well so let's make sure the activated system does NOT have our invalid message type string. - $active_messengers = $message_resource_manager->get_active_messengers_option( true ); - foreach( $active_messengers as $messenger => $settings ) { - $this->assertFalse( - isset( $settings[ 'settings' ][ $messenger . '-message_types' ][ 'bogus_message_type' ] ), - sprintf( 'The %s messenger should not have "bogus_message_type" active on it but it does.', $messenger ) - ); - } - } - - - - - /** - * Ensure getting default creator works as expected - * @since 4.6.0 - */ - public function test_get_default_creator_id() { - //clear out any previous users that may be lurking in teh system - foreach( get_users() as $wp_user ){ - wp_delete_user( $wp_user->ID ); - } - //set some users; and just make it interesting by having the first user NOT be an admin - $this->factory->user->create_many( 2 ); - $users = $this->factory->user->create_many( 2 ); - //make users administrators. - foreach ( $users as $user_id ) { - $user = $this->factory->user->get_object_by_id( $user_id ); - //verify - $this->assertInstanceOf( 'WP_User', $user ); - //add role - $user->add_role( 'administrator' ); - } - - //get all users so we know who is the first one that we should be expecting. - $expected_id = reset( $users ); - $this->assertEquals( EEH_Activation::get_default_creator_id(), $expected_id ); - - /** - * ok now let's verify EEH_Activation::reset() properly clears the cache - * on EEH_Activation. This is important for subsequent unit tests (because - * EEH_Activation::reset() is called between unit tests), but also when an admin - * resets their EE database, or when anyone wants to reset that cache) - * clear out any previous users that may be lurking in teh system - */ - EEH_Activation::reset(); - foreach( get_users() as $wp_user ){ - wp_delete_user( $wp_user->ID ); - } - //set some users; and just make it interesting by having the first user NOT be an admin - $this->factory->user->create_many( 2 ); - $users_created_after_reset = $this->factory->user->create_many( 2 ); - //make users administrators. - foreach ( $users_created_after_reset as $user_id ) { - $user = $this->factory->user->get_object_by_id( $user_id ); - //verify - $this->assertInstanceOf( 'WP_User', $user ); - //add role - $user->add_role( 'administrator' ); - } - - //get all users so we know who is the first one that we should be expecting. - $new_expected_id = reset( $users_created_after_reset ); - $this->assertEquals( EEH_Activation::get_default_creator_id(), $new_expected_id ); - - } - - function test_get_cron_tasks__old() { - add_filter( 'FHEE__EEH_Activation__get_cron_tasks', array( $this, 'change_cron_tasks' ) ); - $old_cron_tasks = EEH_Activation::get_cron_tasks( 'old' ); - $this->assertArrayHasKey( self::expired_cron_task_name, $old_cron_tasks ); - $this->assertArrayNotHasKey( self::current_cron_task_name, $old_cron_tasks ); - } - function test_get_cron_tasks__all() { - add_filter( 'FHEE__EEH_Activation__get_cron_tasks', array( $this, 'change_cron_tasks' ) ); - $old_cron_tasks = EEH_Activation::get_cron_tasks( 'all' ); - $this->assertArrayHasKey( self::expired_cron_task_name, $old_cron_tasks ); - $this->assertArrayHasKey( self::current_cron_task_name, $old_cron_tasks ); - } - - - /** - * @see https://events.codebasehq.com/projects/event-espresso/tickets/9501 - * @since 4.8.36 - */ - function test_remove_cron_tasks_with_empty_timestamp_values() { - //first cache existing cron array - $old_cron_option = _get_cron_array(); - //merge in a bunch of empty timestamps - $empty_timestamps = array( - time() + 30 => array(), - time() + 600 => array(), - time() - 400 => array() - ); - _set_cron_array( - array_merge( $empty_timestamps, $old_cron_option ) - ); - - //now let's run the EEH_Activation::remove_cron_tasks - EEH_Activation::remove_cron_tasks(); - - //and verify that there are no empty timestamps - $updated_cron_option = _get_cron_array(); - $this->assertEquals( count( $old_cron_option ), count( $updated_cron_option ) ); - - //now restore - _set_cron_array( $old_cron_option ); - } - - - /** - * Makes it so this function can be independent on what the current cron tasks actually are - * (because they'll likely change, whereas some of these functions just want to check that - * we are retrieving cron tasks correctly) - * - * @param array $old_cron_tasks - * @return array - */ - function change_cron_tasks( $old_cron_tasks ) { - return array( - self::current_cron_task_name => 'hourly', - self::expired_cron_task_name => EEH_Activation::cron_task_no_longer_in_use - ); - } - - function test_table_exists__success() { - $this->assertTrue( EEH_Activation::table_exists( 'posts' ) ); - $this->assertTrue( EEH_Activation::table_exists( 'esp_attendee_meta' ) ); - } - - function test_table_exists__false() { - $this->assertFalse( EEH_Activation::table_exists( 'monkeys' ) ); - } - - - -} //end class EEH_Activation_Test -// location: tests/testcases/core/helpers/EEH_Activation_Test.php diff --git a/tests/testcases/core/helpers/EEH_Array_Test.php b/tests/testcases/core/helpers/EEH_Array_Test.php deleted file mode 100644 index ffcff9f70fb..00000000000 --- a/tests/testcases/core/helpers/EEH_Array_Test.php +++ /dev/null @@ -1,214 +0,0 @@ - 'apple', - 'b' => 'banana', - ); - // add to start - $fruits = EEH_Array::insert_into_array( $fruits, array( 'c' => 'coconut' ) ); - $this->assertEquals( 'coconut', reset( $fruits ) ); - $this->assertEquals( 'apple', next( $fruits ) ); - $this->assertEquals( 'banana', next( $fruits ) ); - // add to end - $fruits = EEH_Array::insert_into_array( $fruits, array( 'd' => 'date' ), null, false ); - $this->assertEquals( 'coconut', reset( $fruits ) ); - $this->assertEquals( 'apple', next( $fruits ) ); - $this->assertEquals( 'banana', next( $fruits ) ); - $this->assertEquals( 'date', next( $fruits ) ); - // add to middle BEFORE 'banana' - $fruits = EEH_Array::insert_into_array( $fruits, array( 'e' => 'elderberry' ), 'b' ); - $this->assertEquals( 'coconut', reset( $fruits ) ); - $this->assertEquals( 'apple', next( $fruits ) ); - $this->assertEquals( 'elderberry', next( $fruits ) ); - $this->assertEquals( 'banana', next( $fruits ) ); - $this->assertEquals( 'date', next( $fruits ) ); - } - - - - /** - * test_insert_into_array_with_numeric_indexes - */ - function test_insert_into_array_with_numeric_indexes() { - // starting data - $fruits = array( - 1 => 'one', - 2 => 'two' - ); - // add to start - $fruits = EEH_Array::insert_into_array( $fruits, array( 3 => 'three' ) ); - //echo '$fruits: ', var_dump( $fruits ); - $this->assertEquals( 'three', reset( $fruits ) ); - $this->assertEquals( 'one', next( $fruits ) ); - $this->assertEquals( 'two', next( $fruits ) ); - // add to end - $fruits = EEH_Array::insert_into_array( $fruits, array( 4 => 'four' ), null, false ); - $this->assertEquals( 'three', reset( $fruits ) ); - $this->assertEquals( 'one', next( $fruits ) ); - $this->assertEquals( 'two', next( $fruits ) ); - $this->assertEquals( 'four', next( $fruits ) ); - // add to middle before 2 - $fruits = EEH_Array::insert_into_array( $fruits, array( 5 => 'five' ), 2 ); - $this->assertEquals( 'three', reset( $fruits ) ); - $this->assertEquals( 'one', next( $fruits ) ); - $this->assertEquals( 'five', next( $fruits ) ); - $this->assertEquals( 'two', next( $fruits ) ); - $this->assertEquals( 'four', next( $fruits ) ); - // try to bork keys and add onto the end while also specifying the last known key - $fruits = EEH_Array::insert_into_array( $fruits, array( 6 => 'six' ), 4, false ); - //echo '$fruits: ', var_dump( $fruits ); - $this->assertEquals( 'three', reset( $fruits ) ); - $this->assertEquals( 'one', next( $fruits ) ); - $this->assertEquals( 'five', next( $fruits ) ); - $this->assertEquals( 'two', next( $fruits ) ); - $this->assertEquals( 'four', next( $fruits ) ); - $this->assertEquals( 'six', next( $fruits ) ); - // add to end and reindex keys - $fruits = EEH_Array::insert_into_array( $fruits, array( 7 => 'seven' ), null, false, false ); - $this->assertEquals( 'three', reset( $fruits ) ); - $this->assertEquals( 'one', next( $fruits ) ); - $this->assertEquals( 'five', next( $fruits ) ); - $this->assertEquals( 'two', next( $fruits ) ); - $this->assertEquals( 'four', next( $fruits ) ); - $this->assertEquals( 'six', next( $fruits ) ); - $this->assertEquals( 'seven', next( $fruits ) ); - // now test keys - reset( $fruits ); - $this->assertEquals( 0, key( $fruits ) ); - next( $fruits ); - $this->assertEquals( 1, key( $fruits ) ); - next( $fruits ); - $this->assertEquals( 2, key( $fruits ) ); - next( $fruits ); - $this->assertEquals( 3, key( $fruits ) ); - next( $fruits ); - $this->assertEquals( 4, key( $fruits ) ); - next( $fruits ); - $this->assertEquals( 5, key( $fruits ) ); - next( $fruits ); - $this->assertEquals( 6, key( $fruits ) ); - } - - - - /** - * test_insert_into_array_with_mixed_indexes - */ - function test_insert_into_array_with_mixed_indexes() { - // starting data - $fruits = array( - 1 => 'one', - 'p' => 'potato' - ); - // add to start - $fruits = EEH_Array::insert_into_array( $fruits, array( 2 => 'two' ) ); - //echo '$fruits: ', var_dump( $fruits ); - $this->assertEquals( 'two', reset( $fruits ) ); - $this->assertEquals( 'one', next( $fruits ) ); - $this->assertEquals( 'potato', next( $fruits ) ); - // add to end - $fruits = EEH_Array::insert_into_array( $fruits, array( 't' => 'tomato' ), null, false ); - //echo '$fruits: ', var_dump( $fruits ); - $this->assertEquals( 'two', reset( $fruits ) ); - $this->assertEquals( 'one', next( $fruits ) ); - $this->assertEquals( 'potato', next( $fruits ) ); - $this->assertEquals( 'tomato', next( $fruits ) ); - // add to middle before potato - $fruits = EEH_Array::insert_into_array( $fruits, array( 3 => 'three' ), 'p' ); - //echo '$fruits: ', var_dump( $fruits ); - $this->assertEquals( 'two', reset( $fruits ) ); - $this->assertEquals( 'one', next( $fruits ) ); - $this->assertEquals( 'three', next( $fruits ) ); - $this->assertEquals( 'potato', next( $fruits ) ); - $this->assertEquals( 'tomato', next( $fruits ) ); - // try to bork keys and add onto the end while also specifying the last known key - $fruits = EEH_Array::insert_into_array( $fruits, array( 6 => 'tornado' ), 't', false ); - $this->assertEquals( 'two', reset( $fruits ) ); - $this->assertEquals( 'one', next( $fruits ) ); - $this->assertEquals( 'three', next( $fruits ) ); - $this->assertEquals( 'potato', next( $fruits ) ); - $this->assertEquals( 'tomato', next( $fruits ) ); - $this->assertEquals( 'tornado', next( $fruits ) ); - // add to end and reindex keys - $fruits = EEH_Array::insert_into_array( $fruits, array( 'g' => 'GO NATO' ), null, false, false ); - $this->assertEquals( 'two', reset( $fruits ) ); - $this->assertEquals( 'one', next( $fruits ) ); - $this->assertEquals( 'three', next( $fruits ) ); - $this->assertEquals( 'potato', next( $fruits ) ); - $this->assertEquals( 'tomato', next( $fruits ) ); - $this->assertEquals( 'tornado', next( $fruits ) ); - $this->assertEquals( 'GO NATO', next( $fruits ) ); - // now test keys - reset( $fruits ); - $this->assertEquals( 0, key( $fruits ) ); - next( $fruits ); - $this->assertEquals( 1, key( $fruits ) ); - next( $fruits ); - $this->assertEquals( 2, key( $fruits ) ); - next( $fruits ); - $this->assertEquals( 'p', key( $fruits ) ); - next( $fruits ); - $this->assertEquals( 't', key( $fruits ) ); - next( $fruits ); - $this->assertEquals( 3, key( $fruits ) ); - next( $fruits ); - $this->assertEquals( 4, key( $fruits ) ); - } - - /** - * @group 9784 - */ - public function test_convert_array_values_to_keys() { - $arr = array( 'top', 'middle', 'bottom' ); - $val = 'value'; - $this->assertEquals( - array( - 'top' => array( - 'middle' => array( - 'bottom' => 'value' - ) - ) - ), - EEH_Array::convert_array_values_to_keys( $arr, $val) - ); - } - -} - -// End of file EEH_Array_Test.php \ No newline at end of file diff --git a/tests/testcases/core/helpers/EEH_DTT_Helper_Test.php b/tests/testcases/core/helpers/EEH_DTT_Helper_Test.php deleted file mode 100644 index 50cae60e075..00000000000 --- a/tests/testcases/core/helpers/EEH_DTT_Helper_Test.php +++ /dev/null @@ -1,481 +0,0 @@ -loadModelFieldMocks(array('EE_Datetime_Field')); - $this->_datetime_field = new EE_Datetime_Field_Mock( - $table_column, - $nice_name, - $nullable, - $default_value, - $timezone, - $date_format, - $time_format, - $pretty_date_format, - $pretty_time_format - ); - } - - - /** - * test_get_valid_timezone_string - */ - public function test_get_valid_timezone_string() - { - - $original_timezone_string = get_option('timezone_string'); - // TEST 1: retrieval of WP timezone string - $expected_timezone_string = 'UTC'; - update_option('timezone_string', $expected_timezone_string); - $timezone_string = EEH_DTT_Helper::get_valid_timezone_string(); - $this->assertEquals($timezone_string, $expected_timezone_string); - // TEST 2: retrieval of specific timezone string - $expected_timezone_string = 'America/Vancouver'; - update_option('timezone_string', $expected_timezone_string); - $timezone_string = EEH_DTT_Helper::get_valid_timezone_string($expected_timezone_string); - $this->assertEquals($timezone_string, $expected_timezone_string); - // TEST 3: bogus timezone string - try { - $timezone_string = EEH_DTT_Helper::get_valid_timezone_string('me got funky pants and like to dance'); - $this->fail( - sprintf( - __( - 'The timezone string %1$s should have thrown an Exception, but did not!', - 'event_espresso' - ), - $timezone_string - ) - ); - } catch (EE_Error $e) { - $this->assertTrue(true); - } - // reset timezone_string - update_option('timezone_string', $original_timezone_string); - } - - - /** - * test_get_timezone_string_from_gmt_offset - */ - public function test_get_timezone_string_from_gmt_offset() - { - // TEST 4: gmt offsets - $orig_timezone_string = get_option('timezone_string'); - $orig_gmt_offset = get_option('gmt_offset'); - // set timezone string to empty string - update_option('timezone_string', ''); - $this->assertEmpty(get_option('timezone_string')); - $gmt_offsets = array( - -12, - -11.5, - -11, - -10.5, - -10, - -9.5, - -9, - -8.5, - -8, - -7.5, - -7, - -6.5, - -6, - -5.5, - -5, - -4.5, - -4, - -3.5, - -3, - -2.5, - -2, - -1.5, - -1, - -0.5, - 0, - 0.5, - 1, - 1.5, - 2, - 2.5, - 3, - 3.5, - 4, - 4.5, - 5, - 5.5, - 5.75, - 6, - 6.5, - 7, - 7.5, - 8, - 8.5, - 8.75, - 9, - 9.5, - 10, - 10.5, - 11, - 11.5, - 12, - 12.75, - 13, - 13.75, - 14, - ); - foreach ($gmt_offsets as $gmt_offset) { - update_option('gmt_offset', $gmt_offset); - try { - $timezone_string = EEH_DTT_Helper::get_valid_timezone_string(); - $this->assertNotEmpty( - $timezone_string, - sprintf( - __( - 'The WP GMT offset setting %1$s has resulted in an invalid timezone_string!', - 'event_espresso' - ), - $gmt_offset - ) - ); - } catch (EE_Error $e) { - $gmt_offset = $gmt_offset >= 0 ? '+' . (string)$gmt_offset : (string)$gmt_offset; - $gmt_offset = str_replace(array('.25', '.5', '.75'), array(':15', ':30', ':45'), $gmt_offset); - $gmt_offset = 'UTC' . $gmt_offset; - $this->fail( - sprintf( - __( - 'The WP GMT offset setting %1$s has thrown the following Exception, but should not have! %2$s %3$s', - 'event_espresso' - ), - $gmt_offset, - '
    ', - $e->getMessage() - ) - ); - unset($gmt_offset); - } - } - update_option('timezone_string', $orig_timezone_string); - update_option('gmt_offset', $orig_gmt_offset); - } - - - /** - * If the WordPress database has a timezone_string set in the database, then when this method is called with no - * arguments, it is EXPECTED that it will return the actual timezone_string set in the database unless gmt_offset is - * provided. - * - * @group 10626 - */ - public function test_get_timezone_string_from_gmt_offset_when_timezone_string_set() - { - $original_tz = get_option('timezone_string'); - update_option('timezone_string', 'America/New_York'); - $actual = EEH_DTT_Helper::get_timezone_string_from_gmt_offset(); - $this->assertEquals('America/New_York', $actual); - //let's provide 0 as offset - expect UTC back - $actual = EEH_DTT_Helper::get_timezone_string_from_gmt_offset(0); - $this->assertEquals('UTC', $actual); - // let's provide an offset THAT IS A KNOWN OFFSET WITH A MATCHING VALID TIMEZONE, - // whatever timezone string that gets - // returned should have a matching offset. - $actual = EEH_DTT_Helper::get_timezone_string_from_gmt_offset(-5); - $actual = new DateTimeZone($actual); - $now = new DateTime('now', $actual); - $actual = $actual->getOffset($now); - $this->assertEquals(-5 * HOUR_IN_SECONDS, $actual); - // let's provide an offset THAT IS A KNOWN OFFSET WITH NO MATCHING VALID TIMEZONE, - // whatever timezone string that - // gets returned should have a matching offset. - // first we need to get our expected offset based on the invalid offset we provide. - $expected = EEH_DTT_Helper::adjust_invalid_gmt_offsets(-11.5 * HOUR_IN_SECONDS); - $actual = EEH_DTT_Helper::get_timezone_string_from_gmt_offset(-11.5); - $actual = new DateTimeZone($actual); - $now = new DateTime('now', $actual); - $actual = $actual->getOffset($now); - $this->assertEquals($expected, $actual); - update_option('timezone_string', $original_tz); - } - - - /** - * setup_DateTime_object - * - * @param string $timezone_string - * @param int $time - * @return \DateTime - */ - public function setup_DateTime_object($timezone_string = 'Africa/Abidjan', $time = 0) - { - $timezone_string = empty($timezone_string) ? 'Africa/Abidjan' : $timezone_string; - $DateTime = new DateTime('now', new DateTimeZone($timezone_string)); - $time = absint($time); - if ($time) { - $DateTime->setTimestamp($time); - } - return $DateTime; - } - - - /** - * test_date_time_add - */ - public function test_date_time_add() - { - $this->_date_time_modifier_tests(); - } - - - /** - * test_date_time_subtract - */ - public function test_date_time_subtract() - { - $this->_date_time_modifier_tests(false); - } - - - /** - * _date_time_modifier_tests - * - * @param bool $increment_datetimes - * @throws EE_Error - */ - protected function _date_time_modifier_tests($increment_datetimes = true) - { - $orig_timezone_string = get_option('timezone_string'); - $orig_gmt_offset = get_option('gmt_offset'); - // setup data arrays for generating test conditions - $timezones_and_offsets = array( - 'UTC' => '', - 'America/Vancouver' => '', - null => -5 // EST with no DST - ); - $periods = array( - 'years' => 'P%Y', - 'months' => 'P%M', - 'weeks' => 'P%W', - 'days' => 'P%D', - 'hours' => 'PT%H', - 'minutes' => 'PT%M', - 'seconds' => 'PT%S', - ); - // I can not tell a Fib... the following sequence is for Sidney - $intervals = array(0, 1, 2, 3, 5, 8, 13, 21, 34); - // loop thru timezones and gmt_offsets and set up environment - foreach ($timezones_and_offsets as $timezone_string => $gmt_offset) { - $gmt_offset = $gmt_offset !== 'null' ? $gmt_offset : ''; - update_option('timezone_string', $timezone_string); - update_option('gmt_offset', $gmt_offset); - // loop thru remaining data arrays - foreach ($periods as $period => $designator) { - foreach ($intervals as $interval) { - // don't bother adding more than 5 years - if ($period === 'years' && $interval > 5) { - continue; - } - // TEST: add $interval $period ( ie: add 1 year... add 3 months... add 34 seconds ) - // setup some objects used for testing - $expected_datetime = $this->setup_DateTime_object(); - $actual_datetime = EE_Datetime::new_instance(array('DTT_EVT_start' => time())); - $expected_datetime->setTimezone(new DateTimeZone($actual_datetime->get_timezone())); - $period_interval = str_replace('%', $interval, $designator); - // apply conditions to both objects - if ($increment_datetimes) { - $expected_datetime->add(new DateInterval($period_interval)); - $actual_datetime = EEH_DTT_Helper::date_time_add( - $actual_datetime, - 'DTT_EVT_start', - $period, - $interval - ); - } else { - $expected_datetime->sub(new DateInterval($period_interval)); - $actual_datetime = EEH_DTT_Helper::date_time_subtract( - $actual_datetime, - 'DTT_EVT_start', - $period, - $interval - ); - } - $expected = $expected_datetime->format(EE_Datetime_Field::mysql_timestamp_format); - $actual = $actual_datetime->get_DateTime_object('DTT_EVT_start') - ->format(EE_Datetime_Field::mysql_timestamp_format); - $this->assertDateWithinOneMinute( - $expected, - $actual, - EE_Datetime_Field::mysql_timestamp_format, - sprintf( - __( - 'The %1$s method failed to produce correct results for the the period interval %2$s for timezone "%6$s" and UTC offset "%7$s" .%3$sExpected value: %4$s%3$sActual value: %5$s%3$s', - 'event_espresso' - ), - $increment_datetimes - ? 'EEH_DTT_Helper::date_time_add()' - : 'EEH_DTT_Helper::date_time_subtract()', - $period_interval, - "\n", - $expected, - $actual, - $timezone_string, - $gmt_offset - ) - ); - unset($expected_datetime, $actual_datetime); - } - } - } - update_option('timezone_string', $orig_timezone_string); - update_option('gmt_offset', $orig_gmt_offset); - } - - - /** - * @since 4.6.12+ - */ - public function test_get_timestamp_with_offset() - { - //now in timezone currently set. - $default_timezone = new DateTimeZone(EEH_DTT_Helper::get_timezone()); - $now = new DateTime('now', $default_timezone); - $expected_offset = (int)$now->format('U') + (int)timezone_offset_get($default_timezone, $now); - $this->assertEquals( - $expected_offset, - EEH_DTT_Helper::get_timestamp_with_offset($now->format('U')) - ); - //this might fail because of execution time. - $this->assertEquals(current_time('timestamp'), EEH_DTT_Helper::get_timestamp_with_offset()); - //now let's test with a different timezone for the incoming timestamp. - $now->setTimezone(new DateTimeZone('America/Toronto')); - $expected_timestamp = (int)$now->format('U') + (int)timezone_offset_get( - new DateTimeZone('America/Toronto'), - $now - ); - $this->assertEquals( - $expected_timestamp, - EEH_DTT_Helper::get_timestamp_with_offset($now->format('U'), 'America/Toronto') - ); - } - - - /** - * @since 4.7.0 - */ - public function test_dates_represent_one_24_hour_date() - { - $midnight_start = new DateTime('2015-01-25 00:00:00'); - $midnight_end = new DateTime('2015-01-26 00:00:00'); - $midday_start = new DateTime('2015-01-25 12:00:00'); - $midday_end = new DateTime('2015-01-26 12:00:00'); - $midnight_next_day = new DateTime('2015-01-27 00:00:00'); - //first test nulls - $this->assertFalse(EEH_DTT_Helper::dates_represent_one_24_hour_date(null, $midnight_end)); - $this->assertFalse(EEH_DTT_Helper::dates_represent_one_24_hour_date($midnight_start, null)); - //test non midnights - $this->assertFalse(EEH_DTT_Helper::dates_represent_one_24_hour_date($midnight_start, $midday_end)); - $this->assertFalse(EEH_DTT_Helper::dates_represent_one_24_hour_date($midday_start, $midnight_end)); - //test midnights but not 24 hours difference - $this->assertFalse(EEH_DTT_Helper::dates_represent_one_24_hour_date($midnight_start, $midnight_next_day)); - //test correct range - $this->assertTrue(EEH_DTT_Helper::dates_represent_one_24_hour_date($midnight_start, $midnight_end)); - } - - - /** - * @since 4.9.0.rc.025 - */ - public function test_get_timezone_string_for_display() - { - $offsets_to_test = array( - 0 => 'UTC+0:00', - 1 => 'UTC+1:00', - '-1.5' => 'UTC-1:30', - '1.25' => 'UTC+1:15', - ); - $original_timezone_string = get_option('timezone_string'); - $original_offset = get_option('gmt_offset'); - //first test when there is an actual timezone_string - update_option('timezone_string', 'America/New_York'); - $this->assertEquals('New York', EEH_DTT_Helper::get_timezone_string_for_display()); - //clear out timezone string and do offset tests - update_option('timezone_string', ''); - foreach ($offsets_to_test as $offset => $expected) { - update_option('gmt_offset', $offset); - $this->assertEquals($expected, EEH_DTT_Helper::get_timezone_string_for_display()); - } - //restore original timezone_string and offset - update_option('gmt_offset', $original_offset); - update_option('timezone_string', $original_timezone_string); - } - - - /** - * @since 4.9.27.rc - * @group 10417 - */ - public function test_tomorrow() - { - $original_offset = get_option('gmt_offset'); - $original_timezone_string = get_option('timezone_string'); - //set timezone offset to -5 and timezone_string to '' - update_option('gmt_offset', '-5'); - update_option('timezone_string', ''); - //the `5` is not a typo here. You may be thinking expected should be `-5` but the method we're testing converts - //offsets from negative to positive and from positive to negative so that the timestamp accurately represents - //midnight in that sites timezone as it exists in UTC+0 time. - $expected = strtotime('tomorrow') + (5 * 60 * 60); - $this->assertEquals($expected, EEH_DTT_Helper::tomorrow()); - //restore - update_option('gmt_offset', $original_offset); - update_option('timezone_string', $original_timezone_string); - } - - -} -// End of file EEH_DTT_Helper_Test.php -// Location: tests/testcases/core/helpers/EEH_DTT_Helper_Test.php diff --git a/tests/testcases/core/helpers/EEH_File_Test.php b/tests/testcases/core/helpers/EEH_File_Test.php deleted file mode 100644 index afc1fbb53e5..00000000000 --- a/tests/testcases/core/helpers/EEH_File_Test.php +++ /dev/null @@ -1,317 +0,0 @@ -init('/'); - } - - function tearDown() - { - // restore to using the normal WP filesystem - unset($GLOBALS['wp_filesystem']); - remove_filter('filesystem_method_file', array($this, 'filter_abstraction_file')); - remove_filter('filesystem_method', array($this, 'filter_fs_method')); - - parent::tearDown(); - } - - function filter_fs_method($method) - { - return 'MockEEFS'; - } - - function filter_abstraction_file($file) - { - return EE_TESTS_DIR . '/includes/mock-ee-fs.php'; - } - - /** - * Just makes sure we're really using the mock filesystem, not the real fileysstem - * @global type $wp_filesystem - */ - function test_is_MockFS_sane() - { - global $wp_filesystem; - $this->assertTrue(is_a($wp_filesystem, 'WP_Filesystem_MockEEFS')); - - $wp_filesystem->init('/'); - - // Test creation/exists checks - $this->assertFalse($wp_filesystem->is_dir('/test/')); - $wp_filesystem->mkdir('/test'); - $this->assertTrue($wp_filesystem->exists('/test')); - $this->assertTrue($wp_filesystem->is_dir('/test/')); - $this->assertFalse($wp_filesystem->is_file('/test')); - } - - - /** - * - * @global type $wp_filesystem - */ - public function test_verify_filepath_and_permissions() - { - global $wp_filesystem; - - // Test creation/exists checks - $this->assertFalse($wp_filesystem->is_dir('/test/')); - $wp_filesystem->mkdir('/test', '755'); - $this->assertTrue($wp_filesystem->is_dir('/test/')); - $this->assertTrue(EEH_File::verify_filepath_and_permissions('/test/')); - $wp_filesystem->chmod('/test/', '000'); - try { - EEH_File::verify_filepath_and_permissions('/test/'); - $this->fail(sprintf(__('An exception SHOULD have been thrown but wasn\'t', 'event_espresso'))); - } catch (EE_Error $e) { - $this->assertTrue(TRUE); - } - - - } - - /** - * - * @global type $wp_filesystem - */ - public function test_ensure_folder_exists_and_is_writable__and__is_writable() - { - global $wp_filesystem; - $folder_path = '/test/'; - // Test creation/exists checks - $this->assertFalse($wp_filesystem->is_dir($folder_path)); - $this->assertTrue(EEH_File::ensure_folder_exists_and_is_writable($folder_path)); - $this->assertTrue(EEH_File::verify_is_writable($folder_path)); - $wp_filesystem->chmod($folder_path, '000'); - try { - $this->assertFalse(EEH_File::ensure_folder_exists_and_is_writable($folder_path)); - $this->fail(sprintf(__('An exception SHOULD have been thrown but wasn\'t', 'event_espresso'))); - } catch (EE_Error $e) { - $this->assertTrue(TRUE); - } - try { - $this->assertFalse(EEH_File::verify_is_writable($folder_path)); - $this->fail(sprintf(__('An exception SHOULD have been thrown but wasn\'t', 'event_espresso'))); - } catch (EE_Error $e) { - $this->assertTrue(TRUE); - } - - } - - /** - * @group 9059 - * @global type $wp_filesystem - */ - function test_ensure_folder_exists_and_is_writable__recursive_folders() - { - global $wp_filesystem; - $folder_path = '/test/new/thing'; - // Test creation/exists checks - $this->assertFalse($wp_filesystem->is_dir($folder_path)); - $this->assertTrue(EEH_File::ensure_folder_exists_and_is_writable($folder_path)); - $folders_in_new_folder = $wp_filesystem->dirlist('/test/new/'); - $this->assertTrue(isset($folders_in_new_folder['thing'])); - $folders_in_new_folder = $wp_filesystem->dirlist('/test/new'); - $this->assertTrue(isset($folders_in_new_folder['thing'])); - } - - /** - * @group 9059 - * @global type $wp_filesystem - */ - function test_ensure_file_exists_and_is_writable__recursive_folders() - { - global $wp_filesystem; - $folder_path = '/test/new/thing.txt'; - // Test creation/exists checks - $this->assertFalse($wp_filesystem->is_dir($folder_path)); - $this->assertTrue(EEH_File::ensure_file_exists_and_is_writable($folder_path)); - $folders_in_new_folder = $wp_filesystem->dirlist('/test/new/'); - $this->assertTrue(isset($folders_in_new_folder['thing.txt'])); - $folders_in_new_folder = $wp_filesystem->dirlist('/test/new'); - $this->assertTrue(isset($folders_in_new_folder['thing.txt'])); - } - - /** - * - * @global type $wp_filesystem - */ - public function test_ensure_file_exists_and_is_writable() - { - global $wp_filesystem; - $file_path = '/test.txt'; - // Test creation/exists checks - $this->assertFalse($wp_filesystem->exists($file_path)); - $this->assertTrue(EEH_File::ensure_file_exists_and_is_writable($file_path)); - $this->assertTrue(EEH_File::verify_is_writable($file_path)); - $wp_filesystem->chmod($file_path, '000'); - try { - $this->assertFalse(EEH_File::ensure_file_exists_and_is_writable($file_path)); - $this->fail(sprintf(__('An exception SHOULD have been thrown but wasn\'t', 'event_espresso'))); - } catch (EE_Error $e) { - $this->assertTrue(TRUE); - } - try { - $this->assertFalse(EEH_File::verify_is_writable($file_path)); - $this->fail(sprintf(__('An exception SHOULD have been thrown but wasn\'t', 'event_espresso'))); - } catch (EE_Error $e) { - $this->assertTrue(TRUE); - } - - } - - /** - * - * @global type $wp_filesystem - */ - public function test_get_file_contents() - { - global $wp_filesystem; - $file_path = '/test.txt'; - $content = 'hello'; - // Test creation/exists checks - $this->assertFalse($wp_filesystem->exists($file_path)); - $wp_filesystem->put_contents($file_path, $content); - $this->assertTrue($wp_filesystem->exists($file_path)); - $this->assertEquals($content, EEH_File::get_file_contents($file_path)); - } - - /** - * - * @global type $wp_filesystem - */ - public function test_write_to_file() - { - global $wp_filesystem; - $wp_filesystem->chmod('/', '755'); - $file_path = '/test.txt'; - $content1 = 'hello'; - $content2 = ''; - $this->assertFalse($wp_filesystem->exists($file_path)); - $wp_filesystem->put_contents($file_path, $content1, '644'); - $this->assertTrue($wp_filesystem->exists($file_path)); - $this->assertEquals($content1, EEH_File::get_file_contents($file_path)); - //now add to it - EEH_File::write_to_file($file_path, $content2); - $this->assertEquals($content2, EEH_File::get_file_contents($file_path)); - } - - public function test_remove_filename_form_filepath() - { - $file_path = '/var/whatever/thing.txt'; - $this->assertEquals('/var/whatever', EEH_File::remove_filename_from_filepath($file_path)); - } - - public function test_get_filename_from_filepath() - { - $file_path = '/var/whatever/thing.txt'; - $this->assertEquals('thing.txt', EEH_File::get_filename_from_filepath($file_path)); - } - - public function test_get_file_extension() - { - $file_path = '/var/whatever/thing.txt'; - $this->assertEquals('txt', EEH_File::get_file_extension($file_path)); - } - - public function test_get_classname_from_filepath_with_standard_filename() - { - $file_path = '/we/fds/vdw/ew/EE_Thingy.junk.php'; - $this->assertEquals('EE_Thingy', EEH_File::get_classname_from_filepath_with_standard_filename($file_path)); - } - - public function test_standardise_diirectory_seperators_and_end_with_directory_separator() - { - $file_path = '/well\\this/isnt\\very/consistent'; - $this->assertEquals('/well/this/isnt/very/consistent/', EEH_File::standardise_and_end_with_directory_separator($file_path)); - } - - /** - * @group 9059 - */ - public function test_is_in_uploads_folder__barely() - { - $uploads = wp_upload_dir(); - $this->assertTrue(EEH_File::is_in_uploads_folder($uploads['basedir'])); - } - - /** - * @group 9059 - */ - public function test_is_in_uploads_folder__subfolder() - { - $this->assertTrue(EEH_File::is_in_uploads_folder(EVENT_ESPRESSO_UPLOAD_DIR . 'mazurky')); - } - - /** - * @group 9059 - */ - public function test_is_in_uploads_folder__elsewhere() - { - $this->assertFalse(EEH_File::is_in_uploads_folder('/var/somewhere/else/entirely')); - } - - /** - * @group 9059 - */ - public function test_is_in_uploads_folder__elsewhere_but_tricky() - { - $this->assertFalse(EEH_File::is_in_uploads_folder('/not/uploads/dir/' . EVENT_ESPRESSO_UPLOAD_DIR)); - } - - /** - * @group 9059 - */ - public function test_get_parent_folder__file() - { - $this->assertEquals( - '/var/something/', - EEH_File::get_parent_folder('/var/something/thingy.txt')); - } - - /** - * @group 9059 - */ - public function test_get_parent_folder__file_with_one_character() - { - $this->assertEquals( - '/var/something/', - EEH_File::get_parent_folder('/var/something/a')); - } - - /** - * @group 9059 - */ - public function test_get_parent_folder__folder() - { - $this->assertEquals( - '/var/something/', - EEH_File::get_parent_folder('/var/something/somewhere/')); - } - - -} - -// End of file EEH_File_Test.php \ No newline at end of file diff --git a/tests/testcases/core/helpers/EEH_Inflector_Test.php b/tests/testcases/core/helpers/EEH_Inflector_Test.php deleted file mode 100644 index 199138aae3a..00000000000 --- a/tests/testcases/core/helpers/EEH_Inflector_Test.php +++ /dev/null @@ -1,60 +0,0 @@ -assertEquals( 'events', EEH_Inflector::pluralize_and_lower( 'Event' ) ); - } - /** - * at first EEH_Inflector had trouble with the word 'price' because it contains the word - * 'rice', which word pluralizes to 'rice', not 'rices'; so it made the mistake of thinking - * the plural of 'price' was 'price' (not 'priceS') - */ - public function test_pluralize_and_lower__price() { - $this->assertEquals( 'prices', EEH_Inflector::pluralize_and_lower( 'Price' ) ); - } - - public function test_pluralize_and_lower__two_words() { - $this->assertEquals( 'price_types', EEH_Inflector::pluralize_and_lower( 'Price_Type' ) ); - } - - public function test_pluralize_and_lower__three_words() { - $this->assertEquals( 'question_group_questions', EEH_Inflector::pluralize_and_lower( 'Question_Group_Question' ) ); - } - - public function test_pluralize_and_lower__funny_plural() { - $this->assertEquals( 'term_taxonomies', EEH_Inflector::pluralize_and_lower( 'Term_Taxonomy' ) ); - } - public function test_singuralize_and_upper__basic() { - $this->assertEquals( 'Attendee', EEH_Inflector::singularize_and_upper( 'attendees' ) ); - } - public function test_singuralize_and_upper__price() { - $this->assertEquals( 'Price', EEH_Inflector::singularize_and_upper( 'prices' ) ); - } - public function test_singuralize_and_upper__two_words() { - $this->assertEquals( 'Datetime_Ticket', EEH_Inflector::singularize_and_upper( 'datetime_tickets' ) ); - } - public function test_singuralize_and_upper__three_words() { - $this->assertEquals( 'Question_Group_Question', EEH_Inflector::singularize_and_upper( 'question_group_questions' ) ); - } - public function test_singuralize_and_upper__funny_plural() { - $this->assertEquals( 'Term_Taxonomy', EEH_Inflector::singularize_and_upper( 'term_taxonomies' ) ); - } -} - -// End of file EEH_Inflector_Test.php \ No newline at end of file diff --git a/tests/testcases/core/helpers/EEH_Line_Item_Test.php b/tests/testcases/core/helpers/EEH_Line_Item_Test.php deleted file mode 100644 index 86576cc441e..00000000000 --- a/tests/testcases/core/helpers/EEH_Line_Item_Test.php +++ /dev/null @@ -1,930 +0,0 @@ -new_typical_transaction(); - $items_subtotals = EEM_Line_Item::instance()->get_all_of_type_for_transaction( EEM_Line_Item::type_sub_total, $transaction ); - $items_subtotal = array_shift( $items_subtotals ); - $eeh_found_items_subtotal = EEH_Line_Item::get_pre_tax_subtotal( $transaction->total_line_item() ); - $this->assertEquals( $items_subtotal, $eeh_found_items_subtotal ); - } - - public function test_create_default_total_line_item(){ - $total_line_item = EEH_Line_Item::create_total_line_item(); - $this->assertEquals( EEM_Line_Item::type_total, $total_line_item->type() ); - $pre_tax_subtotal = EEH_Line_Item::get_pre_tax_subtotal( $total_line_item ); - $this->assertEquals( EEM_Line_Item::type_sub_total, $pre_tax_subtotal->type() ); - $taxes_subtotal = EEH_Line_Item::get_taxes_subtotal( $total_line_item ); - $this->assertEquals( EEM_Line_Item::type_tax_sub_total, $taxes_subtotal->type() ); - $taxes = $taxes_subtotal->children(); - //by default there should be 1 tax at 15% - $this->assertEquals( 1, count( $taxes ) ); - $tax = array_shift( $taxes ); - $this->assertEquals(EEM_Line_Item::type_tax, $tax->type() ); - $this->assertEquals( 15, $tax->percent() ); - } - - /** - * test_add_ticket_purchase - */ - public function test_add_ticket_purchase(){ - // create grand total - $total_line_item = EEH_Line_Item::create_total_line_item(); - $this->assertEquals( 0, $total_line_item->total() ); - // create a ticket - $ticket = $this->new_ticket( array( - 'dollar_surcharge' => 5, - 'percent_surcharge' => 10, - 'datetimes' => 2 - ) ); - // need to save ticket for other tests to work - $ticket->save(); - // two tickets plz - $ticket_line_item = EEH_Line_Item::add_ticket_purchase( $total_line_item, $ticket, 2 ); - // confirm tickets - $this->assertEquals( 2, $ticket_line_item->quantity() ); - $this->assertEquals( 33, $ticket_line_item->total() ); - // confirm subtotal - $pre_tax_subtotal = EEH_Line_Item::get_pre_tax_subtotal( $total_line_item ); - $this->assertEquals( 33, $pre_tax_subtotal->total() ); - // confirm taxes - $taxes_subtotal = EEH_Line_Item::get_taxes_subtotal( $total_line_item ); - $this->assertEquals( 4.95, $taxes_subtotal->total() ); - // confirm totals - $this->assertEquals( 37.95, $total_line_item->total() ); - // one moar ticket plz - $ticket_line_item = EEH_Line_Item::add_ticket_purchase( $total_line_item, $ticket ); - // confirm tickets - $this->assertEquals( 3, $ticket_line_item->quantity() ); - $this->assertEquals( 49.5, $ticket_line_item->total() ); - // confirm subtotal - $this->assertEquals( 49.5, $pre_tax_subtotal->total() ); - // confirm taxes - $this->assertEquals( 7.43, $taxes_subtotal->total() ); - // confirm totals - $this->assertEquals( 56.93, $total_line_item->total() ); - // total ticket line items count? should just be one ticket line item - $this->assertEquals( 1, count( EEH_Line_Item::get_ticket_line_items( $total_line_item ) ) ); - // now add a different ticket - $new_ticket = $this->new_ticket( array( - 'TKT_price' => 10, - 'TKT_taxable' => false, - 'datetimes' => 1 - ) ); - $new_ticket->save(); - // add one - $new_ticket_line_item = EEH_Line_Item::add_ticket_purchase( $total_line_item, $new_ticket ); - $this->assertEquals( 1, $new_ticket_line_item->quantity() ); - // add one moar - $new_ticket_line_item = EEH_Line_Item::add_ticket_purchase( $total_line_item, $new_ticket ); - $this->assertEquals( 2, $new_ticket_line_item->quantity() ); - // confirm totals - $this->assertEquals( 20, $new_ticket_line_item->total() ); - $this->assertEquals( 69.5, $pre_tax_subtotal->total() ); - // should be same taxes as before - $this->assertEquals( 7.43, $taxes_subtotal->total() ); - $this->assertEquals( 76.93, $total_line_item->total() ); - // total ticket ticket line items? - $this->assertEquals( 2, count( EEH_Line_Item::get_ticket_line_items( $total_line_item ) ) ); - - } - - - - /** - * test_set_tax - */ - function test_set_tax(){ - //first create a line item - $txn = $this->new_typical_transaction(); - $line_item = $txn->total_line_item(); - $old_tax_subtotal = EEH_Line_Item::get_nearest_descendant_of_type( $line_item, EEM_Line_Item::type_tax_sub_total ); - $this->assertInstanceOf( 'EE_Line_Item', $old_tax_subtotal ); - EEH_Line_Item::get_nearest_descendant_of_type( $old_tax_subtotal, EEM_Line_Item::type_tax ); - - $new_tax = EEH_Line_Item::set_total_tax_to( $line_item, 1.5, 'Monkey Tax', 'Only monkey must pay' ); - $this->assertEquals( 1.5, $new_tax->total()); - $this->assertEquals( $new_tax->total(), $old_tax_subtotal->total() ); - $child_of_tax_subtotal = EEH_Line_Item::get_nearest_descendant_of_type( $old_tax_subtotal, EEM_Line_Item::type_tax ); - $this->assertEquals( $new_tax, $child_of_tax_subtotal ); - - $tax_total_before_recalculation = $old_tax_subtotal->total(); - $tax_before_recalculations = $new_tax->total(); - $line_item->recalculate_taxes_and_tax_total(); - - $this->assertEquals( $tax_before_recalculations, $new_tax->total() ); - $this->assertEquals( $tax_total_before_recalculation, $old_tax_subtotal->total() ); - } - /** - * @group 8193 - */ - public function test_calculate_reg_final_prices_per_line_item__1_nontaxable_ticket() { - $transaction = $this->new_typical_transaction( - array( - 'taxable_tickets' => 0 - )); - $totals = EEH_Line_Item::calculate_reg_final_prices_per_line_item( $transaction->total_line_item() ); - $this->assertEquals( $transaction->total(), $totals[ 'total' ] ); - $ticket_line_items = EEM_Line_Item::instance()->get_all( - array( - array( - 'TXN_ID' => $transaction->ID(), - 'LIN_type' => EEM_Line_Item::type_line_item - ) - )); - $this->assertEquals( 1, count( $ticket_line_items ) ); - $ticket_line_item = reset( $ticket_line_items ); - $this->assertEquals( 1, $ticket_line_item->quantity() ); - $this->assertEquals( $ticket_line_item->total(), $totals[ $ticket_line_item->ID() ] ); - } - - /** - * @group 8193 - */ - public function test_calculate_reg_final_prices_per_line_item__1_taxable_ticket() { - $transaction = $this->new_typical_transaction(); - $totals = EEH_Line_Item::calculate_reg_final_prices_per_line_item( $transaction->total_line_item() ); - $this->assertEquals( $transaction->total(), $totals[ 'total' ] ); - $ticket_line_items = EEM_Line_Item::instance()->get_all( - array( - array( - 'TXN_ID' => $transaction->ID(), - 'LIN_type' => EEM_Line_Item::type_line_item - ) - )); - $this->assertEquals( 1, count( $ticket_line_items ) ); - $ticket_line_item = reset( $ticket_line_items ); - $this->assertEquals( 1, $ticket_line_item->quantity() ); - /** @var EE_Ticket $ticket */ - $ticket = $ticket_line_item->ticket(); - $this->assertEquals( $ticket->get_ticket_total_with_taxes(), $totals[ $ticket_line_item->ID() ] ); - } - - /** - * @group 8193 - */ - public function test_calculate_reg_final_prices_per_line_item__1_taxable_ticket_with_quantity_of_2() { - $transaction = $this->new_typical_transaction(); - $ticket_line_items = EEM_Line_Item::instance()->get_all( - array( - array( - 'TXN_ID' => $transaction->ID(), - 'LIN_type' => EEM_Line_Item::type_line_item - ) - )); - $this->assertEquals( 1, count( $ticket_line_items ) ); - $ticket_line_item = reset( $ticket_line_items ); - $ticket_line_item->set_quantity( 2 ); - $transaction->total_line_item()->recalculate_total_including_taxes(); - $this->assertEquals( 2, $ticket_line_item->quantity() ); - /** @var EE_Ticket $ticket */ - $ticket = $ticket_line_item->ticket(); - - $totals = EEH_Line_Item::calculate_reg_final_prices_per_line_item( $transaction->total_line_item() ); - $this->assertEquals( $transaction->total(), $totals[ 'total' ] ); - $this->assertEquals( $ticket->get_ticket_total_with_taxes(), $totals[ $ticket_line_item->ID() ] ); - } - - /** - * @group 8193 - */ - public function test_calculate_reg_final_prices_per_line_item__1_taxable_ticket_with_a_discount() { - $transaction = $this->new_typical_transaction(); - EEH_Line_Item::add_unrelated_item( $transaction->total_line_item(), 'Some Discount', -5 ); - - $totals = EEH_Line_Item::calculate_reg_final_prices_per_line_item( $transaction->total_line_item() ); - $this->assertEquals( $transaction->total(), $totals[ 'total' ] ); - $ticket_line_items = EEM_Line_Item::instance()->get_all( - array( - array( - 'TXN_ID' => $transaction->ID(), - 'LIN_type' => EEM_Line_Item::type_line_item, - 'OBJ_type' => 'Ticket' - ) - )); - $this->assertEquals( 1, count( $ticket_line_items ) ); - $ticket_line_item = reset( $ticket_line_items ); - $this->assertEquals( 6.50, $totals[ $ticket_line_item->ID() ] ); - -// honestly the easiest way to confirm the total was right is to visualize the tree -// EEH_Line_Item::visualize( $transaction->total_line_item() ); - } - - /** - * @group 8193 - */ - public function test_calculate_reg_final_prices_per_line_item__3_taxable_tickets_with_a_discount() { - $transaction = $this->new_typical_transaction( - array( - 'ticket_types' => 2 - )); - //add another ticket purchase for one of the same events - $event1 = EEM_Event::instance()->get_one( - array( - array( - 'Registration.TXN_ID' => $transaction->ID() - ) - )); - $dtt = $event1->get_first_related( 'Datetime' ); - $new_tkt = $this->new_model_obj_with_dependencies( 'Ticket', array( 'TKT_price' => 6 ) ); - $new_tkt->_add_relation_to( $dtt, 'Datetime' ); - $quantity_of_new_tks_purchased = 2; - EEH_Line_Item::add_ticket_purchase( $transaction->total_line_item(), $new_tkt, $quantity_of_new_tks_purchased ); - for( $i = 0; $i < 2; $i++ ) { - $this->new_model_obj_with_dependencies( 'Registration', - array( - 'TXN_ID' => $transaction->ID(), - 'EVT_ID' => $dtt->get( 'EVT_ID' ), - 'TKT_ID' => $new_tkt->ID(), - )); - } - //and add an unrelated purchase - EEH_Line_Item::add_unrelated_item( $transaction->total_line_item(), 'Transaction-Wide Discount', -5 ); - - $totals = EEH_Line_Item::calculate_reg_final_prices_per_line_item( $transaction->total_line_item() ); - - // honestly the easiest way to confirm the total was right is to visualize the tree -// var_dump( $totals ); -// EEH_Line_Item::visualize( $transaction->total_line_item() ); - - //verify that if we added the REG_final_prices onto the regs as derived from $totals, - //that it would equal the grand total - $sum_of_regs_final_prices = 0; - foreach( $transaction->registrations() as $reg ) { - $ticket_line_item = EEM_Line_Item::instance()->get_line_item_for_registration( $reg ); - $sum_of_regs_final_prices += $totals[ $ticket_line_item->ID() ]; - } - $this->assertEquals( $totals[ 'total' ], $sum_of_regs_final_prices ); - - //ok now let's verify the 'REG_final_price' for each ticket's line item is what we expect it to be - //so there should be 3 ticket line items right? - $ticket_line_items = EEM_Line_Item::instance()->get_all( - array( - array( - 'TXN_ID' => $transaction->ID(), - 'OBJ_type' => 'Ticket' - ) - )); - $this->assertCount(3, $ticket_line_items); - //one ticket should be 10 pre-tax - $ten_dollar_ticket = EEM_Line_Item::instance()->get_one( array( - array( - 'TXN_ID' => $transaction->ID(), - 'LIN_unit_price' => 10, - 'LIN_type' => EEM_Line_Item::type_line_item, - ) - )); - $this->assertEquals( 10.31, round( $totals[ $ten_dollar_ticket->ID() ], 2 ) ); - //one ticket should be 20 pre-tax - $twenty_dollar_ticket = EEM_Line_Item::instance()->get_one( array( - array( - 'TXN_ID' => $transaction->ID(), - 'LIN_unit_price' => 20, - 'LIN_type' => EEM_Line_Item::type_line_item, - ) - )); - $this->assertEquals( 20.62, round( $totals[ $twenty_dollar_ticket->ID() ], 2 ) ); - //one ticket should be for 6 pre-tax (although its non-taxable anyway) - $six_dollar_ticket = EEM_Line_Item::instance()->get_one( array( - array( - 'TXN_ID' => $transaction->ID(), - 'LIN_unit_price' => 6, - 'LIN_type' => EEM_Line_Item::type_line_item, - ) - )); - $this->assertEquals( 5.29, round( $totals[ $six_dollar_ticket->ID() ], 2 ) ); - } - - /** - * @group 8193 - */ - public function test_calculate_reg_final_prices_per_line_item__3_taxable_tickets_with_an_event_wide_discount() { - $number_of_tickets = 2; - $transaction = $this->new_typical_transaction( array( 'ticket_types' => $number_of_tickets )); - //add another ticket purchase for one of the same events - $event1 = EEM_Event::instance()->get_one( - array( - array( - 'Registration.TXN_ID' => $transaction->ID() - ) - )); - /** @var EE_Line_Item $event_line_item */ - $event_line_item = EEM_Line_Item::instance()->get_one( - array( - array( - 'TXN_ID' => $transaction->ID(), - 'OBJ_type' => 'Event', - 'OBJ_ID' => $event1->ID() ))); - $this->new_model_obj_with_dependencies( 'Line_Item', - array( - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_name' => 'event discount', - 'LIN_total' => -8, - 'LIN_unit_price' => -8, - 'LIN_quantity' => 1, - 'LIN_parent' => $event_line_item->ID(), - 'LIN_percent' => null, - 'LIN_order' => count( $event_line_item->children() ) - )); - $transaction->total_line_item()->recalculate_pre_tax_total(); - //and add an unrelated purchase - EEH_Line_Item::add_unrelated_item( $transaction->total_line_item(), 'Transaction-Wide Discount', -5 ); - - $totals = EEH_Line_Item::calculate_reg_final_prices_per_line_item( $transaction->total_line_item() ); - - // honestly the easiest way to confirm the total was right is to visualize the tree -// var_dump( $totals ); -// EEH_Line_Item::visualize( $transaction->total_line_item() ); - - //verify that if we added the REG_final_prices onto the regs as derived from $totals, - //that it would equal the grand total - $sum_of_regs_final_prices = 0; - foreach( $transaction->registrations() as $reg ) { - $ticket_line_item = EEM_Line_Item::instance()->get_line_item_for_registration( $reg ); - $sum_of_regs_final_prices += $totals[ $ticket_line_item->ID() ]; - } - $this->assertEquals( $totals[ 'total' ], $sum_of_regs_final_prices ); - - //ok now let's verify the 'REG_final_price' for each ticket's line item is what we expect it to be - //so there should be 3 ticket line items right? - $ticket_line_items = EEM_Line_Item::instance()->get_all( - array( - array( - 'TXN_ID' => $transaction->ID(), - 'OBJ_type' => 'Ticket' - ) - )); - $this->assertCount( $number_of_tickets, $ticket_line_items ); - //one ticket should be 10 pre-tax - $ten_dollar_ticket = EEM_Line_Item::instance()->get_one( array( - array( - 'TXN_ID' => $transaction->ID(), - 'LIN_unit_price' => 10, - 'LIN_type' => EEM_Line_Item::type_line_item, - ) - )); - $this->assertEquals( 3.05, round( $totals[ $ten_dollar_ticket->ID() ], 2 ) ); - //one ticket should be 20 pre-tax - $twenty_dollar_ticket = EEM_Line_Item::instance()->get_one( array( - array( - 'TXN_ID' => $transaction->ID(), - 'LIN_unit_price' => 20, - 'LIN_type' => EEM_Line_Item::type_line_item, - ) - )); - $this->assertEquals( 18.45, round( $totals[ $twenty_dollar_ticket->ID() ], 2 ) ); - } - - /** - * This tests the case where we buy 1 taxable $10 ticket and a nontaxable $10 ticket, - * and apply a 50% taxable discount (ie, taxes factor it in), and there is a 10% tax. - * After teh discount, each should cost $5, and the taxable one should add 10% onto it. - * So we shoudl end up with one costing $5.50 and one $5. - * @group 8193 - */ - function test_calculate_reg_final_prices_per_line_item__percent_discount_partially_taxable() { - $grand_total = $this->new_model_obj_with_dependencies( 'Line_Item', - array( - 'LIN_name' => 'total', - 'LIN_type' => EEM_Line_Item::type_total, - 'LIN_total' => 0 - )); - $subtotal = $this->new_model_obj_with_dependencies( 'Line_Item', - array( - 'LIN_name' => 'subtotal', - 'LIN_type' => EEM_Line_Item::type_sub_total, - 'LIN_total' => 0, - 'LIN_unit_price' => 0, - 'LIN_quantity' => 0, - 'LIN_parent' => $grand_total->ID(), - 'LIN_order' => 0, - )); - $taxable = $this->new_model_obj_with_dependencies( 'Line_Item', - array( - 'LIN_name' => 'taxable', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_is_taxable' => true, - 'LIN_total' => 10, - 'LIN_unit_price' => 10, - 'LIN_quantity' => 1, - 'LIN_parent' => $subtotal->ID(), - 'LIN_order' => 1, - 'OBJ_type' => 'Ticket', - )); - $nontaxable = $this->new_model_obj_with_dependencies( 'Line_Item', - array( - 'LIN_name' => 'taxable', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_is_taxable' => false, - 'LIN_total' => 10, - 'LIN_unit_price' => 10, - 'LIN_quantity' => 1, - 'LIN_parent' => $subtotal->ID(), - 'LIN_order' => 2, - 'OBJ_type' => 'Ticket', - )); - $this->new_model_obj_with_dependencies( 'Line_Item', - array( - 'LIN_name' => 'discount', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_is_taxable' => true, - 'LIN_total' => -10, - 'LIN_unit_price' => 0, - 'LIN_percent' => -50, - 'LIN_quantity' => 1, - 'LIN_parent' => $subtotal->ID(), - 'LIN_order' => 3, - )); - $this->new_model_obj_with_dependencies( 'Line_Item', - array( - 'LIN_name' => 'taxes', - 'LIN_type' => EEM_Line_Item::type_tax_sub_total, - 'LIN_percent' => 10, - 'LIN_parent' => $grand_total->ID(), - 'LIN_order' => 1, - )); - - $totals = EEH_Line_Item::calculate_reg_final_prices_per_line_item( $grand_total ); - $this->assertEquals( 5.5, $totals[ $taxable->ID() ] ); - $this->assertEquals( 5, $totals[ $nontaxable->ID() ] ); -// var_dump($totals); -// EEH_Line_Item::visualize( $subtotal ); - } - - /** - * Verifies discounts only apply to the their sibling ticket line item's REG_final_prices - * @group 8541 - */ - function test_calculate_reg_final_prices_per_line_item__discount_only_for_one_event_subtotal() { - $grand_total = $this->new_model_obj_with_dependencies( 'Line_Item', - array( - 'LIN_name' => 'total', - 'LIN_type' => EEM_Line_Item::type_total, - 'LIN_total' => 0 - )); - $subtotal_a = $this->new_model_obj_with_dependencies( 'Line_Item', - array( - 'LIN_name' => 'subtotal_a', - 'LIN_type' => EEM_Line_Item::type_sub_total, - 'LIN_total' => 0, - 'LIN_unit_price' => 0, - 'LIN_quantity' => 0, - 'LIN_parent' => $grand_total->ID(), - 'LIN_order' => 0, - )); - $subtotal_b = $this->new_model_obj_with_dependencies( 'Line_Item', - array( - 'LIN_name' => 'subtotal_b', - 'LIN_type' => EEM_Line_Item::type_sub_total, - 'LIN_total' => 0, - 'LIN_unit_price' => 0, - 'LIN_quantity' => 0, - 'LIN_parent' => $grand_total->ID(), - 'LIN_order' => 1, - )); - $ticket_line_item_a = $this->new_model_obj_with_dependencies( 'Line_Item', - array( - 'LIN_name' => 'ticket_line_item_a', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_is_taxable' => false, - 'LIN_total' => 10, - 'LIN_unit_price' => 10, - 'LIN_quantity' => 1, - 'LIN_parent' => $subtotal_a->ID(), - 'LIN_order' => 1, - 'OBJ_type' => 'Ticket', - )); - $ticket_line_item_b = $this->new_model_obj_with_dependencies( 'Line_Item', - array( - 'LIN_name' => 'ticket_line_item_b', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_is_taxable' => false, - 'LIN_total' => 10, - 'LIN_unit_price' => 10, - 'LIN_quantity' => 1, - 'LIN_parent' => $subtotal_b->ID(), - 'LIN_order' => 1, - 'OBJ_type' => 'Ticket', - )); - $this->new_model_obj_with_dependencies( 'Line_Item', - array( - 'LIN_name' => 'discount_for_b', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_is_taxable' => false, - 'LIN_total' => -5, - 'LIN_unit_price' => 0, - 'LIN_percent' => -50, - 'LIN_quantity' => 1, - 'LIN_parent' => $subtotal_b->ID(), - 'LIN_order' => 100, - )); - $this->new_model_obj_with_dependencies( 'Line_Item', - array( - 'LIN_name' => 'taxes', - 'LIN_type' => EEM_Line_Item::type_tax_sub_total, - 'LIN_percent' => 0, - 'LIN_parent' => $grand_total->ID(), - 'LIN_order' => 1, - )); - - $totals = EEH_Line_Item::calculate_reg_final_prices_per_line_item( $grand_total ); -// var_dump($totals); -// EEH_Line_Item::visualize( $grand_total ); - //now verify the discount only applied to event B's ticket, not event A's - $this->assertEquals( 10, $totals[ $ticket_line_item_a->ID() ] ); - $this->assertEquals( 5, $totals[ $ticket_line_item_b->ID() ] ); - } - - - /** - * Create a line item tree which was originally for 6 tickets and a discount, - * but 2 got cancelled and so shouldn't count towards the grand total, - * and so the ticket line item's quantity should be 4 - * @group 5580 - */ - function test_cancel_ticket_line_item__with_sub_items_already(){ - $grand_total = EE_Line_Item::new_instance( - array( - 'LIN_code' => 'total', - 'LIN_name' => __( 'Grand Total', 'event_espresso' ), - 'LIN_type' => EEM_Line_Item::type_total, - 'OBJ_type' => 'Transaction' - ) - ); - $grand_total->save(); - $event_subtotal = EE_Line_Item::new_instance( - array( - 'LIN_code' => 'event1', - 'LIN_name' => 'EventA', - 'LIN_type' => EEM_Line_Item::type_sub_total, - 'OBJ_type' => 'Event', - 'LIN_total' => 0, - 'LIN_parent' => $grand_total->ID(), - )); - $event_subtotal->save(); - $normal_line_item = EE_Line_Item::new_instance( - array( - 'LIN_code' => '12354', - 'LIN_name' => 'ticketA', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'OBJ_type' => 'Ticket', - 'LIN_unit_price' => 10, - 'LIN_quantity' => 6, - 'LIN_order' => 1, - 'LIN_parent' => $event_subtotal->ID() - )); - $normal_line_item->save(); - $subitem_base_price = EE_Line_Item::new_instance( - array( - 'LIN_code' => 'baseprice', - 'LIN_name' => 'basepriceA', - 'LIN_type' => EEM_Line_Item::type_sub_line_item, - 'OBJ_type' => 'Price', - 'LIN_unit_price' => 20, - 'LIN_quantity' => 6, - 'LIN_order' => 1, - 'LIN_parent' => $normal_line_item->ID() - )); - $subitem_base_price->save(); - $subitem_percent_price = EE_Line_Item::new_instance( - array( - 'LIN_code' => 'percentdiscount', - 'LIN_name' => 'percentprice', - 'LIN_type' => EEM_Line_Item::type_sub_line_item, - 'OBJ_type' => 'Price', - 'LIN_unit_price' => 0, - 'LIN_percent' => -50, - 'LIN_quantity' => 1, - 'LIN_order' => 2, - 'LIN_parent' => $normal_line_item->ID() - )); - $subitem_percent_price->save(); - - $cancellation_subitem = EE_Line_Item::new_instance( - array( - 'LIN_code' => 'cancellationoruny', - 'LIN_name' => 'cancellationOfA', - 'LIN_type' => EEM_Line_Item::type_cancellation, - 'OBJ_type' => '',//? - 'LIN_unit_price' => 10, - 'LIN_quantity' => 1, - 'LIN_total' => 10, - 'LIN_order' => 3, - 'LIN_parent' => $normal_line_item->ID() - )); - $cancellation_subitem->save(); - $percent_line_item = EE_Line_Item::new_instance( - array( - 'LIN_code' => 'dscntfry', - 'LIN_name' => 'Discounto', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'OBJ_type' => '', - 'LIN_unit_price' => null, - 'LIN_quantity' => null, - 'LIN_percent' => -25, - 'LIN_order' => 1000, - 'LIN_parent' => $event_subtotal->ID() - )); - $percent_line_item->save(); - $event_subtotal->recalculate_total_including_taxes(); - // EEH_Line_Item::visualize( $event_subtotal ); - $this->assertEquals( 60, $normal_line_item->total() ); - $this->assertEquals( 45, $event_subtotal->total() ); - $this->assertEquals( -15, $percent_line_item->total() ); - - //ok now cancel a few and make sure the totals add up correctly - EEH_Line_Item::cancel_ticket_line_item( $normal_line_item ); - EEH_Line_Item::cancel_ticket_line_item( $normal_line_item ); - $event_subtotal->recalculate_total_including_taxes(); - // EEH_Line_Item::visualize( $event_subtotal ); - $this->assertEquals( 40, $normal_line_item->total() ); - $this->assertEquals( 30, $event_subtotal->total() ); - $this->assertEquals( -10, $percent_line_item->total() ); - $cancellation_line_items = EEH_Line_Item::get_descendants_of_type( $event_subtotal, EEM_Line_Item::type_cancellation ); - $the_only_cancellation_item = reset( $cancellation_line_items ); - $this->assertEquals( 3, $the_only_cancellation_item->quantity() ); - $this->assertEquals( 10, $the_only_cancellation_item->total() ); - } - - /** - * Checks we correctly add a cancellation line item - * @group 5580 - */ - function test_cancel_ticket_line_item__with_no_previous_cancellations(){ - $grand_total = EE_Line_Item::new_instance( - array( - 'LIN_code' => 'total', - 'LIN_name' => __( 'Grand Total', 'event_espresso' ), - 'LIN_type' => EEM_Line_Item::type_total, - 'OBJ_type' => 'Transaction' - ) - ); - $grand_total->save(); - $event_subtotal = EE_Line_Item::new_instance( - array( - 'LIN_code' => 'event1', - 'LIN_name' => 'EventA', - 'LIN_type' => EEM_Line_Item::type_sub_total, - 'OBJ_type' => 'Event', - 'LIN_total' => 0, - 'LIN_parent' => $grand_total->ID(), - )); - $event_subtotal->save(); - $normal_line_item = EE_Line_Item::new_instance( - array( - 'LIN_code' => '12354', - 'LIN_name' => 'ticketA', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'OBJ_type' => 'Ticket', - 'LIN_unit_price' => 10, - 'LIN_quantity' => 6, - 'LIN_order' => 1, - 'LIN_parent' => $event_subtotal->ID() - )); - $normal_line_item->save(); - $subitem_base_price = EE_Line_Item::new_instance( - array( - 'LIN_code' => 'baseprice', - 'LIN_name' => 'basepriceA', - 'LIN_type' => EEM_Line_Item::type_sub_line_item, - 'OBJ_type' => 'Price', - 'LIN_unit_price' => 20, - 'LIN_quantity' => 6, - 'LIN_order' => 1, - 'LIN_parent' => $normal_line_item->ID() - )); - $subitem_base_price->save(); - $subitem_percent_price = EE_Line_Item::new_instance( - array( - 'LIN_code' => 'percentdiscount', - 'LIN_name' => 'percentprice', - 'LIN_type' => EEM_Line_Item::type_sub_line_item, - 'OBJ_type' => 'Price', - 'LIN_unit_price' => 0, - 'LIN_percent' => -50, - 'LIN_quantity' => 1, - 'LIN_order' => 2, - 'LIN_parent' => $normal_line_item->ID() - )); - $subitem_percent_price->save(); - $percent_line_item = EE_Line_Item::new_instance( - array( - 'LIN_code' => 'dscntfry', - 'LIN_name' => 'Discounto', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'OBJ_type' => '', - 'LIN_unit_price' => null, - 'LIN_quantity' => null, - 'LIN_percent' => -25, - 'LIN_order' => 1000, - 'LIN_parent' => $event_subtotal->ID() - )); - $percent_line_item->save(); - $grand_total->recalculate_total_including_taxes(); - // EEH_Line_Item::visualize( $grand_total ); - $this->assertEquals( 60, $normal_line_item->total() ); - $this->assertEquals( 45, $event_subtotal->total() ); - $this->assertEquals( -15, $percent_line_item->total() ); - - //ok now cancel a few and make sure the totals add up correctly - EEH_Line_Item::cancel_ticket_line_item( $normal_line_item, 2 ); - $grand_total->recalculate_total_including_taxes(); - // EEH_Line_Item::visualize( $grand_total ); - $this->assertEquals( 40, $normal_line_item->total() ); - $this->assertEquals( 30, $event_subtotal->total() ); - $this->assertEquals( -10, $percent_line_item->total() ); - $cancellation_line_items = EEH_Line_Item::get_descendants_of_type( $event_subtotal, EEM_Line_Item::type_cancellation ); - $the_only_cancellation_item = reset( $cancellation_line_items ); - $this->assertEquals( 2, $the_only_cancellation_item->quantity() ); - $this->assertEquals( 0, $the_only_cancellation_item->total() ); - } - - /** - * Create a line item tree which was originally for 6 tickets and a discount, - * but 2 got cancelled and so shouldn't count towards the grand total. When - * we reinstate a ticket, the ticket's quantity should change from 4 to 5, and - * then when both are reinstated it should increase to 6 and the cancellation - * line item should be removed - * @group 5580 - */ - function test_reinstate_canceled_ticket_line_item(){ - $grand_total = EE_Line_Item::new_instance( - array( - 'LIN_code' => 'total', - 'LIN_name' => __( 'Grand Total', 'event_espresso' ), - 'LIN_type' => EEM_Line_Item::type_total, - 'OBJ_type' => 'Transaction' - ) - ); - $grand_total->save(); - $event_subtotal = EE_Line_Item::new_instance( - array( - 'LIN_code' => 'event1', - 'LIN_name' => 'EventA', - 'LIN_type' => EEM_Line_Item::type_sub_total, - 'OBJ_type' => 'Event', - 'LIN_total' => 1, - 'LIN_parent' => $grand_total->ID(), - )); - $event_subtotal->save(); - $normal_line_item = EE_Line_Item::new_instance( - array( - 'LIN_code' => '12354', - 'LIN_name' => 'ticketA', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'OBJ_type' => 'Ticket', - 'LIN_unit_price' => 10, - 'LIN_quantity' => 4, - 'LIN_order' => 1, - 'LIN_parent' => $event_subtotal->ID() - )); - $normal_line_item->save(); - $subitem_base_price = EE_Line_Item::new_instance( - array( - 'LIN_code' => 'baseprice', - 'LIN_name' => 'basepriceA', - 'LIN_type' => EEM_Line_Item::type_sub_line_item, - 'OBJ_type' => 'Price', - 'LIN_unit_price' => 10, - 'LIN_quantity' => 4, - 'LIN_order' => 1, - 'LIN_parent' => $normal_line_item->ID() - )); - $subitem_base_price->save(); - $cancellation_subitem = EE_Line_Item::new_instance( - array( - 'LIN_code' => 'cancellationoruny', - 'LIN_name' => 'cancellationOfA', - 'LIN_type' => EEM_Line_Item::type_cancellation, - 'OBJ_type' => '',//? - 'LIN_unit_price' => 10, - 'LIN_quantity' => 2, - 'LIN_order' => 2, - 'LIN_parent' => $normal_line_item->ID() - )); - $cancellation_subitem->save(); - $grand_total->recalculate_total_including_taxes(); - // EEH_Line_Item::visualize( $grand_total ); - $this->assertEquals( 40, $normal_line_item->total() ); - //remove the last cancellation - EEH_Line_Item::reinstate_canceled_ticket_line_item( $normal_line_item ); - $grand_total->recalculate_total_including_taxes(); - // EEH_Line_Item::visualize( $grand_total ); - $this->assertEquals( 5, $normal_line_item->quantity() ); - $this->assertEquals( 50, $normal_line_item->total() ); - $this->assertEquals( 1, $cancellation_subitem->quantity() ); - //remove another cancellation - EEH_Line_Item::reinstate_canceled_ticket_line_item( $normal_line_item ); - $grand_total->recalculate_total_including_taxes(); - // EEH_Line_Item::visualize( $grand_total ); - $this->assertEquals( 6, $normal_line_item->quantity() ); - $this->assertEquals( 60, $normal_line_item->total() ); - $this->assertEquals( 0, $cancellation_subitem->quantity() ); - // and then cancel one of the tickets again - EEH_Line_Item::cancel_ticket_line_item( $normal_line_item ); - $grand_total->recalculate_total_including_taxes(); - // EEH_Line_Item::visualize( $grand_total ); - } - - - - /** - * @group 4710 - */ - function test_set_line_items_taxable() { - $t = $this->new_typical_transaction( array( 'taxable_tickets' => 0 ) ); - EEH_Line_Item::add_unrelated_item( $t->total_line_item(), 'Exempt Line Item', 1, 'Description', 1, false, 'exempt_me'); - $reg_line_items = EEH_Line_Item::get_descendants_of_type( $t->total_line_item(), EEM_Line_Item::type_line_item ); - foreach( $reg_line_items as $line_item ) { - $this->assertFalse( $line_item->is_taxable(), print_r( $line_item->model_field_array(), true ) ); - } - EEH_Line_Item::set_line_items_taxable( $t->total_line_item(), true, 'exempt_me' ); - foreach( $reg_line_items as $line_item ) { - if( $line_item->code() == 'exempt_me' ) { - $this->assertFalse( $line_item->is_taxable(), print_r( $line_item->model_field_array(), true ) ); - } else { - $this->assertTrue( $line_item->is_taxable(), print_r( $line_item->model_field_array(), true ) ); - } - } - } - - - - function test_recalculate_total_including_taxes_after_ticket_cancellation() { - // create txn with one $10 ticket that is taxable at default 15% rate - $transaction = $this->new_typical_transaction( array( 'taxable_tickets' => 1 ) ); - $registrations = $transaction->registrations(); - $registration = reset( $registrations ); - $this->assertInstanceOf( 'EE_Registration', $registration ); - $ticket1 = $registration->ticket(); - $this->assertEquals( 10, $ticket1->price() ); - $total_line_item = $transaction->total_line_item(); - $this->assertInstanceOf( 'EE_Line_Item', $total_line_item ); - $this->assertEquals( 11.5, $total_line_item->total() ); - // EEH_Line_Item::visualize( $total_line_item ); - // now cancel the registration - $registration->set_status( \EEM_Registration::status_id_cancelled ); - $registration->save(); - // EEH_Line_Item::cancel_ticket_line_item( $ticket_line_item ); - // now retrieve the line item for the ticket - $ticket_line_items = EEH_Line_Item::get_ticket_line_items( $total_line_item ); - $this->assertCount( 1, $ticket_line_items ); - $ticket_line_item = reset( $ticket_line_items ); - $this->assertInstanceOf( 'EE_Line_Item', $ticket_line_item ); - // and check its quantity - $this->assertEquals( 0, $ticket_line_item->quantity() ); - // EEH_Line_Item::visualize( $total_line_item ); - $ticket_line_items = array(); - $ticket_line_item = null; - // echo "\n\n now add a new $15 ticket: \n"; - // now add a new ticket - $ticket2 = $this->new_ticket( array( 'TKT_price' => 15, 'TKT_taxable' => false ) ); - $this->assertEquals( 15, $ticket2->price() ); - EEH_Line_Item::add_ticket_purchase( $total_line_item, $ticket2 ); - // EEH_Line_Item::visualize( $total_line_item ); - $ticket_line_items = EEH_Line_Item::get_ticket_line_items( $total_line_item ); - $this->assertCount( 2, $ticket_line_items ); - // find ticket 2 - foreach ( $ticket_line_items as $ticket_line_item ) { - if ( $ticket_line_item->OBJ_type() === 'Ticket' && $ticket_line_item->OBJ_ID() === $ticket2->ID() ) { - $this->assertEquals( $ticket2->price(), $ticket_line_item->total() ); - } - } - $this->assertEquals( 15, $total_line_item->total() ); - } - - - - public function test_event_subtotal_line_items() { - $transaction = $this->new_typical_transaction( array( 'ticket_types' => 2 ) ); - /** @var EE_Line_Item $total_line_item */ - $total_line_item = $transaction->total_line_item(); - $total_line_item->recalculate_total_including_taxes(); - // EEH_Line_Item::visualize( $total_line_item ); - foreach ( EEH_Line_Item::get_event_subtotals( $total_line_item ) as $event_line_item ) { - $this->assertNotEquals( 0.0, $event_line_item->unit_price() ); - $this->assertEquals( $event_line_item->unit_price(), ( $event_line_item->total() / $event_line_item->quantity() ) ); - } - } - -} - -// End of file EEH_Line_Item_Test.php -// Location: /tests/testcases/core/helpers/EEH_Line_Item_Test.php \ No newline at end of file diff --git a/tests/testcases/core/helpers/EEH_MSG_Template_Test.php b/tests/testcases/core/helpers/EEH_MSG_Template_Test.php deleted file mode 100644 index deb81d8fba1..00000000000 --- a/tests/testcases/core/helpers/EEH_MSG_Template_Test.php +++ /dev/null @@ -1,109 +0,0 @@ -_message_resource_manager = EE_Registry::instance()->load_lib( 'Message_Resource_Manager' ); - $this->assertInstanceOf( 'EE_Message_Resource_Manager', $this->_message_resource_manager ); - } - - - public function tearDown() { - parent::tearDown(); - $this->_message_resource_manager = null; - } - - - /** - * test messenger that should be active - * - * @since 4.4.1 - */ - public function test_get_active_messenger() { - EEH_Activation::generate_default_message_templates(); - $Message_Resource_Manager = EE_Registry::instance()->load_lib( 'Message_Resource_Manager' ); - $this->assertInstanceOf( - 'EE_messenger', - $Message_Resource_Manager->get_active_messenger( 'email' ) - ); - $this->assertNotInstanceOf( - 'EE_messenger', - $Message_Resource_Manager->get_active_messenger( 'some_random_messenger' ) - ); - } - - - /** - * @since 4.9.0 - */ - public function test_create_new_templates() { - //let's first delete known global templates for the purpose of the test - $MessageTemplateGroup = EEM_Message_Template_Group::instance()->get_one( - array( - array( - 'MTP_messenger' => 'html', - 'MTP_message_type' => 'invoice', - 'MTP_is_global' => true - ) - ) - ); - - $this->assertInstanceOf( 'EE_Message_Template_Group', $MessageTemplateGroup ); - $MessageTemplateGroup->delete_related_permanently( 'Message_Template' ); - $MessageTemplateGroup->delete_permanently(); - - //try to retrieve again just to verify its been deleted. - $MessageTemplateGroup = EEM_Message_Template_Group::instance()->get_one( - array( - array( - 'MTP_messenger' => 'html', - 'MTP_message_type' => 'invoice', - 'MTP_is_global' => true - ) - ) - ); - $this->assertNull( $MessageTemplateGroup ); - - //okay now we can do our create templates test. - EE_Registry::instance()->load_helper( 'MSG_Template' ); - $templates = EEH_MSG_Template::create_new_templates( - 'html', - 'invoice', - 0, - true - ); - $this->assertTrue( is_array( $templates ) ); - $this->assertEquals( 2, count( $templates ) ); - $this->assertTrue( isset( $templates['GRP_ID'] ) ); - $this->assertTrue( isset( $templates['MTP_context'] ) ); - $this->assertTrue( $templates['GRP_ID'] > 0 ); - } - - -} //end EEH_MSG_Template_Test -// Location: tests/testcases/core/helpers/EEH_MSG_Template_Test.php diff --git a/tests/testcases/core/helpers/EEH_Parse_Shortcodes_Test.php b/tests/testcases/core/helpers/EEH_Parse_Shortcodes_Test.php deleted file mode 100644 index 94818050e98..00000000000 --- a/tests/testcases/core/helpers/EEH_Parse_Shortcodes_Test.php +++ /dev/null @@ -1,414 +0,0 @@ -factory->price_chained->create_object(array( - 'PRC_name' => 'Not Free Price', - 'PRC_amount' => '125.00', - )); - $this->_ticket = $this->factory->ticket_chained->create_object(array('PRC_ID' => $price->ID())); - //update ticket price - $this->_ticket->set('TKT_price', '125.00'); - $this->_ticket->set('TKT_name', 'Podracing Entry'); - $this->_ticket->set('TKT_description', 'One entry in the event.'); - $this->_datetime = $this->_ticket->first_datetime(); - $this->_event = $this->_datetime->event(); - - //set the author of the event - $this->_event->set('EVT_wp_user', 1); - require_once EE_TESTS_DIR . 'mocks/core/helpers/EEH_Parse_Shortcodes_Mock.php'; - $this->_parse_shortcodes_helper_mock = new EEH_Parse_Shortcodes_Mock; - } - - - /** - * This grabs an EE_Messages_Addressee object for the Preview data handler. - * - * @param string $context - * @return \EE_Messages_Addressee - */ - protected function _get_addressee($context = 'primary_attendee') - { - $aee = array(); - $data = new EE_Messages_Preview_incoming_data(array('event_ids' => array($this->_event->ID()))); - /** - * @see EE_message_type::_set_defautl_addressee_data() - */ - $addressee_data = array( - 'billing' => $data->billing, - 'taxes' => $data->taxes, - 'tax_line_items' => $data->tax_line_items, - 'additional_line_items' => $data->additional_line_items, - 'grand_total_line_item' => $data->grand_total_line_item, - 'txn' => $data->txn, - 'payments' => $data->payments, - 'payment' => isset($data->payment) ? $data->payment : null, - 'reg_objs' => $data->reg_objs, - 'registrations' => $data->registrations, - 'datetimes' => $data->datetimes, - 'tickets' => $data->tickets, - 'line_items_with_children' => $data->line_items_with_children, - 'questions' => $data->questions, - 'answers' => $data->answers, - 'txn_status' => $data->txn_status, - 'total_ticket_count' => $data->total_ticket_count, - ); - - if (is_array($data->primary_attendee_data)) { - $addressee_data = array_merge($addressee_data, $data->primary_attendee_data); - $addressee_data['primary_att_obj'] = $data->primary_attendee_data['att_obj']; - $addressee_data['primary_reg_obj'] = $data->primary_attendee_data['reg_obj']; - } - - /** - * @see EE_message_type::_process_data() - */ - switch ($context) { - case 'primary_attendee' : - case 'purchaser' : - $aee = $addressee_data; - $aee['events'] = $data->events; - $aee['attendees'] = $data->attendees; - break; - case 'attendee' : - //for the purpose of testing we're just going to do ONE attendee - $attendee = reset($data->attendees); - foreach ($attendee as $item => $value) { - $aee[$item] = $value; - if ($item == 'line_ref') { - foreach ($value as $event_id) { - $aee['events'][$event_id] = $data->events[$event_id]; - } - } - } - $aee['reg_obj'] = array_shift($attendee['reg_objs']); - $aee['attendees'] = $data->attendees; - break; - case 'admin' : - //for the purpose of testing we're only setting up for the event we have active for testing. - $aee['user_id'] = $this->_event->get('EVT_wp_user'); - $aee['events'] = $data->events; - $aee['attendees'] = $data->attendees; - } - return new EE_Messages_Addressee($aee); - } - - - /** - * This helper returns parsed content from the parser to be used for tests using the given params. - * - * @param string $messenger The slug for the messenger being tested. - * @param string $message_type The slug for the message type being tested. - * @param string $field The field being tested. - * @param string $context The context being tested. - * @param array|string $append Append content to a default template for testing with. If - * you want to append to multiple fields, then include an - * array indexed by field. Otherwise the string will be - * appended to the field sent in with the $field param. - * @param EE_Messages_Addressee $addressee Optionally include a - * messages addressee object if you do not wish - * to use the default one generated. This is - * useful for simulating exceptions and failures. - * @return string The parsed content. - */ - protected function _get_parsed_content($messenger, $message_type, $field, $context, $append = '', $addressee = null) - { - //grab the correct template @see EE_message_type::_get_templates() - /** @type EE_Message_Template_Group $mtpg */ - $mtpg = EEM_Message_Template_Group::instance()->get_one(array( - array( - 'MTP_messenger' => $messenger, - 'MTP_message_type' => $message_type, - 'MTP_is_global' => true, - ), - )); - $all_templates = $mtpg instanceof EE_Message_Template_Group ? $mtpg->context_templates() : array(); - $templates = array(); - foreach ($all_templates as $t_context => $template_fields) { - foreach ($template_fields as $template_field => $template_obj) { - $templates[$template_field][$t_context] = $template_obj->get('MTP_content'); - } - } - - //instantiate messenger and message type objects - $msg_class = 'EE_' . str_replace(' ', '_', ucwords(str_replace('_', ' ', $messenger))) . '_messenger'; - $mt_class = 'EE_' . str_replace(' ', '_', ucwords(str_replace('_', ' ', $message_type))) . '_message_type'; - /** @type EE_messenger $messenger */ - $messenger = new $msg_class(); - /** @type EE_message_type $message_type */ - $message_type = new $mt_class(); - - //grab valid shortcodes and setup for parser. - $m_shortcodes = $messenger->get_valid_shortcodes(); - $mt_shortcodes = $message_type->get_valid_shortcodes(); - - //just sending in the content field and primary_attendee context/data for testing. - $template = isset($templates[$field][$context]) ? $templates[$field][$context] : array(); - - /** - * if empty template then its possible that the requested field is inside the "content" - * field array. - */ - if (empty($template)) { - $template = isset($templates['content'][$context]) ? $templates['content'][$context] : array(); - //verify the requested field is present - if (! empty($template) && is_array($template) && ! isset($template[$field])) { - return ''; - } - } - - //if $template is still empty then return an empty string - if (empty($template)) { - return ''; - } - - // any appends? - if (! empty($append)) { - if (is_array($template)) { - //we've already done a check for the presence of field above. - if (is_array($append)) { - foreach ($append as $a_field => $string) { - if (isset($template[$a_field])) { - $template[$a_field] = $template[$a_field] . $string; - } - } - } else { - $template[$field] = $template[$field] . $append; - } - } else { - //only append if $append is not an array because the $template is not an array. - if (! is_array($append)) { - $template .= $append; - } - - } - } - - - $valid_shortcodes = isset($m_shortcodes[$field]) ? $m_shortcodes[$field] : $mt_shortcodes[$context]; - $data = $addressee instanceof EE_Messages_Addressee ? $addressee : $this->_get_addressee(); - - //parser needs EE_Message object - $message = EE_Message_Factory::create( - array( - 'MSG_messenger' => $messenger->name, - 'MSG_message_type' => $message_type->name, - 'MSG_context' => $context, - 'GRP_ID' => $mtpg->ID(), - ) - ); - $parser = new EEH_Parse_Shortcodes(); - return $parser->parse_message_template($template, $data, $valid_shortcodes, $message_type, $messenger, - $message); - } - - - /** - * Tests parsing the message template for email messenger, payment received message - * type. - * - * @group 7585 - * @since 4.6 - */ - public function test_parsing_email_payment_received() - { - $parsed = $this->_get_parsed_content('email', 'payment', 'content', 'primary_attendee'); - - //now that we have parsed let's test the results, note for the purpose of this test we are verifying transaction shortcodes and ticket shortcodes. - - //testing [PRIMARY_REGISTRANT_FNAME], [PRIMARY_REGISTRANT_LNAME] - $this->assertContains('Luke Skywalker', $parsed); - - //testing [PAYMENT_STATUS] - $this->assertContains('Incomplete', $parsed); - - //testing [TXN_ID] - $this->assertContains('999999', $parsed); - - //testing [TOTAL_COST] and [AMOUNT_DUE] (should be $125*3 + 20 shipping charge + taxes) - $total_cost = EEH_Template::format_currency('398.00'); - $this->assertContains($total_cost, $parsed); - //but we should also have a count of TWO for this string - $this->assertEquals(2, substr_count($parsed, $total_cost)); - - //testing [AMOUNT_PAID] - $amount_paid = EEH_Template::format_currency('0'); - $this->assertContains($amount_paid, $parsed); - - - //testing [TICKET_NAME] - $this->assertContains('Podracing Entry', $parsed); - - //testing [TICKET_DESCRIPTION] - $this->assertContains('One entry in the event.', $parsed); - - //testing [TICKET_PRICE] - $this->assertContains(EEH_Template::format_currency('125.00'), $parsed); - - - //testing [TKT_QTY_PURCHASED] - $expected = 'Quantity Purchased: 3'; - $this->assertContains($expected, $parsed, - '[TKT_QTY_PURCHASED] shortcode was not parsed correctly to the expected value which is 3'); - - } - - - /** - * Test parsing the html receipt message templates. - * - * @since 4.6 - * @group 7623 - */ - public function test_parsing_html_receipt() - { - //see https://events.codebasehq.com/projects/event-espresso/tickets/9337, I think when running all tests, html - //messenger is getting stuck deactivated and thus the generated message template for this test will be missing some - //info. - EE_Registry::instance()->load_lib('Message_Resource_Manager')->ensure_messenger_is_active('html'); - //currently with @group 7623 just testing if there are any error notices. - $parsed = $this->_get_parsed_content('html', 'receipt', 'content', 'purchaser'); - - //testing [PAYMENT_GATEWAY] - $this->assertContains('Invoice', $parsed); - } - - - /** - * Test parsing the email registration message templates (registration approved). - * - * @since 4.6 - * @group 7613 - */ - public function test_parsing_email_registration() - { - //add in shortcodes for testing [ANSWER_*] as a part of the [ATTENDEE_LIST] parsing from the [EVENT_LIST] context. - $test_answer_attendee_list_event_list_append = array( - 'event_list' => '[ATTENDEE_LIST]', - 'attendee_list' => 'Custom Answer: [ANSWER_* What is your favorite planet?]', - 'ticket_list' => '[ATTENDEE_LIST]', - 'main' => '[ATTENDEE_LIST]', - ); - - $parsed = $this->_get_parsed_content('email', 'registration', 'attendee_list', 'attendee', - $test_answer_attendee_list_event_list_append); - - //testing [ATTENDEE_LIST] and [ANSWER_*] which should appear three times (because [ATTENDEE_LIST] was added to three fields), - $this->assertEquals(3, substr_count($parsed, 'Custom Answer: Tattoine')); - } - - - /** - * This test is for testing an exception is thrown when invalid attendee - * object in the data sent to the parsers. - * - * @group 7659 - * * @doesNotPerformAssertions - */ - public function test_invalid_attendee_obj_EE_Attendee_Shortcodes() - { - $addressee = $this->_get_addressee(); - - //manipulate to remove data - $addressee->registrations = array(); - - try { - $parsed_content = $this->_get_parsed_content('email', 'registration', 'content', 'admin', '', $addressee); - } catch (EE_Error $e) { - return; - } - $this->fail('Expected an exception for invalid EE_Attendee Object'); - } - - - /** - * @group 10561 - */ - public function test_is_conditional_shortcode() - { - //test is conditional shortcode - $this->assertTrue($this->_parse_shortcodes_helper_mock->is_conditional_shortcode('[IF_something_* id=10]')); - - $non_conditional_expectations = array( - '[SOMETHING]', - '[WHEN_IF_NESTED]', - '[if_lowercase]', - '[/IF_CLOSING_TAG]' - ); - - foreach ($non_conditional_expectations as $non_conditional_expectation) { - //should not be conditional shortcode - $this->assertFalse( - $this->_parse_shortcodes_helper_mock->is_conditional_shortcode( - $non_conditional_expectation - ), - sprintf( - 'This shortcode pattern should not test as matching a conditional shortcode but it did: %s', - $non_conditional_expectation - ) - ); - } - } - -} //end class EEH_Parse_Shortcodes_Test diff --git a/tests/testcases/core/helpers/EEH_TemplateTest.php b/tests/testcases/core/helpers/EEH_TemplateTest.php deleted file mode 100644 index dde865b7490..00000000000 --- a/tests/testcases/core/helpers/EEH_TemplateTest.php +++ /dev/null @@ -1,33 +0,0 @@ -datetime_offset_fix_mock = new DatetimeOffsetFixMock(); - } - - /** - * @group offset_fix_test - * @throws EE_Error - */ - public function testProcessModel() - { - $original_date_and_time = new DateTime('now'); - $expected_positive_offset_datetime = clone $original_date_and_time; - $test_offsets = array( - '2' => $expected_positive_offset_datetime->add(new DateInterval('PT2H')), - //note we have the expectation set here back to the original date and time because offset test _should_ just - //restore the original time. - '-2' => $original_date_and_time - ); - /** @var EE_Datetime $datetime */ - $datetime = $this->factory->datetime->create( - array( - 'DTT_EVT_start' => $original_date_and_time->format('U'), - 'DTT_EVT_end' => $original_date_and_time->format('U') - ) - ); - //k run our tests - foreach ($test_offsets as $offset_to_test => $expected_datetime_object) { - DatetimeOffsetFixMock::updateOffset((float) $offset_to_test); - $this->datetime_offset_fix_mock->processModel('EEM_Datetime'); - //need to clear any entities cached in the model - EEM_Datetime::instance()->clear_entity_map(); - $actual_datetime = EEM_Datetime::instance()->get_one_by_ID($datetime->ID()); - $this->assertEquals( - $expected_datetime_object->format('U'), - $actual_datetime->get_DateTime_object('DTT_EVT_start')->format('U'), - sprintf('Offset being tested is %s', $offset_to_test) - ); - } - } -} diff --git a/tests/testcases/core/libraries/form_sections/base/EE_Form_Section_Base__find_section_from_path_Test.php b/tests/testcases/core/libraries/form_sections/base/EE_Form_Section_Base__find_section_from_path_Test.php deleted file mode 100644 index f2c68e0b01b..00000000000 --- a/tests/testcases/core/libraries/form_sections/base/EE_Form_Section_Base__find_section_from_path_Test.php +++ /dev/null @@ -1,100 +0,0 @@ -_child_section = new EE_Text_Input(); - $this->_sibling_section = new EE_Text_Input(); - $this->_parent_section = new EE_Form_Section_Proper( - array( - 'subsections' => array( - 'child' => $this->_child_section, - 'sibling' => $this->_sibling_section - ) - ) - ); - $this->_cousin_section = new EE_Text_Input(); - $this->_aunt_section = new EE_Form_Section_Proper( - array( - 'subsections' => array( - 'cousin' => $this->_cousin_section - ) - ) - ); - $this->_granparent_section = new EE_Form_Section_Proper( - array( - 'name' => 'grandparent', - 'subsections' => array( - 'parent' => $this->_parent_section, - 'aunt' => $this->_aunt_section - ) - ) - ); - } - //put your code here - public function test_sibling() { - $this->assertEquals( $this->_sibling_section, $this->_child_section->find_section_from_path( '../sibling' ) ); - } - public function test_parent() { - $this->assertEquals( $this->_parent_section, $this->_child_section->find_section_from_path( '../' ) ); - $this->assertEquals( $this->_parent_section, $this->_child_section->find_section_from_path( '../../parent' ) ); - } - public function test_aunt() { - $this->assertEquals( $this->_aunt_section, $this->_child_section->find_section_from_path( '../../aunt' ) ); - } - public function test_cousin() { - $this->assertEquals( $this->_cousin_section, $this->_child_section->find_section_from_path( '../../aunt/cousin' ) ); - } - public function test_nephew() { - $this->assertEquals( $this->_cousin_section, $this->_parent_section->find_section_from_path( '../aunt/cousin' ) ); - } - public function test_child() { - $this->assertEquals( $this->_child_section, $this->_parent_section->find_section_from_path( 'child' ) ); - } - - - public function test_grandparent(){ - $this->assertEquals( $this->_granparent_section, $this->_child_section->find_section_from_path( '../../' ) ); - } - public function test_self() { - $this->assertEquals( $this->_child_section, $this->_child_section->find_section_from_path( '' ) ); - $this->assertEquals( $this->_child_section, $this->_child_section->find_section_from_path( '../child' ) ); - } - public function test_invalid_strings() { - $invalid_strings = array( - 'child-of-child', - '../child/child-of-child', - '../brother-i-never-had' - ); - foreach( $invalid_strings as $invalid_string ) { - $this->assertNull( $this->_child_section->find_section_from_path( $invalid_string ), 'The string ' . $invalid_string . ' shouldnt be considered valid' ); - } - - } -} diff --git a/tests/testcases/core/libraries/form_sections/base/EE_Form_Section_Proper_Test.php b/tests/testcases/core/libraries/form_sections/base/EE_Form_Section_Proper_Test.php deleted file mode 100644 index 3a9ade92c71..00000000000 --- a/tests/testcases/core/libraries/form_sections/base/EE_Form_Section_Proper_Test.php +++ /dev/null @@ -1,472 +0,0 @@ -array( - 'first_name' => new EE_Text_Input(), - 'last_name' => new EE_Text_Input(), - ) - - )); - $data = array('first_name'=>'brent','last_name'=>'possum'); - $form->receive_form_submission( $data ); - $this->assertEquals( $data, $form->input_values() ); - } - public function test_add_subsection__before(){ - $input1 = new EE_Text_Input(); - $input2 = new EE_Text_Input(); - $input3 = new EE_Text_Input(); - $input4 = new EE_Text_Input(); - $input5 = new EE_Text_Input(); - $parent_form = new EE_Form_Section_Proper( array( - 'name' => 'form', - 'subsections' => array( - 'input1' => $input1, - 'input2' => $input2, - ) - )); - $inputs = $parent_form->inputs(); - $this->assertEquals( $input1, reset($inputs) ); - $this->assertEquals( $input2, next( $inputs ) ); - - //ok now add a subsection before the first one - $parent_form->add_subsections( array( 'input3' => $input3 ), 'input1' ); - $inputs = $parent_form->inputs(); - $this->assertEquals( $input3, reset($inputs) ); - $this->assertEquals( $input1, next( $inputs ) ); - $this->assertEquals( $input2, next( $inputs ) ); - - //now add a subsection in the middle - $parent_form->add_subsections( array( 'input4' => $input4 ), 'input1' ); - $inputs = $parent_form->inputs(); - $this->assertEquals( $input3, reset($inputs) ); - $this->assertEquals( $input4, next($inputs) ); - $this->assertEquals( $input1, next( $inputs ) ); - $this->assertEquals( $input2, next( $inputs ) ); - - //lastly add a subsection onto the very end - $parent_form->add_subsections( array( 'input5' => $input5 ), null, false ); - $inputs = $parent_form->inputs(); - $this->assertEquals( $input3, reset($inputs) ); - $this->assertEquals( $input4, next($inputs) ); - $this->assertEquals( $input1, next( $inputs ) ); - $this->assertEquals( $input2, next( $inputs ) ); - $this->assertEquals( $input5, next( $inputs ) ); - } - public function test_add_subsection__after(){ - $input1 = new EE_Text_Input(); - $input2 = new EE_Text_Input(); - $input3 = new EE_Text_Input(); - $input4 = new EE_Text_Input(); - $input5 = new EE_Text_Input(); - $parent_form = new EE_Form_Section_Proper( array( - 'name' => 'form', - 'subsections' => array( - 'input1' => $input1, - 'input2' => $input2, - ) - )); - $inputs = $parent_form->inputs(); - $this->assertEquals( $input1, reset($inputs) ); - $this->assertEquals( $input2, next( $inputs ) ); - - //ok now add a subsection after the last one - $parent_form->add_subsections( array( 'input3' => $input3 ), 'input2', false ); - $inputs = $parent_form->inputs(); - $this->assertEquals( $input1, reset($inputs) ); - $this->assertEquals( $input2, next( $inputs ) ); - $this->assertEquals( $input3, next( $inputs ) ); - - //now add a subsection in the middle - $parent_form->add_subsections( array( 'input4' => $input4 ), 'input2', false ); - $inputs = $parent_form->inputs(); - $this->assertEquals( $input1, reset($inputs) ); - $this->assertEquals( $input2, next($inputs) ); - $this->assertEquals( $input4, next( $inputs ) ); - $this->assertEquals( $input3, next( $inputs ) ); - - //lastly add a subsection onto the very beginning - $parent_form->add_subsections( array( 'input5' => $input5 ) ); - $inputs = $parent_form->inputs(); - $this->assertEquals( $input5, reset($inputs) ); - $this->assertEquals( $input1, next($inputs) ); - $this->assertEquals( $input2, next($inputs) ); - $this->assertEquals( $input4, next( $inputs ) ); - $this->assertEquals( $input3, next( $inputs ) ); - } - public function test_add_subsection__weird_subsection_names(){ - $grandparent_form = new EE_Form_Section_Proper(array( - 'name'=>'grandparent', - 'subsections'=>array( - '123-reg-money'=> new EE_Form_Section_Proper(array( - 'subsections'=>array( - '!0!a77y-bad`string' => new EE_Text_Input() - ) - )) - ) - )); - $grandparent_form->add_subsections(array('new_one'=>new EE_Text_Input())); - $added_input = $grandparent_form->get_input('new_one'); - $this->assertInstanceOf('EE_Text_Input', $added_input); - $this->assertEquals( 'new_one', $added_input->name() ); - $this->assertEquals( 'grandparent[new_one]', $added_input->html_name() ); - - $grandparent_form->add_subsections(array(12=>new EE_Text_Input())); - $other_added_input = $grandparent_form->get_input( 12 ); - $this->assertInstanceOf('EE_Text_Input', $other_added_input); - - } - public function test_form_data_present_in__normal(){ - $granparent_form = new EE_Form_Section_Proper(array( - 'name'=>'grandparent', - 'subsections'=>array( - 'parent' => new EE_Form_Section_Proper( array( - 'subsections' => array( - 'form' => new EE_Form_Section_Proper( array( - 'subsections' => array( - 'input' => new EE_Text_Input(), - 'input2' => new EE_Text_Input() - ) - ) - )) - ) - )) - ) - ); - - $req_data_good = array('grandparent'=>array('parent' => array( 'form' =>array( 'input' => 'value', 'input2' => 'value2')))); - $req_data_bad = array('foo'=>array('bar'=>array('monkey' => 'poop' ) ), - 'fluff' => array( 'baz' => array( 'lizard' => 'tail' ))); - $this->assertTrue( $granparent_form->form_data_present_in( $req_data_good) ); - $this->assertFalse( $granparent_form->form_data_present_in( $req_data_bad ) ); - } - public function test_form_data_present_in__custom_html_name(){ - $granparent_form = new EE_Form_Section_Proper(array( - 'name'=>'grandparent', - 'subsections'=>array( - 'parent' => new EE_Form_Section_Proper( array( - 'subsections' => array( - 'form' => new EE_Form_Section_Proper( array( - 'subsections' => array( - 'input' => new EE_Text_Input(array( - 'html_name' => 'foo[bar][monkey]', - )), - 'input2' => new EE_Text_Input(array( - 'html_name' => 'fluff[baz][lizard]' - )) - ) - ) - )) - ) - )) - ) - ); - - $req_data_bad = array('grandparent'=>array('parent' => array( 'form' =>array( 'input' => 'value', 'input2' => 'value2')))); - $req_data_good = array('foo'=>array('bar'=>array('monkey' => 'poop' ) ), - 'fluff' => array( 'baz' => array( 'lizard' => 'tail' ))); - $this->assertTrue( $granparent_form->form_data_present_in( $req_data_good) ); - $this->assertFalse( $granparent_form->form_data_present_in( $req_data_bad ) ); - - $parent_form = $granparent_form->get_subsection( 'parent' ); - $this->assertTrue( $parent_form->form_data_present_in( $req_data_good) ); - $this->assertFalse( $parent_form->form_data_present_in( $req_data_bad ) ); - - $form = $parent_form->get_subsection( 'form' ); - $this->assertTrue( $form->form_data_present_in( $req_data_good) ); - $this->assertFalse( $form->form_data_present_in( $req_data_bad ) ); - - } - - public function test_is_valid(){ - $form = new EE_Form_Section_Proper( array( - 'name'=>'form', - 'subsections' => array( - 'subform1' => new EE_Form_Section_Proper( array( - 'subsections' => array( - 'input1' => new EE_Text_Input() - ) - )) - ) - )); - $req_data_bad = array(); - $req_data_good = array('form' => array( 'subform1' => array( 'input1' => 'value' ) ) ); - $this->assertTrue( $form->was_submitted( $req_data_good ) ); - $form->receive_form_submission( $req_data_good ); - $this->assertTrue( $form->is_valid() ); - - } - - /** - * @group ticket_6505 - */ - public function test_numeric_named_inputs(){ - $form = new EE_Form_Section_Proper( - array( - 'html_id' => 'ee-available-payment-method-inputs', - 'subsections' => array( - 0 => new EE_Radio_Button_Input( - array( 'one' => 'One','two' => 'Two', 'three' => 'Three' ), - array( - 'html_name' => 'selected_method_of_payment', - 'html_class' => 'spco-payment-method', - 'default' => 'three' - ) - ) - ) - ) - ); - $this->assertEquals(1, count( $form->inputs() ) ); - } - - /** - * @group 6781 - */ - public function test_get_validation_errors_accumulated(){ - $form = new EE_Form_Section_Proper( - array( - 'name' => 'Form', - 'subsections' => array( - 'radio1' => new EE_Radio_Button_Input( - array( 'one' => 'One','two' => 'Two', 'three' => 'Three' ), - array( - 'html_class' => 'spco-payment-method', - 'default' => 'three' - ) - ), - 'input2' => new EE_Text_Input( array( - 'required' => TRUE - )), - 'subsubsection' => new EE_Form_Section_Proper( array( - 'subsections' => array( - 'input3' => new EE_Float_Input(), - 'input4' => new EE_Text_Input() - ) - )) - ) - ) - ); - $post_data = array( - 'Form' => array( - 'radio1' => 'four-invalid', - 'input2' => '', - 'subsubsection' => array( - 'input3' => 'non-number', - 'input4' => 'whatever-ok' - )) - ); - $form->receive_form_submission( $post_data ); - //submit twice, which should be fine; it shoudl jsut reset before - //2nd submission - $form->receive_form_submission( $post_data ); - $this->assertFalse( $form->is_valid() ); - $all_errors = $form->get_validation_errors_accumulated(); - $this->assertEquals( 3, count( $all_errors ) ); - $error1 = array_shift( $all_errors ); - $error2 = array_shift( $all_errors ); - $error3 = array_shift( $all_errors ); - - - $this->assertInstanceOf( 'EE_Validation_Error', $error1 ); - $this->assertInstanceOf( 'EE_Radio_Button_Input', $error1->get_form_section() ); - $this->assertEquals( 'radio1', $error1->get_form_section()->name() ); - - - $this->assertInstanceOf( 'EE_Validation_Error', $error2 ); - $this->assertInstanceOf( 'EE_Text_Input', $error2->get_form_section() ); - $this->assertEquals( 'input2', $error2->get_form_section()->name() ); - $this->assertInstanceOf( 'EE_Validation_Error', $error3 ); - $this->assertInstanceOf( 'EE_Float_Input', $error3->get_form_section() ); - $this->assertEquals( 'input3', $error3->get_form_section()->name() ); - } - - /** - * Tests the form was submitted functionality. - * - * @group 7431 - */ - public function test_form_was_submitted() { - $form = new EE_Form_Section_Proper( array( - 'name' => 'test_form', - 'html_id' => 'test_form', - 'subsections' => array( - 'yes_no' => new EE_Yes_No_Input( - array( - 'html_label_text' => 'testing', - 'default' => false - ) - ) - ) - ) - ); - $post_data = array( - 'test_form' => array( - 'yes_no' => '0' - ) - ); - $this->assertTrue( $form->was_submitted( $post_data ) ); - } - /** - * @group 9784 - * Verify EE_FOrm_SEction_proper::submitted_values() generates an array - * exactly like the submitted data - */ - public function test_submitted_values() { - $form = new EE_Form_Section_Proper( - array( - 'name' => 'top', - 'subsections' => array( - 'middle' => new EE_Form_Section_Proper( - array( - 'subsections' => array( - 'bottom_input1' => new EE_Phone_Input(), - 'bottom_checkbox' => new EE_Checkbox_Multi_Input( - array( - 'op1' => 'option1', - 'op2' => 'option2', - 'op3' => 'option3' - ) - ) - ) - ) - ), - 'middle_checkbox' => new EE_Checkbox_Multi_Input( - array( - 'op1' => 'option1', - 'op2' => 'option2', - 'op3' => 'option3' - ) - ), - 'middle_radio' => new EE_Radio_Button_Input( - array( - 'op1' => 'option1', - 'op2' => 'option2' - ) - ) - ) - ) - ); - $form->_construct_finalize(null, null ); - $submitted_data = array( - 'top' => array( - 'middle' => array( - 'bottom_input1' => 'not-a-phone-number', - 'bottom_checkbox' => array( - 'op2', - 'not-existent-op' - ) - ), - 'middle_checkbox' => array( - 'op2', - 'not-existent-op' - ), - 'middle_radio' => 'op1' - ) - ); - $form->receive_form_submission( - $submitted_data - ); - $this->assertEquals( - $submitted_data, - $form->submitted_values( true ) - ); - } - - /** - * @group 9784 - * Verify EE_FOrm_section_Proper::submitted_values generates the post-like submission - * array when there are custom names on inputs - */ - public function test_submitted_values__custom_html_name_on_input(){ - $form = new EE_Form_Section_Proper( - array( - 'name' => 'top', - 'subsections' => array( - 'middle' => new EE_Form_Section_Proper( - array( - 'subsections' => array( - 'bottom' => new EE_Text_Input( - array( - 'html_name' => 'custom_html_name' - ) - ) - ) - ) - ) - ) - ) - ); - $form->_construct_finalize(null, null); - $submitted_data = array( - 'custom_html_name' => 'value' - ); - $form->receive_form_submission( $submitted_data ); - $this->assertEquals( - $submitted_data, - $form->submitted_values( true ) - ); - } - - - - /** - * validate the form (which caches the result) then re-submit it and verify the cache got cleared - * @group 11381 - */ - public function testIsValidCached() - { - $f = new EE_Form_Section_Proper( - array( - 'name' => 'form', - 'subsections'=> array( - 'int' => new EE_Integer_Input( - array( - 'required' => true - ) - ) - ) - ) - ); - $f->receive_form_submission( - array( - 'form' => array( - 'int' => '4' - ) - ) - ); - $this->assertTrue($f->is_valid()); - //and double-check calling it again works fine too - $this->assertTrue($f->is_valid()); - //now change the form's input - $f->receive_form_submission( - array( - 'form' => array( - 'int' => 'saskquatch' - ) - ) - ); - $this->assertFalse($f->is_valid()); - - } -} - -// End of file EE_Form_Section_Proper_Test.php diff --git a/tests/testcases/core/libraries/form_sections/inputs/EE_Form_Input_Base_Test.php b/tests/testcases/core/libraries/form_sections/inputs/EE_Form_Input_Base_Test.php deleted file mode 100644 index fdd862cf137..00000000000 --- a/tests/testcases/core/libraries/form_sections/inputs/EE_Form_Input_Base_Test.php +++ /dev/null @@ -1,246 +0,0 @@ -'grandparent', - 'subsections'=>array( - 'parent' => new EE_Form_Section_Proper( array( - 'subsections' => array( - 'form' => new EE_Form_Section_Proper( array( - 'subsections' => array( - 'input' => new EE_Text_Input() - ) - ) - )) - ) - )) - ) - ); - - $input = $granparent_form->get_subsection( 'parent' )->get_subsection( 'form' )->get_subsection( 'input' ); - $this->assertInstanceOf('EE_Form_Input_Base', $input); - $this->assertEquals('grandparent[parent][form][input]', $input->html_name()); - } - - public function test_find_form_data_for_this_section__custom_html_name(){ - $granparent_form = new EE_Form_Section_Proper(array( - 'name'=>'grandparent', - 'subsections'=>array( - 'parent' => new EE_Form_Section_Proper( array( - 'subsections' => array( - 'form' => new EE_Form_Section_Proper( array( - 'subsections' => array( - 'input' => new EE_Text_Input(array( - 'html_name' => 'foo[bar][monkey]' - )) - ) - ) - )) - ) - )) - ) - ); - $input = $granparent_form->get_subsection( 'parent' )->get_subsection( 'form' )->get_subsection( 'input' ); - $req_data_bad = array('grandparent'=>array('parent' => array( 'form' =>array( 'input' => 'value')))); - $req_data_good = array('foo'=>array('bar'=>array('monkey' => 'value'))); - $this->assertNull($input->find_form_data_for_this_section( $req_data_bad ) ); - $this->assertEquals( 'value', $input->find_form_data_for_this_section( $req_data_good ) ); - } - - public function test_find_form_data_for_this_section__normal(){ - $granparent_form = new EE_Form_Section_Proper(array( - 'name'=>'grandparent', - 'subsections'=>array( - 'parent' => new EE_Form_Section_Proper( array( - 'subsections' => array( - 'form' => new EE_Form_Section_Proper( array( - 'subsections' => array( - 'input' => new EE_Text_Input() - ) - ) - )) - ) - )) - ) - ); - $input = $granparent_form->get_subsection( 'parent' )->get_subsection( 'form' )->get_subsection( 'input' ); - $req_data_good = array('grandparent'=>array('parent' => array( 'form' =>array( 'input' => 'value')))); - $req_data_bad = array('foo'=>array('bar'=>array('monkey' => 'value'))); - $this->assertNull($input->find_form_data_for_this_section( $req_data_bad ) ); - $this->assertEquals( 'value', $input->find_form_data_for_this_section( $req_data_good ) ); - } - - public function test_form_data_present_in__normal(){ - $granparent_form = new EE_Form_Section_Proper(array( - 'name'=>'grandparent', - 'subsections'=>array( - 'parent' => new EE_Form_Section_Proper( array( - 'subsections' => array( - 'form' => new EE_Form_Section_Proper( array( - 'subsections' => array( - 'input' => new EE_Text_Input(), - 'input2' => new EE_Text_Input() - ) - ) - )) - ) - )) - ) - ); - - $req_data_good = array('grandparent'=>array('parent' => array( 'form' =>array( 'input' => 'value', 'input2' => 'value2')))); - $req_data_bad = array('foo'=>array('bar'=>array('monkey' => 'poop' ) ), - 'fluff' => array( 'baz' => array( 'lizard' => 'tail' ))); - $input = $granparent_form->get_subsection( 'parent' )->get_subsection( 'form' )->get_subsection( 'input' ); - $this->assertTrue( $input->form_data_present_in( $req_data_good) ); - $this->assertFalse( $input->form_data_present_in( $req_data_bad ) ); - } - public function test_form_data_present_in__custom_html_name(){ - $granparent_form = new EE_Form_Section_Proper(array( - 'name'=>'grandparent', - 'subsections'=>array( - 'parent' => new EE_Form_Section_Proper( array( - 'subsections' => array( - 'form' => new EE_Form_Section_Proper( array( - 'subsections' => array( - 'input' => new EE_Text_Input(array( - 'html_name' => 'foo[bar][monkey]', - )), - 'input2' => new EE_Text_Input(array( - 'html_name' => 'fluff[baz][lizard]' - )) - ) - ) - )) - ) - )) - ) - ); - - $req_data_bad = array('grandparent'=>array('parent' => array( 'form' =>array( 'input' => 'value', 'input2' => 'value2')))); - $req_data_good = array('foo'=>array('bar'=>array('monkey' => 'poop' ) ), - 'fluff' => array( 'baz' => array( 'lizard' => 'tail' ))); - $input = $granparent_form->get_subsection( 'parent' )->get_subsection( 'form' )->get_subsection( 'input' ); - $this->assertTrue( $input->form_data_present_in( $req_data_good) ); - $this->assertFalse( $input->form_data_present_in( $req_data_bad ) ); - - - } - - /** - * Verifies that the inputs default HTML names reflect the actual form structure. - * @group 10110 - */ - public function test_input_names_should_be_consistent_regardless_of_when_input_was_added() { - $input1 = new EE_Text_Input(); - $form = new EE_Form_Section_Proper( - array( - 'subsections' => array( - 'input1' => $input1, - ) - ) - ); - $form->_construct_finalize( null, null ); - //ok so subform is complete right? Well let's now make it a subform. - //what could possibly go wrong when you do that? - $top_form = new EE_Form_Section_Proper( - array( - 'subsections' => array( - 'subform' => $form - ) - ) - ); - $top_form->_construct_finalize(null, 'topform' ); - //ok great. Now let's add something to the form. It shouldn't - //matter if the input was added when the form was constructed, - //or after it was all done being constructed. It should still work. - $input2 = new EE_Text_Input(); - $form->add_subsections( - array( - 'input2' => $input2 - ) - ); - //both inputs, regardless of when they were added, should have pretty well the - //same html name. - $this->assertEquals( 'topform[subform][input1]', $input1->html_name() ); - $this->assertEquals( 'topform[subform][input2]', $input2->html_name() ); - } - - - - /** - * Tests that if `ignore_input` is provided, we get the null normalization and no validation strategies - * @group 11380 - */ - public function testIgnoreInput() { - $f = new EE_Form_Section_Proper( - array( - 'name' => 'form', - 'subsections' => array( - 'text' => new EE_Text_Input( - array( - 'ignore_input' => true - ) - ), - 'email' => new EE_Email_Input( - array( - 'ignore_input' => true - ) - ), - 'checkbox' => new EE_Checkbox_Multi_Input( - array('a','b'), - array( - 'ignore_input' => true - ) - ), - 'radio' => new EE_Radio_Button_Input( - array('a','b'), - array( - 'ignore_input' => true - ) - ), - 'ok' => new EE_Text_Input() - ) - ) - ); - $f->receive_form_submission( - array( - 'form' => array( - 'text' => 'hackerz', - 'email' => 'virus!', - 'checkbox' => array( 2, 3), - 'radio' => 3, - 'ok' => 'yep' - ) - ) - ); - $this->assertNull($f->get_input_value('text')); - $this->assertNull($f->get_input_value('email')); - $this->assertNull($f->get_input_value('checkbox')); - $this->assertNull($f->get_input_value('radio')); - //verify we still get normal inputs - $this->assertEquals('yep', $f->get_input_value('ok')); - //verify the form is still valid, even though the inputs had null normalization - $this->assertTrue($f->is_valid()); - } -} - -// End of file EE_Form_Input_Base_Test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/form_sections/inputs/EE_Form_Input_With_Options_Test.php b/tests/testcases/core/libraries/form_sections/inputs/EE_Form_Input_With_Options_Test.php deleted file mode 100644 index 6938682e263..00000000000 --- a/tests/testcases/core/libraries/form_sections/inputs/EE_Form_Input_With_Options_Test.php +++ /dev/null @@ -1,85 +0,0 @@ - 'test1', - 'subsections' => array( - 'radio1' => new EE_Radio_Button_Input(array( - 'option1' => 'Option 1', - 'option2' => 'Option 2' ) - )) - )); - $radio_button = $form->get_input( 'radio1' ); - //that radio button's normalization strategy is correct - $this->assertInstanceOf( 'EE_Radio_Button_Input', $radio_button ); - $this->assertInstanceOf( 'EE_Text_Normalization', $radio_button->get_normalization_strategy() ); - //and that when it receives input, it sets it correctly - $form->receive_form_submission( array( 'radio1' => 'option1' ) ); - $this->assertTrue($form->is_valid() ); - $form->receive_form_submission( array( 'radio1' => 'option_nonexistent' ) ); - $this->assertFalse( $form->is_valid() ); - } - - /** - * Verifies we don't change these options into booleans - * @group 8006 - */ - function test_double_valued_with_blank(){ - EEM_Country::reset(); - EEM_Country::instance()->update( array( 'CNT_active' => false ), array() ); - EEM_Country::instance()->update( array( 'CNT_active' => true), array( 'limit' => 1 ) ); - $active_countries = EEM_Country::instance()->get_all( array( array( 'CNT_active' => true ) ) ); - $this->assertEquals( 1, count( $active_countries ) ); - $active_country = reset( $active_countries ); - $country_input = new EE_Country_Select_Input(); - $this->assertEquals( - array( - '' => '', - $active_country->ID() => $active_country->name() - ), - $country_input->options() ); - $this->assertInstanceOf( 'EE_Text_Normalization', $country_input->get_normalization_strategy() ); - } - - function test_many_valued(){ - //create a form with radio button in it. - $form = new EE_Form_Section_Proper(array( - 'name' => 'test1', - 'subsections' => array( - 'checkbox1' => new EE_Checkbox_Multi_Input(array( - 'option1' => 'Option 1', - 'option2' => 'Option 2' ) - )) - )); - $checkbox = $form->get_input( 'checkbox1' ); - //that radio button's normalization strategy is correct - $this->assertInstanceOf( 'EE_Checkbox_Multi_Input', $checkbox ); - $this->assertInstanceOf( 'EE_Many_Valued_Normalization', $checkbox->get_normalization_strategy() ); - //and that when it receives input, it sets it correctly - $form->receive_form_submission( array( 'checkbox1' => array( 'option1' ) ) ); - $this->assertTrue($form->is_valid() ); - $form->receive_form_submission( array( 'checkbox1' => array( 'option_nonexistent' ) ) ); - $this->assertFalse( $form->is_valid() ); - $form->receive_form_submission( array( 'checkbox1' => 'option1' ) ); - $this->assertTrue( $form->is_valid() ); - $form->receive_form_submission( array( 'checkbox1' => 'option_nonexistent' ) ); - $this->assertFalse( $form->is_valid() ); - } - -} - -// End of file EE_Radio_Button_Input_Test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/form_sections/inputs/EE_Radio_Button_Input_Test.php b/tests/testcases/core/libraries/form_sections/inputs/EE_Radio_Button_Input_Test.php deleted file mode 100644 index c5f9a1d3e6e..00000000000 --- a/tests/testcases/core/libraries/form_sections/inputs/EE_Radio_Button_Input_Test.php +++ /dev/null @@ -1,57 +0,0 @@ - 'test', - 'subsections' => array( - 'use_captcha' => new EE_Radio_Button_Input( - array( - 1 => __( 'Yes', 'event_espresso' ), - 0 => __( 'No', 'event_espresso' ) - ), - array( - 'html_label_text' => __( 'Use reCAPTCHA', 'event_espresso' ), - 'default' => isset( EE_Registry::instance()->CFG->registration->use_captcha ) ? EE_Registry::instance()->CFG->registration->use_captcha : FALSE, - 'normalization_strategy' => new EE_Int_Normalization() - ) - ) - ) - )); - $form->receive_form_submission( array( - 'test' => array( - 'use_captcha' => '1' - ) - )); - $this->assertTrue( $form->is_valid() ); - $this->assertTrue( 1 === $form->get_input( 'use_captcha' )->normalized_value() ); - $this->assertTrue( '1' === $form->get_input( 'use_captcha' )->raw_value() ); - - $form->receive_form_submission( array( - 'test' => array( - 'use_captcha' => '0' - ) - )); - $this->assertTrue( $form->is_valid() ); - $this->assertTrue( 0 === $form->get_input( 'use_captcha' )->normalized_value() ); - $this->assertTrue( '0' === $form->get_input( 'use_captcha' )->raw_value() ); - } -} - -// End of file EE_Radio_Button_Input_Test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/form_sections/inputs/EE_State_Select_Input_Test.php b/tests/testcases/core/libraries/form_sections/inputs/EE_State_Select_Input_Test.php deleted file mode 100644 index 5d945e089f3..00000000000 --- a/tests/testcases/core/libraries/form_sections/inputs/EE_State_Select_Input_Test.php +++ /dev/null @@ -1,105 +0,0 @@ - 'where-you-live', - 'subsections' => array( - 'state' => new EE_State_Select_Input(null) - ) - ) - ); - $submitted_data = array('where-you-live' => array()); - $form->receive_form_submission($submitted_data); - $this->assertTrue($form->is_valid()); - $this->assertEmpty($form->submission_error_message()); - $this->assertEquals( - null, - $form->get_input('state')->normalized_value() - ); - $this->assertEquals( - '', - $form->get_input('state')->raw_value() - ); - $this->assertEquals( - array('where-you-live' => array('state' => '')), - $form->submitted_values(true) - ); - } - - - /** - * @group 10643 - * @throws EE_Error - */ - public function test_required_EE_State_Input_with_no_input() - { - $form = new EE_Form_Section_Proper( - array( - 'name' => 'where-you-live', - 'subsections' => array( - 'state' => new EE_State_Select_Input(null, array('required' => true)) - ) - ) - ); - $submitted_data = array('where-you-live' => array()); - $form->receive_form_submission($submitted_data); - $this->assertFalse($form->is_valid()); - $this->assertNotEmpty($form->submission_error_message()); - } - - - - /** - * @group 10643 - * @throws EE_Error - */ - public function test_EE_State_Input_with_input() - { - $form = new EE_Form_Section_Proper( - array( - 'name' => 'where-you-live', - 'subsections' => array( - 'state' => new EE_State_Select_Input(null) - ) - ) - ); - $submitted_data = array('where-you-live' => array('state' => 61)); - $form->receive_form_submission($submitted_data); - $this->assertTrue($form->is_valid()); - $this->assertEquals( - 61, - $form->get_input('state')->normalized_value() - ); - $this->assertEquals( - '61', - $form->get_input('state')->raw_value() - ); - $this->assertEquals( - $submitted_data, - $form->submitted_values(true) - ); - } - - -} - -// End of file EE_Radio_Button_Input_Test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/form_sections/strategies/display/EE_Button_Input_Display_Strategy_Test.php b/tests/testcases/core/libraries/form_sections/strategies/display/EE_Button_Input_Display_Strategy_Test.php deleted file mode 100644 index 4c69432410c..00000000000 --- a/tests/testcases/core/libraries/form_sections/strategies/display/EE_Button_Input_Display_Strategy_Test.php +++ /dev/null @@ -1,38 +0,0 @@ -Brent On skateboard'; - $input = new EE_Button_Input( - array( - 'button_content' => $button_content, - 'default' => 'brent-skateboard' - ) - ); - $input->_construct_finalize(null, 'brent-on-skateboard'); - $output = $input->get_display_strategy()->display(); - $expected = ''; - $this->assertHTMLEquals($expected,$output); - } -} - -// End of file EE_Button_Input_Display_Strategy_Test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/form_sections/strategies/display/EE_Checkbox_Display_Strategy_Test.php b/tests/testcases/core/libraries/form_sections/strategies/display/EE_Checkbox_Display_Strategy_Test.php deleted file mode 100644 index cb227d99480..00000000000 --- a/tests/testcases/core/libraries/form_sections/strategies/display/EE_Checkbox_Display_Strategy_Test.php +++ /dev/null @@ -1,58 +0,0 @@ - 'form', - 'subsections' => array( - 'input1' => new EE_Checkbox_Multi_Input(array('foo' => 'Foo', 'bar' => 'Bar', "baz'em" => 'Baz')), - ), - )); - $input = $form->get_input('input1'); - // data-question_label="ee_reg_qstn-6-11-lbl" - $expected_output = ' - - -'; - $this->assertHTMLEquals($expected_output, $input->get_html_for_input()); - //now if we set the default, does it get selected? - $form->populate_defaults(array( - 'input1' => array("baz'em", 'bar'), - )); - $this->assertEquals(array("baz'em", 'bar'), $input->normalized_value()); - $this->assertEquals(array("baz'em", 'bar'), $input->raw_value()); - $expected_output2 = ' - - -'; - $this->assertHTMLEquals($expected_output2, $input->get_html_for_input()); - } -} - -// End of file tests/testcases/core/libraries/form_sections/strategies/display/EE_Checkbox_Display_Strategy_Test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/form_sections/strategies/display/EE_Number_Input_Display_Strategy_Test.php b/tests/testcases/core/libraries/form_sections/strategies/display/EE_Number_Input_Display_Strategy_Test.php deleted file mode 100644 index 186911bf70a..00000000000 --- a/tests/testcases/core/libraries/form_sections/strategies/display/EE_Number_Input_Display_Strategy_Test.php +++ /dev/null @@ -1,84 +0,0 @@ -_construct_finalize(null, 'age'); - $output = $input->get_display_strategy()->display(); - $expected = ''; - $this->assertHTMLEquals($expected,$output); - } - - /** - * @group 10586 - */ - public function test_display__with_min_max_required() - { - $input = new EE_Integer_Input( - array( - 'min_value' => 2, - 'max_value' => 5, - 'html_class' => 'funky', - 'required' => true - )); - $input->_construct_finalize(null, 'age'); - $output = $input->get_display_strategy()->display(); - $expected = ''; - $this->assertHTMLEquals($expected,$output); - } - - /** - * @group 10586 - */ - public function test_display__for_float() - { - $input = new EE_Float_Input( - array( - 'html_class' => 'funky', - 'required' => true, - 'step_value' => 'any', - 'min_value' => -2 - ) - ); - $input->_construct_finalize(null, 'age'); - $output = $input->get_display_strategy()->display(); - $expected = ''; - $this->assertHTMLEquals($expected,$output); - } - - /** - * @group 10586 - */ - public function test_display__with_value() - { - $input = new EE_Integer_Input( - array( - 'default' => 123 - ) - ); - $input->_construct_finalize(null, 'age'); - $output = $input->get_display_strategy()->display(); - $expected = ''; - $this->assertHTMLEquals($expected,$output); - } -} - -// End of file EE_Checkbox_Display_Strategy_Test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/form_sections/strategies/display/EE_Radio_Button_Display_Strategy_Test.php b/tests/testcases/core/libraries/form_sections/strategies/display/EE_Radio_Button_Display_Strategy_Test.php deleted file mode 100644 index 3141a8df189..00000000000 --- a/tests/testcases/core/libraries/form_sections/strategies/display/EE_Radio_Button_Display_Strategy_Test.php +++ /dev/null @@ -1,114 +0,0 @@ - 'test', - 'subsections' => array( - 'use_captcha' => new EE_Radio_Button_Input( - array( - 1 => __('Yes', 'event_espresso'), - 0 => __('No', 'event_espresso'), - ), - array( - 'html_label_text' => __('Use reCAPTCHA', 'event_espresso'), - 'default' => 1, - 'normalization_strategy' => new EE_Int_Normalization(), - ) - ), - ), - )); - $this->assertEquals(1, $form->get_input('use_captcha')->normalized_value()); - $this->assertEquals('1', $form->get_input('use_captcha')->raw_value()); - $this->assertHTMLEquals(' - - -
    -
    ', $form->get_input('use_captcha')->get_html_for_input()); - - $form->populate_defaults(array('use_captcha' => 0)); - //the first option should be selected now - $this->assertEquals(0, $form->get_input('use_captcha')->normalized_value()); - $this->assertEquals('0', $form->get_input('use_captcha')->raw_value()); - $this->assertHTMLEquals(' - - -
    -
    ', $form->get_input('use_captcha')->get_html_for_input()); - } - - - /** - * @group 7121 - * @group html - * @throws EE_Error - */ - public function test_display__normalizing_as_string() - { - $form = new EE_Form_Section_Proper(array( - 'name' => 'test', - 'subsections' => array( - 'use_captcha' => new EE_Radio_Button_Input( - array( - "yes ma'am" => __('Yes', 'event_espresso'), - "no ma'am" => __('No', 'event_espresso'), - ), - array( - 'html_label_text' => __('Use reCAPTCHA', 'event_espresso'), - 'default' => "yes ma'am", - ) - ), - ), - )); - $this->assertEquals("yes ma'am", $form->get_input('use_captcha')->normalized_value()); - $this->assertEquals("yes ma'am", $form->get_input('use_captcha')->raw_value()); - $this->assertHTMLEquals(' - - -
    -
    ', $form->get_input('use_captcha')->get_html_for_input()); - - $form->populate_defaults(array('use_captcha' => "no ma'am")); - //the first option should be selected now - $this->assertEquals("no ma'am", $form->get_input('use_captcha')->normalized_value()); - $this->assertEquals("no ma'am", $form->get_input('use_captcha')->raw_value()); - $this->assertHTMLEquals(' - - -
    -
    ', $form->get_input('use_captcha')->get_html_for_input()); - } -} - -// End of file tests/testcases/core/libraries/form_sections/strategies/display/EE_Radio_Button_Display_Strategy_Test.php diff --git a/tests/testcases/core/libraries/form_sections/strategies/display/EE_Select_Display_Strategy_Test.php b/tests/testcases/core/libraries/form_sections/strategies/display/EE_Select_Display_Strategy_Test.php deleted file mode 100644 index 0c46d2bb1e8..00000000000 --- a/tests/testcases/core/libraries/form_sections/strategies/display/EE_Select_Display_Strategy_Test.php +++ /dev/null @@ -1,85 +0,0 @@ - 'form', - 'subsections' => array( - 'input1' => new EE_Select_Input( array( 'foo' => 'Foo', 'bar' => 'Bar', "baz'em" => 'Baz' ) ) - ) - )); - $input = $form->get_input( 'input1' ); - $expected_output = ' -'; - $this->assertHTMLEquals( $expected_output, $input->get_html_for_input() ); - //now if we set the default, does it get selected? - $form->populate_defaults( array( - 'input1' => "baz'em" - )); - $this->assertEquals( "baz'em", $input->normalized_value() ); - $this->assertEquals( "baz'em", $input->raw_value() ); - $expected_output2 = ' -'; - $this->assertHTMLEquals( $expected_output2, $input->get_html_for_input() ); - - } - - /** - * @group html - */ - public function test_display_flat_multidimensional_array(){ - $input = new EE_Select_Input( array( - 'code_var_names' => array( - 'foo' => 'Foo', - 'bar' => 'Bar', - 'baz' => 'Baz' ), - 'primates' => array( - 'chimp' => 'Chimp', - 'orangutan' => 'Orangutan', - 'baboon' => 'Baboon' - ))); - $expected_output = ' -'; - $this->assertHTMLEquals( $expected_output, $input->get_html_for_input() ); - - - } -} - -// End of file EE_Select_Display_Strategy_Test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/form_sections/strategies/display/EE_Select_Multiple_Display_Strategy_Test.php b/tests/testcases/core/libraries/form_sections/strategies/display/EE_Select_Multiple_Display_Strategy_Test.php deleted file mode 100644 index 6ef18ca97d8..00000000000 --- a/tests/testcases/core/libraries/form_sections/strategies/display/EE_Select_Multiple_Display_Strategy_Test.php +++ /dev/null @@ -1,53 +0,0 @@ - 'form', - 'subsections' => array( - 'input1' => new EE_Select_Multiple_Input( array( 'foo' => 'Foo', 'bar' => 'Bar', "baz'em" => 'Baz' ) ) - ) - )); - $input = $form->get_input( 'input1' ); - $expected_output = ' -'; - $this->assertHTMLEquals( $expected_output, $input->get_html_for_input() ); - //now if we set the default, does it get selected? - $form->populate_defaults( array( - 'input1' => array( "baz'em", 'bar' ) - )); - $this->assertEquals( array( "baz'em", 'bar' ), $input->normalized_value() ); - $this->assertEquals( array( "baz'em", 'bar' ), $input->raw_value() ); - $expected_output2 = ' -'; - $this->assertHTMLEquals( $expected_output2, $input->get_html_for_input() ); - - } -} - -// End of file EE_Select_Display_Strategy_Test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/form_sections/strategies/display/EE_Submit_Input_Display_Strategy_Test.php b/tests/testcases/core/libraries/form_sections/strategies/display/EE_Submit_Input_Display_Strategy_Test.php deleted file mode 100644 index 9a7ca6f7711..00000000000 --- a/tests/testcases/core/libraries/form_sections/strategies/display/EE_Submit_Input_Display_Strategy_Test.php +++ /dev/null @@ -1,72 +0,0 @@ -_construct_finalize(null, 'search'); - $output = $input->get_display_strategy()->display(); - $expected = ''; - $this->assertHTMLEquals($expected,$output); - } - - /** - * Verifies that even if the form is submitted WITHOUT pressing the submit button, - * when we show the form we will still show the submit input with the same value - * @group 11107 - */ - public function test_display__dont_change_value() - { - $submit_input = new EE_Submit_Input( - array( - 'default' => 'Apply', - ) - ); - $form = new EE_Form_Section_Proper(array( - 'name' => 'myform', - 'subsections' => array( - 'discount_code' => new EE_Text_Input(), - 'apply' => $submit_input - ) - )); - $form->receive_form_submission( - array( - 'myform' => array( - 'discount_code' => '', - //missing 'apply' on purrpose - ) - ) - ); - $this->assertEquals( - '', - $submit_input->raw_value() - ); - $this->assertEquals( - '', - $submit_input->normalized_value() - ); - $output = $submit_input->get_display_strategy()->display(); - $expected = ''; - $this->assertHTMLEquals($expected,$output); - } -} - -// End of file EE_Checkbox_Display_Strategy_Test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/form_sections/strategies/filter/VsprintfFilterTest.php b/tests/testcases/core/libraries/form_sections/strategies/filter/VsprintfFilterTest.php deleted file mode 100644 index 7b449c57669..00000000000 --- a/tests/testcases/core/libraries/form_sections/strategies/filter/VsprintfFilterTest.php +++ /dev/null @@ -1,96 +0,0 @@ - new VsprintfFilter( - '^^-1%1$s--2%2$s---3%3$s----4%4$s-1%1$s^^', - array( - 'argument1', - 'argument2', - ) - ), - 'subsections' => array( - 'some_input' => new EE_Text_Input() - ) - ) - ); - - //get the html for the form - $actual_output = $form->get_html(); - //our expectations are the following output: - //^^-1argument1--2argument2---3 - // - // - // - // - // - // - // - // - //
    - // - // - // - //
    - // - // - // - // ----4 - // - // - // - // - // - // - // - // - //-1argument1^^ - - //there should be two instances of the following, one at the beginning and one at the end - $expected_string_end = '-1argument1^^'; - $this->assertEquals(2, substr_count($actual_output, '-1argument1')); - $this->assertEquals(0, strpos($actual_output, '^^-1argument1')); - $this->assertEquals( - strlen($actual_output)-strlen($expected_string_end), - strrpos($actual_output, $expected_string_end) - ); - - //there should be one instance of the following - $this->assertEquals(1, substr_count($actual_output, '--2argument2')); - $this->assertEquals(0, strpos($actual_output, '^^-1argument1--2argument2')); - - //entire form should be in here - $this->assertEquals( - 1, - substr_count($actual_output, '') - ); - - //text input should appear twice - $this->assertEquals( - 2, - substr_count($actual_output, '_strategy = new EE_Float_Normalization(); - $input = new EE_Text_Input(); - $this->_strategy->_construct_finalize( $input ); - } - - - /** - * Data Provider for OK float inputs - * @return array{ - * array{ - * $0 the expected float - * $1 the input value - * } - * } - */ - public function ok_float_inputs(){ - return array( - array(null,''), - array(null,' '), - array(10, '10'), - array(10, '10'), - array(1000,'1,000'), - array(1000,' 1 000'), - array(10,'$10'), - array(1,'1.00'), - array(1000,' 1, 000.00'), - array(-1,'-1'), - array(-1,'- 1'), - array(20,'20 guineas'), - array(10,10.00), - array(56, '5 quid 6 pence'), - array(null, 'one hundred'), - ); - } - - - - /** - * @group 10586 - * @dataProvider ok_float_inputs - * @param $expected - * @param $input - * @throws EE_Validation_Error - */ - public function test_normalize_ok($expected, $input){ - $this->assertEquals($expected, $this->_strategy->normalize($input)); - } - - - /** - * Data Provider for bad float inputs - * @return array of arrays with the invalid inputs - */ - public function bad_float_inputs(){ - return array( - array(array()), - array(new stdClass()), - ); - } - - - - /** - * @group 10586 - * @dataProvider bad_float_inputs - * @expectedException EE_Validation_Error - * @param $input - * @throws EE_Validation_Error - */ - public function test_bad_float_inputs($input){ - $this->_strategy->normalize( $input ); - } -} - -// End of file EE_Float_Normalization_Test.php -// Location: tests/testcases/core/libraries/form_sections/strategies/normalization/EE_Float_Normalization_Test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/form_sections/strategies/normalization/EE_Int_Normalization_Test.php b/tests/testcases/core/libraries/form_sections/strategies/normalization/EE_Int_Normalization_Test.php deleted file mode 100644 index 4c2145159da..00000000000 --- a/tests/testcases/core/libraries/form_sections/strategies/normalization/EE_Int_Normalization_Test.php +++ /dev/null @@ -1,104 +0,0 @@ -_strategy = new EE_Int_Normalization(); - $input = new EE_Text_Input(); - $this->_strategy->_construct_finalize( $input ); - } - - - /** - * Data Provider for OK float inputs - * @return array{ - * array{ - * $0 the expected integer - * $1 the input value - * } - * } - */ - public function ok_int_inputs(){ - return array( - array(null,''), - array(null,' '), - array(10, '10'), - array(10, '10'), - array(1000,'1,000'), - array(1000,' 1 000'), - array(-1,'-1'), - array(-1,'- 1'), - array(10,10), - array(20,'20 guineas'), - array(10,'10.00'), - array(10,'10.0'), - array(10,'10.00000'), - array(10,'$10'), - array(56, '5 quid 6 pence'), - array(null, 'one hundred'), - ); - } - - - - /** - * @group 10586 - * @dataProvider ok_int_inputs - * @param $expected - * @param $input - * @throws EE_Validation_Error - */ - public function test_normalize_ok($expected, $input){ - $this->assertEquals($expected, $this->_strategy->normalize($input)); - } - - - /** - * Data Provider for bad float inputs - * @return array of arrays with the invalid inputs - */ - public function bad_int_inputs(){ - return array( - array(array()), - array(new stdClass()), - array('10.01'), - array('10.') - ); - } - - - - /** - * @group 10586 - * @dataProvider bad_int_inputs - * @expectedException EE_Validation_Error - * @param $input - * @throws EE_Validation_Error - */ - public function test_bad_float_inputs($input){ - $this->_strategy->normalize( $input ); - } -} - -// End of file EE_Int_Normalization_Test.php -// Location: tests/testcases/core/libraries/form_sections/strategies/normalization/EE_Int_Normalization_Test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/form_sections/strategies/validation/EE_Email_Validation_Strategy_Test.php b/tests/testcases/core/libraries/form_sections/strategies/validation/EE_Email_Validation_Strategy_Test.php deleted file mode 100644 index 39d638c28a9..00000000000 --- a/tests/testcases/core/libraries/form_sections/strategies/validation/EE_Email_Validation_Strategy_Test.php +++ /dev/null @@ -1,322 +0,0 @@ -_validator = new EE_Email_Validation_Strategy(); - //finalize its construction, but we don't actually need the input anyways - $this->_validator->_construct_finalize( new EE_Email_Input() ); - } - - - - /** - * @param $counter - * @param $email_address - * @param bool $assert_success - */ - public function validate_email_address( $counter, $email_address, $assert_success = true ) { - - if ( $assert_success ) { - $success = true; - $fail = false; - } else { - $success = false; - $fail = true; - } - try { - $this->_validator->validate( $email_address ); - $this->assertTrue( - $success, - sprintf( - 'Email addy #%1$s "%2$s" passed validation when it should have failed.', - $counter, - $email_address - ) - ); - } catch ( EE_Validation_Error $e ) { - $this->assertTrue( - $fail, - sprintf( - 'Email addy #%1$s "%2$s" failed validation when it should have passed.', - $counter, - $email_address - ) - ); - } - // i'm using = and NOT ==, so that I can bypass the following tests, - // these were only added for dev purposes, but fail too often to be useful - /*if ( $test_PHP_and_WP_validators = false ) { - if ( $assert_success ) { - $this->assertEquals( - $email_address, - filter_var( $email_address, FILTER_VALIDATE_EMAIL ), - sprintf( - 'PHP says email addy #%1$s "%2$s" failed validation when it should have passed.', - $counter, - $email_address - ) - ); - $this->assertEquals( - $email_address, - is_email( $email_address ), - sprintf( - 'WordPress says email addy #%1$s "%2$s" failed validation when it should have passed.', - $counter, - $email_address - ) - ); - } else { - $this->assertFalse( - filter_var( $email_address, FILTER_VALIDATE_EMAIL ), - sprintf( - 'PHP says email addy #%1$s "%2$s" passed validation when it should have failed.', - $counter, - $email_address - ) - ); - $this->assertFalse( - is_email( $email_address ), - sprintf( - 'WordPress says email addy #%1$s "%2$s" passed validation when it should have failed.', - $counter, - $email_address - ) - ); - } - }*/ - - } - - - - public function test_validate__pass_basic() { - EE_Registry::instance()->CFG->registration->email_validation_level = 'basic'; - // these should pass ALL validations - $good_addys = array( - 'bogus@eventespresso.com', - 'developers@eventespresso.museum', - 'รผรฑรฎรงรธรฐรฉ@example.com', // (Unicode characters in local part) - 'รครถรผร„ร–รœรŸ@eventespresso.com', // lรถtsรค umlรครผts - '็”จๆˆท@ไพ‹ๅญ.ๅนฟๅ‘Š', // ( Chinese, Unicode ) - 'เค‰เคชเคฏเฅ‹เค—เค•เคฐเฅเคคเคพ@เค‰เคฆเคพเคนเคฐเคฃ.เค•เฅ‰เคฎ', // ( Hindi, Unicode ) - 'ัŽะทะตั€@ะตะบะทะฐะผะฟะป.ะบะพะผ', // ( Ukrainian, Unicode ) - 'ฮธฯƒฮตฯ@ฮตฯ‡ฮฑฮผฯ€ฮปฮต.ฯˆฮฟฮผ', // ( Greek, Unicode ) - 'Dรถrte@Sรถrensen.example.com', // ( German, Unicode ) - // short domain - 'developers@e.com', - 'developers@eventespresso.c', - // from https://en.wikipedia.org/wiki/Email_address#Examples - 'niceandsimple@example.com', - 'very.common@example.com', - 'a.little.lengthy.but.fine@dept.example.com', - 'disposable.style.email.with+symbol@example.com', - "!#$%&'*+-/=?^_`{}|~@example.org", - // the following, despite being valid, do NOT pass our validation - //'user@[IPv6:2001:db8:1ff::a0b:dbd0]', - '"much.more unusual"@example.com', - '"very.unusual.@.unusual.com"@example.com', - '"very.(),:;<>[]\".VERY.\"very@\ \"very\".unusual"@strange.example.com', - 'postbox@com', - 'admin@mailserver1', // local domain name with no TLD - '"()<>[]:,;@\\"!#$%&\'*+-/=?^_`{}| ~.a"@example.org', - '" "@example.org', // (space between the quotes) - // the following, despite being INVALID, pass validation when they should NOT - // haxxor - '@eventespresso.com', - ); - // turn off DNS checks - foreach ( $good_addys as $count => $good_addy ) { - $this->validate_email_address( $count, $good_addy ); - } - } - - - - public function test_validate__fail_basic(){ - EE_Registry::instance()->CFG->registration->email_validation_level = 'basic'; - $bad_addys = array( - // double dots - 'develop..ers@eventespresso.com', - 'developers@event..espresso.com', - // no local - '@eventespresso.com', - // no domain - 'developers@', - ); - foreach ( $bad_addys as $count => $bad_addy ) { - $this->validate_email_address( $count, $bad_addy, false ); - } - } - - - - public function test_validate__pass_wp_default() { - EE_Registry::instance()->CFG->registration->email_validation_level = 'wp_default'; - // these should pass ALL validations - $good_addys = array( - 'bogus@eventespresso.com', - 'developers@eventespresso.museum', - // short domain - 'developers@e.com', - 'developers@eventespresso.c', - // from https://en.wikipedia.org/wiki/Email_address#Examples - 'niceandsimple@example.com', - 'very.common@example.com', - 'a.little.lengthy.but.fine@dept.example.com', - 'disposable.style.email.with+symbol@example.com', - "!#$%&'*+-/=?^_`{}|~@example.org", - // the following, despite being valid, do NOT pass WordPress is_email() validation - //'รผรฑรฎรงรธรฐรฉ@example.com', // (Unicode characters in local part) - //'รครถรผร„ร–รœรŸ@eventespresso.com', // lรถtsรค umlรครผts - //'็”จๆˆท@ไพ‹ๅญ.ๅนฟๅ‘Š', // ( Chinese, Unicode ) - //'เค‰เคชเคฏเฅ‹เค—เค•เคฐเฅเคคเคพ@เค‰เคฆเคพเคนเคฐเคฃ.เค•เฅ‰เคฎ', // ( Hindi, Unicode ) - //'ัŽะทะตั€@ะตะบะทะฐะผะฟะป.ะบะพะผ', // ( Ukrainian, Unicode ) - //'ฮธฯƒฮตฯ@ฮตฯ‡ฮฑฮผฯ€ฮปฮต.ฯˆฮฟฮผ', // ( Greek, Unicode ) - //'Dรถrte@Sรถrensen.example.com', // ( German, Unicode ) - //'user@[IPv6:2001:db8:1ff::a0b:dbd0]', - //'"much.more unusual"@example.com', - //'"very.unusual.@.unusual.com"@example.com', - //'"very.(),:;<>[]\".VERY.\"very@\ \"very\".unusual"@strange.example.com', - //'postbox@com', - //'admin@mailserver1', // local domain name with no TLD - //'"()<>[]:,;@\\"!#$%&\'*+-/=?^_`{}| ~.a"@example.org', - //'" "@example.org', // (space between the quotes) - ); - // turn off DNS checks - foreach ( $good_addys as $count => $good_addy ) { - $this->validate_email_address( $count, $good_addy ); - } - } - - - - public function test_validate__fail_wp_default() { - EE_Registry::instance()->CFG->registration->email_validation_level = 'wp_default'; - $bad_addys = array( - // double dots - 'develop..ers@eventespresso.com', - 'developers@event..espresso.com', - // haxxor - '@eventespresso.com', - // no local - '@eventespresso.com', - // no domain - 'developers@', - // valid but international - 'รผรฑรฎรงรธรฐรฉ@example.com', // (Unicode characters in local part) - 'รครถรผร„ร–รœรŸ@eventespresso.com', // lรถtsรค umlรครผts - '็”จๆˆท@ไพ‹ๅญ.ๅนฟๅ‘Š', // ( Chinese, Unicode ) - 'เค‰เคชเคฏเฅ‹เค—เค•เคฐเฅเคคเคพ@เค‰เคฆเคพเคนเคฐเคฃ.เค•เฅ‰เคฎ', // ( Hindi, Unicode ) - 'ัŽะทะตั€@ะตะบะทะฐะผะฟะป.ะบะพะผ', // ( Ukrainian, Unicode ) - 'ฮธฯƒฮตฯ@ฮตฯ‡ฮฑฮผฯ€ฮปฮต.ฯˆฮฟฮผ', // ( Greek, Unicode ) - 'Dรถrte@Sรถrensen.example.com', // ( German, Unicode ) - ); - foreach ( $bad_addys as $count => $bad_addy ) { - $this->validate_email_address( $count, $bad_addy, false ); - } - } - - - - public function test_validate__pass_i18n() { - EE_Registry::instance()->CFG->registration->email_validation_level = 'i18n'; - // these should pass ALL validations - $good_addys = array( - 'bogus@eventespresso.com', - 'developers@eventespresso.museum', - 'รผรฑรฎรงรธรฐรฉ@example.com', // (Unicode characters in local part) - 'รครถรผร„ร–รœรŸ@eventespresso.com', // lรถtsรค umlรครผts - '็”จๆˆท@ไพ‹ๅญ.ๅนฟๅ‘Š', // ( Chinese, Unicode ) - 'เค‰เคชเคฏเฅ‹เค—เค•เคฐเฅเคคเคพ@เค‰เคฆเคพเคนเคฐเคฃ.เค•เฅ‰เคฎ', // ( Hindi, Unicode ) - 'ัŽะทะตั€@ะตะบะทะฐะผะฟะป.ะบะพะผ', // ( Ukrainian, Unicode ) - 'ฮธฯƒฮตฯ@ฮตฯ‡ฮฑฮผฯ€ฮปฮต.ฯˆฮฟฮผ', // ( Greek, Unicode ) - 'Dรถrte@Sรถrensen.example.com', // ( German, Unicode ) - // short domain - 'developers@e.com', - // from https://en.wikipedia.org/wiki/Email_address#Examples - 'niceandsimple@example.com', - 'very.common@example.com', - 'a.little.lengthy.but.fine@dept.example.com', - 'disposable.style.email.with+symbol@example.com', - "!#$%&'*+-/=?^_`{}|~@example.org", - // the following, despite being valid, do NOT pass our validation - //'user@[IPv6:2001:db8:1ff::a0b:dbd0]', - //'"much.more unusual"@example.com', - //'"very.unusual.@.unusual.com"@example.com', - //'"very.(),:;<>[]\".VERY.\"very@\ \"very\".unusual"@strange.example.com', - //'postbox@com', - //'admin@mailserver1', // local domain name with no TLD - //'"()<>[]:,;@\\"!#$%&\'*+-/=?^_`{}| ~.a"@example.org', - //'" "@example.org', // (space between the quotes) - ); - // turn off DNS checks - foreach ( $good_addys as $count => $good_addy ) { - $this->validate_email_address( $count, $good_addy ); - } - } - - - - public function test_validate__fail_i18n() { - EE_Registry::instance()->CFG->registration->email_validation_level = 'i18n'; - $bad_addys = array( - // double dots - 'develop..ers@eventespresso.com', - 'developers@event..espresso.com', - // haxxor - '@eventespresso.com', - // domain too short - 'developers@eventespresso.c', - // no local - '@eventespresso.com', - // no domain - 'developers@', - ); - foreach ( $bad_addys as $count => $bad_addy ) { - $this->validate_email_address( $count, $bad_addy, false ); - } - } - - - - public function test_DNS_and_MX_record_check_fail(){ - EE_Registry::instance()->CFG->registration->email_validation_level = 'i18n_dns'; - $bad_addys = array( - // no MX records (bogus addresses) - 'valid-but-not-real@siiiiiiiiiiiiiiite.com', - 'developers@eventespresso.museum', - '็”จๆˆท@ไพ‹ๅญ.ๅนฟๅ‘Š', // ( Chinese, Unicode ) - 'เค‰เคชเคฏเฅ‹เค—เค•เคฐเฅเคคเคพ@เค‰เคฆเคพเคนเคฐเคฃ.เค•เฅ‰เคฎ', // ( Hindi, Unicode ) - 'ัŽะทะตั€@ะตะบะทะฐะผะฟะป.ะบะพะผ', // ( Ukrainian, Unicode ) - 'ฮธฯƒฮตฯ@ฮตฯ‡ฮฑฮผฯ€ฮปฮต.ฯˆฮฟฮผ', // ( Greek, Unicode ) - 'Dรถrte@Sรถrensen.staaaaaaaandooooooooort.com', // ( German, Unicode ) - ); - foreach ( $bad_addys as $count => $bad_addy ) { - $this->validate_email_address( $count, $bad_addy, false ); - } - } - - -} -// End of file tests/testcases/core/libraries/form_sections/strategies/validation/EE_Email_Validation_Strategy_Test.php diff --git a/tests/testcases/core/libraries/form_sections/strategies/validation/EE_Max_Length_Validation_Strategy_Test.php b/tests/testcases/core/libraries/form_sections/strategies/validation/EE_Max_Length_Validation_Strategy_Test.php deleted file mode 100644 index eb1995d7261..00000000000 --- a/tests/testcases/core/libraries/form_sections/strategies/validation/EE_Max_Length_Validation_Strategy_Test.php +++ /dev/null @@ -1,81 +0,0 @@ -_validator = new EE_Max_Length_Validation_Strategy( 'oups', 5 ); - $input = new EE_Text_Input(); - //finalize its construction, but we don't actually need the input anyways - $this->_validator->_construct_finalize( $input ); - } - /** - * tests that it can be left blank and pass validation (because the required validation - * strategy is what should fail here, if it's added as a validation strategy) - */ - public function test_validate__blank_but_not_required() { - try{ - $this->_validator->validate( '' ); - $this->assertTrue(true); - }catch(EE_Validation_Error $e ){ - $this->assertFalse( true, 'The empty string is shorter than 5 so it should be ok' ); - } - } - - /** - * tests that validation passes with LESS than the maximum characters - */ - public function test_validate__pass() { - try{ - $this->_validator->validate( '1234' ); - $this->assertTrue(true); - }catch(EE_Validation_Error $e ){ - $this->assertFalse( true, '1234 has less than 5 characters and so should be ok' ); - } - } - - /** - * tests validation passes with the maximum number of characters - */ - public function test_validate__pass_but_barely() { - try{ - $this->_validator->validate( '12345' ); - $this->assertTrue(true); - }catch(EE_Validation_Error $e ){ - $this->assertFalse( true, '12345 has 5 characters and so should be ok' ); - } - } - - /** - * tests that validation fails when there are FEWER than the maximum number of characters - */ - public function test_validate__fail() { - try{ - $this->_validator->validate( '123456' ); - $this->assertFalse( true, '123456 has too MANY character' ); - }catch(EE_Validation_Error $e ){ - $this->assertTrue( true ); - } - } - - - -} - -// End of file EE_Max_Length_Validation_Strategy_Test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/form_sections/strategies/validation/EE_Min_Length_Validation_Strategy_Test.php b/tests/testcases/core/libraries/form_sections/strategies/validation/EE_Min_Length_Validation_Strategy_Test.php deleted file mode 100644 index 1f50a732699..00000000000 --- a/tests/testcases/core/libraries/form_sections/strategies/validation/EE_Min_Length_Validation_Strategy_Test.php +++ /dev/null @@ -1,81 +0,0 @@ -_validator = new EE_Min_Length_Validation_Strategy( 'oups', 5 ); - $input = new EE_Text_Input(); - //finalize its construction, but we don't actually need the input anyways - $this->_validator->_construct_finalize( $input ); - } - /** - * tests that it can be left blank and pass validation (because the required validation - * strategy is what should fail here, if it's added as a validation strategy) - */ - public function test_validate__blank_but_not_required() { - try{ - $this->_validator->validate( '' ); - $this->assertTrue(true); - }catch(EE_Validation_Error $e ){ - $this->assertFalse( true, 'Even though the empty string is shorter than the min length, that indicates no response was given. And that should be checked by the REQUIRED validation' ); - } - } - - /** - * tests that validation passes with MORE than th eminimum characters - */ - public function test_validate__pass() { - try{ - $this->_validator->validate( '123456' ); - $this->assertTrue(true); - }catch(EE_Validation_Error $e ){ - $this->assertFalse( true, '123456 has more than 5 characters and so should be ok' ); - } - } - - /** - * tests validation passes with the minimum number of characters - */ - public function test_validate__pass_but_barely() { - try{ - $this->_validator->validate( '12345' ); - $this->assertTrue(true); - }catch(EE_Validation_Error $e ){ - $this->assertFalse( true, '12345 has 5 characters and so should be ok' ); - } - } - - /** - * tests that validation fails when there are FEWER than the minimum number of characters - */ - public function test_validate__fail() { - try{ - $this->_validator->validate( '123' ); - $this->assertFalse( true, '123 has too FEW character' ); - }catch(EE_Validation_Error $e ){ - $this->assertTrue( true ); - } - } - - - -} - -// End of file EE_Min_Length_Validation_Strategy_Test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/form_sections/strategies/validation/EE_Model_Matching_Query_Validation_Strategy_Test.php b/tests/testcases/core/libraries/form_sections/strategies/validation/EE_Model_Matching_Query_Validation_Strategy_Test.php deleted file mode 100644 index 1d8de31b32b..00000000000 --- a/tests/testcases/core/libraries/form_sections/strategies/validation/EE_Model_Matching_Query_Validation_Strategy_Test.php +++ /dev/null @@ -1,71 +0,0 @@ - array( 'LIKE', '%bar' ) - ) - ) - ); - $ev = $this->new_model_obj_with_dependencies( 'Event', array( 'EVT_name' => 'bobit' ) ); - try{ - $validator->validate( $ev->ID() + 1 ); - $this->fail( 'this one doesn\'t match because there is no event with this ID'); - }catch( EE_Validation_Error $e ) {} - try{ - $this->assertfalse( $validator->validate( $ev->ID() ) ); - $this->fail("this one doesn't match because the validator only looks for events with EVT_name like '%bar'" ); - }catch( EE_Validation_Error $e ) {} - - $ev->set( 'EVT_name', 'foobar' ); - $ev->save(); - //this one is valid because the name matches the validator's criteria and - //and the id exists - $validator->validate( $ev->ID() ); - } - - /** - * @since 4.10.7.p - * @throws EE_Error - * @throws EE_Validation_Error - * @doesNotPerformAssertions - */ - public function test_valid__treating_input_as_other_field() { - $validator = new EE_Model_Matching_Query_Validation_Strategy( - '', - 'Event', - array(), - 'EVT_name' - ); - $ev = $this->new_model_obj_with_dependencies( 'Event', array( 'EVT_name' => 'bobit' ) ); - try{ - $validator->validate( 'non-existent-event-name' ); - $this->fail( 'There is no event with this name so it shouldnt pass validation'); - } catch ( EE_Validation_Error $ex) {} - $validator->validate('bobit'); - } -} \ No newline at end of file diff --git a/tests/testcases/core/libraries/form_sections/strategies/validation/EE_Plaintext_Validation_Strategy_Test.php b/tests/testcases/core/libraries/form_sections/strategies/validation/EE_Plaintext_Validation_Strategy_Test.php deleted file mode 100644 index 6f6b7bac973..00000000000 --- a/tests/testcases/core/libraries/form_sections/strategies/validation/EE_Plaintext_Validation_Strategy_Test.php +++ /dev/null @@ -1,46 +0,0 @@ -_validator = new EE_Plaintext_Validation_Strategy(); - $input = new EE_Text_Input(); - //finalize its construction, but we don't actually need the input anyways - $this->_validator->_construct_finalize( $input ); - } - function test_validate__fail(){ - try{ - $this->_validator->validate( ' ' ); - $this->assertTrue( false ); - }catch( EE_Validation_Error $e ) { - $this->assertTrue( true ); - } - } - - /** - * @doesNotPerformAssertions - */ - function test_validate__pass(){ - $this->_validator->validate( 'just some text; no html anywhere' ); - } -} - -// End of file EE_Plaintext_Validation_Strategy_Test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/form_sections/strategies/validation/EE_Text_Length_Validation_Strategy_Test.php b/tests/testcases/core/libraries/form_sections/strategies/validation/EE_Text_Length_Validation_Strategy_Test.php deleted file mode 100644 index 9b8b255a44c..00000000000 --- a/tests/testcases/core/libraries/form_sections/strategies/validation/EE_Text_Length_Validation_Strategy_Test.php +++ /dev/null @@ -1,73 +0,0 @@ -_validator = new EE_Text_Validation_Strategy( 'oups', '~Darth ([\w]*)~' ); - $input = new EE_Text_Input(); - //finalize its construction, but we don't actually need the input anyways - $this->_validator->_construct_finalize( $input ); - } - /** - * tests that it can be left blank and pass validation (because the required validation - * strategy is what should fail here, if it's added as a validation strategy) - */ - public function test_validate__blank_but_not_required() { - try{ - $this->_validator->validate( '' ); - $this->assertTrue(true); - }catch(EE_Validation_Error $e ){ - $this->assertFalse( true, 'This isnt the requried validation. Blank string is ok' ); - } - } - - /** - * tests that validation passes with LESS than the maximum characters - */ - public function test_validate__pass() { - try{ - $this->_validator->validate( 'Darth Vader' ); - $this->assertTrue(true); - }catch(EE_Validation_Error $e ){ - $this->assertFalse( true, 'This should have matched the regex' ); - } - } - - - /** - * tests that validation fails when there are FEWER than the maximum number of characters - */ - public function test_validate__fail() { - try{ - $this->_validator->validate( 'Han Solo' ); - $this->assertFalse( true, '"Han Solo" should not mathc regex' ); - }catch(EE_Validation_Error $e ){ - $this->assertTrue( true ); - } - } - - public function test_regex_js(){ - $this->assertEquals( 'Darth ([\w]*)', $this->_validator->regex_js() ); - } - - -} - -// End of file EE_Text_Validation_Strategy_Test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/line_item_filters/EE_Line_Item_Filter_Processor_Test.php b/tests/testcases/core/libraries/line_item_filters/EE_Line_Item_Filter_Processor_Test.php deleted file mode 100644 index 11a95fe2d86..00000000000 --- a/tests/testcases/core/libraries/line_item_filters/EE_Line_Item_Filter_Processor_Test.php +++ /dev/null @@ -1,44 +0,0 @@ -new_typical_transaction( array( 'ticket_types' => 2 ) ); - $original_total = $txn->total(); - //in order for us to do a good test, let's verify - $this->assertNotEquals( 0, $original_total ); - $this->assertEquals( 2, count( $txn->registrations() ) ); - //ok now use the processor with some kind of filter - $collection = new EE_Line_Item_Filter_Collection(); - $collection->add( new EE_Single_Registration_Line_Item_Filter( $txn->primary_registration() ) ); - $processor = new EE_Line_Item_Filter_Processor( $collection, $txn->total_line_item() ); - $filtered_line_item_tree = $processor->process(); - //doesn't matter which filter so long as it just changes the grand total line item's total is all - $this->assertNotEquals( $txn->total_line_item()->total(), $filtered_line_item_tree->total() ); - //and now verify the transaction wasn't changed in this process - $this->assertEquals( $original_total, $txn->total() ); - - } -} - -// End of file EE_Line_Item_Filter_Processor_Test.php -// Location: /tests/testcases/core/libraries/line_item_filters/EE_Line_Item_Filter_Processor_Test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/line_item_filters/EE_Non_Zero_Line_Item_Filter_Test.php b/tests/testcases/core/libraries/line_item_filters/EE_Non_Zero_Line_Item_Filter_Test.php deleted file mode 100644 index 539f6d10801..00000000000 --- a/tests/testcases/core/libraries/line_item_filters/EE_Non_Zero_Line_Item_Filter_Test.php +++ /dev/null @@ -1,151 +0,0 @@ - 'subtotal', - 'LIN_code' => 'subtotal', - 'LIN_type' => EEM_Line_Item::type_sub_total, - )); - //and four children: - //a ticket with a quantity of 1 - $tktli1 = EE_Line_Item::new_instance( - array( - 'LIN_name' => 'tktli1', - 'LIN_code' => 'tktli1', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_unit_price' => 10, - 'LIN_quantity' => 1, - 'OBJ_type' => 'Ticket' - )); - $subtotal->add_child_line_item( $tktli1 ); - //a ticket with a quantity of 0 - $tktli2 = EE_Line_Item::new_instance( - array( - 'LIN_name' => 'tktli2', - 'LIN_code' => 'tktli2', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_unit_price' => 10, - 'LIN_quantity' => 0, - 'OBJ_type' => 'Ticket' - )); - $subtotal->add_child_line_item( $tktli2 ); - //a non-ticket with a quantity of 1 - $non_tkt_li = EE_Line_Item::new_instance( - array( - 'LIN_name' => 'non_tkt', - 'LIN_code' => 'non_tkt', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_unit_price' => 10, - 'LIN_quantity' => 1, - 'OBJ_type' => null - )); - $subtotal->add_child_line_item( $non_tkt_li ); - //and a discount which erroneously has a quantity of 0 - $discount = EE_Line_Item::new_instance( - array( - 'LIN_name' => 'discount', - 'LIN_code' => 'discount', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_unit_price' => 0, - 'LIN_percent' => 25, - 'LIN_quantity' => 0, - 'OBJ_type' => null - )); - $subtotal->add_child_line_item( $discount ); - //when filtered, only the ticket with a quantity of 1 should be removed - $filter = new EE_Non_Zero_Line_Item_Filter(); - $filter->process( $subtotal ); - $filtered_children = $subtotal->children(); - $this->assertContains( $tktli1, $filtered_children ); - $this->assertNotContains( $tktli2, $filtered_children ); - $this->assertContains( $non_tkt_li, $filtered_children ); - $this->assertContains( $discount, $filtered_children ); - } - /** - */ - function test_filter__removed_subtotals_with_no_ticket_children() { - //verify that normal subtotals stay, but subtotals with no ticket children get removed - //so create a total - $total = EE_Line_Item::new_instance( - array( - 'LIN_name' => 'total', - 'LIN_code' => 'total', - 'LIN_type' => EEM_Line_Item::type_total - )); - //and a subttoal WITH a ticket (but the subtotal itself was erroneously labelled as quantity 0) - $subtotal_with_tkt = EE_Line_Item::new_instance( - array( - 'LIN_name' => 'subtotal-with-tkt', - 'LIN_code' => 'subttoal-with-tkt', - 'LIN_type' => EEM_Line_Item::type_sub_total, - 'LIN_quantity' => 0, //we should be setting it to 1 from now on, but earlier code set it to 0 - )); - $total->add_child_line_item( $subtotal_with_tkt ); - $tkt1 = EE_Line_Item::new_instance( - array( - 'LIN_name' => 'tkt1', - 'LIN_code' => 'tkt1', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'OBJ_type' => 'Ticket', - 'LIN_quantity' => 1 - )); - $subtotal_with_tkt->add_child_line_item( $tkt1 ); - - //and another subtotal with a ticket but quantity 0, and another non-ticket line item with quantity 1 - $subtotal_without_tkt = EE_Line_Item::new_instance( - array( - 'LIN_name' => 'subtotal-without-tkt', - 'LIN_code' => 'subttoal-without-tkt', - 'LIN_type' => EEM_Line_Item::type_sub_total, - 'LIN_quantity' => 0, //we should be setting it to 1 from now on, but earlier code set it to 0 - )); - $total->add_child_line_item( $subtotal_without_tkt ); - $tkt2 = EE_Line_Item::new_instance( - array( - 'LIN_name' => 'tkt2', - 'LIN_code' => 'tkt2', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'OBJ_type' => 'Ticket', - 'LIN_quantity' => 0,//IMPORTANT! - )); - $subtotal_without_tkt->add_child_line_item( $tkt2 ); - $non_tkt_li = EE_Line_Item::new_instance( - array( - 'LIN_name' => 'non_tkt_li', - 'LIN_code' => 'non_tkt_li', - 'LIN_type' => EEM_Line_Item::type_line_item, - 'OBJ_type' => null, - 'LIN_quantity' => 1, - )); - $subtotal_without_tkt->add_child_line_item( $non_tkt_li ); - - //only the subtotal without a ticket should get filtered out - $filter = new EE_Non_Zero_Line_Item_Filter(); - $filter->process( $total ); - $totals_children = $total->children(); - $this->assertContains( $subtotal_with_tkt, $totals_children ); - $this->assertNotContains( $subtotal_without_tkt, $totals_children ); - } -} - -// End of file EE_Non_Zero_Line_Item_Filter_Test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/line_item_filters/EE_Specific_Registrations_Line_Item_Filter_Test.php b/tests/testcases/core/libraries/line_item_filters/EE_Specific_Registrations_Line_Item_Filter_Test.php deleted file mode 100644 index 6dfaa90ed44..00000000000 --- a/tests/testcases/core/libraries/line_item_filters/EE_Specific_Registrations_Line_Item_Filter_Test.php +++ /dev/null @@ -1,446 +0,0 @@ - EEM_Line_Item::type_total, - 'LIN_name' => 'Total', - )); - $pretax_total = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_sub_total, - 'LIN_code' => 'pretax', - 'LIN_name' => 'pretax', - 'LIN_order' => 1, - )); - $grand_total->add_child_line_item( $pretax_total ); - - $tax_total = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_tax_sub_total, - 'LIN_code' => 'tax-total', - 'LIN_name' => 'tax-total', - 'LIN_order' => 1000 - )); - $grand_total->add_child_line_item( $tax_total ); - $event_subtotal = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_sub_total, - 'LIN_code' => 'event1', - 'LIN_name' => 'event1', - ) ); - $pretax_total->add_child_line_item( $event_subtotal ); - - $ticket_quantities = array( - 1 => array( - 'included' => 2, - 'not' => 3 - ) - ); - $ticket_li = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_code' => 'ticket1', - 'LIN_name' => 'ticket1', - 'OBJ_ID' => 1, - 'OBJ_type' => 'Ticket', - 'LIN_unit_price' => 10, - 'LIN_quantity' => 5 - )); - $event_subtotal->add_child_line_item( $ticket_li ); - $regs_to_include = $this->_create_regs( $ticket_quantities, $grand_total); - //ok now let's use the filter - $filter = new EE_Specific_Registrations_Line_Item_Filter( $regs_to_include ); - $filtered_total = $filter->process( $grand_total ); - //the filter doesn't recalculate totals, and it edits the inputted tree; - //hat's ok, the processor does both of those. But we need to manually do it here - $this->assertEquals( $grand_total, $filtered_total ); - $grand_total->recalculate_total_including_taxes(); - $this->assertEquals( 2, $ticket_li->quantity() ); - $this->assertEquals( 10, $ticket_li->unit_price() ); - $this->assertEquals( 20, $ticket_li->total() ); - } - - function test_process__1_taxless_ticket_and_percent_discount() { - $grand_total = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_total, - 'LIN_name' => 'Total', - )); - $pretax_total = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_sub_total, - 'LIN_code' => 'pretax', - 'LIN_name' => 'pretax', - 'LIN_order' => 1, - )); - $grand_total->add_child_line_item( $pretax_total ); - - $tax_total = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_tax_sub_total, - 'LIN_code' => 'tax-total', - 'LIN_name' => 'tax-total', - 'LIN_order' => 1000 - )); - $grand_total->add_child_line_item( $tax_total ); - $event_subtotal = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_sub_total, - 'LIN_code' => 'event1', - 'LIN_name' => 'event1', - ) ); - $pretax_total->add_child_line_item( $event_subtotal ); - - $ticket_quantities = array( - 1 => array( - 'included' => 4, - 'not' => 6 - ) - ); - $ticket_li = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_code' => 'ticket1', - 'LIN_name' => 'ticket1', - 'OBJ_ID' => 1, - 'OBJ_type' => 'Ticket', - 'LIN_unit_price' => 10, - 'LIN_quantity' => 10, - 'LIN_total' => 100, - )); - $event_subtotal->add_child_line_item( $ticket_li ); - - $percent_discount_li = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_code' => 'discount1', - 'LIN_name' => 'discount1', - 'LIN_unit_price' => 0, - 'LIN_percent' => -25, - 'LIN_total' => -25, - 'LIN_quantity' => 1 - )); - $event_subtotal->add_child_line_item( $percent_discount_li ); - //also need to make registrations - $regs_to_include = $this->_create_regs( $ticket_quantities, $grand_total ); - //ok now let's use the filter - $filter = new EE_Specific_Registrations_Line_Item_Filter( $regs_to_include ); - $filtered_total = $filter->process( $grand_total ); - //the filter doesn't recalculate totals, and it edits the inputted tree; - //hat's ok, the processor does both of those. But we need to manually do it here - $this->assertEquals( $grand_total, $filtered_total ); - $grand_total->recalculate_total_including_taxes(); - $this->assertEquals( 4, $ticket_li->quantity() ); - $this->assertEquals( 10, $ticket_li->unit_price() ); - $this->assertEquals( 40, $ticket_li->total() ); - //and verify the percent line item's total has changed, but not its percent - $this->assertEquals( -25, $percent_discount_li->percent() ); - $this->assertEquals( -10, $percent_discount_li->total() ); - } - - - function test_process__1_taxless_ticket_with_modifier_and_fixed_discount() { - $grand_total = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_total, - 'LIN_name' => 'Total', - )); - $pretax_total = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_sub_total, - 'LIN_code' => 'pretax', - 'LIN_name' => 'pretax', - 'LIN_order' => 1, - )); - $grand_total->add_child_line_item( $pretax_total ); - - $tax_total = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_tax_sub_total, - 'LIN_code' => 'tax-total', - 'LIN_name' => 'tax-total', - 'LIN_order' => 1000 - )); - $grand_total->add_child_line_item( $tax_total ); - $event_subtotal = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_sub_total, - 'LIN_code' => 'event1', - 'LIN_name' => 'event1', - ) ); - $pretax_total->add_child_line_item( $event_subtotal ); - - $ticket_quantities = array( - 1 => array( - 'included' => 5, - 'not' => 5 - ) - ); - $ticket_li = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_code' => 'ticket1', - 'LIN_name' => 'ticket1', - 'OBJ_ID' => 1, - 'OBJ_type' => 'Ticket', - 'LIN_unit_price' => 10, - 'LIN_quantity' => 10, - 'LIN_total' => 100, - )); - $event_subtotal->add_child_line_item( $ticket_li ); - - $base_price_li = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_sub_line_item, - 'LIN_code' => 'price1', - 'LIN_name' => 'price1', - 'OBJ_ID' => 1, - 'OBJ_type' => 'Price', - 'LIN_unit_price' => 9, - 'LIN_quantity' => 10, - 'LIN_total' => 90, - )); - $ticket_li->add_child_line_item( $base_price_li ); - - $modifier_li = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_sub_line_item, - 'LIN_code' => 'price2', - 'LIN_name' => 'price2', - 'OBJ_ID' => 2, - 'OBJ_type' => 'Price', - 'LIN_unit_price' => 1, - 'LIN_quantity' => 10, - 'LIN_total' => 10, - )); - $ticket_li->add_child_line_item( $modifier_li ); - - $percent_discount_li = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_code' => 'discount1', - 'LIN_name' => 'discount1', - 'LIN_unit_price' => -50, - 'LIN_percent' => 0, - 'LIN_total' => -50, - 'LIN_quantity' => 1 - )); - $event_subtotal->add_child_line_item( $percent_discount_li ); - //also need to make registrations - $regs_to_include = $this->_create_regs( $ticket_quantities, $grand_total ); - //ok now let's use the filter - $filter = new EE_Specific_Registrations_Line_Item_Filter( $regs_to_include ); - $filtered_total = $filter->process( $grand_total ); - //the filter doesn't recalculate totals, and it edits the inputted tree; - //hat's ok, the processor does both of those. But we need to manually do it here - $this->assertEquals( $grand_total, $filtered_total ); - $grand_total->recalculate_total_including_taxes(); - $this->assertEquals( 5, $ticket_li->quantity() ); - $this->assertEquals( 10, $ticket_li->unit_price() ); - $this->assertEquals( 50, $ticket_li->total() ); - //and verify the percent line item's total has changed, but not its percent - $this->assertEquals( -25, $percent_discount_li->unit_price() ); - $this->assertEquals( -25, $percent_discount_li->total() ); - } - - -/** - * - */ -function test_process__2_events_some_taxed_with_discounts() { - $grand_total = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_total, - 'LIN_name' => 'Total', - )); - $pretax_total = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_sub_total, - 'LIN_code' => 'pretax', - 'LIN_name' => 'pretax', - 'LIN_order' => 1, - )); - $grand_total->add_child_line_item( $pretax_total ); - - $tax_total = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_tax_sub_total, - 'LIN_code' => 'tax-total', - 'LIN_name' => 'tax-total', - 'LIN_order' => 1000 - )); - $grand_total->add_child_line_item( $tax_total ); - - $a_tax = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_tax, - 'LIN_code' => 'tax', - 'LIN_name' => 'tax', - 'LIN_percent' => 10, - 'LIN_order' => 1000 - )); - $tax_total->add_child_line_item( $a_tax ); - - $event_A_subtotal = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_sub_total, - 'LIN_code' => 'eventA', - 'LIN_name' => 'eventA', - 'LIN_order' => 1, - ) ); - $pretax_total->add_child_line_item( $event_A_subtotal ); - - $event_B_subtotal = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_sub_total, - 'LIN_code' => 'eventB', - 'LIN_name' => 'eventB', - 'LIN_order' => 2, - ) ); - $pretax_total->add_child_line_item( $event_B_subtotal ); - $ticket_quantities = array( - 1 => array( - 'included' => 4, - 'not' => 6 - ), - 2 => array( - 'included' => 0, - 'not' => 2, - ), - 3 => array( - 'included' => 1, - 'not' => 0 - ) - ); - $ticket_1_li = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_code' => 'ticket1', - 'LIN_name' => 'ticket1', - 'OBJ_ID' => 1, - 'OBJ_type' => 'Ticket', - 'LIN_unit_price' => 10, - 'LIN_quantity' => $ticket_quantities[1]['included'] + $ticket_quantities[1]['not'], - 'LIN_total' => 100, - 'LIN_is_taxable' => false, - 'LIN_order' => 1, - )); - $event_A_subtotal->add_child_line_item( $ticket_1_li ); - - $ticket_2_li = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_code' => 'ticket2', - 'LIN_name' => 'ticket2', - 'OBJ_ID' => 2, - 'OBJ_type' => 'Ticket', - 'LIN_unit_price' => 50, - 'LIN_quantity' => $ticket_quantities[2]['included'] + $ticket_quantities[2]['not'], - 'LIN_total' => 50, - 'LIN_is_taxable' => true, - 'LIN_order' => 2, - )); - $event_A_subtotal->add_child_line_item( $ticket_2_li ); - - $percent_discount_li = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_code' => 'discount-percent', - 'LIN_name' => 'discount-percent', - 'LIN_unit_price' => 0, - 'LIN_percent' => -25, - 'LIN_total' => -50, - 'LIN_quantity' => 1, - 'LIN_order' => 3, - )); - $event_A_subtotal->add_child_line_item( $percent_discount_li ); - - $flat_discount_li = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_code' => 'discount-flat', - 'LIN_name' => 'discount-flat', - 'LIN_unit_price' => 0, - 'LIN_percent' => 0, - 'LIN_unit_price' => -10, - 'LIN_total' => -10, - 'LIN_quantity' => 1, - 'LIN_order' => 4, - )); - $event_A_subtotal->add_child_line_item( $flat_discount_li ); - - //and add something to event B - $ticket_3_li = EE_Line_Item::new_instance( array( - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_code' => 'ticket3', - 'LIN_name' => 'ticket3', - 'OBJ_ID' => 3, - 'OBJ_type' => 'Ticket', - 'LIN_unit_price' => 35, - 'LIN_quantity' => $ticket_quantities[3]['included'] + $ticket_quantities[3]['not'], - 'LIN_total' => 35, - 'LIN_is_taxable' => true, - )); - $event_B_subtotal->add_child_line_item( $ticket_3_li ); - - //also need to make registrations - $regs_to_include = $this->_create_regs( $ticket_quantities, $grand_total ); - - //ok now let's use the filter - $filter = new EE_Specific_Registrations_Line_Item_Filter( - $regs_to_include ); - $filtered_total = $filter->process( $grand_total ); -// echo "AFTER tree:"; -// EEH_Line_Item::visualize( $grand_total ); - //the filter doesn't recalculate totals, and it edits the inputted tree; - //hat's ok, the processor does both of those. But we need to manually do it here - $this->assertEquals( $grand_total, $filtered_total ); - $grand_total->recalculate_total_including_taxes(); - //check ticket 1 - $this->assertEquals( 4, $ticket_1_li->quantity() ); - $this->assertEquals( 10, $ticket_1_li->unit_price() ); - $this->assertEquals( 40, $ticket_1_li->total() ); - //check ticket 2 - $this->assertEquals( 0, $ticket_2_li->quantity() ); - $this->assertEquals( 50, $ticket_2_li->unit_price() ); - $this->assertEquals( 0, $ticket_2_li->total() ); - //and verify the percent line item's total has changed, but not its percent - $this->assertEquals( -25, $percent_discount_li->percent() ); - $this->assertEquals( -10, $percent_discount_li->total() ); - //flat discount is tricky. we only show the PART of the flat discount - //that applied to the tickets shown. To determine that, we see what - //percent of the original discount was of the original total, and then multiply - //the new total by that percent. - //the original total = ticket1's-total + ticket2's-total + percent-discount - // = 100 + 100 - 50 = 150 - //flat discount's original percent of total = flat-discount / original total - // = -10 / 150 = 0.0666666 - //new total = ticket1's-filtered-total + ticket2's-filtered-total + percent-discount-for-filtered-total - // = 40 + 0 - 10 = 30 - //new flat total = flat discount's original percent of total x new total - // = 0.0666666 x 30 = 1.9999999 - $this->assertEquals( 1, $flat_discount_li->quantity() ); - $this->assertEquals( -2, $flat_discount_li->unit_price() ); - $this->assertEquals( -2, $flat_discount_li->total() ); - //other event's ticket purchase - $this->assertEquals( 1, $ticket_3_li->quantity() ); - $this->assertEquals( 35, $ticket_3_li->unit_price() ); - $this->assertEquals( 35, $ticket_3_li->total() ); - } - - /** - * Creates a bunch of registrations and returns an array of all the "approved" ones - * @param array $ticket_quantities top-level-keys are ticket IDs, - * next-level keys are either 'included' or 'not'. - * @param EE_Line_Item $grand_total - * @return a flat array of all the registrations that were for 'included' - */ - protected function _create_regs( $ticket_quantities, $grand_total ) { - $txn = $this->new_model_obj_with_dependencies( 'Transaction' ); - $regs_to_include = array(); - foreach( $ticket_quantities as $ticket_id => $approved_or_not_counts ) { - foreach( $approved_or_not_counts as $key => $count ) { - for( $i = 0; $i < $count; $i++ ) { - $r = $this->new_model_obj_with_dependencies( 'Registration', array( 'TXN_ID' => $txn->ID(), 'TKT_ID' => $ticket_id ) ); - if( $key == 'included' ) { - $regs_to_include[] = $r; - } - } - } - } - $grand_total->save_this_and_descendants_to_txn( $txn->ID() ); - return $regs_to_include; - } - -} - -// End of file EE_Specific_Registrations_Line_Item_Filter_Test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/messages/EE_Message_Repository_Test.php b/tests/testcases/core/libraries/messages/EE_Message_Repository_Test.php deleted file mode 100644 index fb892cb7726..00000000000 --- a/tests/testcases/core/libraries/messages/EE_Message_Repository_Test.php +++ /dev/null @@ -1,191 +0,0 @@ -factory->message->create( array( 'nosave' => 1 ) ); - $test_repo = new EE_Message_Repository(); - $this->assertInstanceOf( 'EE_Message_Repository', $test_repo ); - - $test_repo->add( $message ); - - //verify the message was added - $this->assertEquals( 1, $test_repo->count() ); - $test_repo->rewind(); - $this->assertInstanceOf( 'EE_Message', $test_repo->current() ); - return $test_repo; - } - - - - /** - * @depends test_add - * @param EE_Message_Repository $test_repo - */ - function test_remove( EE_Message_Repository $test_repo ) { - //get the object to remove. - $message = $test_repo->current(); - - //let's persist this object for persist tests - $message->save(); - $msgid = $message->ID(); - //verify in db - $this->assertInstanceOf( 'EE_Message', EEM_Message::instance()->get_one_by_ID( $msgid ) ); - - //remove from repo only and verify removed and verify still in db. - $test_repo->remove( $message ); - $this->assertEquals( 0, $test_repo->count() ); - $this->assertInstanceOf( 'EE_Message', EEM_Message::instance()->get_one_by_ID( $msgid ) ); - - //add back to repo and then try persist remove - $test_repo->add( $message ); - $test_repo->delete(); - $this->assertEmpty( EEM_Message::instance()->get_one_by_ID( $msgid ) ); - } - - - /** - * @return EE_Message_Repository - */ - function test_saveAll() { - //create a bunch of message objects and add to repo. - $test_repo = new EE_Message_Repository(); - $generation_data = array( 'MSG_generation_data' => array( - 'REG_ID' => 12 - ), - 'preview' => true - ); - $messages = array(); - for( $i=0;$i<5;$i++) { - $message = $this->factory->message->create( array( 'nosave' => 1 ) ); - //verify not saved - $this->assertEquals( 0, $message->ID() ); - $messages[] = $message; - $test_repo->add( $message, $generation_data ); - } - - $saved = $test_repo->saveAll(); - $this->assertEquals( 5, $saved['updated'] ); - return $test_repo; - } - - - - - /** - * @depends test_saveAll - * @param EE_Message_Repository $test_repo - * @return EE_Message_Repository - */ - function test_getMessageByToken( EE_Message_Repository $test_repo ) { - //pop a message out of the repo to test with - $test_repo->rewind(); - $message = $test_repo->current(); - $this->assertEquals( $message, $test_repo->getMessageByToken( $message->MSG_token() ) ); - return $test_repo; - } - - - /** - * @depends test_getMessageByToken - * @param EE_Message_Repository $test_repo - * @return EE_Message_Repository - */ - function test_get_generation_data( EE_Message_Repository $test_repo ) { - $test_repo->rewind(); - $actual_generation_data = $test_repo->get_generation_data(); - $this->assertTrue( isset( $actual_generation_data['REG_ID'] ) ); - $this->assertEquals( 12, $actual_generation_data['REG_ID'] ); - return $test_repo; - } - - - /** - * @depends test_get_generation_data - * @param EE_Message_Repository $test_repo - */ - function test_is_preview( EE_Message_Repository $test_repo ) { - $test_repo->rewind(); - $this->assertTrue( $test_repo->is_preview() ); - } - - - - - function test__maybe_persist_generation_data() { - $test_repo = new EE_Message_Repository(); - $message = $this->factory->message->create(); - $actual_generation_data = array( 'MSG_generation_data' => array( - 'REG_ID' => 14 - ) ); - $test_repo->add( $message, $actual_generation_data ); - $test_repo->saveAll(); - $test_repo->rewind(); - $message = $test_repo->current(); - $actual_generation_data = $message->get_generation_data(); - $this->assertTrue( isset( $actual_generation_data['REG_ID'] ) ); - $this->assertEquals( 14, $actual_generation_data['REG_ID'] ); - } - - - - - - function test_count_by_priority_and_status() { - $test_repo = new EE_Message_Repository(); - //let's setup some message objects with a variety of priorities and statuses. - //high priority, idle (invoice is high priority hence it is used as a message type). - $messages_a = $this->factory->message->create_many( 3, array( 'STS_ID' => EEM_Message::status_idle, 'MSG_message_type' => 'invoice' ) ); - //medium priority, sent (the default message type has a priority of medium) - $messages_b = $this->factory->message->create_many( 2, array( 'STS_ID' => EEM_Message::status_sent ) ); - //medium priority, resend (the default message type has a priority of medium) - $messages_c = $this->factory->message->create_many( 2, array( 'STS_ID' => EEM_Message::status_resend ) ); - //low priority, resend - $messages_d = $this->factory->message->create_many( 4, array( 'STS_ID' => EEM_Message::status_resend ) ); - //need to manually force this priority because there are no message types currently that set low priority - foreach ( $messages_d as $message ) { - $message->set_priority( EEM_Message::priority_low ); - } - - $all_messages = array_merge( $messages_a, $messages_b, $messages_c, $messages_d ); - - //add to queue - foreach( $all_messages as $message ) { - $test_repo->add( $message ); - } - - //test high priority results - $this->assertEquals( 3, $test_repo->count_by_priority_and_status( EEM_Message::priority_high ) ); - $this->assertEquals( 0, $test_repo->count_by_priority_and_status( EEM_Message::priority_high, EEM_Message::status_incomplete ) ); - $this->assertEquals( 3, $test_repo->count_by_priority_and_status( EEM_Message::priority_high, array( EEM_Message::status_incomplete, EEM_Message::status_idle ) ) ); - - //test medium priority results - $this->assertEquals( 4, $test_repo->count_by_priority_and_status( EEM_Message::priority_medium ) ); - $this->assertEquals( 2, $test_repo->count_by_priority_and_status( EEM_Message::priority_medium, EEM_Message::status_resend ) ); - $this->assertEquals( 4, $test_repo->count_by_priority_and_status( EEM_Message::priority_medium, array( EEM_Message::status_incomplete, EEM_Message::status_resend, EEM_Message::status_sent ) ) ); - - //test low priority results - $this->assertEquals( 4, $test_repo->count_by_priority_and_status( EEM_Message::priority_low, EEM_Message::status_resend ) ); - } - - -} //end EE_Message_Repository_Test \ No newline at end of file diff --git a/tests/testcases/core/libraries/messages/EE_Message_Resource_Manager_Test.php b/tests/testcases/core/libraries/messages/EE_Message_Resource_Manager_Test.php deleted file mode 100644 index b090161549c..00000000000 --- a/tests/testcases/core/libraries/messages/EE_Message_Resource_Manager_Test.php +++ /dev/null @@ -1,423 +0,0 @@ -_message_resource_manager = EE_Registry::instance()->load_lib( 'Message_Resource_Manager' ); - $this->assertInstanceOf( 'EE_Message_Resource_Manager', $this->_message_resource_manager ); - //make sure message type and messenger that might be persisting inactive between tests are fixed. - $this->_message_resource_manager->ensure_message_type_is_active( 'invoice', 'html' ); - } - - - public function tearDown() { - $this->_message_resource_manager = null; - parent::tearDown(); - } - - - public function test_messenger_collection() { - $messenger_collection = $this->_message_resource_manager->messenger_collection(); - $this->assertInstanceOf( 'EE_Messenger_Collection', $messenger_collection ); - } - - - - public function test_active_messengers() { - $active_messengers = $this->_message_resource_manager->active_messengers(); - - //email messenger should be active by default so using that for the test. - $this->assertTrue( isset( $active_messengers['email'] ) ); - $this->assertInstanceOf( 'EE_Email_messenger', $active_messengers['email'] ); - } - - - - public function test_get_messenger() { - $messenger = $this->_message_resource_manager->get_messenger( 'email' ); - $this->assertInstanceOf( 'EE_Email_messenger', $messenger ); - } - - - - public function test_get_active_messenger() { - $messenger_that_is_active = $this->_message_resource_manager->get_active_messenger( 'email' ); - $inactive_messenger = $this->_message_resource_manager->get_active_messenger( 'dummy' ); - $this->assertInstanceOf( 'EE_Email_messenger', $messenger_that_is_active ); - $this->assertNotInstanceOf( 'EE_Email_messenger', $inactive_messenger ); - } - - - - public function test_installed_messengers() { - $installed_messengers = $this->_message_resource_manager->installed_messengers(); - $this->assertTrue( isset( $installed_messengers['email'] ) ); - $this->assertInstanceOf( 'EE_Email_messenger', $installed_messengers['email'] ); - } - - - - - public function test_valid_messenger() { - //test valid first. - $messenger = $this->_message_resource_manager->valid_messenger( 'email' ); - $this->assertInstanceOf( 'EE_Email_messenger', $messenger ); - - //test invalid - $this->setExpectedException( 'EE_Error' ); - $this->_message_resource_manager->valid_messenger( 'dummy' ); - } - - - - - public function test_message_type_collection() { - $message_type_collection = $this->_message_resource_manager->message_type_collection(); - $this->assertInstanceOf( 'EE_Message_Type_Collection', $message_type_collection ); - } - - - - - public function test_active_message_types() { - $active_message_types = $this->_message_resource_manager->active_message_types(); - $this->assertTrue( isset( $active_message_types['email']['settings']['email-message_types']['registration'] ) ); - } - - - - public function test_get_message_type() { - $message_type = $this->_message_resource_manager->get_message_type( 'invoice' ); - $this->assertInstanceOf( 'EE_Invoice_message_type', $message_type ); - } - - - - public function test_get_active_message_type_for_messenger() { - $active_message_type = $this->_message_resource_manager->get_active_message_type_for_messenger( 'email', 'registration' ); - $invalid_message_type = $this->_message_resource_manager->get_active_message_type_for_messenger( 'email', 'invoice' ); - $this->assertInstanceOf( 'EE_Registration_message_type', $active_message_type ); - $this->assertNull( $invalid_message_type ); - } - - - - - public function test_is_message_type_active_for_messenger() { - $active_message_type = $this->_message_resource_manager->is_message_type_active_for_messenger( 'email', 'registration' ); - $invalid_message_type = $this->_message_resource_manager->is_message_type_active_for_messenger( 'email', 'invoice' ); - $this->assertTrue( $active_message_type ); - $this->assertFalse( $invalid_message_type ); - } - - - - public function test_is_messenger_active() { - $this->assertTrue( $this->_message_resource_manager->is_messenger_active( 'email' ) ); - $this->assertFalse( $this->_message_resource_manager->is_messenger_active( 'dummy' ) ); - } - - - - public function test_get_message_type_settings_for_messenger() { - $message_type_settings = $this->_message_resource_manager->get_message_type_settings_for_messenger( 'email', 'registration' ); - //currently this will always be an empty array because no message type has settings, so this should always return an array. - $this->assertTrue( is_array( $message_type_settings ) ); - } - - - - - public function test_messenger_has_active_message_types() { - $this->assertTrue( $this->_message_resource_manager->messenger_has_active_message_types( 'email' ) ); - $this->assertFalse( $this->_message_resource_manager->messenger_has_active_message_types( 'pdf' ) ); - } - - - - - public function test_get_active_message_types_for_messenger() { - $active_message_types = $this->_message_resource_manager->get_active_message_types_for_messenger( 'email' ); - $this->assertTrue( isset( $active_message_types['registration'] ) ); - $this->assertInstanceOf( 'EE_Registration_message_type', $active_message_types['registration'] ); - } - - - - public function test_list_of_active_message_types() { - $active_message_type_list = $this->_message_resource_manager->list_of_active_message_types(); - $this->assertArrayContains( 'invoice', $active_message_type_list ); - } - - - - public function test_get_active_message_type_objects() { - $active_message_type_objects = $this->_message_resource_manager->get_active_message_type_objects(); - $this->assertTrue( isset( $active_message_type_objects['invoice'] ) ); - $this->assertInstanceOf( 'EE_Invoice_message_type', $active_message_type_objects['invoice'] ); - } - - - - - public function test_installed_message_types() { - $installed_message_types = $this->_message_resource_manager->installed_message_types(); - $this->assertTrue( isset( $installed_message_types['invoice'] ) ); - $this->assertInstanceOf( 'EE_Invoice_message_type', $installed_message_types['invoice'] ); - } - - - - public function test_valid_message_type() { - //test valid - $this->assertInstanceOf( 'EE_Registration_message_type', $this->_message_resource_manager->valid_message_type( 'registration' ) ); - - //test invalid throwing exception - $this->setExpectedException( 'EE_Error' ); - $this->_message_resource_manager->valid_message_type( 'dummy' ); - } - - - - public function test_valid_message_type_for_messenger() { - //test valid - $html_messenger = $this->_message_resource_manager->get_messenger( 'html' ); - $this->assertTrue( $this->_message_resource_manager->valid_message_type_for_messenger( $html_messenger, 'invoice' ) ); - - //test invalid throwing exception - $email_messenger = $this->_message_resource_manager->get_messenger( 'email' ); - $this->setExpectedException( 'EE_Error' ); - $this->_message_resource_manager->valid_message_type_for_messenger( $email_messenger, 'invoice' ); - } - - - - public function test_get_active_messengers_option() { - $active_messengers_option = $this->_message_resource_manager->get_active_messengers_option( true ); - - //this should be the same as what gets returned for the active_message_types property. - $this->assertEquals( - $active_messengers_option, - $this->_message_resource_manager->active_message_types() - ); - } - - - - public function test_update_active_messengers_option() { - $this->markTestIncomplete( - 'This test is incomplete because for now it is tested indirectly via other tests in this class.' - ); - } - - - - - public function test_get_has_activated_messengers_option() { - $has_activated = $this->_message_resource_manager->get_has_activated_messengers_option(true); - $this->assertTrue( isset( $has_activated['email'] ) ); - $this->assertArrayContains( 'registration', $has_activated['email'] ); - } - - - - public function test_update_has_activated_messengers_option() { - $has_activated = $this->_message_resource_manager->get_has_activated_messengers_option(); - $has_activated['email'][] = 'test_message_type'; - $this->assertTrue( $this->_message_resource_manager->update_has_activated_messengers_option( $has_activated ) ); - - $has_activated_persistent_check = $this->_message_resource_manager->get_has_activated_messengers_option( true ); - $this->assertTrue( isset( $has_activated_persistent_check['email'] ) ); - $this->assertArrayContains( 'test_message_type', $has_activated_persistent_check['email'] ); - } - - - - public function test_reset_active_messengers_and_message_types() { - $this->markTestIncomplete( - 'Not sure how to usefully perform this test just yet so this is just a marker.' - ); - } - - - /** - * tests to make sure forcing a messenger to be active works. - * - * Note this also indirectly tests the following methods in the MRM: - * - active_messengers - * - deactivate_messenger - * - update_active_messengers_option - * - is_messenger_active - * - * @since 4.9.0 - */ - public function test_ensure_messenger_is_active() { - //make sure html messenger is setup (should be by default) - $current_active_messengers = $this->_message_resource_manager->active_messengers(); - $this->assertTrue( isset( $current_active_messengers['html'] ), sprintf( 'The messenger %s should be active on fresh install, but it is not.', 'html' ) ); - - //let's deactivate the html messenger from active messengers and update the db - $this->_message_resource_manager->deactivate_messenger( 'html' ); - $this->_message_resource_manager->update_active_messengers_option(); - //verify active_messengers prop in MRM doesn't have html in it - $current_active_messengers = $this->_message_resource_manager->active_messengers(); - $this->assertFalse( isset( $current_active_messengers['html'] ) ); - - //verify its not active - $this->assertFalse( $this->_message_resource_manager->is_messenger_active( 'html' ) ); - - //now let's FORCE reactivation. - $response = $this->_message_resource_manager->ensure_messenger_is_active( 'html' ); - $this->assertTrue( $response ); - - //verify html messenger IS actually active now. - $current_active_messengers = $this->_message_resource_manager->active_messengers(); - $this->assertTrue( isset( $current_active_messengers['html'] ), 'The html messenger should have been forced to be active again but it is not.' ); - } - - - - public function test_ensure_messengers_are_active() { - $this->markTestIncomplete( - 'For now, this test is mostly covered by test_ensure_messenger_is_active.' - ); - } - - - /** - * This test also indirectly tests the following methods: - * - get_active_message_type_objects - * - deactivate_message_type - * - update_active_messengers_option - * - * - * @since 4.9.0 - */ - public function test_ensure_message_type_is_active() { - //get all active message types. - $current_active_message_types = $this->_message_resource_manager->get_active_message_type_objects(); - $this->assertTrue( isset( $current_active_message_types['invoice'] ) ); - - //deactivate the invoice message type and persist - $this->_message_resource_manager->deactivate_message_type( 'invoice' ); - $this->_message_resource_manager->update_active_messengers_option(); - - //verify message type isn't active anywhere internally on the class. - $list_of_active_message_types = $this->_message_resource_manager->list_of_active_message_types(); - $this->assertArrayDoesNotContain( 'invoice', $list_of_active_message_types ); - - //now let's force reactivation (for html messenger) - $response = $this->_message_resource_manager->ensure_message_type_is_active( 'invoice', 'html' ); - $this->assertTrue( $response ); - - //very invoice message type IS actually active now. - $current_active_message_types = $this->_message_resource_manager->get_active_message_type_objects(); - $this->assertTrue( isset( $current_active_message_types['invoice'] ) ); - } - - - - public function test_ensure_message_types_are_active() { - $this->markTestIncomplete( - 'This test is mostly covered via test_ensure_message_type_is_active' - ); - } - - - - public function test_activate_messenger() { - $this->markTestIncomplete( - 'This method is indirectly covered in the test_ensure_messenger_is_active' - ); - } - - - - public function test_add_settings_for_message_type() { - $this->markTestIncomplete( - 'There are currently no message types that have settings so not tested yet.' - ); - } - - - - public function test_add_settings_for_messenger() { - $this->markTestIncomplete( - 'There are currently no messengers that have settings so not tested yet.' - ); - } - - - - public function test_deactivate_messenger() { - $this->assertTrue( $this->_message_resource_manager->is_messenger_active( 'html' ) ); - $this->_message_resource_manager->deactivate_messenger( 'html' ); - $this->assertFalse( $this->_message_resource_manager->is_messenger_active( 'html' ) ); - } - - - - public function test_deactivate_message_type() { - $this->assertTrue( $this->_message_resource_manager->is_message_type_active_for_messenger( 'html', 'invoice' ) ); - $this->_message_resource_manager->deactivate_message_type( 'invoice' ); - $this->assertFalse( $this->_message_resource_manager->is_message_type_active_for_messenger( 'html', 'invoice' ) ); - } - - - - public function test_deactivate_message_type_for_messenger() { - $this->assertTrue( $this->_message_resource_manager->is_message_type_active_for_messenger( 'html', 'invoice' ) ); - $this->_message_resource_manager->deactivate_message_type_for_messenger( 'invoice', 'html' ); - $this->assertFalse( $this->_message_resource_manager->is_message_type_active_for_messenger( 'html', 'invoice' ) ); - } - - - - - public function test_is_generating_messenger_and_active() { - //get email messenger - $email_messenger = $this->_message_resource_manager->get_messenger( 'email' ); - //get registration message type - $registration_message_type = $this->_message_resource_manager->get_message_type( 'registration' ); - //get invoice message type - $invoice_message_type = $this->_message_resource_manager->get_message_type( 'invoice' ); - - $this->assertTrue( $this->_message_resource_manager->is_generating_messenger_and_active( $email_messenger, $registration_message_type ) ); - $this->assertFalse( $this->_message_resource_manager->is_generating_messenger_and_active( $email_messenger, $invoice_message_type ) ); - } - - - - function test_get_all_contexts() { - $contexts = $this->_message_resource_manager->get_all_contexts(); - - //expected four contexts. - $this->assertEquals( 4, count( $contexts ) ); - - //expecting an array with 'admin', 'attendee', and 'primary_attendee', and 'purchaser' in it. - $this->arrayHasKey( 'admin', $contexts ); - $this->arrayHasKey( 'attendee', $contexts ); - $this->arrayHasKey( 'primary_attendee', $contexts ); - $this->arrayHasKey( 'purchaser', $contexts ); - } - - -} //end EE_messages_Test class -// Location: tests/testcases/core/libraries/messages/EE_Message_Resource_Manager_Test.php diff --git a/tests/testcases/core/libraries/messages/EE_Message_Template_Group_Collection_Test.php b/tests/testcases/core/libraries/messages/EE_Message_Template_Group_Collection_Test.php deleted file mode 100644 index a092b20bdb8..00000000000 --- a/tests/testcases/core/libraries/messages/EE_Message_Template_Group_Collection_Test.php +++ /dev/null @@ -1,75 +0,0 @@ -get_one( - array( - array( - 'MTP_messenger' => 'email', - 'MTP_message_type' => 'registration', - ), - ) - ); - $this->assertInstanceOf('EE_Message_Template_Group', $message_template_group); - - $test_repo = new EE_Message_Template_Group_Collection(); - - $this->assertInstanceOf('EE_Message_Template_Group_Collection', $test_repo); - - //add mtpg to repo with dummy evtID used for later tests. - $test_repo->add($message_template_group, 22); - - //verify the message was added - $this->assertEquals(1, $test_repo->count()); - $test_repo->rewind(); - $this->assertInstanceOf('EE_Message_Template_Group', $test_repo->current()); - return $test_repo; - } - - - /** - * @depends test_add - * @param EE_Message_Template_Group_Collection $test_repo - * @return EE_Message_Template_Group_Collection - */ - public function test_get_by_ID(EE_Message_Template_Group_Collection $test_repo) - { - //get the object to remove. - $mtpg = $test_repo->current(); - - //verify that retrieving the object by ID works - $this->assertEquals($mtpg, $test_repo->get_by_ID($mtpg->ID())); - - return $test_repo; - } - - - /** - * @depends test_get_by_ID - * @param EE_Message_Template_Group_Collection $test_repo - */ - public function test_get_by_key(EE_Message_Template_Group_Collection $test_repo) - { - $key_should_exist = $test_repo->getKey('email', 'registration', array(22)); - $key_should_not_exist = $test_repo->getKey('email', 'registration', array(15)); - $this->assertNotInstanceOf('EE_Message_Template_Group', $test_repo->get_by_key($key_should_not_exist)); - $this->assertInstanceOf('EE_Message_Template_Group', $test_repo->get_by_key($key_should_exist)); - } - - -} diff --git a/tests/testcases/core/libraries/messages/EE_Message_To_Generate_Test.php b/tests/testcases/core/libraries/messages/EE_Message_To_Generate_Test.php deleted file mode 100644 index 5836a5c6a07..00000000000 --- a/tests/testcases/core/libraries/messages/EE_Message_To_Generate_Test.php +++ /dev/null @@ -1,56 +0,0 @@ -assertInstanceOf( 'EE_Registration_message_type', $mtg->message_type() ); - $this->assertInstanceOf( 'EE_Email_messenger', $mtg->messenger() ); - $this->assertEquals( array(), $mtg->data() ); - $this->assertEquals( 'admin', $mtg->context() ); - $this->assertTrue( $mtg->preview() ); - return $mtg; - } - - - - - /** - * @depends test_construct - * @param EE_Message_To_Generate $mtg - */ - function test_get_EE_Message( EE_Message_To_Generate $mtg ) { - /** @type EE_Message $msg */ - $msg = $mtg->get_EE_Message(); - $this->assertInstanceOf( 'EE_Message', $msg ); - $this->assertEquals( 'email', $msg->messenger() ); - $this->assertEquals( 'registration', $msg->message_type() ); - $this->assertEquals( 'admin', $msg->context() ); - $this->assertEquals( EEM_Message::status_incomplete, $msg->STS_ID() ); - - //this is also implicitly testing the _get_priority_for_message_type method because Registration message type - //and email messenger should result in EEM_Message::priority_medium. - $this->assertEquals( EEM_Message::priority_medium, $msg->priority() ); - } - -} //end EE_Message_To_Generate_Test class \ No newline at end of file diff --git a/tests/testcases/core/libraries/messages/EE_Messages_Data_Handler_Collection_Test.php b/tests/testcases/core/libraries/messages/EE_Messages_Data_Handler_Collection_Test.php deleted file mode 100644 index 94eb8d86c21..00000000000 --- a/tests/testcases/core/libraries/messages/EE_Messages_Data_Handler_Collection_Test.php +++ /dev/null @@ -1,84 +0,0 @@ -loadTestScenarios(); - //need to add some events for previewer to use... we'll just use the event scenarios - $this->scenarios->get_scenarios_by_type( 'event' ); - - $data_handler = new EE_Messages_Preview_incoming_data(); - $test_repo = new EE_Messages_Data_Handler_Collection(); - - $this->assertInstanceOf( 'EE_Messages_Data_Handler_Collection', $test_repo ); - - $test_repo->add( $data_handler, array() ); - - //verify the message was added - $this->assertEquals( 1, $test_repo->count() ); - $test_repo->rewind(); - $this->assertInstanceOf( 'EE_Messages_Preview_incoming_data', $test_repo->current() ); - return $test_repo; - } - - - - /** - * @depends test_add - * -*@param EE_Messages_Data_Handler_Collection $test_repo - * -*@return EE_Messages_Data_Handler_Collection - */ - function test_remove( EE_Messages_Data_Handler_Collection $test_repo ) { - //get the object to remove. - $data_handler = $test_repo->current(); - - //verify in db - $this->assertInstanceOf( 'EE_Transaction', $data_handler->txn ); - - //remove and verify removed. - $test_repo->remove( $data_handler ); - $this->assertEquals( 0, $test_repo->count() ); - - //add back to repo for next test. - $test_repo->add( $data_handler, array() ); - return $test_repo; - } - - - - - /** - * @depends test_remove - * -*@param EE_Messages_Data_Handler_Collection $test_repo - */ - function test_get_by_key( EE_Messages_Data_Handler_Collection $test_repo ) { - $key_should_exist = $test_repo->get_key( 'EE_Messages_Preview_incoming_data', array() ); - $key_should_not_exist = $test_repo->get_key( 'Some_Bogus_Class', array() ); - $this->assertNotInstanceOf( 'EE_Messages_Preview_incoming_data', $test_repo->get_by_key( $key_should_not_exist ) ); - $this->assertInstanceOf( 'EE_Messages_Preview_incoming_data', $test_repo->get_by_key( $key_should_exist ) ); - } - - -} //end EE_Messages_Data_Handler_Collection_Test diff --git a/tests/testcases/core/libraries/messages/EE_Messages_Generator_Test.php b/tests/testcases/core/libraries/messages/EE_Messages_Generator_Test.php deleted file mode 100644 index ee76a26a5a4..00000000000 --- a/tests/testcases/core/libraries/messages/EE_Messages_Generator_Test.php +++ /dev/null @@ -1,77 +0,0 @@ -assertInstanceOf('EE_Messages_Generator', $generator); - return $generator; - } - - - /** - * This test verifies that the generation queue only generates messages with the status of incomplete. - * - * @see https://events.codebasehq.com/projects/event-espresso/tickets/9787 - * @group 9787 - */ - function test_generate_only_incomplete_messages() - { - $message_processor = EE_Registry::instance()->load_lib('Messages_Processor'); - //make sure there is nothing in the queue - $this->assertFalse($message_processor->batch_generate_from_queue(array(), true)); - - //get an event (with relations via creating the ticket) in the db for the message preview - $this->factory->ticket_chained->create(); - - //get some ready to generate - $this->factory->message->create_many(5); - - /** @var EE_Messages_Queue $new_queue */ - $new_queue = $message_processor->batch_generate_from_queue(); - $this->assertInstanceOf('EE_Messages_Queue', $new_queue); - - //now let's grab the generated messages from this queue and send it in to the batch_generate_from_queue - $messages = array(); - $new_queue->get_message_repository()->rewind(); - while ($new_queue->get_message_repository()->valid()) { - $messages[] = $new_queue->get_message_repository()->current(); - $new_queue->get_message_repository()->next(); - } - - /** @var EE_Messages_Queue $newer_queue */ - $newer_queue = $message_processor->batch_generate_from_queue($messages); - $this->assertInstanceOf('EE_Messages_Queue', $newer_queue); - //there should be NO fails in the queue. - $this->assertEquals(0, $newer_queue->count_STS_in_queue(array(EEM_Message::status_failed))); - } - - -} //end EE_Messages_Generator_Test class -// Location: tests/testcases/core/libraries/messages/EE_Messages_Generator_Test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/messages/EE_Messages_Processor_Test.php b/tests/testcases/core/libraries/messages/EE_Messages_Processor_Test.php deleted file mode 100644 index 5303dbf37b2..00000000000 --- a/tests/testcases/core/libraries/messages/EE_Messages_Processor_Test.php +++ /dev/null @@ -1,388 +0,0 @@ -loadTestScenarios(); - //setup events etc for previewer to use - $this->scenarios->get_scenarios_by_type('event'); - } - - - /** - * This returns an array of components used in testing. - * An array with the following: - * - EE_messages object - * - EE_Messages_Processor object (clean) - * - EE_Message_To_Generate object. - * - * @return array - */ - protected function _test_components() - { - return array( - 'proc' => EE_Registry::instance()->load_lib('Messages_Processor'), - 'mtg' => new EE_Message_To_Generate( - 'email', - 'registration', - array(), - 'admin', - true - ), - ); - } - - - /** - * Tests constructing the processor object and retrieving a EE_Messages_Queue after construct. - * Passes along EE_Messages_Processor for other test. - * - * @return EE_Messages_Processor - */ - function test_construct_and_get_queue() - { - $message_proc = null; - try { - /** @type EE_Messages_Processor $message_proc */ - $message_proc = EE_Registry::instance()->load_lib('Messages_Processor'); - } catch (Exception $e) { - $this->fail(sprintf('Loading EE_Messages_Processor failed: %s', $e->getMessage())); - } - - //verify things loaded okay via the queue. - $this->assertInstanceOf('EE_Messages_Queue', $message_proc->get_queue()); - return $message_proc; - } - - - /** - * @depends test_construct_and_get_queue - * @param EE_Messages_Processor $message_proc - */ - function test_batch_generate_from_queue(EE_Messages_Processor $message_proc) - { - //first we know there is nothing in the db, so let's verify that returns false. (this also verifies the clear param) - $this->assertFalse($message_proc->batch_generate_from_queue(array(), true)); - - //now let's test getting some batch ready to generate. - $this->factory->message->create_many(5); - - $new_queue = $message_proc->batch_generate_from_queue(); - - $this->assertInstanceOf('EE_Messages_Queue', $new_queue); - //this will be 5 because there the messages the factory create set the preview data handler for the data used. - $this->assertEquals(5, $new_queue->get_message_repository()->count()); - } - - - /** - * Same as above test except only doing batch generation on specific messages - * - * @depends test_construct_and_get_queue - * @param EE_Messages_Processor $message_proc - */ - function test_batch_generate_from_queue_with_messages(EE_Messages_Processor $message_proc) - { - //make sure clear works - $this->assertFalse($message_proc->batch_generate_from_queue(array(), true)); - - //setup some messages for generation. - $messages_to_test = $this->factory->message->create_many(5); - - //now let's create 3 more that will NOT be used. - $this->factory->message->create_many(3); - - $new_queue = $message_proc->batch_generate_from_queue($messages_to_test); - - $this->assertInstanceOf('EE_Messages_Queue', $new_queue); - - //verify 5 got generated - $this->assertEquals(5, $new_queue->get_message_repository()->count()); - - //verify the original MIC Messages do not exist in the db anymore. - $messages_no_exist = EEM_Message::instance()->count(array( - array( - 'MSG_ID' => array('IN', array_keys($messages_to_test)), - ), - )); - - $this->assertEquals(0, $messages_no_exist); - } - - - /** - * @depends test_construct_and_get_queue - * @param EE_Messages_Processor $message_proc - */ - function test_batch_send_from_queue(EE_Messages_Processor $message_proc) - { - - //create messages ready to send. - $this->factory->message->create_many(5, array('STS_ID' => EEM_Message::status_idle)); - - $sent_queue = $message_proc->batch_send_from_queue(array(), true); - - $this->assertInstanceOf('EE_Messages_Queue', $sent_queue); - $this->assertEquals(5, $sent_queue->get_message_repository()->count()); - - //verify no errors - $this->assertEquals(0, - $sent_queue->count_STS_in_queue(EEM_Message::instance()->stati_indicating_failed_sending())); - - $this->assertEquals(5, $sent_queue->count_STS_in_queue(EEM_Message::status_sent)); - } - - - /** - * Same as previous test except tests with sending in messages. - * - * @depends test_construct_and_get_queue - * @param EE_Messages_Processor $messages_proc - */ - function test_batch_send_from_queue_with_messages(EE_Messages_Processor $messages_proc) - { - //create messages we're going to use for sending - $messages_to_send = $this->factory->message->create_many(5, array('STS_ID' => EEM_Message::status_idle)); - - //create messages that are not ready for sending as a foil. - $this->factory->message->create_many(3); - - $sent_queue = $messages_proc->batch_send_from_queue($messages_to_send, true); - - $this->assertInstanceOf('EE_Messages_Queue', $sent_queue); - $this->assertEquals(5, $sent_queue->get_message_repository()->count()); - - //verify no errors - $this->assertEquals(0, - $sent_queue->count_STS_in_queue(EEM_Message::instance()->stati_indicating_failed_sending())); - $this->assertEquals(5, $sent_queue->count_STS_in_queue(EEM_Message::status_sent)); - } - - - /** - * This simulates the behaviour of EE_Messages_Processor::init_queue_and_generator for resetting the - * Messages_Generator on the processor. - */ - function test__init_queue_and_generator() - { - //load processor - $message_proc = EE_Registry::instance()->load_lib('Messages_Processor'); - - //grab generation queue. - $orig_generator_queue = $message_proc->get_queue(); - - //load generator via EE_Registry::factory() (which simulates what happens when executing EE_Messages_Processor::_init_queue_and_generator - $generator = EE_Registry::factory('EE_Messages_Generator'); - $new_generator_queue = $generator->generation_queue(); - - //these two queues should NOT be the same objects. - $this->assertNotEquals(spl_object_hash($orig_generator_queue), spl_object_hash($new_generator_queue)); - } - - - /** - * This implicitly tests the following methods as well: - * - queue_for_generation - * - queue_for_generation_loop - */ - function test_generate_and_return() - { - $test_components = $this->_test_components(); - /** @type EE_Messages_Processor $proc */ - $proc = $test_components['proc']; - $mtg = $test_components['mtg']; - - $generated_queue = $proc->generate_and_return($mtg); - - $this->assertInstanceOf('EE_Messages_Queue', $generated_queue); - - /** - * Expect 1 generated messages from the one MTG because there is a specific context provided (admin) that - * should only result in one message. - */ - $this->assertEquals(1, $generated_queue->count_STS_in_queue(EEM_Message::status_idle)); - - //messages in queue should be saved - this is because the cc field for email messages is extra meta and when - //that's added it saves the object to get an ID for the extra meta relation. - $generated_queue->get_message_repository()->rewind(); - $msg = $generated_queue->get_message_repository()->current(); - $this->assertGreaterThan(0, $msg->ID()); - } - - - function test_batch_queue_for_generation_and_persist() - { - $this->_common_test_with_specific_expected_status('batch_queue_for_generation_and_persist', null, false, 0); - } - - - function test_batch_queue_for_generation_no_persist() - { - $this->_common_test_with_specific_expected_status('batch_queue_for_generation_no_persist', null, false, 0); - } - - - function test_generate_and_queue_for_sending() - { - $this->_common_test_with_specific_expected_status('generate_and_queue_for_sending', EEM_Message::status_idle, - false, 0); - //now there should be Messages in the database all queued up for sending. Let's check - $messages = EEM_Message::instance()->get_all(array( - array( - 'STS_ID' => EEM_Message::status_idle, - ), - )); - - //expecting only one message because the specific context was provided. - $this->assertEquals(1, count($messages)); - } - - - function test_generate_for_preview() - { - $test_components = $this->_test_components(); - /** @type EE_Messages_Processor $proc */ - $proc = $test_components['proc']; - /** @type EE_Message_To_Generate $mtg */ - $mtg = $test_components['mtg']; - - $this->assertTrue($mtg->preview()); - $generated_queue = null; - - try { - /** @type EE_Messages_Queue $generated_queue */ - $generated_queue = $proc->generate_for_preview($mtg); - } catch (Exception $e) { - $this->fail(sprintf('Something went wrong with the test: %s', $e->getMessage())); - } - - //if made it here then we should have some content to verify. We're not matching entire string, just key - //components of what should be generated for the email messenger and registration message type using - //default dummy preview data. - $this->assertInstanceOf('EE_Messages_Queue', $generated_queue); - $generated_queue->get_message_repository()->rewind(); - /** @type EE_Message $msg */ - $msg = $generated_queue->get_message_repository()->current(); - $this->assertInstanceOf('EE_Message', $msg); - $this->assertContains('Registration Notification', $msg->content()); - $this->assertContains('Luke Skywalker', $msg->content()); - $this->assertContains('Test Scenario EVT A', $msg->content()); - - //messages in queue should be saved - this is because the cc field for email messages is extra meta and when - //that's added it saves the object to get an ID for the extra meta relation. - $this->assertGreaterThan(0, $msg->ID()); - - //verify sent! - $this->assertEquals(EEM_Message::status_sent, $msg->STS_ID()); - } - - - function test_setup_messages_from_ids_and_send() - { - //setup processor to work with - /** @type EE_Messages_Processor $proc */ - $proc = EE_Registry::instance()->load_lib('Messages_Processor'); - - //setup up messages we'll use for sending that have the right status - $messages_with_right_status = $this->factory->message->create_many(5, - array('STS_ID' => EEM_Message::status_sent)); - //include some EEM_Message::status_retry messages in the "right_status" group - $i = 0; - foreach ($messages_with_right_status as $message) { - $message->set_STS_ID(EEM_Message::status_retry); - $i++; - if ($i === 2) { - break; - } - } - $messages_with_wrong_status = $this->factory->message->create_many(5); - - $messages_with_right_status = array_map( - function ($message) { - return $message instanceof EE_Message ? $message->ID() : 0; - }, - $messages_with_right_status - ); - $messages_with_wrong_status = array_map( - function ($message) { - return $message instanceof EE_Message ? $message->ID() : 0; - }, - $messages_with_wrong_status - ); - - //first test correct messages - $proc->setup_messages_from_ids_and_send($messages_with_right_status); - $this->assertEquals(5, $proc->get_queue()->count_STS_in_queue(EEM_Message::status_resend)); - - //next test incorrect messages - //note calling this method SHOULD reset the internal queue. - $proc->setup_messages_from_ids_and_send($messages_with_wrong_status); - $this->assertEquals(0, $proc->get_queue()->count_STS_in_queue(EEM_Message::status_resend)); - } - - - /** - * Has common assertions for multiple EE_Messages_Processor method tests. - * - * @param string $method_to_test EE_Messages_Processor method being tested - * @param string $expected_status Expected EEM_Message::STS_ID() for the status test. - * @param bool $in_database Whether the test for persistence in db should be checked. - * @param int $expected_message_objects How many message objects are expected in the queue. - */ - protected function _common_test_with_specific_expected_status( - $method_to_test, - $expected_status, - $in_database = true, - $expected_message_objects = 1 - ) { - $test_components = $this->_test_components(); - /** @type EE_Messages_Processor $proc */ - $proc = $test_components['proc']; - /** @type EE_Message_To_Generate $mtg */ - $mtg = $test_components['mtg']; - - $queue = $proc->get_queue(); - - $proc->$method_to_test(array($mtg)); - - //queue should have $expected_message_objects EE_Message_object(s) and it/they should not be in the db and it/they - //should have status for the sent in status. - $this->assertEquals($expected_message_objects, $queue->get_message_repository()->count(), - sprintf('Failed test for the %s method', $method_to_test)); - if ($expected_message_objects > 0) { - $queue->get_message_repository()->rewind(); - $msg = $queue->get_message_repository()->current(); - $this->assertInstanceOf('EE_Message', $msg, sprintf('Failed test for the %s method', $method_to_test)); - if ($in_database) { - $this->assertInstanceOf('EE_Message', EEM_Message::instance()->get_one_by_ID($msg->ID()), - sprintf('Failed test for the %s method', $method_to_test)); - } else { - $this->assertEquals(0, $msg->ID(), sprintf('Failed test for the %s method', $method_to_test)); - } - $this->assertEquals($expected_status, $msg->STS_ID(), - sprintf('Failed test for the %s method', $method_to_test)); - } - } - - -} //end EE_Messages_Processor_Test -// Location: tests/testcases/core/libraries/messages/EE_Messages_Processor_Test.php diff --git a/tests/testcases/core/libraries/messages/EE_Messages_Queue_Test.php b/tests/testcases/core/libraries/messages/EE_Messages_Queue_Test.php deleted file mode 100644 index 2f8b53047ca..00000000000 --- a/tests/testcases/core/libraries/messages/EE_Messages_Queue_Test.php +++ /dev/null @@ -1,233 +0,0 @@ -load_lib( 'Messages_Queue' ); - } - - - - - - /** - * Testing adding to the queue - * @return EE_Messages_Queue - */ - function test_add_and_get_queue() { - $queue = $this->_get_queue(); - $message = $this->factory->message->create(array('nosave'=> 1)); - - - //add message - $added = $queue->add( $message ); - - //verify bool returns that it was added - $this->assertTrue( $added ); - - //get_message_repository to verify EE_Message is in it. - $test_queue = $queue->get_message_repository(); - $this->assertInstanceOf( 'EE_Message_Repository', $test_queue ); - - //verify the queue contains the message object - $test_queue->rewind(); - $this->assertTrue( $test_queue->valid() ); - $this->assertInstanceOf( 'EE_Message', $test_queue->current() ); - return $queue; - } - - - - - - /** - * @param EE_Messages_Queue $queue - * @depends test_add_and_get_queue - * @return EE_Messages_Queue - */ - function test_remove( EE_Messages_Queue $queue ) { - $test_queue = $queue->get_message_repository(); - - $test_queue->rewind(); - $this->assertTrue( $test_queue->valid() ); - $message = $test_queue->current(); - $test_queue->remove( $message ); - - //validate that the queue is empty - $test_queue->rewind(); - $this->assertFalse( $test_queue->valid() ); - - //add the message back to the queue for the next test - $test_queue->add( $message ); - return $queue; - } - - - - - - /** - * @param EE_Messages_Queue $queue - * @depends test_remove - * @return EE_Messages_Queue - */ - function test_save( EE_Messages_Queue $queue ) { - //first verify that the current EE_Message object in the queue does - //not have an ID() (it shouldn't) - $test_queue = $queue->get_message_repository(); - $test_queue->rewind(); - $this->assertEmpty( $test_queue->current()->ID() ); - - //save! - $queue->save(); - $test_queue->rewind(); - //verify we have an ID and can retrieve from db. - $message = EEM_Message::instance()->get_one_by_ID( $test_queue->current()->ID() ); - $this->assertInstanceOf( 'EE_Message', $message ); - return $queue; - } - - - - - - /** - * @param EE_Messages_Queue $queue - * @depends test_save - * @return EE_Messages_Queue - */ - function test_remove_with_persist( EE_Messages_Queue $queue ) { - $test_queue = $queue->get_message_repository(); - $test_queue->rewind(); - //verify we have a message object before removing - $message = $test_queue->current(); - $this->assertInstanceOf( 'EE_Message', $message ); - - //now do a remove of this message object but with the persist flag set. - $queue->remove( $message, true ); - - //did it get removed? - $test_queue->rewind(); - $this->assertFalse( $test_queue->valid() ); - //ensure message gets removed from entity map - EEM_Message::instance()->clear_entity_map( $message->ID() ); - //should not be in db either - $this->assertEmpty( EEM_Message::instance()->get_one_by_ID( $message->ID() ) ); - } - - - - - - /** - * This is also testing the lock functionality - * @return EE_Messages_Queue - */ - function test_get_batch_to_generate() { - //grab a bunch of message objects and add to queue. - $queue = $this->_get_queue(); - for ( $i=0;$i<5;$i++ ) { - $queue->add( $this->factory->message->create() ); - } - - //now get a new queue - $queue = $this->_get_queue(); - - //test getting batch and that there is the right count in the batch. - $this->assertTrue( $queue->get_batch_to_generate() ); - $this->assertEquals( 5, $queue->get_message_repository()->count() ); - - //test lock is set. - $lock_test_queue = $this->_get_queue(); - $this->assertTrue( $lock_test_queue->is_locked() ); - $this->assertFalse( $lock_test_queue->get_batch_to_generate() ); - - //test unlocking - $lock_test_queue->unlock_queue( 'generation' ); - $this->assertFalse( $lock_test_queue->is_locked() ); - $this->assertTrue( $lock_test_queue->get_batch_to_generate() ); - } - - - - - function test_get_to_send_batch_and_send() { - //grab a bunch of message objects and add to queue. - $queue = $this->_get_queue(); - for ( $i=0;$i<5;$i++ ) { - $queue->add( $this->factory->message->create() ); - } - //persist - $queue->save(); - - //next verify that nothing gets processed when there are no messages TO send (i.e. current EE_Message objects - //in db should be all incomplete. - $test_queue = $this->_get_queue(); - $this->assertFalse( $test_queue->get_to_send_batch_and_send() ); - - //okay let's now set all messages to be ready for sending. - foreach( $queue->get_message_repository() as $message ) { - $message->set_STS_ID( EEM_Message::status_idle ); - } - - //save queue - $queue->save(); - - //run test - $test_queue = $this->_get_queue(); - $this->assertTrue( $test_queue->get_to_send_batch_and_send() ); - - //verify no messages have failed status. - $this->assertEquals( 0, $test_queue->count_STS_in_queue( EEM_Message::instance()->stati_indicating_failed_sending() ) ); - //verify all have been marked as sent. - $this->assertEquals( 5, $test_queue->count_STS_in_queue(EEM_Message::status_sent ) ); - } - - - /** - * This is used to test the execute method when there are messages in the queue that are NOT with a status representing - * to send. They should NOT get sent if that's the case. - * @group 9787 - */ - public function test_send_only_ready_to_send_messages() { - //get some messages ready for the test and add to queue - $queue = $this->_get_queue(); - for ( $i = 0; $i < 5; $i++ ) { - $queue->add( $this->factory->message->create() ); - } - - //should be 5 items in the queue with MIC status - $this->assertEquals( 5, $queue->count_STS_in_queue( array( EEM_Message::status_incomplete ) ) ); - - //now if we execute now, NOTHING should get sent and we should still see all messages in the queue as MIC. - //anything else and we know the test has failed. - $queue->execute(); - - $this->assertEquals( 5, $queue->count_STS_in_queue( array( EEM_Message::status_incomplete ) ) ); - - } - - -} //end EE_Messages_Queue_Test \ No newline at end of file diff --git a/tests/testcases/core/libraries/messages/EE_Messages_Scheduler_Test.php b/tests/testcases/core/libraries/messages/EE_Messages_Scheduler_Test.php deleted file mode 100644 index ebfd50070e9..00000000000 --- a/tests/testcases/core/libraries/messages/EE_Messages_Scheduler_Test.php +++ /dev/null @@ -1,67 +0,0 @@ -addSomeMessagesForTesting(); - EE_Registry::instance()->CFG->messages->delete_threshold = 0; - EE_Messages_Scheduler::cleanup(); - //there should still be the old message in there. - $this->assertEquals(3, EEM_Message::instance()->count()); - } - - - /** - * Tests the cleanup method for messages when config is set to remove. - * @group 10417 - */ - public function test_cleanup_turned_on() - { - //create some messages - $this->addSomeMessagesForTesting(); - EE_Registry::instance()->CFG->messages->delete_threshold = 3; - EE_Messages_Scheduler::cleanup(); - $this->assertEquals(1, EEM_Message::instance()->count()); - } - - - protected function addSomeMessagesForTesting() - { - $messages_to_create = array( - array( - 'STS_ID' => EEM_Message::status_idle, - 'MSG_modified' => time() - (4*MONTH_IN_SECONDS) - ), - array( - 'STS_ID' => EEM_Message::status_debug_only, - 'MSG_modified' => time() - (4*MONTH_IN_SECONDS) - ), - array( - 'STS_ID' => EEM_Message::status_sent, - 'MSG_modified' => time() - (4*MONTH_IN_SECONDS) - ) - ); - foreach ($messages_to_create as $message_to_create) { - $this->factory->message->create($message_to_create); - } - } - -} \ No newline at end of file diff --git a/tests/testcases/core/libraries/messages/EE_Messages_Validator_Test.php b/tests/testcases/core/libraries/messages/EE_Messages_Validator_Test.php deleted file mode 100644 index 07a1ca9e54b..00000000000 --- a/tests/testcases/core/libraries/messages/EE_Messages_Validator_Test.php +++ /dev/null @@ -1,66 +0,0 @@ -loadMessagesMocks(); - $this->_messagesValidatorMock = new EE_Messages_Validator_Mock(); - } - - - - /** - * This tests validating dynamic messages shortcodes against the _invalid_shortcodes - * method in the EE_Messages_Validator class. - * - * @since @4.6.0 - * @group 7534 - */ - public function test_validating_dynamic_shortcodes() { - - $valid_shortcodes_array = array( - '[LINE_ITEM_TAXABLE_*]', - '[CO_TAX_NUMBER_*]', - '[PAYMENT_LIST_*]', - '[RECIPIENT_ANSWER_*]', - '[TKT_USES_*]', - '[INVOICE_PAYEE_TAX_NUMBER_*]', - '[OWING_STATUS_MESSAGE_*]', - '[ANSWER_*]' - ); - $valid_shortcodes_array = array_flip( $valid_shortcodes_array ); - - $string_with_valid_shortcodes = '[LINE_ITEM_TAXABLE_* some_param="this" or this ?] with [CO_TAX_NUMBER_* some_param="this" or this ?] and [PAYMENT_LIST_* some_param="this" or this ?]. But don\'t forget [RECIPIENT_ANSWER_* some_param="this" or this ?] or [TKT_USES_* some_param="this" or this ?] because [INVOICE_PAYEE_TAX_NUMBER_* some_param="this" or this ?] has [OWING_STATUS_MESSAGE_* some_param="this" or this ?] and finally, [ANSWER_* some_param="this" or this ?]'; - - $string_with_invalid_shortcodes = '[JUST_AN_INVALID*_] and another that is [SOMEWHAT_INVALID missing a bracket of course. But then there is [THIS_ONE_* (that does have a bracket)], and finally [JUST_A_PLAIN_INVALID_SHORTCODE]'; - - //test valid shortcodes - $this->assertFalse( $this->_messagesValidatorMock->invalid_shortcodes( $string_with_valid_shortcodes, $valid_shortcodes_array ) ); - - //test invalid shortcodes - $this->assertContains( '[JUST_AN_INVALID*_]', $this->_messagesValidatorMock->invalid_shortcodes( $string_with_invalid_shortcodes, $valid_shortcodes_array ) ); - $this->assertContains( '[THIS_ONE_* (that does have a bracket)]', $this->_messagesValidatorMock->invalid_shortcodes( $string_with_invalid_shortcodes, $valid_shortcodes_array ) ); - $this->assertContains( '[JUST_A_PLAIN_INVALID_SHORTCODE]', $this->_messagesValidatorMock->invalid_shortcodes( $string_with_invalid_shortcodes, $valid_shortcodes_array ) ); - $this->assertContains( '[SOMEWHAT_INVALID', $this->_messagesValidatorMock->invalid_shortcodes( $string_with_invalid_shortcodes, $valid_shortcodes_array ) ); - } -} diff --git a/tests/testcases/core/libraries/plugin_api/EE_Register_Addon_Test.php b/tests/testcases/core/libraries/plugin_api/EE_Register_Addon_Test.php deleted file mode 100644 index 221c60c82ae..00000000000 --- a/tests/testcases/core/libraries/plugin_api/EE_Register_Addon_Test.php +++ /dev/null @@ -1,508 +0,0 @@ -_mock_addon_path = EE_MOCKS_DIR . 'addons/eea-new-addon/'; - $this->_reg_args = array( - 'version' => '1.0.0', - 'min_core_version' => '4.0.0', - 'main_file_path' => $this->_mock_addon_path . 'eea-new-addon.php', - 'dms_paths' => $this->_mock_addon_path . 'core/data_migration_scripts', - 'model_paths' => $this->_mock_addon_path . 'core/db_models', - 'class_paths' => $this->_mock_addon_path . 'core/db_classes', - 'class_extension_paths' => $this->_mock_addon_path . 'core/db_class_extensions', - 'model_extension_paths' => $this->_mock_addon_path . 'core/db_model_extensions', - ); - $this->_addon_name = 'New_Addon'; - parent::__construct($name, $data, $dataName); - } - - - - public function setUp() - { - parent::setUp(); - add_filter( - 'FHEE__EEH_Activation__create_table__short_circuit', - array($this, 'dont_short_circuit_new_addon_table'), - 20, - 3 - ); - } - - - - /** - * OK's the creation of the esp_new_addon table, because this hooks in AFTER EE_UNitTestCase's callback on this same hook - * - * @param bool $short_circuit - * @param string $table_name - * @param string $create_sql - * @return boolean - */ - public function dont_short_circuit_new_addon_table($short_circuit = false, $table_name = '', $create_sql = '') - { - $table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true); - if ( - in_array($table_name, array('esp_new_addon_thing', 'esp_new_addon_attendee_meta'), true) - && ! $table_analysis->tableExists($table_name) - ) { - // echo "\r\n\r\nDONT short circuit $sql"; - // it's not altering. it's ok to allow this - return false; - } - // echo "3\r\n\r\n short circuit:$sql"; - return $short_circuit; - } - - - - //test registering a bare minimum addon, and then de-registering it - public function test_register_mock_addon_fail() - { - // echo "\n\n " . __LINE__ . ") " . __METHOD__ . "()"; - //we're registering the addon WAAAY after EE_System has set thing up, so - //registering this first time should throw an E_USER_NOTICE - try { - EE_Register_Addon::register($this->_addon_name, $this->_reg_args); - $this->fail('We should have had a warning saying that we are setting up the ee addon at the wrong time'); - } catch (PHPUnit_Framework_Error_Notice $e) { - $this->assertTrue(true); - } - //check that we didn't actually register the addon - $this->assertArrayNotHasKey('EE_New_Addon', EE_Registry::instance()->addons); - //check DMSs weren't setup either - $DMSs_available = EE_Data_Migration_Manager::reset()->get_all_data_migration_scripts_available(); - $this->assertArrayNotHasKey('EE_DMS_New_Addon_1_0_0', $DMSs_available); - //check that we didn't register the addon's deactivation hook either - $this->assertFalse(has_action('deactivate_' . plugin_basename($this->_reg_args['main_file_path']))); - } - - - - public function test_register_mock_addon_fail__bad_parameters() - { - //we're registering the addon with the wrong parameters - $this->_pretend_addon_hook_time(); - if (did_action('activate_plugin')) { - $this->assertTrue(false); - } - try { - EE_Register_Addon::register( - $this->_addon_name, - array( - 'version' => '1.0.0', - 'min_core_version' => '4.0.0', - 'dms_paths' => $this->_mock_addon_path . 'core/data_migration_scripts', - ) - ); - $this->fail( - 'We should have received a warning that the "main_file_path" is a required argument when registering an addon' - ); - } catch (EE_Error $e) { - $this->assertTrue(true); - } - //check that we didn't actually register the addon - $this->assertArrayNotHasKey('EE_New_Addon', EE_Registry::instance()->addons); - //check DMSs weren't setup either - $DMSs_available = EE_Data_Migration_Manager::reset()->get_all_data_migration_scripts_available(); - $this->assertArrayNotHasKey('EE_DMS_New_Addon_1_0_0', $DMSs_available); - //check that we didn't register the addon's de-activaiton hook either - $this->assertFalse(has_action('deactivate_' . plugin_basename($this->_reg_args['main_file_path']))); - } - - - - public function test_register_mock_addon_success() - { - //ensure model and class extensions weren't setup beforehand - $this->assertFalse($this->_class_has_been_extended()); - $this->assertFalse($this->_model_has_been_extended()); - $this->_pretend_addon_hook_time(); - if (did_action('activate_plugin')) { - $this->assertTrue(false); - } - $this->assertArrayNotHasKey('EE_New_Addon', EE_Registry::instance()->addons); - //just to make this test truly test the "eea-new-addon", use its own addon params - //this way we're more likely to keep the EE_New_Addon up-to-date - require_once(EE_TESTS_DIR . 'mocks/addons/eea-new-addon/eea-new-addon.php'); - require_once(EE_TESTS_DIR . 'mocks/addons/eea-new-addon/EE_New_Addon.class.php'); - EE_New_Addon::register_addon(); - $this->assertArrayHasKey( - 'EE_New_Addon', - EE_Registry::instance()->addons - ); - $this->assertInstanceOf( - 'EE_New_Addon', - EE_Registry::instance()->addons->EE_New_Addon - ); - //check DMSs were setup properly too - $DMSs_available = EE_Data_Migration_Manager::reset()->get_all_data_migration_scripts_available(); - $this->assertArrayHasKey('EE_DMS_New_Addon_1_0_0', $DMSs_available); - //and check the deactivation hook was setup properly - $this->assertTrue( - has_action('deactivate_' . EE_Registry::instance()->addons->EE_New_Addon->get_main_plugin_file_basename()) - ); - //check that the model was registered properly - EE_System::instance()->load_core_configuration(); - $this->assertArrayContains('EEM_New_Addon_Thing', EE_Registry::instance()->non_abstract_db_models); - $this->assertArrayContains('EEM_New_Addon_Thing', EE_Registry::instance()->models); - $dms = EE_Registry::instance()->load_dms('New_Addon_1_0_0'); - $this->assertInstanceOf('EE_Data_Migration_Script_Base', $dms); - $dms->set_migrating(false); - $dms->schema_changes_before_migration(); - $dms->schema_changes_after_migration(); - $this->assertTableExists('esp_new_addon_thing', 'New_Addon_Thing'); - //check that the model extension was registered properly - $this->assertTrue($this->_class_has_been_extended(true)); - $this->assertTrue($this->_model_has_been_extended(true)); - //check that the caps maps were registered properly too - $this->_pretend_capabilities_registered(); - $current_user = $this->factory->user->create_and_get(); - $other_user = $this->factory->user->create_and_get(); - //give user administrator role for test! - $current_user->add_role('administrator'); - $a_thing = $this->new_model_obj_with_dependencies('New_Addon_Thing', array('NEW_wp_user' => $current_user->ID)); - $others_thing = $this->new_model_obj_with_dependencies( - 'New_Addon_Thing', - array('NEW_wp_user' => $other_user->ID) - ); - $this->assertTrue( - EE_Capabilities::instance()->user_can($current_user, 'edit_thing', 'testing_edit', $a_thing->ID()) - ); - $this->assertTrue( - EE_Capabilities::instance()->user_can($current_user, 'edit_thing', 'testing_edit', $others_thing->ID()) - ); - } - - - - /** - * Utility function to just setup valid capabilities for tests in this suite. - * - * @since 1.0.0 - * @return void - */ - private function _pretend_capabilities_registered() - { - EE_Registry::instance()->load_core('Capabilities'); - EE_Capabilities::instance()->init_caps(true); - //validate caps were registered and init saved. - $admin_caps_init = EE_Capabilities::instance()->get_ee_capabilities('administrator'); - $this->assertArrayContains('edit_thing', $admin_caps_init); - //verify new caps are in the role - $role = get_role('administrator'); - $this->assertContains( - array('edit_thing', 'edit_things', 'edit_others_things', 'edit_private_things'), - $role->capabilities - ); - } - - /** - * uses the connection settings on EE_New_Addon::register() instead - * of our copy of them - */ - // function test_register_mock_addon_success_using_its_callback(){ - // //ensure model and class extensions weren't setup beforehand - // $this->assertFalse( $this->_class_has_been_extended() ); - // $this->assertFalse( $this->_model_has_been_extended() ); - // - // $this->_pretend_addon_hook_time(); - // if( did_action( 'activate_plugin' ) ){ - // $this->assertTrue( FALSE ); - // } - // $this->assertFalse(property_exists(EE_Registry::instance()->addons, 'EE_New_Addon')); - // - // - // //use the function in mocks/addons/new_addon/eea-new-addon.php - // load_espresso_new_addon(); - // - // $this->assertAttributeNotEmpty('EE_New_Addon',EE_Registry::instance()->addons); - // //check DMSs were setup properly too - // $DMSs_available = EE_Data_Migration_Manager::reset()->get_all_data_migration_scripts_available(); - // $this->assertArrayHasKey('EE_DMS_New_Addon_1_0_0',$DMSs_available); - // - // //and check the deactivation hook was setup properly - // $this->assertTrue( has_action( 'deactivate_' . EE_Registry::instance()->addons->EE_New_Addon->get_main_plugin_file_basename() ) ); - // - // //check that the model was registered properly - // EE_System::instance()->load_core_configuration(); - // $this->assertArrayContains('EEM_New_Addon_Thing', EE_Registry::instance()->non_abstract_db_models); - // $this->assertArrayContains('EEM_New_Addon_Thing', EE_Registry::instance()->models); - // - // $dms = EE_Registry::instance()->load_dms('New_Addon_1_0_0'); - // $this->assertInstanceOf( 'EE_Data_Migration_Script_Base', $dms ); - // $dms->schema_changes_before_migration(); - // $dms->schema_changes_after_migration(); - // $this->assertTableExists( 'esp_new_addon_thing', 'New_Addon_Thing' ); - // //check that the model extension was registered properly - // $this->assertTrue( $this->_class_has_been_extended( TRUE ) ); - // $this->assertTrue( $this->_model_has_been_extended( TRUE ) ); - // } - /** - * check that when we register an addon and then another after the 'activate_plugin' - * action fired, that there are no errors and the 2nd addon's activation indicator - * was set properly - * - * @throws \EE_Error - */ - public function test_register_mock_addon__activation() - { - $this->_pretend_after_plugin_activation(); - EE_Register_Addon::register($this->_addon_name, $this->_reg_args); - $this->assertArrayHasKey( - 'EE_New_Addon', - EE_Registry::instance()->addons - ); - $this->assertInstanceOf( - 'EE_New_Addon', - EE_Registry::instance()->addons->EE_New_Addon - ); - $this->assertWPOptionExists( - EE_Registry::instance()->addons->EE_New_Addon->get_activation_indicator_option_name() - ); - } - - - - /** - * registers an addon as usual, but then calls 'activate_plugin', as if a different - * addon had been activated. Because the register method is called twice, this has the potential - * for problems - * - * @throws \EE_Error - */ - public function test_register_addon_called_twice_on_activation() - { - EE_System::reset(); - $this->_pretend_addon_hook_time(); - if (did_action('activate_plugin')) { - $this->assertTrue(false); - } - $this->assertFalse(property_exists(EE_Registry::instance()->addons, 'EE_New_Addon')); - EE_Register_Addon::register($this->_addon_name, $this->_reg_args); - $this->assertArrayHasKey( - 'EE_New_Addon', - EE_Registry::instance()->addons - ); - $this->assertInstanceOf( - 'EE_New_Addon', - EE_Registry::instance()->addons->EE_New_Addon - ); - global $wp_actions; - $times_load_addons_fired = $wp_actions['AHEE__EE_System__load_espresso_addons']; - do_action('activate_plugin'); - $this->assertGreaterThan($times_load_addons_fired, $wp_actions['AHEE__EE_System__load_espresso_addons']); - } - - - - public function tearDown() - { - if (isset($this->_addon_name, EE_Registry::instance()->addons->EE_New_Addon)) { - $main_file_path_before_deregistration = EE_Registry::instance() - ->addons - ->EE_New_Addon - ->get_main_plugin_file_basename(); - EE_Register_Addon::deregister($this->_addon_name); - $this->assertArrayNotHasKey('EE_New_Addon', EE_Registry::instance()->addons); - //verify the de-activation hook was removed - $this->assertFalse(has_action('deactivate_' . $main_file_path_before_deregistration)); - //verify the models were deregistered - EE_System::instance()->load_core_configuration(); - $this->assertArrayDoesNotContain('EEM_New_Addon_Thing', EE_Registry::instance()->non_abstract_db_models); - $this->assertArrayDoesNotContain('EEM_New_Addon_Thing', EE_Registry::instance()->models); - EE_Registry::instance()->reset_model('Attendee'); - //verify that the model and class extensions have been removed - $this->assertFalse($this->_class_has_been_extended()); - $this->assertFalse($this->_model_has_been_extended()); - } - //verify DMSs deregistered - $DMSs_available = EE_Data_Migration_Manager::reset()->get_all_data_migration_scripts_available(); - $this->assertArrayNotHasKey('EE_DMS_New_Addon_1_0_0', $DMSs_available); - $this->_stop_pretending_addon_hook_time(); - $this->_stop_pretending_after_plugin_activation(); - remove_all_filters('AHEE__EE_System__load_espresso_addons'); - parent::tearDown(); - } - - /** - * double checks that we the example addon is registering correctly. - * - * @todo: to make sure our example addon is really working, we should try using it - * on its own - */ - // public function test_regular_new_addon_activation(){ - // $this->_pretend_addon_hook_time(); - // require_once( EE_TESTS_DIR . 'mocks/addons/eea-new-addon/eea-new-addon.php' ); - // EE_New_Addon::register_addon(); - // $this->assertAttributeNotEmpty('EE_New_Addon',EE_Registry::instance()->addons); - // - // //and then it should be torn down by tearDown() - // } - protected function _stop_pretending_after_plugin_activation() - { - global $wp_actions; - unset($wp_actions['activate_plugin']); - } - - - - protected function _pretend_after_plugin_activation() - { - do_action('activate_plugin'); - } - - - - protected function _pretend_addon_hook_time() - { - global $wp_actions; - unset( - $wp_actions['AHEE__EEM_Attendee__construct__end'], - $wp_actions['AHEE__EE_System__load_core_configuration__begin'], - $wp_actions['AHEE__EE_System__register_shortcodes_modules_and_widgets'], - $wp_actions['AHEE__EE_System__core_loaded_and_ready'] - ); - parent::_pretend_addon_hook_time(); - } - - - - /** - * Determines if the attendee class has been extended by teh mock extension - * - * @param bool $throw_error - * @return bool - * @throws \EE_Error - */ - private function _class_has_been_extended($throw_error = false) - { - try { - $a = EE_Attendee::new_instance(); - $a->foobar(); - return true; - } catch (EE_Error $e) { - if ($throw_error) { - throw $e; - } - return false; - } - } - - - - /** - * Determines if the Attendee model has been extended by the mock extension - * - * @param bool $throw_error - * @return bool - * @throws \EE_Error - */ - private function _model_has_been_extended($throw_error = false) - { - try { - /** @var EEM_Attendee $att */ - $att = EE_Registry::instance()->reset_model('Attendee'); - if (! $att->has_field('ATT_foobar')) { - if ($throw_error) { - throw new EE_Error( - sprintf( - __( - 'The field ATT_foobar is not on EEM_Attendee, but the extension should have added it. fields are: %s', - 'event_espresso' - ), implode(",", array_keys(EEM_Attendee::instance()->field_settings())) - ) - ); - } - return false; - } - if (! $att->has_relation('New_Addon_Thing')) { - if ($throw_error) { - throw new EE_Error( - sprintf( - __( - 'The relation of type New_Addon_Thing on EEM_Attendee, but the extension should have added it. fields are: %s', - 'event_espresso' - ), implode(",", array_keys(EEM_Attendee::instance()->field_settings())) - ) - ); - } - return false; - } - $att->get_all_new_things(); - return true; - } catch (EE_Error $e) { - if ($throw_error) { - throw $e; - } - return false; - } - } - - - - public function test_effective_version() - { - //use reflection to test this protected method - $method = new ReflectionMethod('EE_Register_Addon', '_effective_version'); - $method->setAccessible(true); - $this->assertEquals('4.3.0.dev.000', $method->invoke(null, '4.3.0')); - $this->assertEquals('4.3.0.p.000', $method->invoke(null, '4.3.0.p')); - $this->assertEquals('4.3.0.rc.123', $method->invoke(null, '4.3.0.rc.123')); - } - - - - public function test_meets_min_core_version_requirement() - { - //use reflection to test this protected method - $method = new ReflectionMethod('EE_Register_Addon', '_meets_min_core_version_requirement'); - $method->setAccessible(true); - $this->assertTrue($method->invoke(null, '4.3.0', '4.3.0.p')); - $this->assertTrue($method->invoke(null, '4.3.0', '4.3.0.rc.032')); - $this->assertTrue($method->invoke(null, '4.3.0.p', '4.3.0.p')); - $this->assertTrue($method->invoke(null, '4.3.0.p', '4.4.0.p')); - $this->assertTrue($method->invoke(null, '4.3.0.rc.000', '4.3.0.p')); - $this->assertFalse($method->invoke(null, '4.4.0', '4.3.0.p')); - $this->assertFalse($method->invoke(null, '4.4.0.p', '4.3.0.p')); - $this->assertFalse($method->invoke(null, '4.3.0.rc.123', '4.3.0.rc.001')); - } - -} - -// End of file EE_Register_Addon_Test.php -// Location: testcases/core/libraries/plugin_api/EE_Register_Addon_Test.php diff --git a/tests/testcases/core/libraries/plugin_api/EE_Register_Capabilities_Test.php b/tests/testcases/core/libraries/plugin_api/EE_Register_Capabilities_Test.php deleted file mode 100644 index 1064663f240..00000000000 --- a/tests/testcases/core/libraries/plugin_api/EE_Register_Capabilities_Test.php +++ /dev/null @@ -1,403 +0,0 @@ - array( - 'test_reads', - 'test_writes', - 'test_others_read', - 'test_others_write', - 'test_private_read', - 'test_private_write', - ), - ); - $non_numeric_cap_maps_array = array( - 'EE_Meta_Capability_Map_Read' => array( - 'test_read', - array('Event', 'test_published_read', 'test_others_read', 'test_private_read'), - ), - 'EE_Meta_Capability_Map_Edit' => array( - 'test_write', - array('Event', 'test_published_write', 'test_others_write', 'test_private_write'), - ), - ); - $numeric_cap_maps_array = array( - 0 => array( - 'EE_Meta_Capability_Map_Read' => array( - 'test_read', - array('Event', 'test_published_read', 'test_others_read', 'test_private_read'), - ), - ), - 1 => array( - 'EE_Meta_Capability_Map_Edit' => array( - 'test_write', - array('Event', 'test_published_write', 'test_others_write', 'test_private_write'), - ), - ), - ); - $this->_valid_capabilities = array( - 'capabilities' => $capabilities_array, - 'capability_maps' => $non_numeric_cap_maps_array, - ); - $this->_valid_capabilities_numeric_caps_map = array( - 'capabilities' => $capabilities_array, - 'capability_maps' => $numeric_cap_maps_array, - ); - } - - - /** - * Utility function to just ensure and admin user is setup for tests in this suite - * - * @since 4.5.0 - * @return void - */ - private function setupUser() - { - //create a user for checking caps on. - $user_id = $this->factory->user->create(); - $this->_user = $this->factory->user->get_object_by_id($user_id); - //give user administrator role for test! - $this->_user->add_role('administrator'); - - //verify administrator role set - $this->assertTrue(user_can($this->_user, 'administrator')); - } - - - /** - * Utility function to just setup valid capabilities for tests in this suite. - * - * @since 1.0.0 - * @return void - */ - private function _pretend_capabilities_registered($non_numeric = true) - { - //pretend correct hookpoint set. - global $wp_actions; - unset($wp_actions['AHEE__EE_System___detect_if_activation_or_upgrade__begin']); - //register capabilities - $capabilities_to_register = $non_numeric ? $this->_valid_capabilities : $this->_valid_capabilities_numeric_caps_map; - EE_Register_Capabilities::register('Test_Capabilities', $capabilities_to_register); - - $this->_add_test_helper_filters(); - - EE_Registry::instance()->load_core('Capabilities'); - EE_Capabilities::instance()->init_caps(true); - - //remove filters that were added to prevent pollution in other tests - $this->_remove_test_helper_filters(); - //validate caps were registered and init saved. - $admin_caps_init = EE_Capabilities::instance()->get_ee_capabilities('administrator'); - $this->assertArrayContains('test_reads', $admin_caps_init); - - //verify new caps are in the role - $role = get_role('administrator'); - $this->assertContains($this->_valid_capabilities['capabilities']['administrator'], $role->capabilities); - - //make sure we didn't erase the existing capabilities (@see https://events.codebasehq.com/projects/event-espresso/tickets/6700) - $this->assertContains(array('ee_read_ee', 'ee_read_events'), $role->capabilities, - 'Looks like registering capabilities is overwriting default capabilites, that will cause problems'); - - //setup user - $this->setupUser(); - } - - - /** - * Adds filter to help with tests that in turn verify things that should be setup are. - */ - private function _add_test_helper_filters() - { - //use filters to access some of the data normally private to EE_Capabilities because we want to verify it - add_filter('FHEE__EE_Capabilities__init_caps_map__caps', array($this, '_remember_what_caps_were_beforehand'), - 1); - add_filter('FHEE__EE_Capabilities__init_caps_map__caps', array($this, '_verify_new_cap_map_ok'), 100); - - //verify the cap_map_maps - add_filter('FHEE__EE_Capabilities___set_meta_caps__meta_caps', array($this, '_verify_new_meta_caps_ok'), 200); - } - - - /** - * Removes the helper filters that were added initially for helping verify setup. - */ - private function _remove_test_helper_filters() - { - remove_filter('FHEE__EE_Capabilities__init_caps_map__caps', array($this, '_remember_what_caps_were_beforehand'), - 1); - remove_filter('FHEE__EE_Capabilities__init_caps_map__caps', array($this, '_verify_new_cap_map_ok'), 100); - remove_filter('FHEE__EE_Capabilities___set_meta_caps__meta_caps', array($this, '_verify_new_meta_caps_ok'), - 200); - } - - - /** - * Verify that the $incoming_cap_map looks normal after EE_Register_Capabilities has played with it - * - * @param array $incoming_cap_map - * @return array - */ - public function _verify_new_cap_map_ok($incoming_cap_map) - { - foreach ($this->_caps_before_registering_new_ones as $role => $caps) { - $this->assertArrayHasKey($role, $incoming_cap_map); - foreach ($caps as $cap) { - $this->assertArrayContains($cap, $incoming_cap_map[$role]); - } - } - return $incoming_cap_map; - } - - - /** - * Verify that the $incoming_meta_caps (via _set_meta_caps ) looks normal after EE_Register_Capabilities has played - * with it - * - * @param array $incoming_meta_caps - * @return array - */ - public function _verify_new_meta_caps_ok($incoming_meta_caps) - { - foreach ($this->_valid_capabilities['capability_maps'] as $meta_ref => $meta_cap_info) { - $has_meta_cap = false; - $meta_cap_to_check = $meta_cap_info[0]; - //loop through and make sure that this meta cap is set on an instantiated map - foreach ($incoming_meta_caps as $meta_cap_class) { - if ($meta_cap_class->meta_cap == $meta_cap_to_check) { - $has_meta_cap = true; - break; - } - } - - if (! $has_meta_cap) { - $this->fail(sprintf('Expecting the %s meta cap to be registered but it is not.', $meta_cap_to_check)); - } - } - return $incoming_meta_caps; - } - - - /** - * Verify that the $incoming_cap_map looks normal after EE_Register_Capabilities has deregistered existing - * registered caps - * - * @param array $incoming_cap_map - * @return array - */ - public function _verify_new_cap_map_ok_after_deregister($incoming_cap_map) - { - $this->assertNotContains($this->_valid_capabilities['capabilities']['administrator'], - $incoming_cap_map['administrator']); - return $incoming_cap_map; - } - - - /** - * Verify that the $incoming_meta_caps looks normal after EE_Register_Capabilities has deregistered existing - * registered caps. - * - * @param array $incoming_meta_caps - * @return array - */ - public function _verify_new_meta_cap_ok_after_deregister($incoming_meta_caps) - { - foreach ($this->_valid_capabilities['capability_maps'] as $meta_ref => $meta_cap_info) { - $has_meta_cap = false; - $meta_cap_to_check = $meta_cap_info[0]; - //loop through and make sure that this meta cap is set on an instantiated map - foreach ($incoming_meta_caps as $meta_cap_class) { - if ($meta_cap_class->meta_cap == $meta_cap_to_check) { - $has_meta_cap = true; - break; - } - } - - if ($has_meta_cap) { - $this->fail(sprintf('Expecting the %s meta cap to not be registered but it is.', $meta_cap_to_check)); - } - } - return $incoming_meta_caps; - } - - - /** - * Gets all the caps BEFORE the registered caps get added to make sure none get - * removed. - * - * @param type $incoming_cap_map - * @return array - */ - public function _remember_what_caps_were_beforehand($incoming_cap_map) - { - $this->_caps_before_registering_new_ones = $incoming_cap_map; - return $incoming_cap_map; - } - - - /** - * Gets all the cap maps BEFORE the registered caps get added to make sure none get - * removed. - * - * @param type $incoming_cap_map - * @return array - */ - public function _remember_what_meta_caps_were_beforehand($incoming_cap_map) - { - $this->_meta_caps_before_registering_new_ones = $incoming_cap_map; - return $incoming_cap_map; - } - - - public function test_registering_capabilities_too_early() - { - - //test activating in the wrong spot. - try { - EE_Register_Capabilities::register('Test_Capabilities', $this->_valid_capabilities); - $this->fail('We should have had a warning saying that we are registering capabilities at the wrong time'); - } catch (PHPUnit_Framework_Error_Notice $e) { - $this->assertTrue(true); - } - } - - - public function test_registering_capabilities_and_they_are_assigned() - { - $this->_pretend_capabilities_registered(); - - //now capabilities *SHOULD* be set on the user. Let's verify. - $this->assertTrue(user_can($this->_user, 'test_reads')); - $this->assertTrue(user_can($this->_user, 'test_writes')); - $this->assertTrue(user_can($this->_user, 'test_others_read')); - $this->assertTrue(user_can($this->_user, 'test_others_write')); - $this->assertTrue(user_can($this->_user, 'test_private_read')); - $this->assertTrue(user_can($this->_user, 'test_private_write')); - } - - - public function test_capability_maps_registered_non_numeric() - { - $this->_pretend_capabilities_registered(); - //the best way to test this is to ensure the registered maps work. So let's author an event by the user. - - //main users event. - $event = $this->factory->event->create(array('EVT_wp_user' => $this->_user->ID)); - - //other users event (checking others event caps). - $user_id = $this->factory->user->create(); - $other_user = $this->factory->user->get_object_by_id($user_id); - $other_event = $this->factory->event->create(array('EVT_wp_user' => $other_user->ID)); - - //make sure we have an event - $this->assertInstanceOf('EE_Event', $event); - $this->assertInstanceOf('EE_Event', $other_event); - - //check map items for event. - $this->assertTrue(EE_Capabilities::instance()->user_can($this->_user, 'test_read', 'testing_read', - $event->ID())); - $this->assertTrue(EE_Capabilities::instance()->user_can($this->_user, 'test_write', 'testing_edit', - $event->ID())); - $this->assertTrue(EE_Capabilities::instance()->user_can($this->_user, 'test_read', 'testing_read', - $other_event->ID())); - $this->assertTrue(EE_Capabilities::instance()->user_can($this->_user, 'test_write', 'testing_edit', - $other_event->ID())); - } - - - public function test_capability_maps_registered_numeric() - { - $this->_pretend_capabilities_registered(false); - //the best way to test this is to ensure the registered maps work. So let's author an event by the user. - - //main users event. - $event = $this->factory->event->create(array('EVT_wp_user' => $this->_user->ID)); - - //other users event (checking others event caps). - $user_id = $this->factory->user->create(); - $other_user = $this->factory->user->get_object_by_id($user_id); - $other_event = $this->factory->event->create(array('EVT_wp_user' => $other_user->ID)); - - //make sure we have an event - $this->assertInstanceOf('EE_Event', $event); - $this->assertInstanceOf('EE_Event', $other_event); - - //check map items for event. - $this->assertTrue(EE_Capabilities::instance()->user_can($this->_user, 'test_read', 'testing_read', - $event->ID())); - $this->assertTrue(EE_Capabilities::instance()->user_can($this->_user, 'test_write', 'testing_edit', - $event->ID())); - $this->assertTrue(EE_Capabilities::instance()->user_can($this->_user, 'test_read', 'testing_read', - $other_event->ID())); - $this->assertTrue(EE_Capabilities::instance()->user_can($this->_user, 'test_write', 'testing_edit', - $other_event->ID())); - } - - - public function test_capability_maps_deregistered() - {//setup registered caps first - $this->_pretend_capabilities_registered(); - - //now let's add filter verify that new cap map doesn't have the mapped items after de-registering. The callback - //on these filters should get called when EE_Register_Capabilities::deregister calls the EE_Capability::init_caps() method - //so at that point they'll verify that the items that should be removed were actually removed. - add_filter('FHEE__EE_Capabilities__init_caps_map__caps', - array($this, '_verify_new_cap_map_ok_after_deregister'), 100); - add_filter('FHEE__EE_Capabilities___set_meta_caps__meta_caps', - array($this, '_verify_new_meta_cap_ok_after_deregister'), 200); - - //now deregister - EE_Register_Capabilities::deregister('Test_Capabilities'); - - //remove filters - remove_filter('FHEE__EE_Capabilities__init_caps_map__caps', - array($this, '_verify_new_cap_map_ok_after_deregister'), 100); - remove_filter('FHEE__EE_Capabilities___set_meta_caps__meta_caps', - array($this, '_verify_new_meta_cap_ok_after_deregister'), 200); - } - - public function tearDown() - { - EE_Register_Capabilities::deregister('Test_Capabilities'); - parent::tearDown(); - } -} diff --git a/tests/testcases/core/libraries/plugin_api/EE_Register_Data_Migration_Scripts_Test.php b/tests/testcases/core/libraries/plugin_api/EE_Register_Data_Migration_Scripts_Test.php deleted file mode 100644 index 787ba453b62..00000000000 --- a/tests/testcases/core/libraries/plugin_api/EE_Register_Data_Migration_Scripts_Test.php +++ /dev/null @@ -1,55 +0,0 @@ -_stop_pretending_addon_hook_time(); - remove_all_filters('FHEE__EE_Data_Migration_Manager__get_data_migration_script_folders'); - $pretend_addon_name = 'More_Core'; - $args = array( - 'dms_paths'=>array(EE_TESTS_DIR.'mocks/core/data_migration_scripts') - ); - //try registering at wrong time - try{ - EE_Register_Data_Migration_Scripts::register($pretend_addon_name, $args); - $this->fail('We should have had a warning saying that we are setting up the ee addon at the wrong time'); - }catch(PHPUnit_Framework_Error_Notice $e){ - $this->assertTrue(True); - } - //and check we didn't actually register the DMSs (because we attempted to do so at teh wrong time) - $DMSs_available = EE_Data_Migration_Manager::reset()->get_all_data_migration_scripts_available(); - $this->assertArrayNotHasKey('EE_DMS_Core_1_0_0',$DMSs_available); - - //ok now pretend we're registering the DMS at the right time - $this->_pretend_addon_hook_time(); - EE_Register_Data_Migration_Scripts::register($pretend_addon_name, $args); - $DMSs_available = EE_Data_Migration_Manager::reset()->get_all_data_migration_scripts_available(); - $this->assertArrayHasKey('EE_DMS_Core_1_0_0',$DMSs_available); - - //now deregister it - EE_Register_Data_Migration_Scripts::deregister($pretend_addon_name); - $DMSs_available = EE_Data_Migration_Manager::reset()->get_all_data_migration_scripts_available(); - $this->assertArrayNotHasKey('EE_DMS_Core_1_0_0',$DMSs_available); - - $this->_stop_pretending_addon_hook_time(); - } -} - -// End of file EE_Register_Data_Migration_Scripts_test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/plugin_api/EE_Register_Model_Extensions_Test.php b/tests/testcases/core/libraries/plugin_api/EE_Register_Model_Extensions_Test.php deleted file mode 100644 index 23b196868fb..00000000000 --- a/tests/testcases/core/libraries/plugin_api/EE_Register_Model_Extensions_Test.php +++ /dev/null @@ -1,196 +0,0 @@ -_reg_args = array( - 'model_extension_paths' => array( EE_MOCKS_DIR . 'core/db_model_extensions/' ), - 'class_extension_paths' => array( EE_MOCKS_DIR . 'core/db_class_extensions/' ) - ); - $this->_model_group = 'Mock'; - parent::__construct($name, $data, $dataName); - } - /** - * Determines if the attendee class has been extended by teh mock extension - * @return boolean - */ - private function _class_has_been_extended( $throw_error = FALSE){ - try{ - $a = EE_Attendee::new_instance(); - $a->foobar(); - return TRUE; - }catch(EE_Error $e){ - if( $throw_error ){ - throw $e; - } - return FALSE; - } - } - - - - /** - * Determines if the Attendee model has been extended by the mock extension - * - * @param bool $throw_error - * @return bool - * @throws \EE_Error - */ - private function _model_has_been_extended( $throw_error = FALSE){ - try{ - $att = EE_Registry::instance()->load_model('Attendee'); - $att->reset()->foobar(); - if( ! $att->has_field('ATT_foobar')){ - if( $throw_error ){ - throw new EE_Error(sprintf( __( 'The field ATT_foobar is not on EEM_Attendee, but the extension should have added it. fields are: %s', 'event_espresso' ), implode(",",array_keys(EEM_Attendee::instance()->field_settings())))); - } - return FALSE; - } - if( ! $att->has_relation('Transaction')){ - if( $throw_error ){ - throw new EE_Error(sprintf( __( 'The relation of type Transaction on EEM_Attendee, but the extension should have added it. fields are: %s', 'event_espresso' ), implode(",",array_keys(EEM_Attendee::instance()->field_settings())))); - } - return FALSE; - } - return TRUE; - }catch(EE_Error $e){ - if( $throw_error ){ - throw $e; - } - return FALSE; - } - } - - //test registering a bare minimum addon, and then deregistering it - function test_register_mock_model_fail(){ - //we're registering the addon WAAAY after EE_System has set thing up, so - //registering this first time should throw an E_USER_NOTICE - $this->assertFalse( $this->_class_has_been_extended() ); - $this->assertFalse( $this->_model_has_been_extended() ); - try{ - EE_Register_Model_Extensions::register($this->_model_group, $this->_reg_args); - $this->fail('We should have had a warning saying that we are setting up the ee addon at the wrong time'); - }catch(EE_Error $e){ - $this->assertTrue(True); - } - //verify they still haven't been extended - $this->assertFalse( $this->_class_has_been_extended() ); - $this->assertFalse( $this->_model_has_been_extended() ); - } - - function test_register_mock_model_extension_fail__bad_parameters(){ - //we're registering the addon with the wrong parameters - $this->_pretend_addon_hook_time(); - $this->assertFalse( $this->_class_has_been_extended() ); - $this->assertFalse( $this->_model_has_been_extended() ); - try{ - EE_Register_Model_Extensions::register($this->_model_group, array('foo' => 'bar')); - $this->fail('We should have had a warning saying that we are setting up the ee addon at the wrong time'); - }catch(EE_Error $e){ - $this->assertTrue(True); - } - //verify they still haven't been extended - $this->assertFalse( $this->_class_has_been_extended() ); - $this->assertFalse( $this->_model_has_been_extended() ); - } - - protected function _pretend_addon_hook_time() { - global $wp_actions; - unset( $wp_actions['AHEE__EEM_Attendee__construct__end'] ); - parent::_pretend_addon_hook_time(); - } - - function test_register_mock_addon_success(){ - - $this->assertFalse( $this->_class_has_been_extended() ); - $this->assertFalse( $this->_model_has_been_extended() ); - $this->_pretend_addon_hook_time(); - - EE_Register_Model_Extensions::register($this->_model_group, $this->_reg_args); - EEM_Attendee::instance()->reset(); - //verify they still haven't been extended - $this->assertTrue( $this->_class_has_been_extended( TRUE ) ); - $this->assertTrue( $this->_model_has_been_extended( TRUE ) ); - //and that we can still use EEM_Attendee - EE_Attendee::new_instance(); - EEM_Attendee::instance()->get_all(); - EE_Registry::instance()->load_model('Attendee')->get_all(); - - //now deregister it - EE_Register_Model_Extensions::deregister($this->_model_group); - $this->assertFalse( $this->_class_has_been_extended() ); - $this->assertFalse( $this->_model_has_been_extended() ); - EEM_Attendee::instance()->reset(); - //and EEM_Attendee still works right? both ways of instantiating it? - EE_Attendee::new_instance(); - EEM_Attendee::instance()->get_all(); - EE_Registry::instance()->load_model('Attendee')->get_all(); - - } - public function setUp(){ - parent::setUp(); - //whitelist the table we're about to add - add_filter( 'FHEE__EEH_Activation__create_table__short_circuit', array($this, 'dont_short_circuit_mock_table' ), 25, 3 ); - //add table from related DMS - EEH_Activation::create_table('esp_mock_attendee_meta', ' - MATTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT, - ATT_ID int(10) unsigned NOT NULL, - ATT_foobar int(10) unsigned NOT NULL, - PRIMARY KEY (MATTM_ID)' - ); - $this->assertTableExists( 'esp_mock_attendee_meta' ); - - EE_Register_Model_Extensions::deregister( $this->_model_group ); - } - - - - /** - * OK's the creation of the esp_new_addon table, because this hooks in AFTER EE_UNitTestCase's callback on this same hook - * - * @param bool $short_circuit - * @param string $table_name - * @param string $create_sql - * @return array - */ - public function dont_short_circuit_mock_table( $short_circuit = false, $table_name = '', $create_sql = '' ){ - $table_analysis = EE_Registry::instance()->create( 'TableAnalysis', array(), true ); - if( $table_name == 'esp_mock_attendee_meta' && ! $table_analysis->tableExists( $table_name) ){ -// echo "\r\n\r\nDONT short circuit $sql"; - //it's not altering. it's ok to allow this - return false; - }else{ -// echo "3\r\n\r\n short circuit:$sql"; - return $short_circuit; - } - } - public function tearDown(){ - //ensure the models aren't stil registered. they should have either been - //deregistered during the test, or not been registered at all - $this->_stop_pretending_addon_hook_time(); - parent::tearDown(); - } -} - -// End of file EE_Register_Model_Test.php -// Location: \tests\testcases\core\libraries\plugin_api\EE_Register_Model_Extensions_Test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/plugin_api/EE_Register_Model_Test.php b/tests/testcases/core/libraries/plugin_api/EE_Register_Model_Test.php deleted file mode 100644 index c5dd93ff8d1..00000000000 --- a/tests/testcases/core/libraries/plugin_api/EE_Register_Model_Test.php +++ /dev/null @@ -1,123 +0,0 @@ -_reg_args = array( - 'model_paths' => array(EE_MOCKS_DIR . 'core/db_models/'), - 'class_paths' => array(EE_MOCKS_DIR . 'core/db_classes/'), - ); - $this->_model_group = 'Mock'; - parent::__construct($name, $data, $dataName); - } - - - - public function setUp() - { - parent::setUp(); - $this->_stop_pretending_addon_hook_time(); - // EE_System::instance()->load_core_configuration(); - } - - - - //test registering a bare minimum addon, and then deregistering it - function test_register_mock_model_fail() - { - //we're registering the addon WAAAY after EE_System has set thing up, so - //registering this first time should throw an E_USER_NOTICE - $this->assertArrayDoesNotContain('EEM_Mock', EE_Registry::instance()->non_abstract_db_models); - $this->assertArrayDoesNotContain('EEM_Mock', EE_Registry::instance()->models); - try { - EE_Register_Model::register($this->_model_group, $this->_reg_args); - $this->fail('We should have had a warning saying that we are setting up the ee addon at the wrong time'); - } catch (PHPUnit_Framework_Error_Notice $e) { - $this->assertTrue(true); - } - EE_System::instance()->load_core_configuration(); - $this->assertArrayDoesNotContain('EEM_Mock', EE_Registry::instance()->non_abstract_db_models); - $this->assertArrayDoesNotContain('EEM_Mock', EE_Registry::instance()->models); - } - - - - function test_register_mock_addon_fail__bad_parameters() - { - //we're registering the addon with the wrong parameters - $this->_pretend_addon_hook_time(); - $this->assertArrayDoesNotContain('EEM_Mock', EE_Registry::instance()->non_abstract_db_models); - $this->assertArrayDoesNotContain('EEM_Mock', EE_Registry::instance()->models); - try { - EE_Register_Model::register($this->_model_group, array( - 'foobar' => '1.0.0', - 'model_paths' => EE_MOCKS_DIR . 'core/db_models', - 'class_paths' => EE_MOCKS_DIR . 'core/db_classes', - )); - $this->fail('We should have received a warning that the \'plugin_main_file\' is a required argument when registerign an addon'); - } catch (EE_Error $e) { - $this->assertTrue(true); - } - EE_System::instance()->load_core_configuration(); - //check that we didn't actually register the addon - $this->assertArrayDoesNotContain('EEM_Mock', EE_Registry::instance()->non_abstract_db_models); - $this->assertArrayDoesNotContain('EEM_Mock', EE_Registry::instance()->models); - } - - - - function test_register_mock_addon_success() - { - $this->_pretend_addon_hook_time(); - $this->assertArrayDoesNotContain('EEM_Mock', EE_Registry::instance()->non_abstract_db_models); - $this->assertArrayDoesNotContain('EEM_Mock', EE_Registry::instance()->models); - //register it for realz - EE_Register_Model::register($this->_model_group, $this->_reg_args); - EE_System::instance()->load_core_configuration(); - $this->assertArrayContains('EEM_Mock', EE_Registry::instance()->non_abstract_db_models); - $this->assertArrayContains('EEM_Mock', EE_Registry::instance()->models); - //now deregister it - EE_Register_Model::deregister($this->_model_group); - EE_System::instance()->load_core_configuration(); - $this->assertArrayDoesNotContain('EEM_Mock', EE_Registry::instance()->non_abstract_db_models); - $this->assertArrayDoesNotContain('EEM_Mock', EE_Registry::instance()->models); - } - - - - public function tearDown() - { - //ensure the models aren't stil registered. they should have either been - //deregistered during the test, or not been registered at all - $this->assertArrayDoesNotContain('EEM_Mock', EE_Registry::instance()->non_abstract_db_models); - $this->assertArrayDoesNotContain('EEM_Mock', EE_Registry::instance()->models); - $this->_stop_pretending_addon_hook_time(); - parent::tearDown(); - } -} - -// End of file EE_Register_Model_Test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/plugin_api/EE_Register_Payment_Method_Test.php b/tests/testcases/core/libraries/plugin_api/EE_Register_Payment_Method_Test.php deleted file mode 100644 index d4e76a9910e..00000000000 --- a/tests/testcases/core/libraries/plugin_api/EE_Register_Payment_Method_Test.php +++ /dev/null @@ -1,79 +0,0 @@ -_pmt_args = array( - 'payment_method_paths' => - array( - EE_TESTS_DIR . 'mocks/payment_methods/Mock_Onsite', - ), - ); - $this->_pmt_name = 'Mock_Onsite'; - $this->payment_method_manager = LoaderFactory::getLoader()->getShared('EE_Payment_Method_Manager'); - } - - - public function tearDown() - { - parent::tearDown(); - $this->_pmt_args = null; - $this->_pmt_name = null; - $this->payment_method_manager = null; - } - - public function test_register__fail() - { - $this->_stop_pretending_addon_hook_time(); - remove_all_filters('FHEE__EE_Payment_Method_Manager__register_payment_methods__payment_methods_to_register'); - - //first verify it doesn't already exists - $pmt_exists = $this->payment_method_manager->payment_method_type_exists($this->_pmt_name); - $this->assertFalse($pmt_exists); - - //try registering at wrong time - try { - EE_Register_Payment_Method::register($this->_pmt_name, $this->_pmt_args); - $this->fail('We should have had a warning saying that we are setting up the payment methods at the wrong time'); - } catch (PHPUnit_Framework_Error_Notice $e) { - $this->assertTrue(true); - } - } - - public function test_register__success() - { - $this->_pretend_addon_hook_time(); - //double-check no one else is filtering payment method types - remove_all_filters('FHEE__EE_Payment_Method_Manager__register_payment_methods__payment_methods_to_register'); - - //first verify it doesn't already exists - $pmt_exists = $this->payment_method_manager->payment_method_type_exists($this->_pmt_name); - $this->assertFalse($pmt_exists); - - - EE_Register_Payment_Method::register($this->_pmt_name, $this->_pmt_args); - //now check it does exist - $pmt_exists = EE_Payment_Method_Manager::instance()->payment_method_type_exists($this->_pmt_name, true); - $this->assertTrue($pmt_exists); - } -} diff --git a/tests/testcases/core/libraries/rest_api/Capabilities_Test.php b/tests/testcases/core/libraries/rest_api/Capabilities_Test.php deleted file mode 100644 index 97314f3ac88..00000000000 --- a/tests/testcases/core/libraries/rest_api/Capabilities_Test.php +++ /dev/null @@ -1,81 +0,0 @@ -markTestSkipped( - 'Test being run on a version of WP that does not have the REST framework installed' - ); - } - } - - - - /** - * Ensures we can correctly detect when users have partial access - */ - function test_current_user_has_partial_access_to() { - //yes - they can access some generally - //the user has free access to prices - $this->assertTrue( Capabilities::currentUserHasPartialAccessTo( \EE_Registry::instance()->load_model( 'Price' ) ) ); - //although there are some restrictions, the current user can access SOME events - $this->assertTrue( Capabilities::currentUserHasPartialAccessTo( \EE_Registry::instance()->load_model( 'Event' ) ) ); - //yes - they can access this field specifically sometimes - $this->assertTrue( Capabilities::currentUserHasPartialAccessTo( \EE_Registry::instance()->load_model( 'Event' ), \EEM_Base::caps_read, 'EVT_wp_user' ) ); - //no - no they can never access it - } - - /** - * Makes sure that we are able to filter out inaccessible items in the entity correctly - * (and that related items taht are included are left as-is) - * @group now - */ - function test_filter_out_inaccessible_entity_fields() { - $e = $this->new_model_obj_with_dependencies( 'Event' ); - $entity = $e->model_field_array(); - $entity[ 'datetimes' ] = array( array( 'DTT_ID' => 12 ) ); - $filtered_entity = Capabilities::filterOutInaccessibleEntityFields( - $entity, - \EE_Registry::instance()->load_model( 'Event' ), - \EEM_Base::caps_read, - new ModelVersionInfo( '4.8.29' ) - ); - //the filtered entity shouldn't have had EVT_desc raw - $this->assertFalse( - isset( $filtered_entity['EVT_desc'] ) - && is_array( $filtered_entity['EVT_desc'] ) - && isset( $filtered_entity['EVT_desc']['raw'] ) - ); - //the filtered entity should have had EVT_desc rendered - $this->assertFalse( - isset( $filtered_entity['EVT_desc'] ) - && is_array( $filtered_entity['EVT_desc'] ) - &&isset( $filtered_entity['EVT_desc']['rendered'] ) - ); - } - - /** - * placeholder because other tests have been at least temporarily removed - */ - function test_nothing(){ - $this->assertTrue(true); - } -} - -// End of file EE_REST_API_Capabilities_Test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/rest_api/ModelDataTranslatorTest.php b/tests/testcases/core/libraries/rest_api/ModelDataTranslatorTest.php deleted file mode 100644 index e11e94c2e62..00000000000 --- a/tests/testcases/core/libraries/rest_api/ModelDataTranslatorTest.php +++ /dev/null @@ -1,1094 +0,0 @@ -assertEquals( - $expected_unixtimestamp, - ModelDataTranslator::prepareFieldValueFromJson( - new EE_Datetime_Field( - 'post_date', - esc_html__('Date/Time Event Created', 'event_espresso'), - false, - EE_Datetime_Field::now - ), - $timestamp, - '4.8.36', - $timezone_string - ) - ); - } - - - /** - * @dataProvider invalidTimestampDataProvider - * @expectedException EventEspresso\core\libraries\rest_api\RestException - * @expectedExceptionCode 400 - * @throws DomainException - * @throws EE_Error - * @throws InvalidArgumentException - * @throws RestException - * @throws Exception - * @group 11368 - */ - public function testIncomingInvalidTimestamp($timestamp, $timezone) - { - ModelDataTranslator::prepareFieldValueFromJson( - new EE_Datetime_Field( - 'post_date', - esc_html__('Date/Time Event Created', 'event_espresso'), - false, - EE_Datetime_Field::now - ), - $timestamp, - $timezone - ); - } - - - public function testPrepareQueryParamsForRestApi() - { - $mysql_date = '2015-01-01 00:00:00'; - $statuses_in_query = array( - EEM_Registration::status_id_cancelled, - EEM_Registration::status_id_declined, - ); - $model_query = array( - array( - 'STS_ID' => array( - 'IN', - $statuses_in_query, - ), - 'REG_date' => strtotime($mysql_date), - 'REG_deleted' => false, - ), - 'limit' => 10, - ); - $rest_query = ModelDataTranslator::prepareQueryParamsForRestApi($model_query, EEM_Registration::instance()); - //assert the reg date matches and is in the right format - $this->assertArrayHasKey('where', $rest_query); - $this->assertArrayHasKey('REG_date', $rest_query['where']); - $this->assertEquals(strtotime($mysql_date), rest_parse_date($rest_query['where']['REG_date'])); - //assert statuses got translated - $this->assertArrayHasKey('STS_ID', $rest_query['where']); - $this->assertEquals($statuses_in_query, $rest_query['where']['STS_ID'][1]); - //assert limit got translated - $this->assertArrayHasKey('limit', $rest_query); - $this->assertEquals(10, (int)$rest_query['limit']); - //assert booleans correctly translated - $this->assertArrayHasKey('REG_deleted', $rest_query['where']); - $this->assertEquals(false, $rest_query['where']['REG_deleted']); - } - - /** - * @group private-1 - */ - public function testPrepareConditionsQueryParamsForModelsUnprivilegedUseOfPassword() - { - $this->setExceptionExpected(RestException::class); - // you can't filter by password unless you're an admin - ModelDataTranslator::prepareConditionsQueryParamsForModels( - array( - 'password' => 'imahacker' - ), - EEM_Event::instance(), - '4.8.36' - ); - } - - /** - * @group private-1 - */ - public function testPrepareConditionsQueryParamsForModelsPrivilegedUseOfPassword() - { - // you can't filter by password unless you're an admin - $this->authenticate_as_admin(); - $password = 'imanadmin'; - $query_params = ModelDataTranslator::prepareConditionsQueryParamsForModels( - array( - 'password' => $password - ), - EEM_Event::instance(), - '4.8.36' - ); - $this->assertEquals( - $query_params['password'], - $password - ); - } - - - - /** - * Verifies prepare_conditions_query_params_for_models works properly, - * especially with datetimes which can be in UTC or local time - */ - public function testPrepareConditionsQueryParamsForModels__gmtDatetimes() - { - $data_translator = new ModelDataTranslator(); - $gmt_offsets = array(-12, -10.5, -9, -7.5, -6, -4.5, -3, -1.5, 0, 1.5, 3, 4.5, 6, 7.5, 9, 10.5, 12); - foreach ($gmt_offsets as $gmt_offset) { - //set the offset - update_option('gmt_offset', $gmt_offset); - //set the current time from our timezone helper to more closely mimic how dates and times pass through our - //model. We can't use WP's `current_time` because wp ALWAYS uses offset directly if its present whereas EE - //tries to coerce a closest matching timezone string for "invalid" offsets (PHP version < 5.6). - $datetime = new DateTime('now', new DateTimeZone( - EEH_DTT_Helper::get_timezone_string_from_gmt_offset($gmt_offset) - )); - $now_local_time = $datetime->format(EE_Datetime_Field::mysql_timestamp_format); - $now_utc_time = current_time('mysql', true); - //should always be not equal except when offset is 0 - if ($gmt_offset !== 0) { - $this->assertNotEquals($now_local_time, $now_utc_time, sprintf('For gmt offset %d', $gmt_offset)); - } else { - $this->assertEquals($now_local_time, $now_utc_time); - } - $model_data = $data_translator::prepareConditionsQueryParamsForModels( - array( - 'EVT_created' => mysql_to_rfc3339($now_local_time), - 'EVT_modified_gmt' => mysql_to_rfc3339($now_utc_time), - ), - \EEM_Event::instance(), - '4.8.36' - ); - //verify the model data being inputted is in UTC - $this->assertDateWithinOneMinute($now_utc_time, date('Y-m-d H:i:s', $model_data['EVT_created']), 'Y-m-d H:i:s'); - //NOT in local time - $this->assertNotEquals( - $now_local_time, - $model_data['EVT_created'], - sprintf('For gmt offset %d', $gmt_offset) - ); - //notice that there's no "_gmt" on EVT_modified. That's (currently at least) - //not a real model field. It just indicates to treat the time already being in UTC - $this->assertEquals($now_utc_time, date('Y-m-d H:i:s', $model_data['EVT_modified'])); - } - } - - - - public function testIsGmtDateFieldName__success() - { - $this->assertTrue(ModelDataTranslator::isGmtDateFieldName('Event.EVT_created_gmt')); - } - - - - public function testIsGmtDateFieldName__fail() - { - $this->assertFalse(ModelDataTranslator::isGmtDateFieldName('Event.EVT_created')); - } - - - - public function testIsGmtDateFieldName__failTinyInput() - { - $this->assertFalse(ModelDataTranslator::isGmtDateFieldName('foo')); - } - - - - public function testRemoveGmtFromFieldName() - { - $this->assertEquals( - 'Event.EVT_created', - ModelDataTranslator::removeGmtFromFieldName('Event.EVT_created_gmt')); - } - - - - public function testRemoveGmtFromFieldName__noGmtAnyways() - { - $this->assertEquals( - 'Event.EVT_created', - ModelDataTranslator::removeGmtFromFieldName('Event.EVT_created')); - } - - - - /** - * @return array first item is the expected value, 2nd is the input, 3rd is the field object to use - */ - public function dataProviderForTestPrepareFieldValueFromJsonOk() - { - $serialized_field = new EE_Maybe_Serialized_Simple_HTML_Field('whatever', 'Whatever', true); - $bool_field = new EE_Boolean_Field('whatever2', 'whatever2', true); - return array( - ['1', '1', $serialized_field], - ['stringy', 'stringy', $serialized_field], - [['foo' => 'bar'], ['foo' => 'bar'], $serialized_field], - [false, 'false', $bool_field], - [false, 0, $bool_field], - [true, 'true', $bool_field], - [true, 1, $bool_field], - ); - } - - - - /** - * @dataProvider dataProviderForTestPrepareFieldValueFromJsonOk - * @param mixed $expected_result - * @param mixed $inputted_json_value - * @param EE_Model_Field_Base $field_obj - * @group 9222 - */ - public function testPrepareFieldValueFromJsonOk( - $expected_result, - $inputted_json_value, - EE_Model_Field_Base $field_obj - ) { - $this->assertEquals( - $expected_result, - ModelDataTranslator::prepareFieldValueFromJson( - $field_obj, - $inputted_json_value, - '4.8.36' - ) - ); - } - - - - /** - * @return array where the first item is value that would be retrieved from the request which should throw an - * exception. The 2nd item is an EE_Model_Field_Base child - */ - public function dataProviderForTestPrepareFieldValueFromJsonBad() - { - $serializable_field = new EE_Maybe_Serialized_Simple_HTML_Field('whatever', 'Whatever', true); - $serializable_field->_construct_finalize('Foobar', 'test_serialized_field','Foobar'); - $text_field = new EE_Plain_Text_Field('whatever', 'whatever', true); - $text_field->_construct_finalize('Foobar', 'test_text_field','Foobar'); - return array( - array('s:6:"foobar";', $serializable_field),//that's a serialized string alright! - array('O:4:"Evil":0:{}', $serializable_field),//that's a string with a serialized object of class "Evil" - array(array('s:6:"foobar";'), $serializable_field),//that's an array with a serialized string in it - array(array('s:6:"foobar";' => 1), $serializable_field),//that's an array with a serialized string as a key - array('O:4:"Evil":0:{}', $text_field),//double-check we don't even accept serialized text even on normal - // text fields. Theoretically these won't get unserialized, but I don't see much need for anyone to ever - // submit this kind of malicious junk, and having them sit around in our DB is dangerous - array( - array( - 'error_code' => 'php_object_not_return', - 'error_message' => esc_html__( - 'The value of this field in the database is a PHP object, which can\'t be represented in JSON.', - 'event_espresso' - ) - ), - $serializable_field - ) - ); - } - - - - /** - * @dataProvider dataProviderForTestPrepareFieldValueFromJsonBad - * @expectedException EventEspresso\core\libraries\rest_api\RestException - * @param mixed $expected_result - * @param mixed $inputted_json_value - * @param EE_Model_Field_Base $field_obj - * @group 9222 - */ - public function testPrepareFieldValueFromJsonBad($inputted_json_value, EE_Model_Field_Base $field_obj) - { - //ok duck and cover! It's gonna blow! - ModelDataTranslator::prepareFieldValueFromJson($field_obj, $inputted_json_value, '4.8.36'); - } - - - - /** - * @return array 1st item is the expected value, 2nd is the input, 3rd is the field object to use - */ - public function dataProviderForTestPrepareFieldValuesForJson() - { - //if we don't have the WP API infrastructure, return a dummy array - //it doesn't have to work because all the tests will be skipped too - if ( ! class_exists( 'WP_Rest_Request' ) ) { - return array( - array() - ); - } - $field = new EE_Maybe_Serialized_Simple_HTML_Field('whatever', 'whatever', true); - $datetime_field = new EE_Datetime_Field('whatever2', 'whatever2', true, EE_Datetime_Field::now); - $error_response = array( - 'error_code' => 'php_object_not_return', - 'error_message' => esc_html__( - 'The value of this field in the database is a PHP object, which can\'t be represented in JSON.', - 'event_espresso' - ) - ); - $datetime_field_obj = EE_Registry::instance()->load_model('Datetime')->field_settings_for('DTT_EVT_start'); - return array( - array( - array('foo' => 'bar'), - array('foo' => 'bar'), - $field) - , - array( - 1, - 1, - $field - ), - array( - 'stringy', - 'stringy', - $field - ), - array( - '2016-01-03T00:00:00', - new \EventEspresso\core\domain\entities\DbSafeDateTime( - '2016-01-03 00:00:00', - new DateTimeZone('UTC') - ), - $datetime_field, - ), - array( - $error_response, - new stdClass(), - $field - ), - array( - array('obj' => $error_response), - array('obj' => new stdClass()), - $field - ), - array( - $error_response, - @unserialize('O:6:"Foobar":0:{}'), - $field - ), - 'datetime_object_in_default_timezone' => array( - mysql_to_rfc3339(current_time('mysql')), - new DateTime('now'), - $datetime_field_obj, - ), - 'unix_timestamp_in_default_timezone' => array( - mysql_to_rfc3339(date(EE_Datetime_Field::mysql_timestamp_format, 946782245)), - 946782245, - $datetime_field_obj, - ), - 'unix_timestamp_STRING_in_default_timezone' => array( - mysql_to_rfc3339(date(EE_Datetime_Field::mysql_timestamp_format, 946782245)), - '946782245', - $datetime_field_obj, - ), - 'unix_timestamp_FLOAT_in_default_timezone' => array( - mysql_to_rfc3339(date(EE_Datetime_Field::mysql_timestamp_format, 946782245)), - (float)946782245, - $datetime_field_obj, - ), - 'null_datetime' => array( - '', - null, - $datetime_field_obj, - ), - 'mysql_in_default_timezone' => array( - mysql_to_rfc3339('2000-01-02 03:04:05'), - '2000-01-02 03:04:05', - $datetime_field_obj, - ), - 'datetime_object_in_different_timezone' => array( - mysql_to_rfc3339('2000-01-02 03:04:05'), - new DateTime('2000-01-02 03:04:05', new DateTimeZone('America/Vancouver')), - $datetime_field_obj, - 'America/Vancouver', - ), - //the input is a unix timestamp (in GMT) - //the result should be a RFC3339 string also in GMT - 'unix_timestamp_in_different_timezone' => array( - mysql_to_rfc3339('2000-01-02 03:04:05'), - 946782245, - $datetime_field_obj, - 'America/Vancouver', - ), - //so the input is for 3am Vancouver time, and the output should be too - 'mysql_datetime_in_different_timezone' => array( - mysql_to_rfc3339('2000-01-02 03:04:05'), - '2000-01-02 3:04:05', - $datetime_field_obj, - 'America/Vancouver', - ), - ); - } - - - - /** - * @group 9222 - * @dataProvider dataProviderForTestPrepareFieldValuesForJson - * @param $expected - * @param $input - * @param EE_Model_Field_Base $field_obj - */ - public function testPrepareFieldValuesForJson($expected, $input, $field_obj) - { - if ($field_obj instanceof EE_DateTime_Field && ! empty($expected)) { - $this->assertDateWithinOneMinute( - $expected, - ModelDataTranslator::prepareFieldValuesForJson($field_obj, $input, '4.8.36'), - 'Y-m-d\TH:i:s' - ); - } else { - $this->assertEquals( - $expected, - ModelDataTranslator::prepareFieldValuesForJson($field_obj, $input, '4.8.36') - ); - } - } - - - - /** - * @return array { - * @type array $0 input - * @type string $1 the model's name - * @type boolean $2 whether to consider this data as if it's being used for writing, or not - */ - public function dataProviderForTestPrepareConditionsQueryParamsForModelsBad() - { - return array( - 'array isn\'t numerically indexed' => array( - array( - 'EVT_ID' => array( - 'what_is_this_key_doing_here' => 'its_borked' - ) - ), - 'Event', - false - ), - 'invalid key while reading' => array( - array( - 'invalid_key' => 'whatever' - ), - 'Event', - false - ), - 'invalid key while writing' => array( - array( - 'invalid_key' => 'whatever' - ), - 'Registration', - true - ), - 'logic parameter while writing' => array( - array( - 'OR' => array( - 'EVT_name' => 'party' - ) - ), - 'Event', - true - ), - 'nested invalid key while reading' => array( - array( - 'or*allyourbase' => array( - 'EVT_ID' => 123, - 'invalid_nested_key' => 'foobar' - ) - ), - 'Event', - false - ), - 'too few arguments for in operator' => array( - array( - 'EVT_ID' => array('IN') - ), - 'Event', - false - ), - 'too many arguments for in operator' => array( - array( - 'EVT_ID' => array('IN', array('thingy'),'what_is_this_doing_here') - ), - 'Event', - false - ), - 'too few arguments for between operator' => array( - array( - 'EVT_created' => array( - 'BETWEEN', - '2017-01-01T00:00:00' - ) - ), - 'Event', - false - ), - 'between with dates separate instead of in array' => array( - array( - 'EVT_created' => array( - 'between', - '2017-01-01T00:00:00', - '2018-01-01T00:00:00', - ) - ), - 'Event', - false - ), - 'between with too few_dates' => array( - array( - 'EVT_created' => array( - 'between', - array( - '2017-01-01T00:00:00', - ) - ) - ), - 'Event', - false - ), - 'between with too many dates' => array( - array( - 'EVT_created' => array( - 'between', - array( - '2017-01-01T00:00:00', - '2018-01-01T00:00:00', - '2019-01-01T00:00:00', - ) - ) - ), - 'Event', - false - ), - 'too few arguments for like operator' => array( - array( - 'EVT_name' => array( - 'LIKE' - ) - ), - 'Event', - false - ), - 'too many arguments for like operator' => array( - array( - 'EVT_name' => array( - 'LIKE', - 'foobar', - 'something_extra' - ) - ), - 'Event', - false - ), - 'too few arguments for normal operator' => array( - array( - 'EVT_ID' => array( - '>' - ) - ), - 'Event', - false - ), - 'too many arguments for normal operator' => array( - array( - 'EVT_ID' => array( - '<', - 123, - 23452343 - ) - ), - 'Event', - false - ), - 'too many arguments for null operator' => array( - array( - 'EVT_ID' => array( - 'IS_NULL', - 'what_is_this_extra_arg' - ) - ), - 'Event', - false - ), - 'quick syntax two operators' => array( - array( - 'EVT_ID' => array( - 'IN' => '1,2', - '<' => 'huh there shouldnt be two operators!' - ) - ), - 'Event', - false - ), - 'quick syntax too few arguments for between operator with csv' => array( - array( - 'EVT_created' => array( - 'BETWEEN' => '2017-01-01T00:00:00' - ) - ), - 'Event', - false - ), - 'quick syntax too few arguments for between operator with json' => array( - array( - 'EVT_created' => array( - 'BETWEEN' => array( - '2017-01-01T00:00:00' - ) - ) - ), - 'Event', - false - ), - 'quick syntax between with too many dates' => array( - array( - 'EVT_created' => array( - 'between' => - array( - '2017-01-01T00:00:00', - '2018-01-01T00:00:00', - '2019-01-01T00:00:00', - ) - ) - ), - 'Event', - false - ), - 'quick syntax too many arguments for like operator' => array( - array( - 'EVT_name' => array( - 'LIKE' => array( - 'foobar', - 'something_extra' - ) - ) - ), - 'Event', - false - ), - 'quick syntax too many arguments for normal operator' => array( - array( - 'EVT_ID' => array( - '<' => array( - 123, - 23452343 - ) - ) - ), - 'Event', - false - ) - ); - } - - - - /** - * @param array $input array of data sent to REST API - * @param string $model_name eg 'Event' - * @param boolean $writing - * @group 9222 - * @dataProvider dataProviderForTestPrepareConditionsQueryParamsForModelsBad - * @expectedException EventEspresso\core\libraries\rest_api\RestException - */ - public function testPrepareConditionsQueryParamsForModelsBad($input, $model_name, $writing) - { - $model = EE_Registry::instance()->load_model($model_name); - //run for cover! it's going to error! - ModelDataTranslator::prepareConditionsQueryParamsForModels( - $input, - $model, - '4.8.36', - $writing - ); - } - - - - /** - * @return array { - * @type array $0 expected output - * @type array $1 input - * @type string $2 model name, eg 'Event' - * @type boolean $3 whether it's data for writing, or just conditions - */ - public function dataProviderForTestPrepareConditionsQueryParamsForModelsGood() - { - if( ! function_exists('rest_parse_date')){ - return array(); - } - return array( - 'empty'=> array( - array(), - array(), - 'Event', - false - ), - 'simple'=> array( - array('EVT_name' => 'foobar'), - array('EVT_name' => 'foobar'), - 'Event', - false - ), - 'nested logic' => array( - array( - 'or' => array( - 'EVT_desc' => 'foobar', - 'EVT_short_desc' => 'foobar' - ), - 'NOT*' => array( - 'EVT_name' => 'foobar' - ) - ), - array( - 'or' => array( - 'EVT_desc' => 'foobar', - 'EVT_short_desc' => 'foobar' - ), - 'NOT*' => array( - 'EVT_name' => 'foobar' - ) - ), - 'Event', - false - ), - 'between operator' => array( - array( - 'EVT_created' => array( - 'between', - array( - rest_parse_date('2015-01-01 00:00:00'), - rest_parse_date('2016-01-01 00:00:00'), - ), - ), - ), - array( - 'EVT_created' => array( - 'between', - array( - '2015-01-01T00:00:00', - '2016-01-01T00:00:00', - ), - ), - ), - 'Event', - false - ), - 'in operator' => array( - array( - 'TKT_uses' => array( - 'IN', - array( - 12, - 13, - EE_INF - ) - ) - ), - array( - 'TKT_uses' => array( - 'IN', - array( - '12', - '13', - '' - ) - ) - ), - 'Ticket', - false - ), - 'like operator' => array( - array( - 'PAY_details' => array( - 'LIKE', - '%foobar%' - ) - ), - array( - 'PAY_details' => array( - 'LIKE', - '%foobar%' - ) - ), - 'Payment', - false - ), - 'null operator' => array( - array( - 'EVT_name' => array('IS_NULL') - ), - array( - 'EVT_name' => array('IS_NULL') - ), - 'Event', - false - ), - 'variety of operators' => array( - array( - 'RPY_amount' => array( - '<', - 19 - ), - 'REG_ID' => array( - '!=', - 12 - ), - ), - array( - 'RPY_amount' => array( - '<', - '19' - ), - 'REG_ID' => array( - '!=', - '12' - ), - ), - 'Registration_Payment', - false - ), - 'related fields' => array( - array( - 'Ticket.Datetime.DTT_reg_limit' => 12 - ), - array( - 'Ticket.Datetime.DTT_reg_limit' => '12' - ), - 'Registration', - false - ), - 'writing-style test with valid fields' => array( - array( - 'TKT_uses' => EE_INF - ), - array( - 'TKT_uses' => '' - ), - 'Ticket', - true - ), - 'quick syntax with in csv' => array( - array( - 'EVT_ID' => array('IN', array('1','2','3')) - ), - array( - 'EVT_ID' => array( - 'IN' => '1,2,3' - ) - ), - 'Event', - false - ), - 'quick syntax with in json' => array( - array( - 'EVT_ID' => array('IN', array(1,2,3)) - ), - array( - 'EVT_ID' => array( - 'IN' => wp_json_encode(array(1,2,3)) - ) - ), - 'Event', - false - ), - 'quick syntax with between csv' => array( - array( - 'DTT_EVT_start' => array( - 'BETWEEN', - array( - rest_parse_date('2015-01-01 00:02:00'), - rest_parse_date('2015-01-01 00:05:00') - ) - ) - ), - array( - 'DTT_EVT_start' => array( - 'BETWEEN' => '2015-01-01T00:02:00, 2015-01-01T00:05:00' - ) - ), - 'Datetime', - false - ), - 'quick syntax with between json' => array( - array( - 'DTT_EVT_start' => array( - 'BETWEEN', - array( - rest_parse_date('2015-01-01 00:02:00'), - rest_parse_date('2015-01-01 00:05:00') - ) - ) - ), - array( - 'DTT_EVT_start' => array( - 'BETWEEN' => wp_json_encode( - array( - '2015-01-01T00:02:00', - '2015-01-01T00:05:00' - ) - ) - ) - ), - 'Datetime', - false - ), - 'quick syntax with normal' => array( - array( - 'EVT_name' => array( - 'LIKE', - '%foobar%' - ) - ), - array( - 'EVT_name' => array( - 'LIKE' => '%foobar%' - ) - ), - 'Event', - false - ), - 'quick syntax with null' => array( - array( - 'EVT_ID' => array('IS_NULL') - ), - array( - 'EVT_ID' => array( - 'IS_NULL' => true - ) - ), - 'Event', - false - ) - ); - } - - /** - * @param array $expected_output - * @param array $input array of data sent to REST API - * @param string $model_name eg 'Event' - * @param boolean $writing - * @group 9222 - * @dataProvider dataProviderForTestPrepareConditionsQueryParamsForModelsGood - */ - public function testPrepareConditionsQueryParamsForModelsGood( - $expected_output, - $input, - $model_name, - $writing - ) { - $model = EE_Registry::instance()->load_model($model_name); - $this->assertEquals( - $expected_output, - ModelDataTranslator::prepareConditionsQueryParamsForModels( - $input, - $model, - '4.8.36', - $writing - ) - ); - } - - /** - * Reproduced issue https://events.codebasehq.com/projects/event-espresso/tickets/10869 - * and https://events.codebasehq.com/projects/event-espresso/tickets/10858 by changing - * the site date format to 'd/m/Y' - */ - public function testPrepareFieldValueForJsonUnusualDateFormat(){ - $field_obj = EE_Registry::instance()->load_model('Datetime')->field_settings_for('DTT_EVT_start'); - if($field_obj instanceof EE_Datetime_Field){ - //change the date format because it used to make this not work - $field_obj->set_date_format('d/m/Y'); - //the default time format excludes seconds, - $field_obj->set_time_format('g:i a s'); - } - $current_time_mysql = current_time('mysql'); - $datetime = new DateTime( $current_time_mysql ); - $formats = EE_Registry::instance()->load_model('Datetime')->get_formats_for('DTT_EVT_start'); - $date_in_site_format = $datetime->format(implode(' ', $formats)); - $this->assertEquals( - mysql_to_rfc3339($current_time_mysql), - ModelDataTranslator::prepareFieldValueForJson( - $field_obj, - $date_in_site_format, - '4.8.36' - ) - ); - } - - - - /** - * If you pass in an empty string, it's the same as using the current time in the field's timezone - * @group 10869 - */ - public function testPrepareFieldValueForJsonPassingInEmptyString(){ - $field_obj = EE_Registry::instance()->load_model('Datetime')->field_settings_for('DTT_EVT_start'); - $field_obj->set_timezone('America/Vancouver'); - update_option('timezone_string', 'America/Vancouver'); - $this->assertDateWithinOneMinute( - mysql_to_rfc3339(current_time('mysql'), false), - ModelDataTranslator::prepareFieldValueForJson( - $field_obj, - '', - '4.8.36' - ), - 'Y-m-d\TH:i:s' - ); - } - -} - -// Location: tests/testcases/core/libraries/rest_api/ModelDataTranslator_Test.php diff --git a/tests/testcases/core/libraries/rest_api/Model_Version_Info_Test.php b/tests/testcases/core/libraries/rest_api/Model_Version_Info_Test.php deleted file mode 100644 index d8e0571fd9a..00000000000 --- a/tests/testcases/core/libraries/rest_api/Model_Version_Info_Test.php +++ /dev/null @@ -1,91 +0,0 @@ -markTestSkipped( - 'Test being run on a version of WP that does not have the REST framework installed' - ); - } - } - - /** - * pretend currently we're on 4.9, but they send in a request for 4.8. So this - * shoudl return all the changes from 4.9 - */ - function test_get_all_model_changes_between_requested_version_and_current__req_46_cur_49() { - $this->_pretend_current_version_49(); - $model_info = new ModelVersionInfo( '4.8.29' ); - $changes = $model_info->modelChangesBetweenRequestedVersionAndCurrent(); - $this->assertArrayNotHasKey( '4.8.29', $changes ); - } - - /** - * @group ignore - * needs to be updated once there is a new field added - */ - function test_fields_on_model_in_this_version__no_reg_paid_in_46() { - $this->_pretend_added_field_onto_registration_model(); - $this->_pretend_current_version_49(); - $model_info = new ModelVersionInfo( '4.6' ); - $fields_on_reg = $model_info->fieldsOnModelInThisVersion( \EEM_Registration::instance() ); - $this->assertArrayNotHasKey( 'REG_paid', $fields_on_reg ); - } - - /** - * @group ignore - * needs to be updated once there is a new field added - */ - function test_fields_on_model_in_this_version__has_reg_paid_in_47() { - $this->_pretend_added_field_onto_registration_model(); - $this->_pretend_current_version_49(); - $model_info = new ModelVersionInfo( '4.7' ); - $fields_on_reg = $model_info->fieldsOnModelInThisVersion( \EEM_Registration::instance() ); - $this->assertArrayHasKey( 'REG_paid', $fields_on_reg ); - } - - protected function _pretend_current_version_49(){ - add_filter( 'FHEE__EED_Core_REST_API__core_version', array( $this, '_tell_EED_Core_REST_API_current_version_is_49' ) ); - } - - /** - * Used on a filter to make the API think core's version is 4.8 - * @param type $current_version - * @return string - */ - public function _tell_EED_Core_REST_API_current_version_is_49( $current_version ) { - return '4.9.2'; - } - - protected function _pretend_added_field_onto_registration_model(){ - add_filter( 'FHEE__EEM_Registration__construct__fields', array( $this, '_add_reg_paid_field' ) ); - \EEM_Registration::reset(); - } - - public function _add_reg_paid_field( $reg_fields ) { - if( ! isset( $reg_fields[ 'Registration'][ 'REG_paid' ] ) ) { - $reg_fields[ 'Registration'][ 'REG_paid' ] = new \EE_Money_Field( 'REG_paid', __( 'Amount paid for registration', 'event_espresso' ), true ); - } - return $reg_fields; - } -} - -// End of file EE_REST_API_Model_Version_Info_Test.php \ No newline at end of file diff --git a/tests/testcases/core/libraries/rest_api/controllers/Checkin_Test.php b/tests/testcases/core/libraries/rest_api/controllers/Checkin_Test.php deleted file mode 100644 index 1f7f226c060..00000000000 --- a/tests/testcases/core/libraries/rest_api/controllers/Checkin_Test.php +++ /dev/null @@ -1,192 +0,0 @@ -markTestSkipped( - 'Test being run on a version of WP that does not have the REST framework installed' - ); - } - } - - - - - /* - * we're doing stuff that we know will add error notices, so we don't care - * if there are errors (that's part of these tests) - */ - public function tearDown() - { - \EE_Error::reset_notices(); - parent::tearDown(); - } - - - - - /** - * @param int $reg_id - * @param int $dtt_id - * @return \WP_REST_Request - */ - protected function _create_checkin_request($reg_id, $dtt_id) - { - $req = new \WP_REST_Request( - 'POST', - '/' . \EED_Core_Rest_Api::ee_api_namespace . '4.8.33/registrations/' . $reg_id . '/toggle_checkin_for_datetime/' . $dtt_id - ); - $req->set_url_params( - array( - 'REG_ID' => $reg_id, - 'DTT_ID' => $dtt_id, - ) - ); - $req->set_body_params( - array( - 'force' => "false", - ) - ); - return $req; - } - - - - public function test_handle_checkin__success() - { - $checkins_before = \EEM_Checkin::instance()->count(); - global $current_user; - $current_user = $this->wp_admin_with_ee_caps(); - $reg = $this->new_model_obj_with_dependencies('Registration', array('STS_ID' => \EEM_Registration::status_id_approved)); - $dtt = $this->new_model_obj_with_dependencies('Datetime'); - $dtt->_add_relation_to($reg->get('TKT_ID'), 'Ticket'); - $response = rest_do_request($this->_create_checkin_request($reg->ID(), $dtt->ID())); - $data = $response->get_data(); - $this->assertEquals($checkins_before + 1, \EEM_Checkin::instance()->count()); - - $this->assertTrue(isset($data['CHK_ID'])); - $checkin_obj = \EEM_Checkin::instance()->get_one_by_ID($data['CHK_ID']); - $this->assertEquals($reg->ID(), $checkin_obj->get('REG_ID')); - $this->assertEquals($dtt->ID(), $checkin_obj->get('DTT_ID')); - $this->assertEquals(true, $data['CHK_in']); - $this->assertDateWithinOneMinute( - mysql_to_rfc3339(date('c')), - $data['CHK_timestamp'], - 'Y-m-d\TH:m:i+' - ); - } - - - - - public function test_handle_checkin__fail_not_approved() - { - $checkins_before = \EEM_Checkin::instance()->count(); - global $current_user; - $current_user = $this->wp_admin_with_ee_caps(); - $reg = $this->new_model_obj_with_dependencies('Registration', array('STS_ID' => \EEM_Registration::status_id_incomplete)); - $dtt = $this->new_model_obj_with_dependencies('Datetime'); - $dtt->_add_relation_to($reg->get('TKT_ID'), 'Ticket'); - $response = rest_do_request($this->_create_checkin_request($reg->ID(), $dtt->ID())); - $this->assertEquals($checkins_before, \EEM_Checkin::instance()->count()); - $data = $response->get_data(); - $this->assertTrue(isset($data['code'])); - $this->assertEquals('rest_toggle_checkin_failed', $data['code']); - $this->assertTrue(isset($data['additional_errors'])); - $this->assertFalse(empty($data['additional_errors'][0]['message'])); - } - - - - - //doesnt have permission - public function test_handle_checkin__fail_no_permitted() - { - //notice that we have NOT logged in! - $checkins_before = \EEM_Checkin::instance()->count(); - $reg = $this->new_model_obj_with_dependencies('Registration', array('STS_ID' => \EEM_Registration::status_id_incomplete)); - $dtt = $this->new_model_obj_with_dependencies('Datetime'); - $dtt->_add_relation_to($reg->get('TKT_ID'), 'Ticket'); - $response = rest_do_request($this->_create_checkin_request($reg->ID(), $dtt->ID())); - $this->assertEquals($checkins_before, \EEM_Checkin::instance()->count()); - $data = $response->get_data(); - $this->assertTrue(isset($data['code'])); - $this->assertEquals('rest_user_cannot_toggle_checkin', $data['code']); - } - - - - - //regsitered too many times - public function test_handle_checkin__fail_checked_in_too_many_times() - { - global $current_user; - $current_user = $this->wp_admin_with_ee_caps(); - $tkt = $this->new_model_obj_with_dependencies('Ticket', array('TKT_uses' => 1)); - $reg = $this->new_model_obj_with_dependencies( - 'Registration', - array( - 'STS_ID' => \EEM_Registration::status_id_approved, - 'TKT_ID' => $tkt->ID(), - ) - ); - $dtt = $this->new_model_obj_with_dependencies('Datetime'); - $dtt->_add_relation_to($reg->get('TKT_ID'), 'Ticket'); - $dtt2 = $this->new_model_obj_with_dependencies('Datetime'); - $dtt2->_add_relation_to($reg->get('TKT_ID'), 'Ticket'); - //create a previous checkin entry, so the reg shouldn't be allowed to checkin more - $old_checkin = $this->new_model_obj_with_dependencies( - 'Checkin', - array( - 'REG_ID' => $reg->ID(), - 'DTT_ID' => $dtt->ID(), - 'CHK_in' => true, - ) - ); - $checkins_before = \EEM_Checkin::instance()->count(); - $response = rest_do_request($this->_create_checkin_request($reg->ID(), $dtt2->ID())); - $this->assertEquals($checkins_before, \EEM_Checkin::instance()->count()); - $data = $response->get_data(); - $this->assertTrue(isset($data['code'])); - $this->assertEquals('rest_toggle_checkin_failed_not_forceable', $data['code']); - $this->assertTrue(isset($data['additional_errors'])); - $this->assertFalse(empty($data['additional_errors'][0]['message'])); - } - - - - - //registered too many times but force it - public function test_handle_checkin__success_only_because_forced() - { - global $current_user; - $current_user = $this->wp_admin_with_ee_caps(); - $reg = $this->new_model_obj_with_dependencies( - 'Registration', - array( - 'STS_ID' => \EEM_Registration::status_id_cancelled, - ) - ); - $dtt = $this->new_model_obj_with_dependencies('Datetime'); - $dtt->_add_relation_to($reg->get('TKT_ID'), 'Ticket'); - $checkins_before = \EEM_Checkin::instance()->count(); - $req = $this->_create_checkin_request($reg->ID(), $dtt->ID()); - $req->set_body_params(array('force' => "true")); - $response = rest_do_request($req); - $this->assertEquals($checkins_before + 1, \EEM_Checkin::instance()->count()); - } -} - diff --git a/tests/testcases/core/libraries/rest_api/controllers/Config_Test.php b/tests/testcases/core/libraries/rest_api/controllers/Config_Test.php deleted file mode 100644 index 880f7ee54b1..00000000000 --- a/tests/testcases/core/libraries/rest_api/controllers/Config_Test.php +++ /dev/null @@ -1,34 +0,0 @@ -admin->affiliate_id = 'star_wars'; - - global $current_user; - $current_user = $this->wp_admin_with_ee_caps(); - - $req = new WP_REST_Request( 'GET', '/' . \EED_Core_Rest_Api::ee_api_namespace . '4.8.36/config'); - - $response = rest_do_request($req); - - $data = json_decode(wp_json_encode($response->get_data()),true); - $this->assertEquals(EE_Config::instance()->admin->affiliate_id, $data['admin']['affiliate_id'] ); - } - -} - diff --git a/tests/testcases/core/libraries/rest_api/controllers/ReadProtectedTest.php b/tests/testcases/core/libraries/rest_api/controllers/ReadProtectedTest.php deleted file mode 100644 index 631704a7eaa..00000000000 --- a/tests/testcases/core/libraries/rest_api/controllers/ReadProtectedTest.php +++ /dev/null @@ -1,1675 +0,0 @@ -new_model_obj_with_dependencies( - 'Event', - array( - 'password' => $password, - 'status' => EEM_Event::post_status_publish, - 'EVT_desc' => $post_body, - ) - ); - return $event; - } - - /** - * test get_all on a model with a password field, with no password provided. - * @since 4.9.74.p - */ - public function testGetAllNoPassword() - { - $event = $this->setupPasswordProtectedEvent(); - - $req = new WP_REST_Request('GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events'); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertTrue(is_array($response_data)); - $this->assertEquals($event->ID(), $response_data[0]['EVT_ID']); - // note that this event was password-protected - $this->assertEquals('', $response_data[0]['EVT_desc']['rendered']); - $this->assertFalse(isset($response_data[0]['EVT_desc']['raw'])); - } - - /** - * Asserts that _protected can be excluded using "include" parameter (if using that, you probably wanted - * to cut down on the response size). - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testGetAllNoPasswordDontIncludeProtectedProperty() - { - $event = $this->setupPasswordProtectedEvent(); - - $req = new WP_REST_Request('GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events'); - $req->set_query_params( - array( - 'include' => 'EVT_desc' - ) - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertTrue(is_array($response_data)); - $this->assertEquals($event->ID(), $response_data[0]['EVT_ID']); - // note that this event was password-protected - $this->assertEquals('', $response_data[0]['EVT_desc']['rendered']); - $this->assertArrayNotHasKey( - '_protected', - $response_data[0] - ); - } - - /** - * Asserts that _protected can be excluded using "include" parameter (if using that, you probably wanted - * to cut down on the response size). - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testGetAllNoPasswordIncludeSpecificFieldsAndProtectedProperty() - { - $event = $this->setupPasswordProtectedEvent(); - - $req = new WP_REST_Request('GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events'); - $req->set_query_params( - array( - 'include' => 'EVT_desc, _protected' - ) - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertTrue(is_array($response_data)); - $this->assertEquals($event->ID(), $response_data[0]['EVT_ID']); - // note that this event was password-protected - $this->assertEquals('', $response_data[0]['EVT_desc']['rendered']); - $this->assertArrayHasKey( - '_protected', - $response_data[0] - ); - $this->assertEquals( - array( - 'EVT_desc' - ), - $response_data[0]['_protected'] - ); - } - - /** - * Slight variation on the previous test, just verifying password protected content is even protected from - * admins because that's what the WP API does... although no guanratee this won't change. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - public function getAllNoPasswordAsAdmin() - { - $event = $this->setupPasswordProtectedEvent(); - // now don't provide the password, but authenticate - // WP core currently actually hides this content from admins too - // in the REST API, and web front-end. So we do too. - $this->authenticate_as_admin(); - $response = rest_do_request( - new WP_REST_Request('GET', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $event->ID()) - ); - $this->assertInstanceOf('WP_REST_Response', $response); - $data = $response->get_data(); - $this->assertEquals( - '', - $data['EVT_desc']['rendered'] - ); - } - - /** - * Get all events but provide the wrong password. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - public function testGetAllWrongPassword() - { - $event = $this->setupPasswordProtectedEvent(); - $req = new WP_REST_Request('GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events'); - $req->set_query_params( - array( - 'password' => $event->get('password') . ' made incorrect!' - ) - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertTrue(is_array($response_data)); - $this->assertEquals('rest_post_incorrect_password', $response_data['code']); - } - - /** - * Get all events, but with the correct password. There is only one password so it's fine. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - public function testGetAllCorrectPassword() - { - $event = $this->setupPasswordProtectedEvent(); - $req = new WP_REST_Request('GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events'); - $req->set_query_params( - array( - 'password' => $event->get('password') - ) - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertTrue(is_array($response_data)); - $this->assertEquals($event->ID(), $response_data[0]['EVT_ID']); - // note that this event was password-protected - $this->assertEquals($event->get_pretty('EVT_desc'), $response_data[0]['EVT_desc']['rendered']); - } - - /** - * Get all events, using the correct password BUT multiple events are returned, some with a different password. - * Seeing how we want to avoid brute force attack trying to guess a post password, this is denied. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - public function testGetAllCorrectAndWrongPassword() - { - $event = $this->setupPasswordProtectedEvent(); - $event2 = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'password' => '', - 'status' => EEM_Event::post_status_publish, - ) - ); - $req = new WP_REST_Request('GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events'); - $req->set_query_params( - array( - 'password' => $event->get('password') - ) - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertTrue(is_array($response_data)); - // the password was incorrect for one of the selected events, so they get an error... - // if you provide a password, you need to also know which events you think its the password for. - $this->assertEquals('rest_post_incorrect_password', $response_data['code']); - } - - - /** - * Get one password-protected event, without providing the password. - * @since 4.9.74.p - */ - public function testGetOneNoPassword() - { - $event = $this->setupPasswordProtectedEvent(); - - $req = new WP_REST_Request('GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $event->ID()); - $req->set_url_params( - array( - 'id' => $event->ID(), - ) - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertTrue(is_array($response_data)); - $this->assertEquals($event->ID(), $response_data['EVT_ID']); - // note that this event was password-protected - $this->assertEquals('', $response_data['EVT_desc']['rendered']); - $this->assertFalse(isset($response_data['EVT_desc']['raw'])); - } - - // Get one event with the wrong password. - public function testGetOneWrongPassword() - { - $event = $this->setupPasswordProtectedEvent(); - $req = new WP_REST_Request('GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $event->ID()); - $req->set_url_params( - array( - 'id' => $event->ID(), - ) - ); - $req->set_query_params( - array( - 'password' => $event->get('password') . ' made incorrect!' - ) - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertTrue(is_array($response_data)); - $this->assertEquals('rest_post_incorrect_password', $response_data['code']); - } - - /** - * Get one event with the correct password. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - public function testGetOneCorrectPassword() - { - $event = $this->setupPasswordProtectedEvent(); - $req = new WP_REST_Request('GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $event->ID()); - $req->set_url_params( - array( - 'id' => $event->ID(), - ) - ); - $req->set_query_params( - array( - 'password' => $event->get('password') - ) - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertTrue(is_array($response_data)); - $this->assertEquals($event->ID(), $response_data['EVT_ID']); - // note that this event was password-protected - $this->assertEquals($event->get_pretty('EVT_desc'), $response_data['EVT_desc']['rendered']); - } - - /** - * Creates two datetimes, the first for a public event, the second for a password-protected event. - * @since 4.9.74.p - * @return EE_Datetime[] first one is for a public event, the second is for a password-protected event. - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - protected function setupPasswordProtectedDatetimes() - { - // create two events, one being password protected - $e_no_password = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'password' => '', - 'status' => EEM_Event::post_status_publish, - 'EVT_desc' => 'no password needed to view this' - )); - $e_with_password = $this->setupPasswordProtectedEvent(); - - // create datetimes for each - $datetime_no_password = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $e_no_password->ID() - ) - ); - $datetime_password = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $e_with_password->ID() - ) - ); - return array($datetime_no_password, $datetime_password); - } - - /** - * Test get_all on a model protected by another model's password field, with no password provided. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - * @group private-1 - */ - public function testGetAllDatetimesForPasswordProtectedEvents() - { - list($datetime_no_password, $datetime) = $this->setupPasswordProtectedDatetimes(); - - //send a request for the two datetimes - $response = rest_do_request( - new WP_REST_Request('GET', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/datetimes') - ); - $this->assertInstanceOf('WP_REST_Response', $response); - $data = $response->get_data(); - - // only the datetime for non-password protected events are visible - $this->assertEquals(1, count($data)); - $this->assertEquals( - $datetime_no_password->ID(), - $data[0]['DTT_ID'] - ); - } - - /** - * Helper method for setting up two tickets, the first for a datetime on a public event, the second for a datetime - * on a password-protected event. - * @since 4.9.74.p - * @return EE_Ticket[]. The first is for a event with no password, the second is for an event that has a password - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - protected function setupPasswordProtectedTickets() - { - list($datetime_no_password, $datetime_password) = $this->setupPasswordProtectedDatetimes(); - $ticket_no_password = $this->new_model_obj_with_dependencies('Ticket'); - $ticket_no_password->_add_relation_to($datetime_no_password->ID(), 'Datetime'); - $ticket_password = $this->new_model_obj_with_dependencies('Ticket'); - $ticket_password->_add_relation_to($datetime_password->ID(), 'Datetime'); - return array($ticket_no_password, $ticket_password); - } - - /** - * Test get_all on a model protected by another model's password field (that's not directly related), - * with no password provided. - * @since 4.9.74.p - * @group private-1 - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - public function testGetAllTicketsForPasswordProtectedEvents() - { - list($ticket_no_password, $ticket) = $this->setupPasswordProtectedTickets(); - - //send a request for the two datetimes - $response = rest_do_request( - new WP_REST_Request('GET', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/tickets') - ); - $this->assertInstanceOf('WP_REST_Response', $response); - $data = $response->get_data(); - - // only the datetime for non-password protected events are visible - $this->assertEquals(1, count($data)); - $this->assertEquals( - $ticket_no_password->ID(), - $data[0]['TKT_ID'] - ); - } - - /** - * Test get_all on a model protected by another model's password field, with the wrong password provided. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - * @group private-1 - */ - public function testGetAllDatetimesForPasswordProtectedEventsWrongPassword() - { - list($datetime_no_password, $datetime) = $this->setupPasswordProtectedDatetimes(); - - //send a request for the two datetimes - $request = new WP_REST_Request('GET', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/datetimes'); - $request->set_query_params( - array( - 'password' => $datetime->event()->get('password') . ' made incorrect' - ) - ); - $response = rest_do_request($request); - $response_data = $response->get_data(); - $this->assertTrue(is_array($response_data)); - $this->assertEquals('rest_post_incorrect_password', $response_data['code']); - } - - /** - * Test get_all on a model protected by another model's password field, with the correct password provided. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - * @group private-1 - */ - public function testGetAllDatetimesForPasswordProtectedEventsCorrectPassword() - { - list($datetime_no_password, $datetime) = $this->setupPasswordProtectedDatetimes(); - - $request = new WP_REST_Request('GET', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/datetimes'); - $request->set_query_params( - array( - 'password' => $datetime->event()->get('password'), - 'where' => array( - 'DTT_ID' => $datetime->ID() - ) - ) - ); - //send a request for the two datetimes - $response = rest_do_request($request); - $this->assertInstanceOf('WP_REST_Response', $response); - $data = $response->get_data(); - - // only the datetime for non-password protected events are visible - $this->assertEquals(1, count($data)); - $this->assertEquals( - $datetime->ID(), - $data[0]['DTT_ID'] - ); - } - - /** - * Test get_all on a model protected by another model's password field, with the correct password provided. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - * @group private-1 - */ - public function testGetAllDatetimesForPasswordProtectedEventsCorrectAndWrongPassword() - { - list($datetime_no_password, $datetime) = $this->setupPasswordProtectedDatetimes(); - - $request = new WP_REST_Request('GET', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/datetimes'); - $request->set_query_params( - array( - 'password' => $datetime->event()->get('password'), - ) - ); - //send a request for the two datetimes, providing the correct password for only one. - $response = rest_do_request($request); - $response_data = $response->get_data(); - $this->assertTrue(is_array($response_data)); - $this->assertEquals('rest_post_incorrect_password', $response_data['code']); - } - - /** - * Test get_one on a model protected by another model's password field, with no password provided. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - * @group private-1 - */ - public function testGetOneDatetimesForPasswordProtectedEvents() - { - list($datetime_no_password, $datetime) = $this->setupPasswordProtectedDatetimes(); - - //send a request for the two datetimes - $request = new WP_REST_Request('GET', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/datetimes/' . $datetime->ID()); - $request->set_url_params( - array( - 'id' => $datetime->ID() - ) - ); - $response = rest_do_request($request); - $response_data = $response->get_data(); - $this->assertTrue(is_array($response_data)); - $this->assertEquals('rest_post_password_required', $response_data['code']); - } - - /** - * Test get_one on a model protected by another model's password field, with the wrong password provided. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - * @group private-1 - */ - public function testGetOneDatetimesForPasswordProtectedEventsWrongPassword() - { - list($datetime_no_password, $datetime) = $this->setupPasswordProtectedDatetimes(); - - //send a request for the two datetimes - $request = new WP_REST_Request('GET', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/datetimes'); - $request->set_url_params( - array( - 'id' => $datetime->ID() - ) - ); - $request->set_query_params( - array( - 'password' => $datetime->event()->get('password') . ' made incorrect' - ) - ); - $response = rest_do_request($request); - $response_data = $response->get_data(); - $this->assertTrue(is_array($response_data)); - $this->assertEquals('rest_post_incorrect_password', $response_data['code']); - } - - /** - * Test get_one on a model protected by another model's password field, with the correct password provided. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - * @group private-1 - */ - public function testGetOneDatetimesForPasswordProtectedEventsCorrectPassword() - { - list($datetime_no_password, $datetime) = $this->setupPasswordProtectedDatetimes(); - - $request = new WP_REST_Request('GET', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/datetimes/' . $datetime->ID()); - $request->set_url_params( - array( - 'id' => $datetime->ID(), - ) - ); - $request->set_query_params( - array( - 'password' => $datetime->event()->get('password'), - ) - ); - //send a request for the two datetimes - $response = rest_do_request($request); - $this->assertInstanceOf('WP_REST_Response', $response); - $data = $response->get_data(); - - $this->assertEquals( - $datetime->ID(), - $data['DTT_ID'] - ); - } - - /** - * Test get_related with a model with a password field, with no password provided. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - * @group private-1 - */ - public function testGetRelatedDatetimesForPasswordProtectedEvents() - { - list($datetime_no_password, $datetime) = $this->setupPasswordProtectedDatetimes(); - - //send a request for the two datetimes - $request = new WP_REST_Request( - 'GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $datetime->event()->ID() . '/datetimes' - ); - $request->set_url_params( - array( - 'id' => $datetime->ID() - ) - ); - $response = rest_do_request($request); - $response_data = $response->get_data(); - $this->assertTrue(is_array($response_data)); - $this->assertEquals('rest_post_password_required', $response_data['code']); - } - - /** - * Test get_related on a model protected by another model's password field, with the wrong password provided. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - * @group private-1 - */ - public function testGetRelatedDatetimesForPasswordProtectedEventsWrongPassword() - { - list($datetime_no_password, $datetime) = $this->setupPasswordProtectedDatetimes(); - - //send a request for the two datetimes - $request = new WP_REST_Request( - 'GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $datetime->event()->ID() . '/datetimes' - ); - $request->set_url_params( - array( - 'id' => $datetime->ID() - ) - ); - $request->set_query_params( - array( - 'password' => $datetime->event()->get('password') . ' made incorrect' - ) - ); - $response = rest_do_request($request); - $response_data = $response->get_data(); - $this->assertTrue(is_array($response_data)); - $this->assertEquals('rest_post_incorrect_password', $response_data['code']); - } - - /** - * Test get_related on a model protected by another model's password field, with the correct password provided. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - * @group private-1 - */ - public function testGetRelatedDatetimesForPasswordProtectedEventsCorrectPassword() - { - list($datetime_no_password, $datetime) = $this->setupPasswordProtectedDatetimes(); - - $request = new WP_REST_Request( - 'GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $datetime->event()->ID() . '/datetimes' - ); - $request->set_url_params( - array( - 'id' => $datetime->ID() - ) - ); - $request->set_query_params( - array( - 'password' => $datetime->event()->get('password'), - ) - ); - //send a request for the two datetimes - $response = rest_do_request($request); - $this->assertInstanceOf('WP_REST_Response', $response); - $data = $response->get_data(); - $this->assertEquals(1, count($data)); - $this->assertEquals( - $datetime->ID(), - $data[0]['DTT_ID'] - ); - } - - /** - * Creates a venue with a password whose country is Canada. Eh. - * @since 4.9.74.p - * @return EE_Venue - * @throws EE_Error - */ - protected function setupPasswordProtectedVenue() - { - return $this->new_model_obj_with_dependencies( - 'Venue', - array( - 'status' => EEM_Event::post_status_publish, - 'password' => 'correct_password', - 'CNT_ISO' => 'CA', - 'VNU_desc' => 'post body' - ) - ); - } - - /** - * test get_related with an UNPROTECTED model, but the related model is protected, and no password is provided. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testGetRelatedUnprotectedToProtectedNoPassword() - { - $venue = $this->setupPasswordProtectedVenue(); - $request = new WP_REST_Request( - 'GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/countries/CA/venues' - ); - $request->set_url_params( - array( - 'id' =>'CA' - ) - ); - $response = rest_do_request($request); - $this->assertInstanceOf('WP_REST_Response', $response); - $data = $response->get_data(); - $this->assertEquals(1, count($data)); - $this->assertEquals( - $venue->ID(), - $data[0]['VNU_ID'] - ); - $this->assertEquals( - '', - $data[0]['VNU_desc']['rendered'] - ); - } - - /** - * test get_related with an UNPROTECTED model, but the related model is protected, and WRONG password is provided. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testGetRelatedUnprotectedToProtectedWrongPassword() - { - $venue = $this->setupPasswordProtectedVenue(); - $request = new WP_REST_Request( - 'GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/countries/CA/venues' - ); - $request->set_url_params( - array( - 'id' =>'CA' - ) - ); - $request->set_query_params( - array( - 'password' => $venue->get('password') . ' made incorrect', - ) - ); - $response = rest_do_request($request); - $response_data = $response->get_data(); - $this->assertTrue(is_array($response_data)); - $this->assertEquals('rest_post_incorrect_password', $response_data['code']); - } - - /** - * test get_related with an UNPROTECTED model, but the related model is protected, and the CORRECT password provided. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testGetRelatedUnprotectedToProtectedCorrectPassword() - { - $venue = $this->setupPasswordProtectedVenue(); - $request = new WP_REST_Request( - 'GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/countries/CA/venues' - ); - $request->set_url_params( - array( - 'id' =>'CA' - ) - ); - $request->set_query_params( - array( - 'password' => $venue->get('password'), - ) - ); - $response = rest_do_request($request); - $this->assertInstanceOf('WP_REST_Response', $response); - $data = $response->get_data(); - $this->assertEquals(1, count($data)); - $this->assertEquals( - $venue->ID(), - $data[0]['VNU_ID'] - ); - $this->assertEquals( - $venue->get_pretty('VNU_desc'), - $data[0]['VNU_desc']['rendered'] - ); - } - - /** - * Test including on a model with a password, and the related model is password protected (eg country to venue), - * and no password is provided. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testGetRelatedProtectedToUnprotectedNoPassword() - { - $venue = $this->setupPasswordProtectedVenue(); - $request = new WP_REST_Request( - 'GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/venues/' . $venue->ID() . '/country' - ); - $request->set_url_params( - array( - 'id' => $venue->ID() - ) - ); - $response = rest_do_request($request); - $response_data = $response->get_data(); - $this->assertTrue(is_array($response_data)); - $this->assertEquals('rest_post_password_required', $response_data['code']); - } - - /** - * test get_related with an UNPROTECTED model, but the related model is protected, and WRONG password is provided. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testGetRelatedProtectedToUnprotectedWRongPassword() - { - $venue = $this->setupPasswordProtectedVenue(); - $request = new WP_REST_Request( - 'GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/venues/' . $venue->ID() . '/country' - ); - $request->set_url_params( - array( - 'id' => $venue->ID() - ) - ); - $request->set_query_params( - array( - 'password' => $venue->get('password') . ' made incorrect', - ) - ); - $response = rest_do_request($request); - $response_data = $response->get_data(); - $this->assertTrue(is_array($response_data)); - $this->assertEquals('rest_post_incorrect_password', $response_data['code']); - } - - /** - * test get_related with an UNPROTECTED model, but the related model is protected, and the CORRECT password provided. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testGetRelatedProtectedToUnprotectedCorrectPassword() - { - $venue = $this->setupPasswordProtectedVenue(); - $request = new WP_REST_Request( - 'GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/venues/' . $venue->ID() . '/country' - ); - $request->set_url_params( - array( - 'id' => $venue->ID() - ) - ); - $request->set_query_params( - array( - 'password' => $venue->get('password'), - ) - ); - $response = rest_do_request($request); - $this->assertInstanceOf('WP_REST_Response', $response); - $data = $response->get_data(); - $this->assertEquals( - 'CA', - $data['CNT_ISO'] - ); - } - - /** - * Tests that we still get the correct error when trying to get tickets from a datetime for a draft event. - * @since 4.9.75.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testGetRelatedDatetimesToTicketsEventDraft() - { - // Create a datetime, and event, that's not password protected. - $event = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'status' => EEM_Event::post_status_draft - ) - ); - $dtt = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $event->ID() - ) - ); - // And create a ticket for it. - $tkt = $this->new_model_obj_with_dependencies('Ticket'); - $dtt->_add_relation_to($tkt, 'Ticket'); - $request = new WP_REST_Request( - 'GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/datetimes/' . $dtt->ID() . '/tickets' - ); - $response = rest_do_request($request); - $this->assertInstanceOf('WP_REST_Response', $response); - $data = $response->get_data(); - $this->assertEquals('rest_tickets_cannot_list',$data['code']); - } - - /** - * @since 4.9.75.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testGetRelatedDatetimesToTickets() - { - // Create a datetime, and event, that's not password protected. - $event = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'status' => EEM_Event::post_status_publish - ) - ); - $dtt = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $event->ID() - ) - ); - // And create a ticket for it. - $tkt = $this->new_model_obj_with_dependencies('Ticket'); - $dtt->_add_relation_to($tkt, 'Ticket'); - $request = new WP_REST_Request( - 'GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/datetimes/' . $dtt->ID() . '/tickets' - ); - $response = rest_do_request($request); - $this->assertInstanceOf('WP_REST_Response', $response); - $data = $response->get_data(); - $this->assertEquals(1, count($data)); - $this->assertEquals($tkt->ID(),$data[0]['TKT_ID']); - } - - /** - * * Verifies that if a ticket is archived, there is no erroneous requirement for a password (this was a problem - * at one point). - * @since 4.9.75.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testGetRelatedDatetimesToTicketsDeleted() - { - // Create a datetime, and event, that's not password protected. - $event = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'status' => EEM_Event::post_status_publish - ) - ); - $dtt = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $event->ID() - ) - ); - // And create a ticket for it. - $tkt = $this->new_model_obj_with_dependencies( - 'Ticket', - array( - 'TKT_deleted' => true - ) - ); - $dtt->_add_relation_to($tkt, 'Ticket'); - $request = new WP_REST_Request( - 'GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/datetimes/' . $dtt->ID() . '/tickets' - ); - $response = rest_do_request($request); - $this->assertInstanceOf('WP_REST_Response', $response); - $data = $response->get_data(); - $this->assertEquals(1, count($data)); - $this->assertEquals($tkt->ID(),$data[0]['TKT_ID']); - } - - /** - * Verifies that if a datetime is trashed, there is no erroneous requirement for a password (this was a problem - * at one point). - * @since 4.9.75.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testGetRelatedDatetimesDeletedTo() - { - // Create a datetime, and event, that's not password protected. - $event = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'status' => EEM_Event::post_status_publish - ) - ); - $dtt = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $event->ID(), - 'DTT_deleted' => true - ) - ); - // And create a ticket for it. - $tkt = $this->new_model_obj_with_dependencies('Ticket'); - $dtt->_add_relation_to($tkt, 'Ticket'); - $request = new WP_REST_Request( - 'GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/datetimes/' . $dtt->ID() . '/tickets' - ); - $response = rest_do_request($request); - $this->assertInstanceOf('WP_REST_Response', $response); - $data = $response->get_data(); - $this->assertEquals(1, count($data)); - $this->assertEquals($tkt->ID(),$data[0]['TKT_ID']); - } - - /** - * Test fetching an protected model, and including an UNprotected model (venue to country), and no password is provided. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testIncludeProtectedToUnprotectedBelongsToWithNoPassword() - { - $venue = $this->setupPasswordProtectedVenue(); - $request = new WP_REST_Request( - 'GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/venues/' . $venue->ID() - ); - $request->set_url_params( - array( - 'id' => $venue->ID() - ) - ); - $request->set_query_params( - array( - 'include' => 'Country' - ) - ); - $response = rest_do_request($request); - $this->assertInstanceOf('WP_REST_Response', $response); - $data = $response->get_data(); - // country data should not have been included, because which country the venue is in is protected - $this->assertNull( - $data['country'] - ); - $this->assertArrayContains( - 'country', - $data['_protected'] - ); - } - - /** - * Test fetching an protected model, and including an UNprotected model (venue to country), and no password is provided. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testIncludeProtectedToUnprotectedHasManyWithNoPassword() - { - $event = $this->setupPasswordProtectedEvent(); - $request = new WP_REST_Request( - 'GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $event->ID() - ); - $request->set_url_params( - array( - 'id' => $event->ID() - ) - ); - $request->set_query_params( - array( - 'include' => 'Datetime' - ) - ); - $response = rest_do_request($request); - $this->assertInstanceOf('WP_REST_Response', $response); - $data = $response->get_data(); - // country data should not have been included, because which country the venue is in is protected - $this->assertEquals( - array(), - $data['datetimes'] - ); - $this->assertArrayContains( - 'datetimes', - $data['_protected'] - ); - } - - /** - * Test fetching an protected model, and including an UNprotected model (venue to country), and the wrong - * password is provided. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testIncludeProtectedToUnprotectedWithWrongPassword() - { - $venue = $this->setupPasswordProtectedVenue(); - $request = new WP_REST_Request( - 'GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/venues/' . $venue->ID() - ); - $request->set_url_params( - array( - 'id' => $venue->ID() - ) - ); - $request->set_query_params( - array( - 'password' => $venue->get('password') . ' made incorrect', - 'include' => 'Country' - ) - ); - $response = rest_do_request($request); - $this->assertInstanceOf('WP_REST_Response', $response); - $data = $response->get_data(); - $this->assertEquals('rest_post_incorrect_password', $data['code']); - } - - /** - * Test fetching an protected model, and including an UNprotected model (venue to country), and the correct - * password is provided. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testIncludeProtectedToUnprotectedWithCorrectPassword() - { - $venue = $this->setupPasswordProtectedVenue(); - $request = new WP_REST_Request( - 'GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/venues/' . $venue->ID() - ); - $request->set_url_params( - array( - 'id' => $venue->ID() - ) - ); - $request->set_query_params( - array( - 'password' => $venue->get('password'), - 'include' => 'Country' - ) - ); - $response = rest_do_request($request); - $this->assertInstanceOf('WP_REST_Response', $response); - $data = $response->get_data(); - // we should be able to see the country data just fine - $this->assertEquals( - $venue->country_name(), - $data['country']['CNT_name'] - ); - } - /** - * test fetching an unprotected model, and including a protected model (eg country to venue), and no password is - * provided - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testIncludeUnprotectedToProtectedWithNoPassword() - { - $venue = $this->setupPasswordProtectedVenue(); - $request = new WP_REST_Request( - 'GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/countries/CA' - ); - $request->set_url_params( - array( - 'id' => 'CA' - ) - ); - $request->set_query_params( - array( - 'include' => 'Venue' - ) - ); - $response = rest_do_request($request); - $this->assertInstanceOf('WP_REST_Response', $response); - $data = $response->get_data(); - // we should be able to see the venue, but not its protected fields - - $this->assertEquals( - $venue->ID(), - $data['venues'][0]['VNU_ID'] - ); - $this->assertEquals( - '', - $data['venues'][0]['VNU_desc']['rendered'] - ); - $this->assertArrayContains( - 'VNU_desc', - $data['venues'][0]['_protected'] - ); - } - - /** - * Test fetching an unprotected model, and including a protected model (country to venue), and the wrong - * password is provided. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testIncludeUnprotectedToProtectedWithWrongPassword() - { - $venue = $this->setupPasswordProtectedVenue(); - $request = new WP_REST_Request( - 'GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/countries/CA' - ); - $request->set_url_params( - array( - 'id' => 'CA' - ) - ); - $request->set_query_params( - array( - 'password' => $venue->get('password') . ' made incorrect', - 'include' => 'Venue', - ) - ); - $response = rest_do_request($request); - $this->assertInstanceOf('WP_REST_Response', $response); - $data = $response->get_data(); - $this->assertArrayNotHasKey('code', $data); - $this->assertEquals('CA', $data['CNT_ISO']); - $this->assertEquals(array(), $data['venues']); - } - - /** - * Test fetching an protected model, and including an UNprotected model (venue to country), and the correct - * password is provided. - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testIncludeUnprotectedToProtectedWithCorrectPassword() - { - $venue = $this->setupPasswordProtectedVenue(); - $request = new WP_REST_Request( - 'GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/countries/CA' - ); - $request->set_url_params( - array( - 'id' => 'CA' - ) - ); - $request->set_query_params( - array( - 'password' => $venue->get('password'), - 'include' => 'Venue' - ) - ); - $response = rest_do_request($request); - $this->assertInstanceOf('WP_REST_Response', $response); - $data = $response->get_data(); - // we should be able to see the country data just fine - $this->assertEquals( - $venue->get_pretty('VNU_desc'), - $data['venues'][0]['VNU_desc']['rendered'] - ); - } - - /** - * Tests that calculated fields for protected events get replaced with their default too. - * @throws \EE_Error - * @throws \EventEspresso\core\exceptions\InvalidDataTypeException - * @throws \EventEspresso\core\exceptions\InvalidInterfaceException - * @throws \InvalidArgumentException - * @throws \ReflectionException - * @group private-1 - */ - public function testGetAllPasswordProtectedCalculatedFields() - { - // create two events, one password-protected, the other not - // and datetimes and tickets for them - $e = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'status' => EEM_Event::post_status_publish - ) - ); - $e_password = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'status' => EEM_Event::post_status_publish, - 'password' => 'passy' - ) - ); - - // add a featured image too eh - $this->addFeaturedImage($e->ID()); - $this->addFeaturedImage($e_password->ID()); - $d = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $e->ID(), - 'DTT_reg_limit' => 100, - ) - ); - $d_password = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $e_password->ID(), - 'DTT_reg_limit' => 100, - ) - ); - $t_qty = 44; - $t = $this->new_model_obj_with_dependencies( - 'Ticket', - array( - 'TKT_qty' => $t_qty, - ) - ); - $t_password_qty = 22; - $t_password = $this->new_model_obj_with_dependencies( - 'Ticket', - array( - 'TKT_qty' => $t_password_qty - ) - ); - $t->_add_relation_to($d,'Datetime'); - $t_password->_add_relation_to($d_password, 'Datetime'); - - // then request each, from the front-end, and a few calculated fields - $request = new WP_REST_Request('GET', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events'); - $request->set_query_params( - array( - 'calculate' => 'optimum_sales_at_start, image_full' - ) - ); - $response = rest_do_request($request); - $data = $response->get_data(); - $this->assertNotEmpty($data); - - // assert the data is in the expected structure, and the non-protected event worked as normal - $this->assertEquals(2, count($data)); - $this->assertEquals($e->ID(),$data[0]['EVT_ID']); - $this->assertEquals($t_qty, $data[0]['_calculated_fields']->optimum_sales_at_start); - $this->assertNotEquals(null, $data[1]['_calculated_fields']->image_full); - $this->assertEquals($e_password->ID(), $data[1]['EVT_ID']); - - // the protected calculated field should be replaced with their defaults - $this->assertEquals(0,$data[1]['_calculated_fields']->optimum_sales_at_start); - - // featured image calculated fields aren't protected, so it should still be visible - $this->assertNotEquals(null, $data[1]['_calculated_fields']->image_full); - - $this->assertArrayContains( - 'optimum_sales_at_start', - $data[1]['_calculated_fields']->_protected - ); - $this->assertArrayDoesNotContain( - 'image_full', - $data[1]['_calculated_fields']->_protected - ); - } - - /** - * Adds some featured image to that post ID - * @since 4.9.74.p - * @param $post_id - * @return int|\WP_Error - */ - protected function addFeaturedImage($post_id) - { - $file = EE_ADMIN_PAGES . 'events/assets/images/caffeinated_template_features.jpg'; - $contents = file_get_contents($file); - $upload = wp_upload_bits(basename($file), null, $contents); - - $type = ''; - if ( ! empty($upload['type']) ) { - $type = $upload['type']; - } else { - $mime = wp_check_filetype( $upload['file'] ); - if ($mime) - $type = $mime['type']; - } - - $attachment = array( - 'post_title' => basename( $upload['file'] ), - 'post_content' => '', - 'post_type' => 'attachment', - 'post_parent' => $post_id, - 'post_mime_type' => $type, - 'guid' => $upload[ 'url' ], - ); - - // Save the data - $id = wp_insert_attachment( $attachment, $upload[ 'file' ], $post_id ); - wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $upload['file'] ) ); - add_post_meta($post_id, '_thumbnail_id', $id); - return $id; - } - - /** - * Verify requests when caps=read_admin we don't protect any fields etc, even on password-protected events - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testGetAllAdminRequest() - { - $event = $this->setupPasswordProtectedEvent(); - $this->authenticate_as_admin(); - - $req = new WP_REST_Request('GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events'); - $req->set_query_params( - array( - 'caps' => EEM_Base::caps_read_admin - ) - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertTrue(is_array($response_data)); - $this->assertEquals($event->ID(), $response_data[0]['EVT_ID']); - // note that this event was password-protected - $this->assertNotEmpty($response_data[0]['EVT_desc']['rendered']); - $this->assertEmpty($response_data[0]['_protected']); - } - - /** - * Verify requests when caps=read_admin all datetimes get returned (even those for password-protected events) - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testGetAllAdminRequestIndirectlyProtected() - { - list($datetime_no_password, $datetime) = $this->setupPasswordProtectedDatetimes(); - $this->authenticate_as_admin(); - - $req = new WP_REST_Request('GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/datetimes'); - $req->set_query_params( - array( - 'caps' => EEM_Base::caps_read_admin - ) - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - // both datetimes should have been returned - $this->assertEquals(2, count($response_data)); - } - - - /** - * Verify requests when caps=read_admin we don't protect any fields etc, even on password-protected events - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testGetOneAdminRequest() - { - $event = $this->setupPasswordProtectedEvent(); - $this->authenticate_as_admin(); - - $req = new WP_REST_Request('GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $event->ID()); - $req->set_query_params( - array( - 'caps' => EEM_Base::caps_read_admin - ) - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertTrue(is_array($response_data)); - $this->assertEquals($event->ID(), $response_data['EVT_ID']); - // note that this event was password-protected - $this->assertNotEmpty($response_data['EVT_desc']['rendered']); - $this->assertEmpty($response_data['_protected']); - } - - /** - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testGetRelatedAdminRequest() - { - list($datetime_no_password, $datetime) = $this->setupPasswordProtectedDatetimes(); - $this->authenticate_as_admin(); - - //send a request for the two datetimes - $req = new WP_REST_Request('GET', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $datetime->event()->ID(). '/datetimes'); - $req->set_query_params( - array( - 'caps' => EEM_Base::caps_read_admin - ) - ); - $response = rest_do_request($req); - $this->assertInstanceOf('WP_REST_Response', $response); - $data = $response->get_data(); - - // the datetime should have been returned - $this->assertEquals(1, count($data)); - $this->assertEquals( - $datetime->ID(), - $data[0]['DTT_ID'] - ); - } - - /** - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws ReflectionException - */ - public function testIncludeProtectedHasManyAdminRequest() - { - list($datetime_no_password, $datetime_password) = $this->setupPasswordProtectedDatetimes(); - $this->authenticate_as_admin(); - //send a request for the two datetimes - $req = new WP_REST_Request('GET', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $datetime_password->event()->ID()); - $req->set_query_params( - array( - 'caps' => EEM_Base::caps_read_admin, - 'include' => 'Datetime', - ) - ); - $response = rest_do_request($req); - $this->assertInstanceOf('WP_REST_Response', $response); - $data = $response->get_data(); - // the event should include the datetime a-ok - $this->assertEquals($datetime_password->ID(),$data['datetimes'][0]['DTT_ID']); - } -} -// End of file ReadProtectedTest.php -// Location: EventEspresso\core\libraries\rest_api\controllers\model/ReadProtectedTest.php diff --git a/tests/testcases/core/libraries/rest_api/controllers/Read_Test.php b/tests/testcases/core/libraries/rest_api/controllers/Read_Test.php deleted file mode 100644 index 58821705939..00000000000 --- a/tests/testcases/core/libraries/rest_api/controllers/Read_Test.php +++ /dev/null @@ -1,1447 +0,0 @@ -getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read'); - $controller->setRequestedVersion('4.8.29'); - $this->assertEquals(array( - 'EVT_ID', - 'EVT_name', - ), $controller->explodeAndGetItemsPrefixedWith('EVT_ID,EVT_name', '')); - } - - - - public function test_explode_and_get_items_prefixed_with__extra_whitespace() - { - $controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read'); - $controller->setRequestedVersion('4.8.29'); - $this->assertEquals(array( - 'EVT_ID', - 'EVT_name', - 'EVT_desc', - ), $controller->explodeAndGetItemsPrefixedWith('EVT_ID , EVT_name , EVT_desc', '')); - } - - - - public function test_explode_and_get_items_prefixed_with__related_model() - { - $controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read'); - $controller->setRequestedVersion('4.8.29'); - $this->assertEquals(array(), $controller->explodeAndGetItemsPrefixedWith('Registration.*', '')); - } - - - - public function test_explode_and_get_items_prefixed_with__related_model_all() - { - $controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read'); - $controller->setRequestedVersion('4.8.29'); - $this->assertEquals( - array( - '*', - ), - $controller->explodeAndGetItemsPrefixedWith('Registration.*', 'Registration') - ); - } - - - - public function test_explode_and_get_items_prefixed_with__related_models_but_searching_for_this_one() - { - $controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read'); - $controller->setRequestedVersion('4.8.29'); - $this->assertEquals( - array(), - $controller->explodeAndGetItemsPrefixedWith('Registration.REG_ID, Registration.Attendee.ATT_ID', '') - ); - } - - - - public function test_explode_and_get_items_prefixed_with__related_models_but_searching_for_other() - { - $controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read'); - $controller->setRequestedVersion('4.8.29'); - $this->assertEquals( - array( - 'REG_ID', - 'Attendee.ATT_ID', - ), - $controller->explodeAndGetItemsPrefixedWith('Registration.REG_ID, Registration.Attendee.ATT_ID', - 'Registration') - ); - } - - - - /** - * @group 10526 - */ - public function test_handle_request_get_one__event_includes() - { - $event = $this->new_model_obj_with_dependencies('Event', array('status' => 'publish')); - $req = new WP_REST_Request('GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $event->ID()); - $req->set_url_params( - array( - 'id' => $event->ID(), - ) - ); - $req->set_query_params( - array( - 'include' => 'EVT_ID,EVT_name', - ) - ); - $response = rest_do_request($req); - $result = $response->get_data(); - $this->assertEquals( - array( - 'EVT_ID' => $event->ID(), - 'EVT_name' => $event->name(), - ), - $result - ); - } - - - - /** - * Verifies 'featured_image_url' isn't added to all 4.8.29 requests. We had a bug introduced in 4.8.36 - * where requests to 4.8.29 added 'featured_image_url' all the time - * - * @group 10526 - */ - public function test_handle_request_get_one_4_8_29__event_includes() - { - $event = $this->new_model_obj_with_dependencies('Event', array('status' => 'publish')); - $req = new WP_REST_Request('GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.29/events/' . $event->ID()); - $req->set_url_params( - array( - 'id' => $event->ID(), - ) - ); - $req->set_query_params( - array( - 'include' => 'EVT_ID,EVT_name', - ) - ); - $response = rest_do_request($req); - $result = $response->get_data(); - $this->assertEquals( - array( - 'EVT_ID' => $event->ID(), - 'EVT_name' => $event->name(), - ), - $result - ); - } - - - - public function test_handle_request_get_one__event_includes_two_related_models() - { - $event = $this->new_model_obj_with_dependencies('Event', array('status' => 'publish')); - $req = new WP_REST_Request('GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $event->ID()); - $req->set_url_params( - array( - 'id' => $event->ID(), - ) - ); - $req->set_query_params( - array( - 'include' => 'Venue,Datetime', - ) - ); - $response = rest_do_request($req); - $result = $response->get_data(); - //make sure we still included all the normal event fields - $this->assertArrayHasKey( - 'EVT_name', - $result - ); - $this->assertArrayHasKey( - 'datetimes', - $result - ); - $this->assertArrayHasKey( - 'venues', - $result - ); - } - - - - /** - * @group 10526 - */ - public function test_handle_request_get_one__event_include_non_model_field() - { - $this->authenticate_as_admin(); - $event = $this->new_model_obj_with_dependencies('Event'); - $req = new WP_REST_Request('GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $event->ID()); - $req->set_url_params( - array( - 'id' => $event->ID(), - ) - ); - $req->set_query_params( - array( - 'include' => 'EVT_desc', - ) - ); - $response = rest_do_request($req); - $result = $response->get_data(); - $this->assertEquals( - array( - 'EVT_ID' => $event->ID(), - 'EVT_desc' => array( - 'rendered' => $event->get_pretty('EVT_desc'), - 'raw' => $event->get('EVT_desc'), - ), - ), - $result - ); - } - - - - public function test_explode_and_get_items_prefixed_with__null() - { - $controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read'); - $controller->setRequestedVersion('4.8.29'); - $this->assertEquals(array('*'), $controller->explodeAndGetItemsPrefixedWith('*', '')); - } - - - - /** - * @group 9406 - * @group 10976 - */ - public function test_handle_request_get_one__event_calculate_stuff() - { - $this->authenticate_as_admin(); - $limit_on_datetime = 100; - $limit_on_ticket = 50; - /** @var \EE_Event $event */ - $event = $this->new_model_obj_with_dependencies('Event'); - /** @var \EE_Datetime $dtt */ - $dtt = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'DTT_reg_limit' => $limit_on_datetime, - 'EVT_ID' => $event->ID(), - 'DTT_sold' => 0, - 'DTT_reserved' => 0, - ) - ); - /** @var \EE_Ticket $tkt */ - $tkt = $this->new_model_obj_with_dependencies( - 'Ticket', - array( - 'TKT_qty' => $limit_on_ticket, - 'TKT_sold' => 0, - 'TKT_reserved' => 0, - ) - ); - $tkt->_add_relation_to($dtt, 'Datetime'); - /** @var \EE_Registration $registration */ - $registration = $this->new_model_obj_with_dependencies( - 'Registration', - array( - 'EVT_ID' => $event->ID(), - 'TKT_ID' => $tkt->ID(), - 'STS_ID' => \EEM_Registration::status_id_incomplete, - ) - ); - // NOW set status to approved which will increment the corresponding ticket and datetime sold values - $registration->set_status(\EEM_Registration::status_id_approved); - $registration->save(); - $this->assertEquals( - \EEM_Registration::status_id_approved, - $registration->status_ID() - ); - // also confirm relation to event - $this->assertEquals( - $event->ID(), - $registration->event_ID() - ); - $calculator = new EventSpacesCalculator($event); - $this->assertEquals( - $limit_on_ticket, - $calculator->totalSpacesAvailable(), - 'Testing REST API event for "Total Spaces Available"' - ); - $this->assertEquals( - $limit_on_ticket - 1, - $calculator->spacesRemaining(), - 'Testing REST API event for "Spaces Remaining"' - ); - $req = new WP_REST_Request('GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $event->ID()); - $req->set_url_params( - array( - 'id' => $event->ID(), - ) - ); - $req->set_query_params( - array( - 'include' => 'Datetime', - 'calculate' => 'optimum_sales_at_start,spots_taken,spaces_remaining,Datetime.registrations_checked_in_count', - ) - ); - $response = rest_do_request($req); - $result = $response->get_data(); - $this->assertTrue(isset($result['EVT_ID'])); - //check that the requested calculated fields were added. - //Seeing how these calculated fields just wrap other EE methods (which should already be tested) - //the emphasis here is just on whether or not they get included properly, not exhaustively - //testing the calculations themselves - $this->assertTrue(isset($result['_calculated_fields'])); - $this->assertEquals( - (object)array( - 'optimum_sales_at_start' => $limit_on_ticket, - 'spots_taken' => 1, - 'spaces_remaining' => $limit_on_ticket - 1, - '_protected' => array(), - ), - $result['_calculated_fields'] - ); - $this->assertTrue(isset($result['datetimes'])); - $this->assertTrue(isset($result['datetimes'][0])); - $this->assertTrue(isset($result['datetimes'][0]['_calculated_fields'])); - $this->assertEquals( - (object)array( - 'registrations_checked_in_count' => 0, - '_protected' => array() - ), - $result['datetimes'][0]['_calculated_fields'] - ); - } - - - - /** - * Verifies the format of the response hasn't changed (unless of course we actually - * DO change it, in which case this unit test will need to be updated to - * include the known modifications). - * This helps prevent accidental changes - * @group private-1 - */ - public function test_handle_request_get_one__event() - { - $original_gmt_offset = get_option('gmt_offset'); - EED_Core_Rest_Api::set_hooks_for_changes(); - //set a weird timezone - update_option('gmt_offset', -4.5); - $this->authenticate_as_admin(); - $current_time_mysql_gmt = current_time('Y-m-d\TH:i:s', true); - $current_time_mysql = current_time('Y-m-d\TH:i:s'); - - //these model objects were instantiated when the tests started, so their - //default time is actually quite old now (at least a few seconds, possibly a minute or two) - //so make sure we're creating the event with the CURRENT current time - $event = $this->new_model_obj_with_dependencies('Event' - // , - // array( - // 'EVT_created' => $current_time_mysql_gmt, - // 'EVT_modified' => $current_time_mysql_gmt, - // 'EVT_visible_on' => $current_time_mysql_gmt, - // ) - ); - $req = new WP_REST_Request('GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.29/events/' . $event->ID()); - $req->set_url_params( - array( - 'id' => $event->ID(), - ) - ); - $response = rest_do_request($req); - $result = $response->get_data(); - $this->assertTrue(is_array($result)); - //compare all the times, realizing that _gmt times should be in UTC, others in the site's timezone - $this->assertDateWithinOneMinute($current_time_mysql, $result['EVT_created'], 'Y-m-d\TH:i:s'); - $this->assertDateWithinOneMinute($current_time_mysql, $result['EVT_modified'], 'Y-m-d\TH:i:s'); - $this->assertDateWithinOneMinute($current_time_mysql, $result['EVT_visible_on'], 'Y-m-d\TH:i:s'); - $this->assertDateWithinOneMinute($current_time_mysql_gmt, $result['EVT_created_gmt'], 'Y-m-d\TH:i:s'); - $this->assertDateWithinOneMinute($current_time_mysql_gmt, $result['EVT_modified_gmt'],'Y-m-d\TH:i:s'); - $this->assertDateWithinOneMinute($current_time_mysql_gmt, $result['EVT_visible_on_gmt'], 'Y-m-d\TH:i:s'); - //and let's just double-check the site's timezone isn't UTC, which would make it impossible to know if timezone offsets - //are being applied properly or not - $this->assertNotEquals( - $result['EVT_created'], - $result['EVT_created_gmt'], - 'There is no timezone offset, so its impossible to know if the timezone offset is being applied properly' - ); - $properties_we_cant_compare_exactly = array( - 'EVT_created', - 'EVT_modified', - 'EVT_visible_on', - 'EVT_created_gmt', - 'EVT_modified_gmt', - 'EVT_visible_on_gmt', - ); - foreach ($properties_we_cant_compare_exactly as $property_name) { - unset($result[$property_name]); - } - $event_id = $event->ID(); - $this->assertEquals( - array( - 'EVT_ID' => $event->get('EVT_ID'), - 'EVT_name' => $event->get('EVT_name'), - 'EVT_desc' => array( - 'raw' => $event->get('EVT_desc'), - 'rendered' => $event->get_pretty('EVT_desc'), - ), - 'EVT_slug' => $event->get('EVT_slug'), - 'EVT_short_desc' => $event->get('EVT_short_desc'), - 'EVT_wp_user' => $event->get('EVT_wp_user'), - 'parent' => $event->get('parent'), - 'EVT_order' => $event->get('EVT_order'), - 'status' => array( - 'raw' => $event->get('status'), - 'pretty' => $event->get_pretty('status'), - ), - 'comment_status' => $event->get('comment_status'), - 'ping_status' => $event->get('ping_status'), - 'EVT_display_desc' => $event->get('EVT_display_desc'), - 'EVT_display_ticket_selector' => $event->get('EVT_display_ticket_selector'), - 'EVT_additional_limit' => $event->get('EVT_additional_limit'), - 'EVT_default_registration_status' => array( - 'raw' => $event->get('EVT_default_registration_status'), - 'pretty' => $event->get_pretty('EVT_default_registration_status'), - ), - 'EVT_member_only' => $event->get('EVT_member_only'), - 'EVT_phone' => $event->get('EVT_phone'), - 'EVT_allow_overflow' => $event->get('EVT_allow_overflow'), - 'EVT_external_URL' => $event->get('EVT_external_URL'), - 'EVT_donations' => $event->get('EVT_donations'), - 'featured_image_url' => null, - 'EVT_timezone_string' => '', - 'password' => '', - 'link' => get_permalink($event->ID()), - '_links' => array( - 'self' => - array( - 0 => - array( - 'href' => rest_url('/ee/v4.8.29/events/' . $event_id), - ), - ), - 'collection' => - array( - 0 => - array( - 'href' => rest_url('/ee/v4.8.29/events'), - ), - ), - 'https://api.eventespresso.com/registrations' => - array( - 0 => - array( - 'href' => rest_url( - '/ee/v4.8.29/events/' - . $event_id - . '/registrations' - ), - 'single' => false, - ), - ), - 'https://api.eventespresso.com/datetimes' => - array( - 0 => - array( - 'href' => rest_url( - '/ee/v4.8.29/events/' - . $event_id - . '/datetimes' - ), - 'single' => false, - ), - ), - 'https://api.eventespresso.com/question_groups' => - array( - 0 => - array( - 'href' => rest_url( - '/ee/v4.8.29/events/' - . $event_id - . '/question_groups' - ), - 'single' => false, - ), - ), - 'https://api.eventespresso.com/venues' => - array( - 0 => - array( - 'href' => rest_url( '/ee/v4.8.29/events/' . $event_id . '/venues'), - 'single' => false, - ), - ), - 'https://api.eventespresso.com/term_taxonomies' => - array( - 0 => - array( - 'href' => rest_url( - '/ee/v4.8.29/events/' - . $event_id - . '/term_taxonomies' - ), - 'single' => false, - ), - ), - 'https://api.eventespresso.com/message_template_groups' => - array( - 0 => - array( - 'href' => rest_url( - '/ee/v4.8.29/events/' - . $event_id - . '/message_template_groups' - ), - 'single' => false, - ), - ), - 'https://api.eventespresso.com/attendees' => - array( - 0 => - array( - 'href' => rest_url( - '/ee/v4.8.29/events/' - . $event_id - . '/attendees' - ), - 'single' => false, - ), - ), - 'https://api.eventespresso.com/wp_user' => - array( - 0 => - array( - 'href' => rest_url( '/ee/v4.8.29/events/' . $event_id . '/wp_user'), - 'single' => true, - ), - ), - 'https://api.eventespresso.com/post_metas' => - array( - 0 => - array( - 'href' => rest_url( - '/ee/v4.8.29/events/' - . $event_id - . '/post_metas' - ), - 'single' => false, - ), - ), - 'https://api.eventespresso.com/extra_metas' => - array( - 0 => - array( - 'href' => rest_url( - '/ee/v4.8.29/events/' - . $event_id - . '/extra_metas' - ), - 'single' => false, - ), - ), - 'https://api.eventespresso.com/change_logs' => - array( - 0 => - array( - 'href' =>rest_url( - '/ee/v4.8.29/events/' - . $event_id - . '/change_logs' - ), - 'single' => false, - ), - ), - 'https://api.eventespresso.com/term_relationships' => - array( - 0 => - array( - 'href' => rest_url( - '/ee/v4.8.29/events/' - . $event_id - . '/term_relationships' - ), - 'single' => false, - ), - ), - 'https://api.eventespresso.com/event_question_groups' => - array( - 0 => - array( - 'href' => rest_url( - '/ee/v4.8.29/events/' - . $event_id - . '/event_question_groups' - ), - 'single' => false, - ), - ), - ), - '_protected' => array() - ), - $result - ); - // reset timezone - update_option('gmt_offset', $original_gmt_offset); - } - - - - public function test_handle_request_get_one__registration_include_attendee() - { - $this->authenticate_as_admin(); - $r = $this->new_model_obj_with_dependencies('Registration'); - $req = new WP_REST_Request( - 'GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.29/registrations/' . $r->ID() - ); - $req->set_query_params( - array( - 'include' => 'Attendee.*', - ) - ); - $req->set_url_params( - array( - 'id' => $r->ID(), - ) - ); - $response = rest_do_request($req); - $entity = $response->get_data(); - $this->assertArrayHasKey('attendee', $entity); - } - - - - public function test_handle_request_get_one__registration_include_answers_and_questions_use_star() - { - $this->authenticate_as_admin(); - $r = $this->new_model_obj_with_dependencies('Registration'); - $this->new_model_obj_with_dependencies('Answer', array('REG_ID' => $r->ID())); - $req = new WP_REST_Request('GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.29/registrations/' . $r->ID()); - $req->set_query_params( - array( - 'include' => 'Answer.Question.*', - ) - ); - $req->set_url_params( - array( - 'id' => $r->ID(), - ) - ); - $response = rest_do_request($req); - $entity = $response->get_data(); - $this->assertArrayHasKey('REG_date', $entity); - $this->assertArrayHasKey('answers', $entity); - $answers = $entity['answers']; - foreach ($answers as $answer) { - $this->assertArrayHasKey('question', $answer); - } - } - - - - public function test_handle_request_get_one__registration_include_answers_and_questions() - { - $this->authenticate_as_admin(); - $r = $this->new_model_obj_with_dependencies('Registration'); - $this->new_model_obj_with_dependencies('Answer', array('REG_ID' => $r->ID())); - $req = new WP_REST_Request('GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.29/registrations/' . $r->ID()); - $req->set_query_params( - array( - 'include' => 'Answer.Question', - ) - ); - $req->set_url_params( - array( - 'id' => $r->ID(), - ) - ); - $response = rest_do_request($req); - $entity = $response->get_data(); - $this->assertArrayHasKey('REG_date', $entity); - $this->assertArrayHasKey('answers', $entity); - $answers = $entity['answers']; - foreach ($answers as $answer) { - $this->assertArrayHasKey('question', $answer); - } - } - - - /** - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - public function test_handle_request_get_one__registration_include_answers_and_question_bare_min_from_each() - { - $this->authenticate_as_admin(); - $r = $this->new_model_obj_with_dependencies('Registration'); - $this->new_model_obj_with_dependencies('Answer', array('REG_ID' => $r->ID())); - $req = new WP_REST_Request('GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.29/registrations/' . $r->ID()); - $req->set_query_params( - array( - 'include' => 'Answer.ATT_ID, Answer.Question.QST_ID', - ) - ); - $req->set_url_params( - array( - 'id' => $r->ID(), - ) - ); - $response = rest_do_request($req); - $entity = $response->get_data(); - $this->assertArrayHasKey('answers', $entity); - $answers = $entity['answers']; - foreach ($answers as $answer) { - $this->assertArrayHasKey('question', $answer); - } - } - - - /** - * @since 4.9.74.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - public function test_handle_request_get_one__doesnt_exist() - { - $e = $this->new_model_obj_with_dependencies('Event'); - $non_existent_id = $e->ID() + 100; - $req = new WP_REST_Request('GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.29/events/' . $non_existent_id); - $req->set_url_params( - array( - 'id' => $non_existent_id, - ) - ); - $response = rest_do_request($req); - $this->assertInstanceOf('WP_REST_Response', $response); - $this->assertEquals(404, $response->get_status()); - } - - - - public function test_handle_request_get_one__cannot_access() - { - $e = $this->new_model_obj_with_dependencies('Event', array('status' => 'draft')); - $req = new WP_REST_Request('GET', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.29/events/' . $e->ID()); - $req->set_url_params( - array( - 'id' => $e->ID(), - ) - ); - $response = rest_do_request($req); - $this->assertInstanceOf('WP_REST_Response', $response); - $this->assertEquals(403, $response->get_status()); - } - - - - public function test_handle_request_get_all__not_logged_in() - { - $this->new_model_obj_with_dependencies('Registration'); - $response = rest_do_request( - new WP_REST_Request('GET', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.29/registrations') - ); - $this->assertInstanceOf('WP_REST_Response', $response); - $this->assertEquals(403, $response->get_status()); - } - - - - /** - * @group 9406 - * @group 10526 - */ - public function test_handle_request_get_all__set_headers() - { - $datetimes_created = 65; - $event = $this->new_model_obj_with_dependencies('Event', array('status' => EEM_CPT_Base::post_status_publish)); - for ($i = 0; $i < $datetimes_created; $i++) { - $this->new_model_obj_with_dependencies('Datetime', array('EVT_ID' => $event->ID())); - } - $this->assertEquals($datetimes_created, - \EEM_Datetime::instance()->count(array('caps' => \EEM_Base::caps_read))); - //request all datetimes from 4.8.36 (where the headers got added) - $response = rest_do_request( - new WP_REST_Request('GET', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/datetimes') - ); - $this->assertInstanceOf('WP_REST_Response', $response); - $headers = $response->get_headers(); - $this->assertArrayHasKey(Controller_Base::header_prefix_for_wp . 'Total', $headers); - $this->assertArrayHasKey(Controller_Base::header_prefix_for_wp . 'TotalPages', $headers); - $this->assertEquals($datetimes_created, $headers[Controller_Base::header_prefix_for_wp . 'Total']); - $this->assertEquals(ceil($datetimes_created / 50), - $headers[Controller_Base::header_prefix_for_wp . 'TotalPages']); - } - - - - /** - * @param string $role - * @return \WP_User - */ - public function get_wp_user_mock($role = 'administrator') - { - /** @type \WP_User $user */ - $user = $this->factory->user->create_and_get(); - $user->add_role($role); - return $user; - } - - - - /** - * @group 24 - */ - public function test_prepare_rest_query_params_key_for_models() - { - $controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read'); - $this->assertEquals(array( - 'EVT_desc' => 'foobar', - 'OR' => array( - 'EVT_desc*gotcha' => array('LIKE', '%foobar%'), - 'EVT_name' => 'yep', - 'EVT_desc*gotchaagain' => array('IN', array('1', '2')), - ), - ), - $controller->prepareRestQueryParamsKeyForModels( - EEM_Event::instance(), - array( - 'EVT_desc' => 'foobar', - 'OR' => array( - 'EVT_desc*gotcha' => array('LIKE', '%foobar%'), - 'EVT_name' => 'yep', - 'EVT_desc*gotchaagain' => array('IN', array('1', '2')), - ), - ))); - } - - - - /** - * @group 24 - * @group 9406 - */ - public function test_create_model_query_params__4_8_36() - { - $controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read'); - $controller->setRequestedVersion('4.8.36'); - $this->assertEquals(array( - 0 => array( - 'EVT_desc*foobar' => array('LIKE', '%frogs%'), - 'OR*otherfunanimals' => array( - 'EVT_name' => array('IN', array('chickens', 'cows')), - 'EVT_slug' => 'cowbunga', - 'Datetime.DTT_reg_limit' => EE_INF, - 'Datetime.DTT_reg_limit*1' => EE_INF, - 'Datetime.DTT_EVT_start' => array('<', strtotime('2016-01-01 00:00:00')), - ), - ), - 'order_by' => array( - 'EVT_desc' => 'ASC', - ), - 'group_by' => array( - 'EVT_desc', - ), - 'having' => array( - 'EVT_desc' => 'monkey', - ), - 'limit' => 50, - 'caps' => \EEM_Base::caps_read_admin, - ), - $controller->createModelQueryParams( - EEM_Event::instance(), - array( - 'where' => array( - 'EVT_desc*foobar' => array('LIKE', '%frogs%'), - 'OR*otherfunanimals' => array( - 'EVT_name' => array('IN', array('chickens', 'cows')), - 'EVT_slug' => 'cowbunga', - 'Datetime.DTT_reg_limit' => null, - 'Datetime.DTT_reg_limit*1' => '', - 'Datetime.DTT_EVT_start' => array('<', '2016-01-01T00:00:00'), - ), - ), - 'order_by' => array( - 'EVT_desc' => 'ASC', - ), - 'group_by' => array( - 'EVT_desc', - ), - 'having' => array( - 'EVT_desc' => 'monkey', - ), - 'caps' => \EEM_Base::caps_read_admin, - ))); - } - - - - /** - * @group 9389 - * @group 9222 - */ - public function test_handle_request_get_all__automatic_group_by() - { - $request = new WP_REST_Request('GET', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/question_groups'); - $request->set_query_params( - array( - 'where' => array( - 'Question.QST_ID' => array('IS_NOT_NULL'), - ), - 'limit' => '2,2', - ) - ); - $response = rest_do_request($request); - $this->assertEmpty($response->get_data()); - } - - - /** - * @group 536 see https://github.com/eventespresso/event-espresso-core/pull/536 - * @throws EE_Error - */ - public function testHandleRequestGetAllSoldOutEventsToo() - { - $admin = $this->wp_admin_with_ee_caps(); - //sold out events should be included, if they were previously published - $sold_out_event = $this->new_model_obj_with_dependencies( - - 'Event', - array( - 'status' => EEM_Event::sold_out, - 'EVT_wp_user' => $admin->ID(), - ) - ); - $sold_out_event->add_post_meta( - '_previous_event_status', - 'publish' - ); - $sold_out_private_event = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'status' => EEM_Event::sold_out, - 'EVT_wp_user' => $admin->ID(), - ) - ); - $sold_out_private_event->add_post_meta( - '_previous_event_status', - 'private' - ); - //note: we're purposefully not authenticated yet - $request = new WP_REST_Request('GET', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events'); - $response = rest_do_request($request); - $data = $response->get_data(); - $this->assertNotEmpty($data); - //only the previously published event should be available publicly, not the priavte one - $this->assertEquals(1, count($data)); - $this->assertEquals($sold_out_event->ID(), $data[0]['EVT_ID']); - //the other event shouldn't be included - //now let's authenticate - global $current_user; - $current_user = $admin; - $request = new WP_REST_Request('GET', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events'); - $response = rest_do_request($request); - $data = $response->get_data(); - $this->assertNotEmpty($data); - //both events should be visible to the admin - $this->assertEquals(2, count($data)); - $this->assertEquals($sold_out_event->ID(), $data[0]['EVT_ID']); - $this->assertEquals($sold_out_private_event->ID(), $data[1]['EVT_ID']); - } - - - /** - * @group 536 - * @throws EE_Error - */ - public function testHandleRequestGetAllIncludeDatetimesToSoldOutEvents() - { - $admin = $this->wp_admin_with_ee_caps(); - //datetimes for a sold out event should get included - $sold_out_event = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'status' => EEM_Event::sold_out, - 'EVT_wp_user' => $admin->ID(), - ) - ); - $sold_out_event->add_post_meta( - '_previous_event_status', - 'publish' - ); - $datetime_for_sold_event = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $sold_out_event->ID(), - ) - ); - $request = new WP_REST_Request('GET', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events'); - $request->set_query_params( - array( - 'include' => 'Datetime', - ) - ); - $response = rest_do_request($request); - $data = $response->get_data(); - $this->assertNotEmpty($data); - //only the previously published event should be available publicly, not the private one - $this->assertEquals(1, count($data)); - $this->assertEquals($sold_out_event->ID(), $data[0]['EVT_ID']); - $this->assertNotEmpty($data[0]['datetimes']); - $this->assertEquals($datetime_for_sold_event->ID(), $data[0]['datetimes'][0]['DTT_ID']); - } - - /** - * Double-checks a logged-in user who can read venues can read their draft venues. - * This was temporarily broken while working on 536, but no test picked up on it, so here's one that does. - * - * @group 536 see https://github.com/eventespresso/event-espresso-core/pull/536 - * @throws EE_Error - */ - public function testHandleRequestGetAllVenues() - { - global $current_user; - $current_user = $this->wp_admin_with_ee_caps( - array( - 'ee_read_venues', - 'ee_read_others_venues' - ) - ); - //let's create 2 venues, both owned by someone besides $current_user: a public one and a draft one - $my_public_venue = $this->new_model_obj_with_dependencies( - 'Venue', - array( - 'status' => EEM_CPT_Base::post_status_publish, - 'VNU_wp_user' => $current_user->ID + 1, - ) - ); - $others_private_venue = $this->new_model_obj_with_dependencies( - 'Venue', - array( - 'status' => EEM_CPT_Base::post_status_draft, - 'VNU_wp_user' => $current_user->ID + 1, - ) - ); - //make a request to see all venues - $request = new WP_REST_Request('GET', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/venues'); - $response = rest_do_request($request); - $data = $response->get_data(); - $this->assertNotEmpty($data); - //both venues should be visible to the user, not just the public one - //they should see the draft one too because they can see others' posts - $this->assertEquals(2, count($data)); - $this->assertEquals($my_public_venue->ID(), $data[0]['VNU_ID']); - $this->assertEquals($others_private_venue->ID(), $data[1]['VNU_ID']); - } - - /** - * Reproduces https://github.com/eventespresso/event-espresso-core/issues/845, which has been an often-recurring - * regression. - * @since 4.9.76.p - * @throws EE_Error - */ - public function testHandleRequestGeAllTermRelationships() - { - $e = $this->new_model_obj_with_dependencies( - 'Event', - ['status' => EEM_Event::post_status_publish] - ); - $term_taxonomy = $this->new_model_obj_with_dependencies( - 'Term_Taxonomy', - ['taxonomy' => 'espresso_event_categories'] - ); - $e->_add_relation_to($term_taxonomy, 'Term_Taxonomy'); - $request = new WP_REST_Request('GET', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/term_relationships'); - $response = rest_do_request($request); - $data = $response->get_data(); - $this->assertNotEmpty($data); - $this->assertEquals(1, count($data)); - $first_result = reset($data); - $this->assertEquals( - $e->ID(), - $first_result['object_id'] - ); - $this->assertEquals( - $term_taxonomy->ID(), - $first_result['term_taxonomy_id'] - ); - } - - - - - - - /** - * Test that when we set the minimum_others where conditions, we don't find trashed cpt items - * for the current model (because we use normal default where conditions for main model), but not for related - * trashed models (because they only use their minimum where conditions) - * - * @group 10260 - */ - public function test_handle_request_get_all__use_minimum_others_where_conditions() - { - $this->assertEquals(0, EEM_Event::instance()->count(array('default_where_conditions' => 'none'))); - $e_normal = $this->new_model_obj_with_dependencies('Event', - array('status' => EEM_CPT_Base::post_status_publish)); - $e_normal_but_with_trashed_v = $this->new_model_obj_with_dependencies('Event', - array('status' => EEM_CPT_Base::post_status_publish)); - $e_trashed = $this->new_model_obj_with_dependencies('Event', - array('status' => EEM_CPT_Base::post_status_trashed)); - $v_normal = $this->new_model_obj_with_dependencies('Venue', - array('status' => EEM_CPT_Base::post_status_publish)); - $v_trashed = $this->new_model_obj_with_dependencies('Venue', - array('status' => EEM_CPT_Base::post_status_trashed)); - //associate them - $e_normal->_add_relation_to($v_normal, 'Venue'); - $e_normal_but_with_trashed_v->_add_relation_to($v_trashed, 'Venue'); - $e_trashed->_add_relation_to($v_normal, 'Venue'); - //now verify we get what we wanted... - $request = new WP_REST_Request('GET', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events'); - $request->set_query_params( - array( - 'order_by' => array('Venue.VNU_ID' => 'ASC'), - 'default_where_conditions' => 'full_this_minimum_others', - ) - ); - $response = rest_do_request($request); - //we should find the normal event, and the event for the trashed venue - $this->assertCount(2, $response->data); - } - - - - /** - * This tests getting schema object returned for an options request on a valid collection endpoint. - * - * @group rest_schema_request - */ - public function test_handle_schema_request() - { - $request = new WP_REST_Request('OPTIONS', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events'); - $response = rest_do_request($request); - $data = $response->get_data(); - //verify there is a schema array - $this->assertArrayHasKey('schema', $data); - //verify schema has a `$schema` key - $this->assertArrayHasKey('$schema', $data['schema']); - //verify there is a title and it is "Event" - $this->assertArrayHasKey('title', $data['schema']); - $this->assertEquals('Event', $data['schema']['title']); - //verify there is a properties array in the schema and a few of the common fields are there (including that the - //EVT_ID field has `primary_key` flag set to true. - $this->assertArrayHasKey('properties', $data['schema']); - $this->assertArrayHasKey('EVT_ID', $data['schema']['properties']); - $this->assertArrayHasKey('primary_key', $data['schema']['properties']['EVT_ID']); - $this->assertTrue($data['schema']['properties']['EVT_ID']['primary_key']); - $this->assertArrayHasKey('EVT_desc', $data['schema']['properties']); - //finally let's verify that a relation that should be in the events schema (datetimes!) is present and that its - //relation items are correct. - $this->assertArrayHasKey('datetimes', $data['schema']['properties']); - $datetimes_array = $data['schema']['properties']['datetimes']; - $this->assertArrayHasKey('description', $datetimes_array); - $this->assertArrayHasKey('type', $datetimes_array); - $this->assertEquals('array', $datetimes_array['type']); - $this->assertArrayHasKey('relation', $datetimes_array); - $this->assertTrue($datetimes_array['relation']); - $this->assertArrayHasKey('relation_type', $datetimes_array); - $this->assertEquals('EE_Has_Many_Relation', $datetimes_array['relation_type']); - $this->assertArrayHasKey('readonly', $datetimes_array); - $this->assertTrue($datetimes_array['readonly']); - // verify link item - $this->assertArrayHasKey('link', $data['schema']['properties']); - $link = $data['schema']['properties']['link']; - $this->assertArrayHasKey('type', $link); - $this->assertEquals('string', $link['type']); - // verify links item - $this->assertArrayHasKey('_links', $data['schema']['properties']); - $links = $data['schema']['properties']['_links']; - $this->assertEquals( - array('description', 'type', 'readonly', 'properties', 'additionalProperties'), - array_keys($links) - ); - $this->assertEquals( - array( - 'self', - 'collection', - 'https://api.eventespresso.com/registration', - 'https://api.eventespresso.com/datetime', - 'https://api.eventespresso.com/question_group', - 'https://api.eventespresso.com/event_question_group', - 'https://api.eventespresso.com/venue', - 'https://api.eventespresso.com/term_relationship', - 'https://api.eventespresso.com/term_taxonomy', - 'https://api.eventespresso.com/message_template_group', - 'https://api.eventespresso.com/attendee', - 'https://api.eventespresso.com/wp_user', - 'https://api.eventespresso.com/post_meta', - 'https://api.eventespresso.com/extra_meta', - 'https://api.eventespresso.com/change_log', - ), - array_keys($links['properties']) - ); - //verify _calculated_fields - $this->assertArrayHasKey('_calculated_fields', $data['schema']['properties']); - $calculated_fields = $data['schema']['properties']['_calculated_fields']; - $this->assertEquals( - array('description', 'type', 'properties', 'additionalProperties', 'readonly', '_protected'), - array_keys($calculated_fields) - ); - $this->assertEquals( - array( - 'optimum_sales_at_start', - 'optimum_sales_now', - 'spaces_remaining', - 'spots_taken', - 'spots_taken_pending_payment', - 'registrations_checked_in_count', - 'registrations_checked_out_count', - 'image_thumbnail', - 'image_medium', - 'image_medium_large', - 'image_large', - 'image_post_thumbnail', - 'image_full', - ), - array_keys($calculated_fields['properties']) - ); - } - - - - /** - * @group rest_schema_request - */ - public function test_handle_schema_request_returning_defaults() - { - $request = new WP_REST_Request('OPTIONS', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/prices'); - $response = rest_do_request($request); - $data = $response->get_data(); - //verify that defaults are in the schema and in the correct format. - $PRC_amount_defaults = $data['schema']['properties']['PRC_amount']['default']; - $this->assertTrue(is_array($PRC_amount_defaults)); - $this->assertArrayHasKey('raw', $PRC_amount_defaults); - $this->assertArrayHasKey('pretty', $PRC_amount_defaults); - $this->assertEquals((float)0, $PRC_amount_defaults['raw']); - $this->assertEquals('$0.00 (USD)', $PRC_amount_defaults['pretty']); - } - - - - /** - * If someone specifies the same model field in a query parameter, which do we use? WP core uses the non-gmt field - * for now, so we'll do that too. See https://core.trac.wordpress.org/ticket/39954 - * - * @group 9222 - */ - public function test_handle_request_get_all__duplicate_query_fields_specified() - { - $this->authenticate_as_admin(); - //we aren't testing whether the timezone offset is being applied, we are just testing - //to see whether the gmt or non-gmt time is being used - $e = $this->new_model_obj_with_dependencies('Event',array('status' => 'publish')); - $d1 = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $e->ID(), - 'DTT_EVT_start' => \EEM_Datetime::instance()->convert_datetime_for_query( - 'DTT_EVT_start', - '2017-01-02 00:00:00', - \EE_Datetime_Field::mysql_timestamp_format, - \EEM_Datetime::instance()->get_timezone() - ) - ) - ); - $d2 = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $e->ID(), - 'DTT_EVT_start' => \EEM_Datetime::instance()->convert_datetime_for_query( - 'DTT_EVT_start', - '2017-01-03 00:00:00', - \EE_Datetime_Field::mysql_timestamp_format, - \EEM_Datetime::instance()->get_timezone() - ) - ) - ); - $request = new WP_REST_Request('GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/datetimes'); - $request->set_query_params( - array( - 'where' => array( - 'DTT_EVT_start_gmt' => '2017-01-02T00:00:00', - 'DTT_EVT_start' => '2017-01-03T00:00:00' - ) - ) - ); - $response = rest_do_request($request); - $response_data = $response->get_data(); - $this->assertFalse(empty($response_data)); - $this->assertTrue(empty($response_data['code'])); - $first_result = array_shift( $response_data); - //we should have found the datetime which matches the DTT_EVT_start query parameter - //and DTT_EVT_start_gmt should have been ignored - $this->assertEquals('2017-01-03T00:00:00', $first_result['DTT_EVT_start']); - } - - - - /** - * This is to test a bug where getting extra metas were having a parsing error - */ - public function testHandleRequestGetRelatedExtraMeta(){ - $this->authenticate_as_admin(); - $e1 = $this->new_model_obj_with_dependencies('Event'); - $request = new WP_REST_Request( - 'GET', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $e1->ID() . '/extra_metas' - ); - $response = rest_do_request($request); - $response_data = $response->get_data(); - $this->assertTrue(empty($response_data['code'])); - } - /** - * Creates two events: one with registrations, the other without. - * Verify that if we loop over them and render their pretty content (which renders shortcodes) - * we don't accidentally cache the shortcode from one event to the other - * @group 10851 - * @group big_rest_tests - */ - public function testShortcodesNotCachedForDifferentEvents() - { - $this->loadShortcodesManagerAndShortcodes(); - $transaction = $this->new_typical_transaction(); - $event_with_registrations = $transaction->primary_registration()->event(); - $event_with_registrations->set_description('[ESPRESSO_EVENT_ATTENDEES]'); - $event_with_registrations->set('status','publish'); - $event_with_registrations->save(); - - $other_event = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'EVT_desc' => '[ESPRESSO_EVENT_ATTENDEES]', - 'status' => 'publish' - ) - ); - $dtt = $this->new_model_obj_with_dependencies('Datetime'); - $other_event->_add_relation_to( $dtt, 'Datetime' ); - $dtt->_add_relation_to( - $this->new_model_obj_with_dependencies('Ticket'), - 'Ticket' - ); - - $request = new WP_REST_Request( 'GET', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events'); - $response = rest_do_request($request); - $data = $response->get_data(); - $this->assertEquals( 2, count($data)); - $this->assertNotEquals( - $data[0]['EVT_desc']['rendered'], - $data[1]['EVT_desc']['rendered'] - ); - } - - /** - * Reproduces https://github.com/eventespresso/event-espresso-core/issues/903 - * where including an innaccessible model caused the entire request to fail instead - * of just swapping out the response for null. - * @since 4.9.77.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - public function testHandleGetOneIncludeInnaccessibleModel() - { - // Create an event and some registrations - $e = $this->new_model_obj_with_dependencies( - 'Event', - [ - 'status' => EEM_Event::post_status_publish - ] - ); - $d = $this->new_model_obj_with_dependencies('Datetime'); - $t = $this->new_model_obj_with_dependencies('Ticket'); - $d->_add_relation_to($t, 'Ticket'); - $r = $this->new_model_obj_with_dependencies( - 'Registration', - [ - 'EVT_ID' => $e->ID(), - 'TKT_ID' => $t->ID() - ] - ); - - // Request to include the registrations. - $request = new WP_REST_Request( 'GET', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $e->ID()); - $request->set_query_params( - array( - 'include' => 'Registration', - ) - ); - $response = rest_do_request($request); - $data = $response->get_data(); - - // The registrations should just be removed, we shouldn't have a big error response. - $this->assertArrayNotHasKey('code', $data); - $this->assertEquals($e->ID(), $data['EVT_ID']); - $this->assertEquals(array(), $data['registrations']); - } -} -// End of file Read_Test.php -// Location: testcases/core/libraries/rest_api/controllers/Read_Test.php diff --git a/tests/testcases/core/libraries/rest_api/controllers/WriteAddRelationTest.php b/tests/testcases/core/libraries/rest_api/controllers/WriteAddRelationTest.php deleted file mode 100644 index a1d7fe88622..00000000000 --- a/tests/testcases/core/libraries/rest_api/controllers/WriteAddRelationTest.php +++ /dev/null @@ -1,319 +0,0 @@ -authenticate_as_admin(); - $event = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'status' => EEM_CPT_Base::post_status_publish - ) - ); - $datetime = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => 0 - ) - ); - $this->assertNotEquals($event->ID(),$datetime->get('EVT_ID')); - $req = new WP_REST_Request( - 'POST', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $event->ID() . '/datetimes/' . $datetime->ID() - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertArrayHasKey( - 'event', - $response_data - ); - $this->assertArrayHasKey( - 'datetime', - $response_data - ); - $this->assertArrayNotHasKey( - 'join', - $response_data - ); - // The datetime should be updated now - $this->assertEquals($event->ID(),$response_data['event']['EVT_ID']); - $this->assertEquals($datetime->ID(), $response_data['datetime']['DTT_ID']); - $this->assertEquals($event->ID(),$response_data['datetime']['EVT_ID']); - } - - - /** - * test HABTM add - * @since 4.9.76.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - public function testAddRelationWithJoinTableGood() - { - $this->authenticate_as_admin(); - $question = $this->new_model_obj_with_dependencies('Question'); - $question_group = $this->new_model_obj_with_dependencies('Question_Group'); - $req = new WP_REST_Request( - 'POST', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/questions/' . $question->ID() . '/question_groups/' . $question_group->ID() - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertArrayHasKey( - 'question', - $response_data - ); - $this->assertArrayHasKey( - 'question_group', - $response_data - ); - $this->assertArrayHasKey( - 'join', - $response_data - ); - $qgq_join = $question->get_first_related('Question_Group_Question'); - $this->assertEquals($question->ID(),$response_data['question']['QST_ID']); - $this->assertEquals($question_group->ID(), $response_data['question_group']['QSG_ID']); - // The join row should have been returned and have an ID. - $this->assertEquals($qgq_join->ID(),$response_data['join']['question_group_question']['QGQ_ID']); - } - - /** - * Test HABTM with wrong params - * @since 4.9.76.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - public function testAddRelationWithJoinTableWrongParams() - { - $this->authenticate_as_admin(); - $question = $this->new_model_obj_with_dependencies('Question'); - $question_group = $this->new_model_obj_with_dependencies('Question_Group'); - $req = new WP_REST_Request( - 'POST', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/questions/' . $question->ID() . '/question_groups/' . $question_group->ID() - ); - $req->set_body_params( - array( - 'non-existent-field' => 123, - 'QGQ_order' => 234 - ) - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertEquals('invalid_field', $response_data['code']); - // The data should be unchanged. - $question->clear_cache('Question_Group_Question'); - $this->assertNull($question->get_first_related('Question_Group_Question')); - } - - /** - * No related item - * @since 4.9.76.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - public function testAddRelationNoRelatedItem() - { - $this->authenticate_as_admin(); - $event = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'status' => EEM_CPT_Base::post_status_publish - ) - ); - $req = new WP_REST_Request( - 'POST', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $event->ID() . '/datetimes/' . 9999 - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertEquals('rest_datetime_invalid_id', $response_data['code']); - } - - /** - * No primary item - * @since 4.9.76.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - public function testAddRelationNoPrimaryModel() - { - $this->authenticate_as_admin(); - $datetime = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => 0 - ) - ); - $req = new WP_REST_Request( - 'POST', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . 99999 . '/datetimes/' . $datetime->ID() - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertEquals('rest_event_invalid_id', $response_data['code']); - } - - /** - * Already related - * @since 4.9.76.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - public function testAddRelationAlreadyRelated() - { - $this->authenticate_as_admin(); - $event = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'status' => EEM_CPT_Base::post_status_publish - ) - ); - $datetime = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $event->ID() - ) - ); - $this->assertEquals($event->ID(),$datetime->get('EVT_ID')); - $req = new WP_REST_Request( - 'POST', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $event->ID() . '/datetimes/' . $datetime->ID() - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertArrayHasKey( - 'event', - $response_data - ); - $this->assertArrayHasKey( - 'datetime', - $response_data - ); - $this->assertArrayNotHasKey( - 'join', - $response_data - ); - // Nothing is changed. It's all a-ok still. - $this->assertEquals($event->ID(),$response_data['event']['EVT_ID']); - $this->assertEquals($datetime->ID(), $response_data['datetime']['DTT_ID']); - $this->assertEquals($event->ID(),$response_data['datetime']['EVT_ID']); - } - - - /** - * Valid request but not authenticated - * @since 4.9.76.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - public function testAddRelationUnauthenticated() - { - $event = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'status' => EEM_CPT_Base::post_status_publish - ) - ); - $datetime = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => 0 - ) - ); - $this->assertNotEquals($event->ID(),$datetime->get('EVT_ID')); - $req = new WP_REST_Request( - 'POST', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $event->ID() . '/datetimes/' . $datetime->ID() - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertEquals('rest_cannot_edit_events', $response_data['code']); - } - - /** - * Valid request but doesn't have sufficient privileges. - * @since 4.9.76.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - public function testAddRelationInsufficientPrivileges() - { - global $current_user; - //setup our user and set as current user. - $current_user = $this->factory->user->create_and_get(); - $this->assertInstanceOf('WP_User', $current_user); - $current_user->add_role('event_manager'); - $event = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'status' => EEM_CPT_Base::post_status_publish - ) - ); - $datetime = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => 0 - ) - ); - $this->assertNotEquals($event->ID(),$datetime->get('EVT_ID')); - $req = new WP_REST_Request( - 'POST', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $event->ID() . '/datetimes/' . $datetime->ID() - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertEquals('rest_cannot_edit_events', $response_data['code']); - } - -} -// End of file WriteAddRelationTest.php -// Location: EventEspresso\core\libraries\rest_api\controllers\model/WriteAddRelationTest.php diff --git a/tests/testcases/core/libraries/rest_api/controllers/WriteRemoveRelationTest.php b/tests/testcases/core/libraries/rest_api/controllers/WriteRemoveRelationTest.php deleted file mode 100644 index 3164c34df80..00000000000 --- a/tests/testcases/core/libraries/rest_api/controllers/WriteRemoveRelationTest.php +++ /dev/null @@ -1,333 +0,0 @@ -authenticate_as_admin(); - $event = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'status' => EEM_CPT_Base::post_status_publish - ) - ); - $datetime = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $event->ID() - ) - ); - $this->assertEquals($event->ID(),$datetime->get('EVT_ID')); - $req = new \WP_REST_Request( - 'DELETE', - '/' . \EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $event->ID() . '/datetimes/' . $datetime->ID() - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertArrayHasKey( - 'event', - $response_data - ); - $this->assertArrayHasKey( - 'datetime', - $response_data - ); - $this->assertArrayNotHasKey( - 'join', - $response_data - ); - // The event is unaffected... - $this->assertEquals($event->ID(),$response_data['event']['EVT_ID']); - // But the event changed. - $this->assertEquals($datetime->ID(), $response_data['datetime']['DTT_ID']); - $this->assertEquals(0,$response_data['datetime']['EVT_ID']); - } - - - /** - * Test HABTM removal relations. - * @since 4.9.76.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - public function testRemoveRelationWithJoinTableGood() - { - $this->authenticate_as_admin(); - $question = $this->new_model_obj_with_dependencies('Question'); - $question_group = $this->new_model_obj_with_dependencies('Question_Group'); - $question->_add_relation_to($question_group, 'Question_Group', array('QGQ_order' => 123)); - // add another row, just for good measure. It should get deleted too. - $question->_add_relation_to($question_group, 'Question_Group', array('QGQ_order' => 456)); - $qgq_join = $question->get_first_related('Question_Group_Question'); - $req = new WP_REST_Request( - 'DELETE', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/questions/' . $question->ID() . '/question_groups/' . $question_group->ID() - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertArrayHasKey( - 'question', - $response_data - ); - $this->assertArrayHasKey( - 'question_group', - $response_data - ); - $this->assertArrayHasKey( - 'join', - $response_data - ); - // The question group - $this->assertEquals($question->ID(),$response_data['question']['QST_ID']); - $this->assertEquals($question_group->ID(), $response_data['question_group']['QSG_ID']); - $this->assertEquals($qgq_join->ID(),$response_data['join']['question_group_question']['QGQ_ID']); - - // Oh and we should double-check the relation was actually removed in the DB. - $question->clear_cache('Question_Group_Question'); - $qgq_join = $question->get_first_related('Question_Group_Question'); - $this->assertNull($qgq_join); - } - - /** - * Test HABTM with wrong params - * @since 4.9.76.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - public function testRemoveRelationWithJoinTableWrongParams() - { - $this->authenticate_as_admin(); - $question = $this->new_model_obj_with_dependencies('Question'); - $question_group = $this->new_model_obj_with_dependencies('Question_Group'); - $question->_add_relation_to($question_group, 'Question_Group', array('QGQ_order' => 123)); - $qgq_join_original = $question->get_first_related('Question_Group_Question'); - $req = new WP_REST_Request( - 'DELETE', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/questions/' . $question->ID() . '/question_groups/' . $question_group->ID() - ); - $req->set_body_params( - array( - // You would think `QGQ_order` is correct, but this endpoint obliterates all relations, regardless - // of whether you provide this extra parameter. So we actually want this to be an error. - 'QGQ_order' => 123 - ) - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertEquals('invalid_field', $response_data['code']); - // Oh and we should double-check the relation was not actually removed in the DB. - $question->clear_cache('Question_Group_Question'); - $qgq_join = $question->get_first_related('Question_Group_Question'); - $this->assertEquals($qgq_join_original, $qgq_join); - } - - /** - * No related item - * @since 4.9.76.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - public function testRemoveRelationNoRelatedItem() - { - $this->authenticate_as_admin(); - $event = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'status' => EEM_CPT_Base::post_status_publish - ) - ); - $req = new WP_REST_Request( - 'DELETE', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $event->ID() . '/datetimes/' . 9999 - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertEquals('rest_datetime_invalid_id', $response_data['code']); - } - - /** - * No primary item - * @since 4.9.76.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - public function testRemoveRelationNoPrimaryModel() - { - $this->authenticate_as_admin(); - $datetime = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => 0 - ) - ); - $req = new WP_REST_Request( - 'DELETE', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . 99999 . '/datetimes/' . $datetime->ID() - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertEquals('rest_event_invalid_id', $response_data['code']); - } - - /** - * Already related - * @since 4.9.76.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - public function testRemoveRelationNotAlreadyRelated() - { - $this->authenticate_as_admin(); - $event = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'status' => EEM_CPT_Base::post_status_publish - ) - ); - $datetime = $this->new_model_obj_with_dependencies('Datetime'); - $req = new WP_REST_Request( - 'DELETE', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $event->ID() . '/datetimes/' . $datetime->ID() - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertArrayHasKey( - 'event', - $response_data - ); - $this->assertArrayHasKey( - 'datetime', - $response_data - ); - $this->assertArrayNotHasKey( - 'join', - $response_data - ); - // Nothing is changed. They're still not related. - $this->assertEquals($event->ID(), $response_data['event']['EVT_ID']); - $this->assertEquals($datetime->ID(), $response_data['datetime']['DTT_ID']); - $this->assertNotEquals($event->ID(), $response_data['datetime']['EVT_ID']); - } - - - /** - * Valid request but not authenticated - * @since 4.9.76.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - public function testRemoveRelationUnauthenticated() - { - $event = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'status' => EEM_CPT_Base::post_status_publish - ) - ); - $datetime = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $event->ID() - ) - ); - $req = new WP_REST_Request( - 'DELETE', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $event->ID() . '/datetimes/' . $datetime->ID() - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertEquals('rest_cannot_edit_events', $response_data['code']); - $datetime->refresh_from_db(); - $this->assertEquals($event->ID(), $datetime->get('EVT_ID')); - } - - /** - * Valid request but doesn't have sufficient privileges. - * @since 4.9.76.p - * @throws EE_Error - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws InvalidArgumentException - * @throws ReflectionException - */ - public function testRemoveRelationInsufficientPrivileges() - { - global $current_user; - //setup our user and set as current user. - $current_user = $this->factory->user->create_and_get(); - $this->assertInstanceOf('WP_User', $current_user); - $current_user->add_role('event_manager'); - $event = $this->new_model_obj_with_dependencies( - 'Event', - array( - 'status' => EEM_CPT_Base::post_status_publish - ) - ); - $datetime = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $event->ID() - ) - ); - $req = new WP_REST_Request( - 'DELETE', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $event->ID() . '/datetimes/' . $datetime->ID() - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertEquals('rest_cannot_edit_events', $response_data['code']); - $datetime->refresh_from_db(); - $this->assertEquals($event->ID(), $datetime->get('EVT_ID')); - } -} -// End of file WriteRemoveRelationTest.php -// Location: EventEspresso\core\libraries\rest_api\controllers\model/WriteRemoveRelationTest.php diff --git a/tests/testcases/core/libraries/rest_api/controllers/WriteTest.php b/tests/testcases/core/libraries/rest_api/controllers/WriteTest.php deleted file mode 100644 index f0f38b91080..00000000000 --- a/tests/testcases/core/libraries/rest_api/controllers/WriteTest.php +++ /dev/null @@ -1,459 +0,0 @@ -set_body_params( - array( - 'EVT_name' => 'Haha I didnt log in and I inserted an event', - ) - ); - $response = rest_do_request($request); - $data = $response->get_data(); - $this->assertEquals('rest_cannot_create_events', $data['code']); - } - - - - /** - * Verifies that even if the current user can edit events, they shouldn't be able - * to insert until we've sorted that code out - */ - public function testNoInsertLimitedUser() - { - $user = $this->factory->user->create_and_get(array('role' => 'subscriber')); - $user->add_cap('ee_edit_events'); - $user->add_cap('ee_read_events'); - wp_set_current_user($user->ID); - //ok now try to insert an event - $request = new WP_REST_Request('POST', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events'); - $request->set_body_params( - array( - 'EVT_name' => 'Haha I didnt log in and I inserted an event', - ) - ); - $response = rest_do_request($request); - $data = $response->get_data(); - $this->assertEquals('rest_cannot_create_events', $data['code']); - } - - - - /** - * @group 9222 - */ - public function testInsertUtcAndRelativeTimes() - { - //let's set a different WP timezone. - update_option('gmt_offset', '-1'); - $this->authenticate_as_admin(); - $req = new WP_REST_Request( - 'POST', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/datetimes' - ); - $req->set_body_params( - array( - 'DTT_EVT_start_gmt' => '2016-01-02T00:00:00', - 'DTT_EVT_end' => '2016-01-03T00:00:00', - ) - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - if (! isset($response_data['code'])) { - $response_data['code'] = null; - } - $this->assertEmpty( - $response_data['code'], - '$response_data[\'code\'] was not empty and actually contained: ' . $response_data['code'] - . "\n" . ' The full response was: ' . var_export($response_data, true) - ); - $this->assertEquals('2016-01-02T00:00:00', $response_data['DTT_EVT_start_gmt']); - $this->assertEquals('2016-01-01T23:00:00', $response_data['DTT_EVT_start']); - $this->assertEquals('2016-01-03T01:00:00', $response_data['DTT_EVT_end_gmt']); - $this->assertEquals('2016-01-03T00:00:00', $response_data['DTT_EVT_end']); - } - - - - /** - * - * Verify that we follow WP's current behaviour when both a gmt and non-gmt date are provided: - * ignore the gmt datetime. See https://core.trac.wordpress.org/ticket/39954 - * @group 9222 - */ - public function testInsertUtcAndRelativeDuplicate() - { - //let's set a different WP timezone. - update_option('gmt_offset', '-1'); - $this->authenticate_as_admin(); - $req = new WP_REST_Request( - 'POST', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/datetimes' - ); - $req->set_body_params( - array( - 'DTT_EVT_start' => '2016-01-03T00:00:00', - 'DTT_EVT_start_gmt' => '2016-01-02T00:00:00', - ) - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - if (! isset($response_data['code'])) { - $response_data['code'] = null; - } - $this->assertEmpty( - $response_data['code'], - '$response_data[\'code\'] was not empty and actually contained: ' . $response_data['code'] - . "\n" . ' The full response was: ' . var_export($response_data, true) - ); - $this->assertEquals('2016-01-03T00:00:00', $response_data['DTT_EVT_start']); - } - - /** - * Originally I wanted to allow providing selection parameters on write requests, and this - * test verified we could do that. However, Darren had some issues with that, and so - * rather than discuss it further it was removed. So this test now verifies we DON'T - * use selection parameters on write requests. - * @group 9222 - */ - public function testInsertThenUseQuerystring() - { - $this->authenticate_as_admin(); - $event = $this->new_model_obj_with_dependencies('Event'); - $req = new WP_REST_Request( - 'POST', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/datetimes' - ); - $req->set_body_params( - array( - 'EVT_ID' => $event->ID(), - 'DTT_EVT_start_gmt' => '2016-01-02T00:00:00', - ) - ); - //it's a free country, so you can provide a query string - //with parameters for reading in it; but we will ignore it. - $req->set_query_params( - array( - 'include' => 'Event.EVT_ID' - ) - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertTrue(empty($response_data['code'])); - $this->assertTrue(isset($response_data['DTT_ID'])); - //we should NOT include the datetime's related event, because we said we weren't going - //to use READ parameters on WRITE queries like this - $this->assertTrue(empty($response_data['event']['EVT_ID'])); - } - - - - /** - * @group 9222 - */ - public function testUpdateOnlySomeFields() - { - $this->authenticate_as_admin(); - $original_reg_limit = 25; - $original_sold = 100; - $datetime = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'DTT_reg_limit' => $original_reg_limit, - 'DTT_sold' => $original_sold, - ) - ); - $req = new WP_REST_Request( - 'PUT', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/datetimes/' . $datetime->ID() - ); - //just update the reg limit, not the number sold - $req->set_body_params( - array( - 'DTT_reg_limit' => $original_reg_limit * 2, - ) - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - //verify there was no error code - $this->assertTrue(empty($response_data['code'])); - //assert the reg limit was updated properly - $this->assertEquals($original_reg_limit * 2, (int)$response_data['DTT_reg_limit']); - //but that teh sold count wasn't changed - $this->assertEquals($original_sold, (int)$response_data['DTT_sold']); - } - - - - /** - * Verifies that if we pass an invalid ID for a PUT, there is a proper REST API error - * (not just a model or PHP error) - * @group 9222 - */ - public function testUpdateInvalidID() - { - $this->authenticate_as_admin(); - $req = new WP_REST_Request( - 'PUT', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/datetimes/9999999' - ); - //just update the reg limit, not the number sold - $req->set_body_params( - array( - 'DTT_reg_limit' => 2, - ) - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - //verify there was no error code - $this->assertEquals('rest_datetime_invalid_id', $response_data['code']); - } - - - - /** - * Verifies that if we pass an invalid ID for a DELETE, there is a proper REST API error - * (not just a model or PHP error) - * @group 9222 - */ - public function testDeleteInvalidID() - { - $this->authenticate_as_admin(); - $req = new WP_REST_Request( - 'DELETE', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/datetimes/9999999' - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - //verify there was no error code - $this->assertEquals('rest_datetime_invalid_id', $response_data['code']); - } - - - - /** - * @group 9222 - */ - public function testNoDeleteIfNoCaps() - { - $datetime = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'DTT_deleted' => false, - ) - ); - //double-check the datetime isn't trashed - $this->assertFalse($datetime->get('DTT_deleted')); - $request = new WP_REST_Request('DELETE', '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/datetimes/' . $datetime->ID()); - $response = rest_do_request($request); - $data = $response->get_data(); - $this->assertEquals('rest_cannot_delete_datetimes', $data['code']); - } - - - - /** - * @group 9222 - */ - public function testDeleteTrashed() - { - $this->authenticate_as_admin(); - $datetime = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'DTT_deleted' => false, - ) - ); - //double-check the datetime isn't trashed - $this->assertFalse($datetime->get('DTT_deleted')); - $req = new WP_REST_Request( - 'DELETE', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/datetimes/' . $datetime->ID() - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - //verify there was no error code - $this->assertTrue(empty($response_data['code'])); - $this->assertTrue($response_data['DTT_deleted']); - } - - - - /** - * @group 9222 - */ - public function testDeletePermanent() - { - $this->authenticate_as_admin(); - $datetime_count_before_insertion = EEM_Datetime::instance()->count_deleted_and_undeleted(); - $datetime = $this->new_model_obj_with_dependencies('Datetime'); - $req = new WP_REST_Request( - 'DELETE', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/datetimes/' . $datetime->ID() - ); - $req->set_query_params( - array( - 'force' => true, - ) - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - //verify there was no error code - $this->assertTrue(empty($response_data['code'])); - $this->assertTrue(isset($response_data['deleted'], $response_data['previous'])); - $this->assertEquals($datetime->ID(), $response_data['previous']['DTT_ID']); - $this->assertEquals($datetime_count_before_insertion, EEM_Datetime::instance()->count_deleted_and_undeleted()); - } - - /** - * @group 9222 - */ - public function testDeleteCPTPermanent() - { - $this->authenticate_as_admin(); - $event_count_before_insertion = EEM_Event::instance()->count_deleted_and_undeleted(); - $event = $this->new_model_obj_with_dependencies('Event'); - $req = new WP_REST_Request( - 'DELETE', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events/' . $event->ID() - ); - $req->set_query_params( - array( - 'force' => true, - ) - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - //verify there was no error code - $this->assertTrue(empty($response_data['code'])); - $this->assertTrue(isset($response_data['deleted'], $response_data['previous'])); - $this->assertEquals($event->ID(), $response_data['previous']['EVT_ID']); - $this->assertEquals($event_count_before_insertion, EEM_Event::instance()->count_deleted_and_undeleted()); - } - - - - /** - * Tests that when we delete a non-soft-deletable model object, it has an error - * - * @group 9222 - */ - public function testDeleteNotAllowedOnNonSoftDeleteModel() - { - $this->authenticate_as_admin(); - $payment = $this->new_model_obj_with_dependencies('Payment'); - $payment_count_before_deletion = EEM_Payment::instance()->count(); - $req = new WP_REST_Request( - 'DELETE', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/payments/' . $payment->ID() - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - $this->assertEquals('rest_trash_not_supported', $response_data['code']); - } - - - - /** - * Tests that when we delete a non-soft-deletable model object permanently, it works as normal - * - * @group 9222 - */ - public function testDeleteNonSoftDeleteModel() - { - $this->authenticate_as_admin(); - $payment = $this->new_model_obj_with_dependencies('Payment'); - $payment_count_before_deletion = EEM_Payment::instance()->count(); - $req = new WP_REST_Request( - 'DELETE', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/payments/' . $payment->ID() - ); - $req->set_query_params( - array( - 'force' => 'true', - ) - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - //verify there was no error code - $this->assertTrue(empty($response_data['code'])); - $this->assertTrue(isset($response_data['deleted'], $response_data['previous'])); - $this->assertEquals($payment->ID(), $response_data['previous']['PAY_ID']); - $this->assertEquals($payment_count_before_deletion - 1, EEM_Payment::instance()->count()); - } - - - - /** - * Test that we tell API clients when they are using a bad parameter - * @group 9222 - */ - public function testInsertInvalidParamProvided() - { - $this->authenticate_as_admin(); - $req = new WP_REST_Request( - 'POST', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/questions' - ); - $req->set_body_params( - array( - 'non-existent-field-name' => 'restorama', - ) - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - //verify there was no error code - $this->assertTrue(isset($response_data['code'])); - $this->assertEquals('invalid_field', $response_data['code']); - } - - /** - * Test that we tell API clients when they are using a bad parameter - * @group 9222 - */ - public function testInsertPostType() - { - $this->authenticate_as_admin(); - $req = new WP_REST_Request( - 'POST', - '/' . EED_Core_Rest_Api::ee_api_namespace . '4.8.36/events' - ); - $req->set_body_params( - array( - 'post_type' => 'not-event', - 'EVT_name' => 'foobar' - ) - ); - $response = rest_do_request($req); - $response_data = $response->get_data(); - //verify there was an error code; we're not allowed to pass in post_type - $this->assertTrue(isset($response_data['code'])); - $this->assertEquals('invalid_field', $response_data['code']); - } -} -// End of file Write_Test.php -// Location: tests\testcases\core\libraries\rest_api\controllers/Write_Test.php diff --git a/tests/testcases/core/libraries/shortcodes/EE_Shortcodes_Test.php b/tests/testcases/core/libraries/shortcodes/EE_Shortcodes_Test.php deleted file mode 100644 index b36ad1ff4a3..00000000000 --- a/tests/testcases/core/libraries/shortcodes/EE_Shortcodes_Test.php +++ /dev/null @@ -1,104 +0,0 @@ -shortcode_mock = new EE_Shortcodes_Mock; - } - - - /** - * @group 10561 - */ - public function test_mutate_conditional_block_in_template() - { - $data = array( - 'template' => 'This is a template with some conditional tags.' - . ' [IF_MOCK_TEST_ONE_* id=10]Mock Test One Content A[/IF_MOCK_TEST_ONE_*]' - . ' [IF_MOCK_TEST_ONE_* id=14]Mock Test One Content B[/IF_MOCK_TEST_ONE_*]' - . ' [IF_MOCK_TEST_ONE_* id=10]Mock Test One Content C[/IF_MOCK_TEST_ONE_*]' - . ' [IF_MOCK_TEST_TWO_* something=30]Mock Test Two Content[/IF_MOCK_TEST_TWO_*]' - ); - - //not expecting this return a value because the mock doesn't have conditional shortcodes registered. - $this->assertEmpty($this->shortcode_mock->parser('', $data)); - - //test the method we're testing. - //key is shortcode to test, value is expectation on return value. - $assertions_for_hide = array( - '[IF_MOCK_TEST_ONE_* id=10]' => 'This is a template with some conditional tags.' - . ' [IF_MOCK_TEST_ONE_* id=14]Mock Test One Content B[/IF_MOCK_TEST_ONE_*]' - . ' [IF_MOCK_TEST_TWO_* something=30]Mock Test Two Content[/IF_MOCK_TEST_TWO_*]', - '[IF_MOCK_TEST_ONE_* id=14]' => 'This is a template with some conditional tags.' - . ' [IF_MOCK_TEST_ONE_* id=10]Mock Test One Content A[/IF_MOCK_TEST_ONE_*]' - . ' [IF_MOCK_TEST_ONE_* id=10]Mock Test One Content C[/IF_MOCK_TEST_ONE_*]' - . ' [IF_MOCK_TEST_TWO_* something=30]Mock Test Two Content[/IF_MOCK_TEST_TWO_*]', - '[IF_MOCK_TEST_TWO_* something=30]' => 'This is a template with some conditional tags.' - . ' [IF_MOCK_TEST_ONE_* id=10]Mock Test One Content A[/IF_MOCK_TEST_ONE_*]' - . ' [IF_MOCK_TEST_ONE_* id=14]Mock Test One Content B[/IF_MOCK_TEST_ONE_*]' - . ' [IF_MOCK_TEST_ONE_* id=10]Mock Test One Content C[/IF_MOCK_TEST_ONE_*] ' - ); - - $assertions_for_show = array( - '[IF_MOCK_TEST_ONE_* id=10]' => 'This is a template with some conditional tags.' - . ' Mock Test One Content A' - . ' [IF_MOCK_TEST_ONE_* id=14]Mock Test One Content B[/IF_MOCK_TEST_ONE_*]' - . ' Mock Test One Content C' - . ' [IF_MOCK_TEST_TWO_* something=30]Mock Test Two Content[/IF_MOCK_TEST_TWO_*]', - '[IF_MOCK_TEST_ONE_* id=14]' => 'This is a template with some conditional tags.' - . ' [IF_MOCK_TEST_ONE_* id=10]Mock Test One Content A[/IF_MOCK_TEST_ONE_*]' - . ' Mock Test One Content B' - . ' [IF_MOCK_TEST_ONE_* id=10]Mock Test One Content C[/IF_MOCK_TEST_ONE_*]' - . ' [IF_MOCK_TEST_TWO_* something=30]Mock Test Two Content[/IF_MOCK_TEST_TWO_*]', - '[IF_MOCK_TEST_TWO_* something=30]' => 'This is a template with some conditional tags.' - . ' [IF_MOCK_TEST_ONE_* id=10]Mock Test One Content A[/IF_MOCK_TEST_ONE_*]' - . ' [IF_MOCK_TEST_ONE_* id=14]Mock Test One Content B[/IF_MOCK_TEST_ONE_*]' - . ' [IF_MOCK_TEST_ONE_* id=10]Mock Test One Content C[/IF_MOCK_TEST_ONE_*]' - . ' Mock Test Two Content' - ); - - //first lets test the expectations for when a condition results in hiding the contained content. - foreach ($assertions_for_hide as $shortcode => $expectation) { - $this->shortcode_mock->parser('', $data); - $this->assertEquals( - $expectation, - $this->shortcode_mock->mutate_conditional_block_in_template( - $shortcode, - false - ), - sprintf('Testing %s shortcode in the assertions for hide tests.', $shortcode) - ); - } - - //next test the expectations for when a condition results in showing - foreach ($assertions_for_show as $shortcode => $expectation) { - //reset template to original - $this->shortcode_mock->parser('', $data); - $this->assertEquals( - $expectation, - $this->shortcode_mock->mutate_conditional_block_in_template( - $shortcode - ), - sprintf('Testing %s shortcode in the assertions for show tests.', $shortcode) - ); - } - } -} \ No newline at end of file diff --git a/tests/testcases/core/libraries/shortcodes/VenueShortcodesTest.php b/tests/testcases/core/libraries/shortcodes/VenueShortcodesTest.php deleted file mode 100644 index 97fd80199a1..00000000000 --- a/tests/testcases/core/libraries/shortcodes/VenueShortcodesTest.php +++ /dev/null @@ -1,126 +0,0 @@ -parser = new EE_Venue_Shortcodes(); - } - - public function tearDown() - { - parent::tearDown(); - $this->parser = null; - } - - - /** - * - * @return array - */ - protected function getVenueTestValues() - { - return array( - 'VNU_name' => 'Macadassy Hall', - 'VNU_address' => '10th St. & Constitution Ave. NW', - 'VNU_city' => 'Washington', - 'STA_ID' => 10, //District of Columnbia - 'CNT_ISO' => 'US', //United States - 'VNU_zip' => '20560', - 'VNU_desc' => 'test_description', - 'VNU_url' => 'http://testvenue.com', - 'VNU_phone' => '123-123-1234', - 'VNU_address2' => '', - ); - } - - - /** - * Data provider for tests. - * @return array - */ - public function venueShortcodeValuesProvider() - { - $testData = $this->getVenueTestValues(); - $google_map_url = htmlentities2( - 'http://maps.google.com/maps?q=' . urlencode( - $testData['VNU_address'] - . ',' . $testData['VNU_city'] - . ',' . 'District of Columbia' - . ',' . $testData['VNU_zip'] - . ',' . 'United States' - ) - ); - return array( - array('[VENUE_TITLE]', $testData['VNU_name']), - array('[VENUE_DESCRIPTION]', $testData['VNU_desc']), - array('[VENUE_URL]', $testData['VNU_url']), - array('[VENUE_PHONE]', $testData['VNU_phone']), - array('[VENUE_ADDRESS]', $testData['VNU_address']), - array('[VENUE_ADDRESS2]', $testData['VNU_address2']), - array('[VENUE_CITY]', $testData['VNU_city']), - array('[VENUE_COUNTRY]', 'United States'), - array('[VENUE_STATE]', 'District of Columbia'), - array('[VENUE_ZIP]', $testData['VNU_zip']), - array( - '[VENUE_FORMATTED_ADDRESS]', - '
    10th St. & Constitution Ave. NW
    Washington
    District of Columbia
    20560
    United States
    ' - ), - array('[GOOGLE_MAP_URL]', $google_map_url), - array( - '[GOOGLE_MAP_LINK]', - '' - . $google_map_url - . '' - ) - ); - } - - - /** - * Returns an Event object for use by the Venue Shortcodes library tests. - * return EE_Event - */ - protected function getDataForShortcodes() - { - //setup a venue for the event for our tests. - $venue = $this->factory->venue->create($this->getVenueTestValues()); - /** @var EE_Event $event */ - $event = $this->factory->event->create(); - $event->_add_relation_to($venue, 'Venue'); - $event->save(); - return $event; - } - - - /** - * @dataProvider venueShortcodeValuesProvider - * @param string $shortcode_tested - * @param string $expected - */ - public function testShortcodes($shortcode_tested, $expected) - { - $this->assertEquals($expected, $this->parser->parser($shortcode_tested, $this->getDataForShortcodes())); - } - -} \ No newline at end of file diff --git a/tests/testcases/core/request_stack/RequestTest.php b/tests/testcases/core/request_stack/RequestTest.php deleted file mode 100644 index f9816e3c062..00000000000 --- a/tests/testcases/core/request_stack/RequestTest.php +++ /dev/null @@ -1,485 +0,0 @@ - 'edit', - 'id' => 123, - 'event-name-123' => 'Event 123', - ); - } - - public function postParams(array $params = array()) - { - return $params + array( - 'input-a' => 'A', - 'input-b' => 'B', - 'sub' => array( - 'sub-a' => 'AA', - 'sub-b' => 'BB', - 'sub-sub' => array( - 'sub-sub-a' => 'AAA', - 'sub-sub-b' => 'BBB', - ) - ), - ); - } - - public function cookieParams(array $params = array()) - { - return $params + array( - 'PHPSESSID' => 'abcdefghijklmnopqrstuvwxyz', - 'cookie_test' => 'a1b2c3d4e5f6g7h8i9j0.12345678', - ); - } - - - /** - * @param array $get - * @param array $post - * @param array $cookie - * @param array $server - * @param array $files - * @return EE_Request - */ - private function getLegacyRequest(array $get, array $post, array $cookie, array $server, array $files = array()) - { - $request = new Request($get, $post, $cookie, $server, $files); - $legacy_request = new EE_Request(array(), array(), array()); - $legacy_request->setRequest($request); - return $legacy_request; - } - - - public function testGetParams() - { - $request = $this->getLegacyRequest( - $this->getParams(), - array(), - array(), - array() - ); - $this->assertEquals( - $this->getParams(), - $request->get_params() - ); - } - - public function testPostParams() - { - $request = $this->getLegacyRequest( - array(), - $this->postParams(), - array(), - array() - ); - $this->assertEquals( - $this->postParams(), - $request->post_params() - ); - } - - public function testCookieParams() - { - $request = $this->getLegacyRequest( - array(), - array(), - $this->cookieParams(), - array() - ); - $this->assertEquals( - $this->cookieParams(), - $request->cookie_params() - ); - } - - public function testParams() - { - $request = $this->getLegacyRequest( - $this->getParams(), - $this->postParams(), - array(), - array() - ); - $this->assertEquals( - array_merge($this->getParams(), $this->postParams()), - $request->params() - ); - } - - public function testSet() - { - $request = $this->getLegacyRequest( - $this->getParams(), - array(), - array(), - array() - ); - $key = 'new-key'; - $value = 'ima noob'; - $request->set($key, $value); - $params = $request->params(); - $this->assertArrayHasKey($key, $params); - $this->assertEquals($value, $params[$key]); - } - - public function testSetEE() - { - $request = $this->getLegacyRequest( - $this->getParams(), - array(), - array(), - array() - ); - $request->set('ee', 'module-route'); - $params = $request->params(); - $this->assertArrayHasKey('ee', $params); - $this->assertEquals('module-route', $params['ee']); - } - - public function testAlreadySetEE() - { - $request = $this->getLegacyRequest( - $this->getParams(array('ee' => 'existing-route')), - array(), - array(), - array() - ); - $request->set('ee', 'module-route'); - $params = $request->params(); - $this->assertArrayHasKey('ee', $params); - $this->assertNotEquals('module-route', $params['ee']); - $this->assertEquals('existing-route', $params['ee']); - } - - public function testOverrideAlreadySetEE() - { - $request = $this->getLegacyRequest( - $this->getParams(array('ee' => 'existing-route')), - array(), - array(), - array() - ); - $request->set('ee', 'module-route', true); - $params = $request->params(); - $this->assertArrayHasKey('ee', $params); - $this->assertEquals('module-route', $params['ee']); - } - - - - public function testGet() - { - $request = $this->getLegacyRequest( - $this->getParams(), - array(), - array(), - array() - ); - // key exists - $this->assertEquals('edit', $request->get('action')); - // key does NOT exist and no default value set - $this->assertNotEquals('edit', $request->get('me-no-key')); - $this->assertNull($request->get('me-no-key')); - // key does NOT exist but default value set - $this->assertNotEquals( - 'edit', - $request->get('me-no-key', 'me-default') - ); - $this->assertEquals( - 'me-default', - $request->get('me-no-key', 'me-default') - ); - } - - - - public function testGetWithDrillDown() - { - $request = $this->getLegacyRequest( - array(), - $this->postParams(), - array(), - array() - ); - // our post data looks like this: - // array( - // 'input-a' => 'A', - // 'input-b' => 'B', - // 'sub' => array( - // 'sub-a' => 'AA', - // 'sub-b' => 'BB', - // 'sub-sub' => array( - // 'sub-sub-a' => 'AAA', - // 'sub-sub-b' => 'BBB', - // ) - // ) - // ); - // top-level value - $this->assertEquals('A', $request->get('input-a')); - $this->assertEquals('B', $request->get('input-b')); - // second level - $this->assertEquals('AA', $request->get('sub[sub-a]')); - $this->assertEquals('BB', $request->get('sub[sub-b]')); - // third level - $this->assertEquals('AAA', $request->get('sub[sub-sub][sub-sub-a]')); - $this->assertEquals('BBB', $request->get('sub[sub-sub][sub-sub-b]')); - // does not exist - $this->assertNull($request->get('input-c')); - $this->assertNull($request->get('sub[sub-c]')); - $this->assertNull($request->get('sub[sub-sub][sub-sub-c]')); - } - - - - public function testIsSet() - { - $request = $this->getLegacyRequest( - $this->getParams(), - array(), - array(), - array() - ); - $this->assertTrue($request->is_set('action')); - $this->assertFalse($request->is_set('me-no-key')); - } - - - - public function testIsSetWithDrillDown() - { - $request = $this->getLegacyRequest( - array(), - $this->postParams(), - array(), - array() - ); - // our post data looks like this: - // array( - // 'input-a' => 'A', - // 'input-b' => 'B', - // 'sub' => array( - // 'sub-a' => 'AA', - // 'sub-b' => 'BB', - // 'sub-sub' => array( - // 'sub-sub-a' => 'AAA', - // 'sub-sub-b' => 'BBB', - // ) - // ) - // ); - // top-level value - $this->assertTrue($request->is_set('input-a')); - $this->assertTrue($request->is_set('input-b')); - // second level - $this->assertTrue($request->is_set('sub[sub-a]')); - $this->assertTrue($request->is_set('sub[sub-b]')); - // third level - $this->assertTrue($request->is_set('sub[sub-sub][sub-sub-a]')); - $this->assertTrue($request->is_set('sub[sub-sub][sub-sub-b]')); - // not set - $this->assertFalse($request->is_set('input-c')); - $this->assertFalse($request->is_set('sub[sub-c]')); - $this->assertFalse($request->is_set('sub[sub-sub][sub-sub-c]')); - } - - - - public function testUnSet() - { - // do the chevy shuffle with the $_REQUEST global - // in case it's needed by other tests - $EXISTING_REQUEST = $_REQUEST; - $_REQUEST = $this->getParams(); - $request = $this->getLegacyRequest( - $_REQUEST, - array(), - array(), - array() - ); - $this->assertTrue($request->is_set('action')); - $request->un_set('action'); - $this->assertFalse($request->is_set('action')); - $this->assertTrue(isset($_REQUEST['action'])); - // unset 'id' param but from GLOBAL too - $this->assertTrue($request->is_set('id')); - $request->un_set('id', true); - $this->assertFalse($request->is_set('id')); - $this->assertFalse(isset($_REQUEST['id'])); - // reinstate $_REQUEST global - $_REQUEST = $EXISTING_REQUEST; - } - - - - public function testIpAddress() - { - // do the chevy shuffle with the $_SERVER global - // in case it's needed by other tests - $EXISTING_SERVER = $_SERVER; - $server_keys = array( - 'HTTP_CLIENT_IP', - 'HTTP_X_FORWARDED_FOR', - 'HTTP_X_FORWARDED', - 'HTTP_X_CLUSTER_CLIENT_IP', - 'HTTP_FORWARDED_FOR', - 'HTTP_FORWARDED', - 'REMOTE_ADDR', - ); - $x = 0; - // let's test 100 random IP addresses - while ($x < 100) { - // first clear out entries from previous test - foreach ($server_keys as $server_key) { - unset($_SERVER[$server_key]); - } - // randomly generate IP address. plz see: https://stackoverflow.com/a/39846883 - $ip_address = long2ip(mt_rand() + mt_rand() + mt_rand(0, 1)); - // then randomly populate one of the $_SERVER keys used to determine the IP - $_SERVER[$server_keys[mt_rand(0, 6)]] = $ip_address; - $request = $this->getLegacyRequest(array(), array(), array(), $_SERVER); - $this->assertEquals($ip_address, $request->ip_address()); - unset($request); - $x++; - } - // reinstate $_SERVER global - $_SERVER = $EXISTING_SERVER; - } - - - public function testMatches() - { - $request = $this->getLegacyRequest( - $this->getParams(), - array(), - array(), - array() - ); - $this->assertTrue($request->matches('event-*')); - $this->assertTrue($request->matches('*-name-*')); - $this->assertTrue($request->matches('event-name-*')); - $this->assertTrue($request->matches('event*name*')); - $this->assertTrue($request->matches('event?name*')); - $this->assertTrue($request->matches('event-name-123')); - $this->assertFalse($request->matches('event-name-?')); - } - - - public function testMatchesWithDrillDown() - { - $request = $this->getLegacyRequest( - array(), - $this->postParams(), - array(), - array() - ); - // our post data looks like this: - // array( - // 'input-a' => 'A', - // 'input-b' => 'B', - // 'sub' => array( - // 'sub-a' => 'AA', - // 'sub-b' => 'BB', - // 'sub-sub' => array( - // 'sub-sub-a' => 'AAA', - // 'sub-sub-b' => 'BBB', - // ) - // ) - // ); - // top-level value - $this->assertTrue($request->matches('input-?')); - $this->assertTrue($request->matches('input-*')); - // second level - $this->assertTrue($request->matches('sub[sub-?]')); - $this->assertTrue($request->matches('sub[sub-*]')); - // third level - $this->assertTrue($request->matches('sub[sub-sub][sub-sub-?]')); - $this->assertTrue($request->matches('sub[sub-sub][sub-sub-*]')); - // not set - $this->assertFalse($request->matches('input-c-*')); - $this->assertFalse($request->matches('sub[sub-c-*]')); - $this->assertFalse($request->matches('sub[sub-sub-*][sub-sub-c]')); - } - - public function testGetMatch() - { - $request = $this->getLegacyRequest( - $this->getParams(), - array(), - array(), - array() - ); - $this->assertEquals('Event 123', $request->getMatch('event-*')); - $this->assertEquals('Event 123', $request->getMatch('*-name-*')); - $this->assertEquals('Event 123', $request->getMatch('event-name-*')); - $this->assertEquals('Event 123', $request->getMatch('event*name*')); - $this->assertEquals('Event 123', $request->getMatch('event?name*')); - $this->assertEquals('Event 123', $request->getMatch('event-name-123')); - $this->assertNull($request->getMatch('event-name-?')); - // with default - $this->assertEquals('default', $request->getMatch('event-name-?', 'default')); - } - - - public function testGetMatchWithDrillDown() - { - $request = $this->getLegacyRequest( - array(), - $this->postParams(), - array(), - array() - ); - // our post data looks like this: - // array( - // 'input-a' => 'A', - // 'input-b' => 'B', - // 'sub' => array( - // 'sub-a' => 'AA', - // 'sub-b' => 'BB', - // 'sub-sub' => array( - // 'sub-sub-a' => 'AAA', - // 'sub-sub-b' => 'BBB', - // ) - // ) - // ); - // top-level value - $this->assertEquals('A', $request->getMatch('input-?')); - $this->assertEquals('A', $request->getMatch('input-*')); - // with default - $this->assertEquals('default', $request->getMatch('not-an-input-?', 'default')); - // second level - $this->assertEquals('AA', $request->getMatch('sub[sub-?]')); - $this->assertEquals('AA', $request->getMatch('sub[sub-*]')); - // with default - $this->assertEquals('default', $request->getMatch('sub[not-an-input-?]', 'default')); - // third level - $this->assertEquals('AAA', $request->getMatch('sub[sub-sub][sub-sub-?]')); - $this->assertEquals('AAA', $request->getMatch('sub[sub-sub][sub-sub-*]')); - // with default - $this->assertEquals('default', $request->getMatch('sub[sub-sub][not-an-input-?]', 'default')); - // not set - $this->assertNull($request->getMatch('input-c-*')); - $this->assertNull($request->getMatch('sub[sub-c-*]')); - $this->assertNull($request->getMatch('sub[sub-sub-*][sub-sub-c]')); - } -} -// Location: tests/testcases/core/request_stack/RequestTest.php diff --git a/tests/testcases/core/services/assets/I18nRegistryTest.php b/tests/testcases/core/services/assets/I18nRegistryTest.php deleted file mode 100644 index 07bb25722a7..00000000000 --- a/tests/testcases/core/services/assets/I18nRegistryTest.php +++ /dev/null @@ -1,89 +0,0 @@ - array( - 'Do you have a moment to share why you are deactivating Event Espresso?', - "Sure I'll help", - 'Skip' - ), - ); - $this->i18n = new I18nRegistryMock( - $test_map, - $domain - ); - parent::setUp(); - } - - - public function tearDown() - { - parent::tearDown(); - $this->i18n = null; - } - - - /** - * see https://github.com/eventespresso/event-espresso-core/pull/458 - * @group 458 - */ - public function testInlineScriptsOnlyQueuedOnce() - { - // simulate registering the script handle - $this->i18n->registerScriptI18n('test'); - - //let's trigger `print_scripts_array` twice. - apply_filters('print_scripts_array', array('test')); - apply_filters('print_scripts_array', array('test')); - - //now we expect `registerInlineScript to have been called only once - $this->assertEquals( 1, $this->i18n->getCountOfMethodCalled( - 'EventEspresso\tests\mocks\core\services\assets\I18nRegistryMock::registerInlineScript' - ) ); - - //register script again *gasp* - $this->i18n->registerScriptI18n('test'); - - //call apply_filters again - apply_filters('print_scripts_array', array('test')); - - //still should only have been called once - $this->assertEquals( 1, $this->i18n->getCountOfMethodCalled( - 'EventEspresso\tests\mocks\core\services\assets\I18nRegistryMock::registerInlineScript' - ) ); - } -} \ No newline at end of file diff --git a/tests/testcases/core/services/assets/RegistryTest.php b/tests/testcases/core/services/assets/RegistryTest.php deleted file mode 100644 index 0f432a4e648..00000000000 --- a/tests/testcases/core/services/assets/RegistryTest.php +++ /dev/null @@ -1,185 +0,0 @@ -registry = new Registry( - new AssetCollection(), - new i18nRegistry(array(), $domain) - ); - parent::setUp(); - } - - - public function tearDown() - { - parent::tearDown(); - $this->registry = null; - } - - - /** - * @throws InvalidArgumentException - */ - public function test_addData_no_previous_scalar() - { - $this->registry->addData('test', 'has_data'); - $actual = $this->registry->getData('test'); - $this->assertEquals('has_data', $actual); - } - - - /** - * @throws InvalidArgumentException - */ - public function test_addData_no_previous_array() - { - $this->registry->addData('test', array('has_data')); - $actual = $this->registry->getData('test'); - $this->assertEquals('has_data', $actual[0]); - } - - - /** - * @expectedException InvalidArgumentException - */ - public function test_addData_no_overwrite_array() - { - $this->registry->addData('test', array('initial_value')); - $this->registry->addData('test', array('another_value')); - } - - - /** - * @expectedException InvalidArgumentException - */ - public function test_addData_no_overwrite_scalar() - { - $this->registry->addData('test', 'initial_value'); - $this->registry->addData('test', 'cause_exception'); - } - - /** - * @expectedException InvalidArgumentException - * @group 10304 - */ - public function test_addTemplate_no_overwrite() - { - $this->registry->addTemplate('test', 'some_test_content'); - $this->registry->addTemplate('test', 'cause exception'); - } - - - public function pushDataWithArrayProvider() - { - return [ - 'initial creation of dataset when it does not exist' => ['test', 'foo', ['foo']], - 'adding a string to existing dataset' => ['test', 'bar', ['foo', 'bar']], - 'adding an array to existing dataset' => [ - 'test', - ['howdy', 'there'], - ['foo', 'bar', 'howdy', 'there'], - ], - ]; - } - - - /** - * @throws InvalidArgumentException - */ - public function testPushDataWithArrayAddingData() - { - foreach ($this->pushDataWithArrayProvider() as $test_description => $test_data) { - list($key, $value, $expected) = $test_data; - $this->registry->pushData($key, $value); - $this->assertEquals($expected, $this->registry->getData($key), $test_description); - } - } - - - /** - * @expectedException InvalidArgumentException - */ - public function testPushDataExceptionWhenExistingDataIsScalar() - { - $this->registry->addData( 'test', 'foo' ); - $this->registry->pushData( 'test', 'bar' ); - } - - - public function pushDataWithAssociativeArrayProvider() - { - return [ - 'initial creation of dataset' => ['test', ['a' => 'foo'], ['a' => 'foo']], - 'adding new item with different key' => ['test', ['b' => 'bar'], ['a' => 'foo', 'b' => 'bar']], - 'adding new item with pre-existing key' => ['test', ['a' => 'bar'], ['a' => 'bar', 'b' => 'bar']], - 'adding scalar array' => ['test', 'hello', ['a' => 'bar', 'b' => 'bar', 'hello']], - ]; - } - - - public function testPushDataWithAssociativeArray() - { - foreach ($this->pushDataWithAssociativeArrayProvider() as $test_description => $test_data) { - list($key, $value, $expected) = $test_data; - $this->registry->pushData($key, $value); - $this->assertEquals($expected, $this->registry->getData($key), $test_description); - } - } - - - /** - * @group 10304 - * @throws InvalidArgumentException - */ - public function test_getTemplate() - { - $this->registry->addTemplate('test', 'some test content'); - $this->assertEquals('some test content', $this->registry->getTemplate('test')); - } -} -// location: tests/testcases/core/services/assets/RegistryTest.php diff --git a/tests/testcases/core/services/cache/PostRelatedCacheManagerTest.php b/tests/testcases/core/services/cache/PostRelatedCacheManagerTest.php deleted file mode 100644 index 2e6339170a9..00000000000 --- a/tests/testcases/core/services/cache/PostRelatedCacheManagerTest.php +++ /dev/null @@ -1,147 +0,0 @@ -cache_manager = new PostRelatedCacheManagerMock( - new CacheStorageMock() - ); - } - - - private function getPostRelatedCache() - { - return (array)get_option(PostRelatedCacheManager::POST_CACHE_OPTIONS_KEY, array()); - } - - - private function updatePostRelatedCache(array $mock_cache = array()) - { - update_option(PostRelatedCacheManager::POST_CACHE_OPTIONS_KEY, $mock_cache); - } - - - public function testCachePrefix() - { - $this->assertEquals('ee_cache_post_', $this->cache_manager->cachePrefix()); - } - - - public function testGetPostRelatedCache() - { - $this->updatePostRelatedCache(array(123 => array('MOCK_CACHE'))); - $mock_cache = $this->cache_manager->getPostRelatedCache(); - $this->assertCount(1, $mock_cache); - $this->assertArrayHasKey(123, $mock_cache); - $this->assertCount(1, $mock_cache[123]); - $this->assertArrayContains('MOCK_CACHE', $mock_cache[123]); - // now test what happens if the cache is corrupted (need to update option directly) - update_option(PostRelatedCacheManager::POST_CACHE_OPTIONS_KEY, 'i am not serialized data'); - $this->assertEmpty($this->cache_manager->getPostRelatedCache()); - } - - - public function testUpdatePostRelatedCache() - { - // first save nothing to the cache - $this->updatePostRelatedCache(); - $this->assertEmpty($this->getPostRelatedCache()); - // then add our mock cache and verify - $this->cache_manager->updatePostRelatedCache(array(123 => array('MOCK_CACHE'))); - $mock_cache = $this->getPostRelatedCache(); - $this->assertCount(1, $mock_cache); - $this->assertArrayHasKey(123, $mock_cache); - $this->assertCount(1, $mock_cache[123]); - $this->assertArrayContains('MOCK_CACHE', $mock_cache[123]); - } - - - public function testClearPostRelatedCacheOnUpdate() - { - $this->updatePostRelatedCache(); - $this->assertEmpty($this->getPostRelatedCache()); - $this->cache_manager->clearPostRelatedCacheOnUpdate(123, 'MOCK_CACHE'); - $mock_cache = $this->getPostRelatedCache(); - $this->assertCount(1, $mock_cache); - $this->assertArrayHasKey(123, $mock_cache); - $this->assertCount(1, $mock_cache[123]); - $this->assertArrayContains('MOCK_CACHE', $mock_cache[123]); - // now try adding a duplicate, which should not happen - $this->cache_manager->clearPostRelatedCacheOnUpdate(123, 'MOCK_CACHE'); - $mock_cache = $this->getPostRelatedCache(); - $this->assertCount(1, $mock_cache); - $this->assertArrayHasKey(123, $mock_cache); - $this->assertCount(1, $mock_cache[123]); - $this->assertArrayContains('MOCK_CACHE', $mock_cache[123]); - } - - - public function testClearPostRelatedCache() - { - $this->updatePostRelatedCache(array(123 => array('MOCK_CACHE'))); - // first assert that the above exists as expected - $mock_cache = $this->getPostRelatedCache(); - $this->assertCount(1, $mock_cache); - $this->assertArrayHasKey(123, $mock_cache); - $this->assertCount(1, $mock_cache[123]); - $this->assertArrayContains('MOCK_CACHE', $mock_cache[123]); - // now clear it - $this->cache_manager->clearPostRelatedCache(123); - $this->assertEmpty($this->getPostRelatedCache()); - // now add a bunch of duplicated garbage - $this->updatePostRelatedCache( - array( - 123 => array( - 0 => 'MOCK_CACHE', - 1 => 'MOCK_CACHE', - 2 => 'MOCK_CACHE', - 3 => 'MOCK_CACHE', - 4 => 'MOCK_CACHE', - 5 => 'MOCK_CACHE', - ) - ) - ); - // and assert that the above exists as expected - $mock_cache = $this->getPostRelatedCache(); - $this->assertCount(1, $mock_cache); - $this->assertArrayHasKey(123, $mock_cache); - $this->assertCount(6, $mock_cache[123]); - $this->assertArrayContains('MOCK_CACHE', $mock_cache[123]); - // now attempt to clear another post ID that doesn't exist, which should clear duplicates - $this->cache_manager->clearPostRelatedCache(456); - $mock_cache = $this->getPostRelatedCache(); - $this->assertCount(1, $mock_cache); - $this->assertArrayHasKey(123, $mock_cache); - $this->assertCount(1, $mock_cache[123]); - $this->assertArrayContains('MOCK_CACHE', $mock_cache[123]); - } - -} -// Location: tests/testcases/core/services/cache/PostRelatedCacheManagerTest.php diff --git a/tests/testcases/core/services/cache/TransientCacheStorageTest.php b/tests/testcases/core/services/cache/TransientCacheStorageTest.php deleted file mode 100644 index b6ec5e9a2ae..00000000000 --- a/tests/testcases/core/services/cache/TransientCacheStorageTest.php +++ /dev/null @@ -1,219 +0,0 @@ -cache_storage = new \EventEspresso\core\services\cache\TransientCacheStorage(); - parent::setUp(); - } - - - - public function tearDown() - { - parent::tearDown(); - $this->cache_storage = null; - } - - - - /** - * @see http://stackoverflow.com/a/4356295 - * @param int $length - * @return string - */ - private function generateRandomString($length = 100) - { - $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; - $charactersLength = strlen($characters); - $randomString = ''; - for ($i = 0; $i < $length; $i++) { - $randomString .= $characters[mt_rand(0, $charactersLength - 1)]; - } - return $randomString; - } - - - /** - * @group CacheStorageInterface - * @group slow_test - */ - public function test_add() - { - // echo "\n\n** " . __LINE__ . ") " . __METHOD__ . '() **'; - $key = __FUNCTION__; - $data = $this->generateRandomString(); - $added = $this->cache_storage->add($key, $data); - $this->assertTrue($added, __LINE__ . ") Transient {$key} was not added"); - $transient = get_transient($key); - $this->assertEquals($data, $transient); - // now test expiration - $key = __FUNCTION__ . '_expires_in_1_second'; - $added = $this->cache_storage->add($key, $data, 1); - $this->assertTrue($added, __LINE__ . ") Transient {$key} was not added"); - // wait 2 seconds - sleep(2); - $transient = get_transient($key); - $this->assertFalse($transient, __LINE__ . ") Transient {$key} returned data when it should not have"); - } - - - - /** - * @group CacheStorageInterface - * @group slow_test - */ - public function test_get() - { - // echo "\n\n** " . __LINE__ . ") " . __METHOD__ . '() **'; - $key = __FUNCTION__; - $data = $this->generateRandomString(); - $added = $this->cache_storage->add($key, $data); - $this->assertTrue($added, __LINE__ . ") Transient {$key} was not added"); - $transient = $this->cache_storage->get($key); - $this->assertEquals($data, $transient); - // now test expiration - $key = __FUNCTION__ . '_expires_in_1_second'; - $added = $this->cache_storage->add($key, $data, 1); - $this->assertTrue($added, __LINE__ . ") Transient {$key} was not added"); - // wait 2 seconds - sleep(2); - $transient = $this->cache_storage->get($key); - $this->assertNull($transient, __LINE__ . ") Transient {$key} returned data when it should not have"); - // now test standard cache early expiration - $key = __FUNCTION__ . '_expires_in_60_seconds'; - $added = $this->cache_storage->add($key, $data, 60); - $this->assertTrue($added, __LINE__ . ") Transient {$key} was not added"); - // wait 2 seconds - sleep(2); - $transient = $this->cache_storage->get($key); - // should be null because this request should trigger cache regeneration - // BEFORE the cache actually expires in roughly 58 seconds - $this->assertNull($transient, __LINE__ . ") Transient {$key} returned data when it should not have"); - // now attempt to retrieve the cache again, - $transient = $this->cache_storage->get($key); - // however, this second request should receive the cached content - // that still exists from before, therefore avoiding a cache stampede, - // (assuming the previous get() can regenerate the content in time) - $this->assertEquals($data, $transient, __LINE__ . ") Transient {$key} returned incorrect data"); - // now test with standard cache early expiration turned off - $key = __FUNCTION__ . '_not_standard_cache'; - $added = $this->cache_storage->add($key, $data, 60); - $this->assertTrue($added, __LINE__ . ") Transient {$key} was not added"); - // wait 2 seconds - sleep(2); - $transient = $this->cache_storage->get($key, false); - // cached content should be returned despite expiration being less than 60 seconds - // therefore avoiding a cache stampede, - // (assuming the previous get() can regenerate the content in time) - $this->assertEquals($data, $transient, __LINE__ . ") Transient {$key} returned incorrect data"); - } - - - /** - * @group CacheStorageInterface - */ - public function test_delete() - { - // echo "\n\n** " . __LINE__ . ") " . __METHOD__ . '() **'; - $key = __FUNCTION__; - $data = $this->generateRandomString(); - $added = $this->cache_storage->add($key, $data, 300); - $this->assertTrue($added, __LINE__ . ") Transient {$key} was not added"); - $transient = get_transient($key); - $this->assertEquals($data, $transient, __LINE__ . ") Transient {$key} returned incorrect data"); - $this->cache_storage->delete($key); - $transient = get_transient($key); - $this->assertFalse($transient, __LINE__ . ") Transient {$key} returned data when it should not have"); - } - - - - /** - * @group CacheStorageInterface - */ - public function test_deleteMany() - { - // echo "\n\n** " . __LINE__ . ") " . __METHOD__ . '() **'; - $data = $this->generateRandomString(); - $tests = array( - '_no_expiration_' => 0, - '_expires_in_5_minutes_' => 5 * MINUTE_IN_SECONDS, - '_expires_in_1_hour_' => HOUR_IN_SECONDS, - ); - foreach ($tests as $test => $expiration) { - // add transient with nearly identical name to confirm - // that deletion does not target transients it shouldn't - $added = set_transient($test, 'plz do not delete me', HOUR_IN_SECONDS); - $this->assertTrue($added, __LINE__ . ") Transient {$test} was not added"); - for ($x = 0; $x < 4; $x++) { - $key = __FUNCTION__ . $test . $x; - $added = $this->cache_storage->add($key, $data, $expiration); - $this->assertTrue($added, __LINE__ . ") Transient {$key} was not added"); - // assert that all transients exist - $transient = $this->cache_storage->get($key); - $this->assertEquals($data, $transient, __LINE__ . ") Transient {$key} returned incorrect data"); - } - } - // delete transients that expire in 5 minutes - $this->cache_storage->deleteMany(array(__FUNCTION__ . '_expires_in_5_minutes_')); - $results = array( - '_no_expiration_' => $data, - '_expires_in_5_minutes_' => false, - '_expires_in_1_hour_' => $data, - ); - foreach ($results as $test => $result) { - for ($x = 0; $x < 4; $x++) { - $key = __FUNCTION__ . $test . $x; - $message = $result - ? "Transient {$key} does not exist when it should" - : "Transient {$key} exists when it should not"; - $this->assertEquals($result, get_transient($key), $message); - } - // now confirm our similarly named transients still exist - $this->assertEquals( - 'plz do not delete me', - get_transient($test), - "Transient {$test} does not exist when it should" - ); - } - } - - - -} -// End of file CacheStorageTest.php -// Location:/tests/testcases/core/services/cache/TransientCacheStorageTest.php \ No newline at end of file diff --git a/tests/testcases/core/services/collections/iterators/CollectionFilterCallbackIteratorTest.php b/tests/testcases/core/services/collections/iterators/CollectionFilterCallbackIteratorTest.php deleted file mode 100644 index f83d1d40b70..00000000000 --- a/tests/testcases/core/services/collections/iterators/CollectionFilterCallbackIteratorTest.php +++ /dev/null @@ -1,62 +0,0 @@ -loose_collection = new LooseCollection(''); - parent::setUp(); - } - - - - public function tearDown() - { - parent::tearDown(); - $this->loose_collection = null; - } - - - public function testGetFiltered(){ - $ints = array(1,2,6,10,5,4,7,9,3,8); - foreach ($ints as $int) { - $this->loose_collection->add(new BasicIntVoMock($int)); - } - $filter_only_even_values = new CollectionFilterCallbackIterator( - $this->loose_collection, - function (BasicIntVoMock $int_vo) { - return $int_vo->intValue() % 2 === 0; - } - ); - $this->assertCount(5, $filter_only_even_values->getFiltered()); - //filter a specific number - $filter_num_six = new CollectionFilterCallbackIterator( - $this->loose_collection, - function (BasicIntVoMock $int_vo) { - return $int_vo->intValue() === 6; - } - ); - $filtered = $filter_num_six->getFiltered(); - $this->assertEquals(6, reset($filtered)->intValue()); - } -} \ No newline at end of file diff --git a/tests/testcases/core/services/commands/CommandBusTest.php b/tests/testcases/core/services/commands/CommandBusTest.php deleted file mode 100644 index d5905ec4216..00000000000 --- a/tests/testcases/core/services/commands/CommandBusTest.php +++ /dev/null @@ -1,205 +0,0 @@ - EE_Dependency_Map::load_from_cache,) - ); - // need to override the existing alias for the CommandHandlerManagerInterface - // or else the REAL class will still get used - EE_Dependency_Map::instance()->add_alias( - 'EventEspresso\tests\mocks\core\services\commands\CommandHandlerManagerMock', - 'EventEspresso\core\services\commands\CommandHandlerManagerInterface' - ); - parent::setUp(); - } - - - /** - * @param array $middleware - * @throws \PHPUnit\Framework\Exception - */ - protected function setupCommandBus(array $middleware = array()) - { - // setup a Bus that uses our Mocked CommandHandlerManager - $this->command_bus = new EventEspresso\core\services\commands\CommandBus( - new EventEspresso\tests\mocks\core\services\commands\CommandHandlerManagerMock(), - $middleware - ); - $this->assertInstanceOf( - 'EventEspresso\core\services\commands\CommandBus', - $this->command_bus - ); - } - - - /** - * @throws \PHPUnit\Framework\Exception - */ - public function testGetCommandHandlerManager() - { - $this->setupCommandBus(); - $this->assertInstanceOf( - 'EventEspresso\tests\mocks\core\services\commands\CommandHandlerManagerMock', - $this->command_bus->getCommandHandlerManager() - ); - } - - - /** - * @throws InvalidArgumentException - * @throws \EventEspresso\core\exceptions\InvalidDataTypeException - * @throws \EventEspresso\core\services\commands\InvalidCommandHandlerException - * @throws \EventEspresso\core\services\commands\middleware\InvalidCommandBusMiddlewareException - * @throws \PHPUnit\Framework\Exception - */ - public function testExecute() - { - $this->setupCommandBus(); - // final results we want to see from CommandHandler - $you_did_it = 'you done gone an did it now'; - // create CommandHandler and set the results - $command_handler = new MockCommandHandler(); - $command_handler->results = $you_did_it; - // the Command we want to use - $command_fqcn = 'EventEspresso\tests\mocks\core\services\commands\MockCommand'; - $command_handler_manager = $this->command_bus->getCommandHandlerManager(); - // associate CommandHandler with the above Command - $command_handler_manager->addCommandHandler( - $command_handler, - $command_fqcn - ); - // execute Command and get results - $results = $this->command_bus->execute(new MockCommand()); - $this->assertEquals($you_did_it, $results); - } - - - /** - * @throws InvalidArgumentException - * @throws \EventEspresso\core\exceptions\InvalidDataTypeException - * @throws \EventEspresso\core\services\commands\InvalidCommandHandlerException - * @throws \EventEspresso\core\services\commands\middleware\InvalidCommandBusMiddlewareException - * @throws \PHPUnit\Framework\Exception - */ - public function testExecuteWithPassingCapCheck() - { - // add CapChecker middleware that uses Mock that always returns true - $this->setupCommandBus( - array(new CapChecker(new CapabilitiesCheckerMock())) - ); - // final results we want to see from CommandHandler - $passed = 'this command passed its cap check'; - // create CommandHandler and set the results - $command_handler = new MockCommandHandler(); - $command_handler->results = $passed; - // the Command we want to use - $command_fqcn = 'EventEspresso\tests\mocks\core\services\commands\RequiresCapCheckMockCommand'; - $command_handler_manager = $this->command_bus->getCommandHandlerManager(); - // associate CommandHandler with the above Command (note that class names don't match, but that's ok) - $command_handler_manager->addCommandHandler( - $command_handler, - $command_fqcn - ); - $results = $this->command_bus->execute(new RequiresCapCheckMockCommand()); - $this->assertEquals($passed, $results); - } - - - /** - * @throws InvalidArgumentException - * @throws \EventEspresso\core\exceptions\InvalidDataTypeException - * @throws \EventEspresso\core\services\commands\InvalidCommandHandlerException - * @throws \EventEspresso\core\services\commands\middleware\InvalidCommandBusMiddlewareException - * @throws \PHPUnit\Framework\AssertionFailedError - * @throws \PHPUnit\Framework\Exception - */ - public function testExecuteWithFailingCapCheck() - { - $capabilities_checker = new CapabilitiesCheckerMock(); - // now change the CapabilitiesChecker so that ALL cap checks fail - $capabilities_checker->cap_check_passes = false; - // add CapChecker middleware that uses Mock that always returns true - $this->setupCommandBus( - array(new CapChecker($capabilities_checker)) - ); - // final results we want to see from CommandHandler - $passed = 'this command should NOT pass its cap check'; - // create CommandHandler and set the results - $command_handler = new MockCommandHandler(); - $command_handler->results = $passed; - // the Command we want to use - $command_fqcn = 'EventEspresso\tests\mocks\core\services\commands\RequiresCapCheckMockCommand'; - $command_handler_manager = $this->command_bus->getCommandHandlerManager(); - // associate CommandHandler with the above Command - // note that the class names don't match, but that's ok, - // because this Mock doesn't really resolve classnames and instantiate objects, - // it just - $command_handler_manager->addCommandHandler( - $command_handler, - $command_fqcn - ); - $this->setExpectedException('EventEspresso\core\exceptions\InsufficientPermissionsException'); - $this->command_bus->execute(new RequiresCapCheckMockCommand()); - $this->fail('InsufficientPermissionsException should have been thrown'); - } - - /** - * @throws InvalidArgumentException - * @throws \EventEspresso\core\exceptions\InvalidDataTypeException - * @throws \EventEspresso\core\services\commands\InvalidCommandHandlerException - * @throws \EventEspresso\core\services\commands\middleware\InvalidCommandBusMiddlewareException - * @throws \PHPUnit\Framework\AssertionFailedError - * @throws \PHPUnit\Framework\Exception - */ - public function testExecuteWithIncorrectCommand() - { - $this->setupCommandBus(); - // create CommandHandler and set the results - $command_handler = new MockCommandHandler(); - // the Command that we have configured our CommandHandler to expect - $command_handler->expected = 'EventEspresso\tests\mocks\core\services\commands\MockTwoCommand'; - // the Command we are actually going to use - $command_fqcn = 'EventEspresso\tests\mocks\core\services\commands\MockCommand'; - // associate CommandHandler with the above Command - $command_handler_manager = $this->command_bus->getCommandHandlerManager(); - $command_handler_manager->addCommandHandler($command_handler, $command_fqcn); - $this->setExpectedException('EventEspresso\core\exceptions\InvalidEntityException'); - // execute Command - $this->command_bus->execute(new MockCommand()); - $this->fail('InvalidEntityException should have been thrown'); - } -} -// End of file CommandBusTest.php -// Location: testcases/core/services/commands/CommandBusTest.php diff --git a/tests/testcases/core/services/commands/CommandHandlerManagerTest.php b/tests/testcases/core/services/commands/CommandHandlerManagerTest.php deleted file mode 100644 index 4477805ec53..00000000000 --- a/tests/testcases/core/services/commands/CommandHandlerManagerTest.php +++ /dev/null @@ -1,98 +0,0 @@ - EE_Dependency_Map::load_from_cache,) - ); - parent::setUp(); - $this->command_handler_manager = EE_Registry::instance()->create( - 'EventEspresso\tests\testcases\core\services\commands\ExtendedCommandHandlerManager' - ); - } - - - - public function testAddCommandHandler() - { - $command_fqcn = 'EventEspresso\tests\mocks\core\services\commands\MockCommand'; - $this->command_handler_manager->addCommandHandler( - new MockCommandHandler(), - $command_fqcn - ); - $command_handlers = $this->command_handler_manager->getCommandHandlers(); - $this->assertArrayHasKey($command_fqcn, $command_handlers); - $this->assertInstanceOf( - 'EventEspresso\tests\mocks\core\services\commands\MockCommandHandler', - $command_handlers[$command_fqcn] - ); - } - - - - public function testGetCommandHandler() - { - // test regular CommandHandler - $command_handler = $this->command_handler_manager->getCommandHandler(new MockCommand()); - $this->assertInstanceOf( - 'EventEspresso\tests\mocks\core\services\commands\MockCommandHandler', - $command_handler - ); - } - - - - public function testGetCommandHandlerWithCompositeCommandHandler() - { - $this->command_handler_manager->addCommandHandler( - new MockCompositeCommandHandler( - new CommandBusMock(), - EE_Registry::instance()->create('EventEspresso\core\services\commands\CommandFactory') - ), - 'EventEspresso\tests\mocks\core\services\commands\MockCompositeCommand' - ); - $composite_command_handler = $this->command_handler_manager->getCommandHandler( - new MockCompositeCommand() - ); - $this->assertInstanceOf( - 'EventEspresso\tests\mocks\core\services\commands\MockCompositeCommandHandler', - $composite_command_handler - ); - $this->assertInstanceOf( - 'EventEspresso\tests\mocks\core\services\commands\CommandBusMock', - $composite_command_handler->commandBus() - ); - } - -} -// End of file CommandHandlerManagerTest.php -// Location: testcases/core/services/commands/CommandHandlerManagerTest.php \ No newline at end of file diff --git a/tests/testcases/core/services/commands/ExtendedCommandHandlerManager.php b/tests/testcases/core/services/commands/ExtendedCommandHandlerManager.php deleted file mode 100644 index 53114e524db..00000000000 --- a/tests/testcases/core/services/commands/ExtendedCommandHandlerManager.php +++ /dev/null @@ -1,35 +0,0 @@ -command_handlers; - } - - - -} -// End of file ExtendedCommandHandlerManager.php -// Location: EventEspresso\core\services\commands/ExtendedCommandHandlerManager.php \ No newline at end of file diff --git a/tests/testcases/core/services/container/CoffeeShopTest.php b/tests/testcases/core/services/container/CoffeeShopTest.php deleted file mode 100644 index 01fd1accca7..00000000000 --- a/tests/testcases/core/services/container/CoffeeShopTest.php +++ /dev/null @@ -1,612 +0,0 @@ -markTestSkipped('CoffeeShop DI not implemented yet.'); - // instantiate the container - $this->CoffeeShop = new CoffeeShop(); - // create a dependency injector class for resolving class constructor arguments - $this->DependencyInjector = new DependencyInjector( - $this->CoffeeShop, - new \EEH_Array() - ); - // and some coffeemakers, one for creating new instances - $this->CoffeeShop->addCoffeeMaker( - new NewCoffeeMaker($this->CoffeeShop, $this->DependencyInjector), - CoffeeMaker::BREW_NEW - ); - // and one for shared services - $this->CoffeeShop->addCoffeeMaker( - new SharedCoffeeMaker($this->CoffeeShop, $this->DependencyInjector), - CoffeeMaker::BREW_SHARED - ); - } - - - - public function addDefaultRecipes() - { - $this->CoffeeShop->addRecipe(new Recipe(Recipe::DEFAULT_ID)); - } - - - - public function addRecipeForRequest() - { - $this->CoffeeShop->addRecipe( - new Recipe( - 'EE_Request', - 'EE_Request', - array(), - array( - 'get'=> array(), - 'post' => array(), - 'cookie' => array(), - 'server' => array() - ), - CoffeeMaker::BREW_SHARED, - array(EE_CORE . 'request_stack/EE_Request.core.php') - ) - ); - // add recipe for Request, since we're going to need it - $this->CoffeeShop->brew( - 'EventEspresso\core\services\request\Request', - array($_GET, $_POST, $_COOKIE, $_SERVER), - CoffeeMaker::BREW_SHARED - ); - $this->CoffeeShop->addAliases( - 'EventEspresso\core\services\request\Request', - array('Request', 'EventEspresso\core\services\request\RequestInterface') - ); - /** @var EventEspresso\core\services\request\Request $request */ - $request = $this->CoffeeShop->brew('Request'); - /** @var \EE_Request $legacy_request */ - $legacy_request = $this->CoffeeShop->brew('EE_Request'); - $legacy_request->setRequest($request); - } - - - - public function test_addCoffeeMaker() - { - try { - // and CoffeeMaker for classes that do not require instantiation - $added = $this->CoffeeShop->addCoffeeMaker( - new LoadOnlyCoffeeMaker($this->CoffeeShop, $this->DependencyInjector), - CoffeeMaker::BREW_LOAD_ONLY - ); - $this->assertTrue($added); - } catch (Exception $e) { - $this->fail( - sprintf( - 'CoffeeShop::addCoffeeMaker() should Not have thrown the following Exception: %1$s' - ) - ); - } - } - - - - public function test_addClosure() - { - try { - $closure = function () { - return 'I AM CLOSURE'; - }; - $added = $this->CoffeeShop->addClosure('i-am-closure', $closure); - $this->assertInstanceOf('Closure', $added); - } catch (Exception $e) { - $this->fail( - sprintf( - 'CoffeeShop::addClosure() should Not have thrown the following Exception: %1$s', - $e->getMessage() - ) - ); - } - } - - - - public function test_addService() - { - try { - $added = $this->CoffeeShop->addService('i-am-stdClass', new stdClass()); - $this->assertTrue($added); - } catch (Exception $e) { - $this->fail( - sprintf( - 'CoffeeShop::addService() should Not have thrown the following Exception: %1$s', - $e->getMessage() - ) - ); - } - } - - - - public function test_addRecipe() - { - try { - // add default recipe, which should handle loading for most PSR-4 compatible classes - // as long as they are not type hinting for interfaces - $this->assertTrue( - $this->CoffeeShop->addRecipe(new Recipe(Recipe::DEFAULT_ID)) - ); - } catch (Exception $e) { - $this->fail( - sprintf( - 'CoffeeShop::addCoffeeMaker() should Not have thrown the following Exception: %1$s', - $e->getMessage() - ) - ); - } - } - - - - public function test_getRecipe() - { - $this->addDefaultRecipes(); - try { - $recipe = $this->CoffeeShop->getRecipe(Recipe::DEFAULT_ID); - $this->assertInstanceOf('EventEspresso\core\services\container\RecipeInterface', $recipe); - $this->assertEquals(Recipe::DEFAULT_ID, $recipe->identifier()); - $this->assertEquals(CoffeeMaker::BREW_NEW, $recipe->type()); - } catch (Exception $e) { - $this->fail( - sprintf( - 'CoffeeShop::getRecipe() should Not have thrown the following Exception: %1$s', - $e->getMessage() - ) - ); - } - } - - - - public function test_addAliases() - { - try { - $this->CoffeeShop->addAliases('EE_Class_For_Testing_Loading', array('Testing_Loading')); - } catch (Exception $e) { - $this->fail( - sprintf( - 'CoffeeShop::addAliases() should Not have thrown the following Exception: %1$s', - $e->getMessage() - ) - ); - } - } - - - - public function test_has() - { - $this->assertFalse($this->CoffeeShop->has('EE_Class_For_Testing_Loading')); - } - - - - public function test_get() - { - $this->addDefaultRecipes(); - try { - // attempt to get class that should NOT have a valid Recipe yet - $this->CoffeeShop->get('EE_Class_For_Testing_Loading'); - $this->fail('CoffeeShop::get() should have thrown an Exception'); - } catch (Exception $e) { - $this->assertInstanceOf('Exception', $e); - } - } - - - - public function test_brew_new() - { - $this->addDefaultRecipes(); - try { - // attempt to get class that should NOT have a valid Recipe yet - $this->CoffeeShop->get('EE_Class_For_Testing_Loading'); - $this->fail('CoffeeShop::get() should have thrown an Exception'); - } catch (Exception $e) { - $this->assertInstanceOf('Exception', $e); - } - // add recipe for our mock class - $added = $this->CoffeeShop->addRecipe( - new Recipe( - 'EE_Class_For_Testing_Loading', - 'EE_Class_For_Testing_Loading', - array(), - array(), - CoffeeMaker::BREW_NEW, - array( - EE_TESTS_DIR . 'mocks/core/EE_Class_For_Testing_Loading.core.php', - ) - ) - ); - $this->assertTrue($added); - // attempt to brew class - $mock1 = $this->CoffeeShop->brew('EE_Class_For_Testing_Loading'); - $this->assertInstanceOf('EE_Class_For_Testing_Loading', $mock1); - // and another one which should be a NEW instance - $mock2 = $this->CoffeeShop->brew('EE_Class_For_Testing_Loading'); - $this->assertInstanceOf('EE_Class_For_Testing_Loading', $mock2); - $this->assertFalse($mock1 === $mock2); - } - - - - public function test_brew_shared() - { - $this->addDefaultRecipes(); - try { - // attempt to get class that should NOT have a valid Recipe yet - $this->CoffeeShop->get('EE_Class_For_Testing_Loading'); - $this->fail('CoffeeShop::get() should have thrown an Exception'); - } catch (Exception $e) { - $this->assertInstanceOf('Exception', $e); - } - // add recipe for our mock class - $added = $this->CoffeeShop->addRecipe( - new Recipe( - 'EE_Class_For_Testing_Loading', - 'EE_Class_For_Testing_Loading', - array(), - array(), - CoffeeMaker::BREW_SHARED, - array( - EE_TESTS_DIR . 'mocks/core/EE_Class_For_Testing_Loading.core.php', - ) - ) - ); - $this->assertTrue($added); - // attempt to brew class - $mock1 = $this->CoffeeShop->brew('EE_Class_For_Testing_Loading'); - $this->assertInstanceOf('EE_Class_For_Testing_Loading', $mock1); - // and another one which should be the SAME instance - $mock2 = $this->CoffeeShop->brew('EE_Class_For_Testing_Loading'); - $this->assertInstanceOf('EE_Class_For_Testing_Loading', $mock2); - $this->assertTrue($mock1 === $mock2); - } - - - - public function test_brew_new_with_wildcard_recipe() - { - $this->addDefaultRecipes(); - try { - // attempt to get class that should NOT have a valid Recipe yet - $this->CoffeeShop->get('EE_Taxes'); - $this->fail('CoffeeShop::get() should have thrown an Exception'); - } catch (Exception $e) { - $this->assertInstanceOf('Exception', $e); - } - // now add recipe for loading our entities as shared services (singletons) - $added = $this->CoffeeShop->addRecipe( - new Recipe( - 'EE_*', - '', - array(), - array(), - CoffeeMaker::BREW_NEW, - array(EE_CLASSES . '*.class.php') - ) - ); - $this->assertTrue($added); - // attempt to brew EE_Taxes class since it is not coupled to EE_Base_Class - $object_1 = $this->CoffeeShop->brew('EE_Taxes', array()); - $this->assertInstanceOf('EE_Taxes', $object_1); - // and another one which should be the SAME instance - $object_2 = $this->CoffeeShop->brew('EE_Taxes', array()); - $this->assertInstanceOf('EE_Taxes', $object_2); - $this->assertFalse($object_1 === $object_2); - } - - - - public function test_brew_shared_with_wildcard_recipe() - { - $this->addDefaultRecipes(); - try { - // attempt to get class that should NOT have a valid Recipe yet - $this->CoffeeShop->get('EE_Taxes'); - $this->fail('CoffeeShop::get() should have thrown an Exception'); - } catch (Exception $e) { - $this->assertInstanceOf('Exception', $e); - } - // now add recipe for loading our entities as shared services (singletons) - $added = $this->CoffeeShop->addRecipe( - new Recipe( - 'EE_*', - '', - array(), - array(), - CoffeeMaker::BREW_SHARED, - array(EE_CLASSES . '*.class.php') - ) - ); - $this->assertTrue($added); - // attempt to brew EE_Taxes class since it is not coupled to EE_Base_Class - $object_1 = $this->CoffeeShop->brew('EE_Taxes', array()); - $this->assertInstanceOf('EE_Taxes', $object_1); - // and another one which should be the SAME instance - $object_2 = $this->CoffeeShop->brew('EE_Taxes', array()); - $this->assertInstanceOf('EE_Taxes', $object_2); - $this->assertTrue($object_1 === $object_2); - } - - - - /** - * @group CoffeeShopTestRequest - * @throws OutOfBoundsException - * @throws \EventEspresso\core\exceptions\InvalidClassException - * @throws \EventEspresso\core\exceptions\InvalidDataTypeException - * @throws \EventEspresso\core\exceptions\InvalidIdentifierException - * @throws \EventEspresso\core\services\container\exceptions\InstantiationException - * @throws \EventEspresso\core\services\container\exceptions\ServiceExistsException - * @throws \EventEspresso\core\services\container\exceptions\ServiceNotFoundException - * @throws \PHPUnit\Framework\Exception - */ - public function test_brew_with_injected_dependency() - { - $this->addDefaultRecipes(); - $this->addRecipeForRequest(); - try { - // attempt to get class that should NOT have a valid Recipe yet - $this->CoffeeShop->get('EE_Session_Mock'); - $this->fail('CoffeeShop::get() should have thrown an Exception'); - } catch (Exception $e) { - $this->assertInstanceOf('Exception', $e); - } - // add default recipe for our mock classes - $added = $this->CoffeeShop->addRecipe( - new Recipe( - 'EE_*', - '', - array(), - array(), - CoffeeMaker::BREW_SHARED, - array( - EE_TESTS_DIR . 'mocks/core/*.core.php', - ) - ) - ); - $this->assertTrue($added); - // attempt to brew EE_Session_Mock class which type hints for EE_Encryption - // but first add alias for interface - $this->CoffeeShop->addAliases( - 'EventEspresso\core\services\cache\TransientCacheStorage', - 'EventEspresso\core\services\cache\CacheStorageInterface' - ); - $session = $this->CoffeeShop->brew('EE_Session_Mock'); - $this->assertInstanceOf('EE_Session_Mock', $session); - $this->assertInstanceOf('EE_Encryption', $session->encryption()); - } - - - - public function test_ingredients_and_dependency_substitution() - { - $this->addDefaultRecipes(); - // Add Recipe for using HonduranBean in place of BeanInterface - $this->CoffeeShop->addRecipe( - new Recipe( - 'HonduranBean', - 'EventEspresso\tests\mocks\core\services\container\HonduranBean', - array('EventEspresso\tests\mocks\core\services\container\BeanInterface'), - array(), - CoffeeMaker::BREW_SHARED - ) - ); - // Add Recipe for HonduranCoffee - $this->CoffeeShop->addRecipe( - new Recipe( - 'HonduranCoffee', - 'EventEspresso\tests\mocks\core\services\container\Coffee' - ) - ); - /** @var Coffee $HonduranCoffee */ - $HonduranCoffee = $this->CoffeeShop->brew('HonduranCoffee'); - // test it - $this->assertInstanceOf( - 'EventEspresso\tests\mocks\core\services\container\Coffee', - $HonduranCoffee, - "brew HonduranCoffee directly (should be instance of Coffee): " - ); - // test that bean type is an instance of HonduranBean - $this->assertInstanceOf( - 'EventEspresso\tests\mocks\core\services\container\HonduranBean', - $HonduranCoffee->getBeans(), - "bean type should be instance of HonduranBean" - ); - // Add another Recipe for KenyanCoffee - $this->CoffeeShop->addRecipe( - new Recipe( - 'KenyanCoffee', - 'EventEspresso\tests\mocks\core\services\container\Coffee' - ) - ); - /** @var Coffee $HonduranCoffee */ - $KenyanCoffee = $this->CoffeeShop->brew('KenyanCoffee'); - // test it - $this->assertInstanceOf( - 'EventEspresso\tests\mocks\core\services\container\Coffee', - $KenyanCoffee, - "brew KenyanCoffee directly (should be instance of Coffee): " - ); - // test that bean type is an instance of HonduranBean - $this->assertInstanceOf( - 'EventEspresso\tests\mocks\core\services\container\HonduranBean', - $KenyanCoffee->getBeans(), - "bean type should be instance of HonduranBean" - ); - // BUT... It can't be KenyanCoffee if it's using HonduranBean - // Remove Recipe for KenyanCoffee"; - $this->CoffeeShop->removeRecipe('KenyanCoffee'); - // and the Closure used for generating instances of KenyanCoffee - $this->CoffeeShop->removeClosure('KenyanCoffee'); - // Now Add NEW Recipe for KenyanCoffee that specifies KenyanBean - $this->CoffeeShop->addRecipe( - new Recipe( - 'KenyanCoffee', - 'EventEspresso\tests\mocks\core\services\container\Coffee', - array(), - array('EventEspresso\tests\mocks\core\services\container\BeanInterface' => 'EventEspresso\tests\mocks\core\services\container\KenyanBean'), - CoffeeMaker::BREW_NEW - ) - ); - // brew another KenyanCoffee directly - $KenyanCoffee = $this->CoffeeShop->brew('KenyanCoffee'); - $this->assertInstanceOf( - 'EventEspresso\tests\mocks\core\services\container\Coffee', - $KenyanCoffee, - "brew KenyanCoffee directly (should be instance of Coffee): " - ); - // and test that bean type is NOW an instance of KenyanBean - $this->assertInstanceOf( - 'EventEspresso\tests\mocks\core\services\container\KenyanBean', - $KenyanCoffee->getBeans(), - "bean type should be instance of KenyanBean" - ); - } - - - private function addClosureForCoffeeFactory() - { - $this->addDefaultRecipes(); - $this->addRecipeForRequest(); - // can't pass properties directly to a Closure - $coffee_shop = $this->CoffeeShop; - // create a Closure called "CoffeeFromRequest" - $this->CoffeeShop->addClosure( - 'CoffeeFactory', - function () use ($coffee_shop) - { - /** @var EventEspresso\core\services\request\Request $request */ - $request = $coffee_shop->brew('Request'); - $bean_type = $request->getRequestParam('bean_type', 'Honduran'); - $bean_type = in_array($bean_type, array('Honduran', 'Kenyan'), true) - ? "{$bean_type}Bean" - : 'HonduranBean'; - return $coffee_shop->brew( - 'EventEspresso\tests\mocks\core\services\container\Coffee', - array( - $coffee_shop->brew( - 'EventEspresso\tests\mocks\core\services\container\\' . $bean_type - ) - ) - ); - } - ); - } - - - - /** - * @group CoffeeShopAddClosure - * @throws OutOfBoundsException - * @throws \EventEspresso\core\exceptions\InvalidClassException - * @throws \EventEspresso\core\exceptions\InvalidDataTypeException - * @throws \EventEspresso\core\exceptions\InvalidIdentifierException - * @throws \EventEspresso\core\services\container\exceptions\InstantiationException - * @throws \EventEspresso\core\services\container\exceptions\ServiceExistsException - * @throws \EventEspresso\core\services\container\exceptions\ServiceNotFoundException - * @throws \PHPUnit\Framework\Exception - */ - public function test_object_factories_using_addClosure() - { - $this->addClosureForCoffeeFactory(); - // brew a Coffee using the CoffeeFactory, - // which should use the default bean type since we haven't specified one - $default_coffee = $this->CoffeeShop->brew('CoffeeFactory'); - $this->assertInstanceOf( - 'EventEspresso\tests\mocks\core\services\container\Coffee', - $default_coffee, - 'should be instance of Coffee' - ); - // and test that default bean type is an instance of HonduranBean - $this->assertInstanceOf( - 'EventEspresso\tests\mocks\core\services\container\HonduranBean', - $default_coffee->getBeans(), - 'bean type should be instance of HonduranBean' - ); - } - - - /** - * @group CoffeeShopAddClosure - * @throws OutOfBoundsException - * @throws \EventEspresso\core\exceptions\InvalidClassException - * @throws \EventEspresso\core\exceptions\InvalidDataTypeException - * @throws \EventEspresso\core\exceptions\InvalidIdentifierException - * @throws \EventEspresso\core\services\container\exceptions\InstantiationException - * @throws \EventEspresso\core\services\container\exceptions\ServiceExistsException - * @throws \EventEspresso\core\services\container\exceptions\ServiceNotFoundException - * @throws \PHPUnit\Framework\Exception - */ - public function test_object_factories_using_addClosure_and_get_param() - { - // first, add a $_GET param specifying the bean type as Kenyan - $_GET['bean_type'] = 'Kenyan'; - $this->addClosureForCoffeeFactory(); - // brew another Coffee using the CoffeeFactory - $new_coffee = $this->CoffeeShop->brew('CoffeeFactory'); - $this->assertInstanceOf( - 'EventEspresso\tests\mocks\core\services\container\Coffee', - $new_coffee, - 'should be instance of Coffee' - ); - // and test that bean type is NOW an instance of KenyanBean - $this->assertInstanceOf( - 'EventEspresso\tests\mocks\core\services\container\KenyanBean', - $new_coffee->getBeans(), - 'bean type should be instance of KenyanBean' - ); - } - - -} -// End of file CoffeeShopTest.php -// Location: testcases/core/services/container/CoffeeShopTest.php diff --git a/tests/testcases/core/services/context/ContextCheckerTest.php b/tests/testcases/core/services/context/ContextCheckerTest.php deleted file mode 100644 index 001b93d8027..00000000000 --- a/tests/testcases/core/services/context/ContextCheckerTest.php +++ /dev/null @@ -1,159 +0,0 @@ -context_checker = new ContextCheckerMock( - 'This-is-a-Test', - $this->acceptable_values - ); - } - - - public function testGetters() - { - $this->assertEquals('this-is-a-test', $this->context_checker->getIdentifier()); - $this->assertEquals($this->acceptable_values, $this->context_checker->getAcceptableValues()); - $this->assertInstanceOf('Closure', $this->context_checker->getEvaluationCallback()); - $context_checker = new ContextCheckerMock( - 'This-is-a-Test', - $this->acceptable_values, - function() { return true; } - ); - $this->assertInstanceOf('Closure', $context_checker->getEvaluationCallback()); - } - - - - public function testIsAllowed() - { - $this->assertTrue( - $this->context_checker->isAllowed( - new Context('context-one', 'for testing if context-one is valid') - ) - ); - $this->assertTrue( - $this->context_checker->isAllowed( - new Context('context-two', 'for testing if context-two is valid') - ) - ); - $this->assertFalse( - $this->context_checker->isAllowed( - new Context('context-three', 'for testing if context-three is valid') - ) - ); - } - - - public function testIsAllowedWithCustomCallback() - { - $context_three = new Context('context-three', 'for testing if context-three is valid'); - $context_checker_looking_for_three = new ContextCheckerMock( - 'looking-for-three', - $this->acceptable_values, - function (ContextInterface $context) - { - return strpos($context->slug(), 'three' ) !== false; - } - ); - $this->assertTrue($context_checker_looking_for_three->isAllowed($context_three)); - $context_checker_looking_for_four = new ContextCheckerMock( - 'looking-for-four', - $this->acceptable_values, - function (ContextInterface $context) - { - return strpos($context->slug(), 'four' ) !== false; - } - ); - $this->assertFalse($context_checker_looking_for_four->isAllowed($context_three)); - } - - - public function testIsAllowedWithFilter() - { - $context_five = new Context('context-five', 'for testing if context-five is valid'); - // hook into existing ContextChecker using default built-in evaluation callback, - // and add custom detection for the word "five" - add_filter( - 'FHEE__EventEspresso_core_domain_entities_context_ContextChecker__this-is-a-test__isAllowed', - function ($is_allowed, ContextInterface $context) - { - // if context slug contains the word "five" return true, else return previously evaluated result - return strpos($context->slug(), 'five') !== false - ? true - : $is_allowed; - }, - 10, - 2 - ); - $this->assertTrue($this->context_checker->isAllowed($context_five)); - remove_all_filters('FHEE__EventEspresso_core_domain_entities_context_ContextChecker__this-is-a-test__isAllowed'); - // now do it again, but looking for a value that will not be within the context slug - add_filter( - 'FHEE__EventEspresso_core_domain_entities_context_ContextChecker__this-is-a-test__isAllowed', - function ($is_allowed, ContextInterface $context) - { - // if context slug contains the word "six" return true, else return previously evaluated result - return strpos($context->slug(), 'six') !== false - ? true - : $is_allowed; - }, - 10, - 2 - ); - $this->assertFalse($this->context_checker->isAllowed($context_five)); - } - - - public function testIsAllowedWithFilteredAcceptableValues() - { - // and 'context-six' to list of acceptable values - add_filter( - 'FHEE__EventEspresso_core_domain_entities_context_ContextChecker__this-is-a-test__acceptableValues', - function ($acceptable_values) - { - $acceptable_values[] = 'context-six'; - return $acceptable_values; - } - ); - $this->assertTrue( - $this->context_checker->isAllowed( - new Context('context-six', 'for testing if context-six is valid') - ) - ); - } - - -} -// Location: /testcases/core/services/context/ContextCheckerTest.php diff --git a/tests/testcases/core/services/dependencies/ClassAliasTest.php b/tests/testcases/core/services/dependencies/ClassAliasTest.php deleted file mode 100644 index b3c9f520c96..00000000000 --- a/tests/testcases/core/services/dependencies/ClassAliasTest.php +++ /dev/null @@ -1,120 +0,0 @@ -assertInstanceOf( - 'EventEspresso\core\services\dependencies\ClassAlias', - $this->getClassAlias($this->interface, $this->base_class) - ); - } - - /** - * @since 4.9.71.p - * @throws \EventEspresso\core\exceptions\InvalidAliasException - * @throws \PHPUnit\Framework\Exception - */ - public function test__constructWithBadParameters() - { - $exception = 'EventEspresso\core\exceptions\InvalidAliasException'; - if (method_exists($this, 'expectException')) { - $this->expectException($exception); - } elseif (method_exists($this, 'setExpectedException')) { - $this->setExpectedException($exception); - } - $this->getClassAlias($this->base_class, $this->interface); - } - - /** - * @throws \EventEspresso\core\exceptions\InvalidAliasException - */ - public function testAlias() - { - $class_alias = $this->getClassAlias($this->interface, $this->base_class); - $this->assertEquals($this->interface, $class_alias->alias()); - } - - /** - * @throws \EventEspresso\core\exceptions\InvalidAliasException - */ - public function testFqcn() - { - $class_alias = $this->getClassAlias($this->interface, $this->base_class); - $this->assertEquals($this->base_class, $class_alias->fqcn()); - } - - /** - * @throws \EventEspresso\core\exceptions\InvalidAliasException - */ - public function testChildFqcn() - { - $class_alias = $this->getClassAlias($this->base_class, $this->child_class_fqcn); - $this->assertEquals($this->child_class_fqcn, $class_alias->fqcn()); - } - - /** - * @since 4.9.71.p - * @throws \EventEspresso\core\exceptions\InvalidAliasException - * @throws \PHPUnit\Framework\Exception - */ - public function test__constructWithNonSubClass() - { - $exception = 'EventEspresso\core\exceptions\InvalidAliasException'; - if (method_exists($this, 'expectException')) { - $this->expectException($exception); - } elseif (method_exists($this, 'setExpectedException')) { - $this->setExpectedException($exception); - } - $this->getClassAlias( - $this->child_class_fqcn, - 'EventEspresso\core\domain\entities\route_match\specifications\admin\EspressoEventEditorEdit' - ); - } -} -// location: /testcases/core/services/dependencies/ClassAliasTest.php diff --git a/tests/testcases/core/services/dependencies/DependencyResolverTest.php b/tests/testcases/core/services/dependencies/DependencyResolverTest.php deleted file mode 100644 index 7f904c2ee43..00000000000 --- a/tests/testcases/core/services/dependencies/DependencyResolverTest.php +++ /dev/null @@ -1,230 +0,0 @@ -loader = LoaderFactory::getLoader(); - $this->request_params = array( - 'oof' => 'OOF!', - 'ouch' => 'OUCH!', - 'owie' => 'OWIE!', - ); - } - - /** - * @since 4.9.71.p - * @return DependencyResolverMock - */ - public function getDependencyResolver() - { - return new DependencyResolverMock( - $this->loader->getShared('EventEspresso\core\services\container\Mirror'), - $this->loader->getShared('EventEspresso\core\services\loaders\ClassInterfaceCache'), - $this->loader->getShared('EE_Dependency_Map') - ); - } - - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\Exception - */ - public function testMirror() - { - $this->assertInstanceOf( - 'EventEspresso\core\services\container\Mirror', - $this->getDependencyResolver()->mirror() - ); - } - - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\Exception - */ - public function testClassInterfaceCache() - { - $this->assertInstanceOf( - 'EventEspresso\core\services\loaders\ClassInterfaceCache', - $this->getDependencyResolver()->classCache() - ); - } - - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\Exception - */ - public function testDependencyMap() - { - $this->assertInstanceOf( - 'EE_Dependency_Map', - $this->getDependencyResolver()->dependencyMap() - ); - } - - /** - * @throws InvalidAliasException - * @throws \PHPUnit\Framework\Exception - */ - public function testAddAlias() - { - $alias = 'EventEspresso\tests\mocks\core\services\dependencies\composites\OofOuchOwieInterface'; - $fqcn = 'EventEspresso\tests\mocks\core\services\dependencies\composites\OofOuchOwie'; - $DependencyResolver = $this->getDependencyResolver(); - $DependencyResolver->addAlias(new ClassAlias($alias, $fqcn)); - /** @var ClassAlias[] $aliases */ - $aliases = $DependencyResolver->getAliases(); - $this->assertArrayHasKey($alias, $aliases); - $this->assertInstanceOf( - 'EventEspresso\core\services\dependencies\ClassAlias', - $aliases[ $alias ] - ); - $this->assertEquals($fqcn, $aliases[ $alias ]->fqcn()); - } - - /** - * @since 4.9.71.p - * @throws InvalidAliasException - * @throws \PHPUnit\Framework\AssertionFailedError - */ - public function testResolveAlias() - { - $request_alias = 'EventEspresso\core\services\request\RequestInterface'; - $request_fqcn = 'EventEspresso\core\services\request\Request'; - - $DependencyResolver = $this->getDependencyResolver(); - $this->assertFalse(EE_Dependency_Map::instance()->has($request_fqcn)); - $DependencyResolver->addAlias(new ClassAlias($request_alias, $request_fqcn)); - $this->assertEquals( - $request_fqcn, - $DependencyResolver->resolveAlias($request_alias) - ); - // now add a custom alias and try to resolve it - $alias = 'EventEspresso\tests\mocks\core\services\dependencies\composites\OofOuchOwieInterface'; - $fqcn = 'EventEspresso\tests\mocks\core\services\dependencies\composites\OofOuchOwie'; - $DependencyResolver->addAlias(new ClassAlias($alias, $fqcn)); - $this->assertEquals( - $fqcn, - $DependencyResolver->resolveAlias($alias) - ); - } - - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\Exception - */ - public function testAddNamespaceRoot() - { - $namespace_root = 'EventEspresso\tests\mocks\core\services\dependencies\composites'; - $DependencyResolver = $this->getDependencyResolver(); - $DependencyResolver->addNamespaceRoot($namespace_root); - $namespace_roots = $DependencyResolver->getNamespaceRoots(); - $this->assertContains($namespace_root, $namespace_roots); - $key = array_search($namespace_root, $namespace_roots, true); - $this->assertEquals($namespace_root, $namespace_roots[ $key ]); - } - - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\AssertionFailedError - */ - public function testDependencyRecursionExists() - { - $namespace_root = 'EventEspresso\tests\mocks\core\services\dependencies\composites'; - $DependencyResolver = $this->getDependencyResolver(); - $DependencyResolver->addNamespaceRoot($namespace_root); - $this->assertTrue( - $DependencyResolver->dependencyRecursionExists( - 'EventEspresso\tests\mocks\core\services\dependencies\composites\OofOuchOwie' - ) - ); - } - - /** - * @since 4.9.71.p - * @return Owie - */ - public function getBoneHurtingJuice() - { - $request = new Request($this->request_params, array(), array(), array(), array()); - return new Owie( - new Ouch( - new Oof($request), - $request - ), - $request - ); - } - - /** - * @since 4.9.71.p - */ - public function testOofOuchOwie() - { - // confirm our nested objects work properly - $this->assertEquals('OOF!OUCH!OWIE!', $this->getBoneHurtingJuice()->oofOuchOwie()); - } - - - /** - * @since 4.9.71.p - * @throws InvalidAliasException - * @throws \EventEspresso\core\exceptions\InvalidDataTypeException - * @throws \PHPUnit\Framework\AssertionFailedError - * @throws \ReflectionException - * @throws \PHPUnit\Framework\Exception - */ - public function testResolveDependenciesForClass() - { - $namespace_root = 'EventEspresso\tests\mocks\core\services\dependencies\composites'; - $alias = 'EventEspresso\tests\mocks\core\services\dependencies\composites\OofOuchOwieInterface'; - $fqcn = 'EventEspresso\tests\mocks\core\services\dependencies\composites\OofOuchOwie'; - $this->assertFalse(EE_Dependency_Map::instance()->has($fqcn)); - $DependencyResolver = $this->getDependencyResolver(); - $DependencyResolver->addNamespaceRoot($namespace_root); - $DependencyResolver->addAlias(new ClassAlias($alias, $fqcn)); - $DependencyResolver->resolveDependenciesForClass($fqcn); - $this->assertTrue(EE_Dependency_Map::instance()->has($fqcn)); - } - -} - -// location: /tests/testcases/core/services/dependencies/DependencyResolverTest.php \ No newline at end of file diff --git a/tests/testcases/core/services/formatters/AsciiOnlyTest.php b/tests/testcases/core/services/formatters/AsciiOnlyTest.php deleted file mode 100644 index ec364ee6513..00000000000 --- a/tests/testcases/core/services/formatters/AsciiOnlyTest.php +++ /dev/null @@ -1,51 +0,0 @@ -formatter = new AsciiOnly(); - parent::__construct(); - } - - - - /** - */ - public function test_format(){ - //array keys are the strings, values are arrays containign each emoji in that string - $emoji_strings = array( - 'I feel ๐Ÿ˜ today' => array('๐Ÿ˜'), - 'I would like a taco ๐ŸŒฎ, and some ramen ๐Ÿœ too' => array('๐ŸŒฎ','๐Ÿœ'), - 'Party ๐Ÿˆต time' => array('๐Ÿˆต'), - ); - foreach($emoji_strings as $emoji_string => $emojis){ - $this->assertEquals( - str_replace($emojis,'',$emoji_string), - $this->formatter->format($emoji_string) - ); - } - } - - - - -} -// End of file EmojiRemovalTest.php -// Location: tests\testcases\core\services\formatters/EmojiRemovalTest.php \ No newline at end of file diff --git a/tests/testcases/core/services/loaders/CachingLoaderTest.php b/tests/testcases/core/services/loaders/CachingLoaderTest.php deleted file mode 100644 index 4a5777ac85f..00000000000 --- a/tests/testcases/core/services/loaders/CachingLoaderTest.php +++ /dev/null @@ -1,183 +0,0 @@ -load($this->getFqcnForTest()); - $this->assertInstanceOf( - $this->getFqcnForTest(), - $object, - sprintf( - '%1$s is not an instance of %2$s', - is_object($object) ? get_class($object) : print_r($object, true), - $this->getFqcnForTest() - ) - ); - $obj1ID = spl_object_hash($object); - // none of these objects are getting cached because it is turned off for unit testing - $object2 = self::$loader->load($this->getFqcnForTest()); - $obj2ID = spl_object_hash($object2); - $this->assertNotEquals($obj1ID, $obj2ID); - - //this time let's load the object with caching turned on so it gets in the cache and we'll send that objects - //hash along for the persistence test. - add_filter('FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache', '__return_false', 10); - return spl_object_hash(self::$loader->load($this->getFqcnForTest())); - } - - - - /** - * This tests persistence with caching on. - */ - public function testLoadCachingOn() - { - //turn caching on. - remove_all_filters('FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache'); - $this->assertEquals( - spl_object_hash(self::$loader->load($this->getFqcnForTest())), - spl_object_hash(self::$loader->load($this->getFqcnForTest())) - ); - } - - - /** - * This tests the resetting of cache - * - * @throws Exception - */ - public function testResetCache() - { - // turn caching on again - add_filter('FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache', '__return_false', 10); - // add a few different objects this time, but confirm that they are getting cached - $fqcn7 = '\EventEspresso\core\services\address\formatters\AddressFormatter'; - $object7 = self::$loader->load($fqcn7); - $this->assertInstanceOf($fqcn7, $object7); - $this->assertEquals(spl_object_hash($object7), spl_object_hash(self::$loader->load($fqcn7))); - $fqcn8 = '\EventEspresso\core\services\address\formatters\InlineAddressFormatter'; - $object8 = self::$loader->load($fqcn8); - $this->assertInstanceOf($fqcn8, $object8); - $this->assertEquals(spl_object_hash($object8), spl_object_hash(self::$loader->load($fqcn8))); - $fqcn9 = '\EventEspresso\core\services\address\formatters\MultiLineAddressFormatter'; - $object9 = self::$loader->load($fqcn9); - $this->assertInstanceOf($fqcn9, $object9); - $this->assertEquals(spl_object_hash($object9), spl_object_hash(self::$loader->load($fqcn9))); - $this->assertCount(3, self::$loader->getCache()); - // now reset the cache using the do_action() - do_action('AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache'); - $this->assertCount(0, self::$loader->getCache()); - // confirm that reloading the same FCQNs as above results in new objects - $this->assertNotEquals(spl_object_hash($object7), spl_object_hash(self::$loader->load($fqcn7))); - $this->assertNotEquals(spl_object_hash($object8), spl_object_hash(self::$loader->load($fqcn8))); - $this->assertNotEquals(spl_object_hash($object9), spl_object_hash(self::$loader->load($fqcn9))); - } - - /** - * @since 4.9.66.p - * @throws Exception - * @throws InvalidArgumentException - * @throws \PHPUnit\Framework\AssertionFailedError - */ - public function testShare() - { - // turn caching on again - add_filter('FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache', '__return_false', 10); - // create a context object - $context1 = new EventEspresso\core\domain\entities\contexts\Context( - 'testShare', - 'we are testing the share method' - ); - // share it but don't pass any arguments - $added = self::$loader->share('EventEspresso\core\domain\entities\contexts\Context', $context1); - $this->assertTrue($added); - $object1 = self::$loader->load('EventEspresso\core\domain\entities\contexts\Context'); - $this->assertEquals(spl_object_hash($object1), spl_object_hash($context1)); - // create another context object - $context2 = new EventEspresso\core\domain\entities\contexts\Context( - 'testShare2', - 'we are testing the share method again' - ); - // share it but pass an array of its arguments - $added2 = self::$loader->share( - 'EventEspresso\core\domain\entities\contexts\Context', - $context2, - array('testShare2', 'we are testing the share method again') - ); - $this->assertTrue($added2); - // just load using FQCN... should match object 1 - $not_object2 = self::$loader->load('EventEspresso\core\domain\entities\contexts\Context'); - $this->assertNotEquals(spl_object_hash($not_object2), spl_object_hash($context2)); - // because it's context 1 - $this->assertEquals(spl_object_hash($not_object2), spl_object_hash($context1)); - // now load using arguments - $object2 = self::$loader->load( - 'EventEspresso\core\domain\entities\contexts\Context', - array('testShare2', 'we are testing the share method again') - ); - $this->assertEquals(spl_object_hash($object2), spl_object_hash($context2)); - } -} -// Location: testcases/core/services/loaders/CachingLoaderTest.php diff --git a/tests/testcases/core/services/loaders/CoreLoaderTest.php b/tests/testcases/core/services/loaders/CoreLoaderTest.php deleted file mode 100644 index a63274897d2..00000000000 --- a/tests/testcases/core/services/loaders/CoreLoaderTest.php +++ /dev/null @@ -1,72 +0,0 @@ -loader = new CoreLoader(EE_Registry::instance()); - } - - - - /** - * testBadConstruct - */ - public function testBadConstruct() - { - try { - $this->loader = new CoreLoader(new stdClass()); - $this->fail('EventEspresso\core\services\loaders\CoreLoader should have thrown an InvalidArgumentException'); - } catch (Exception $e) { - $this->assertTrue(true); - } - } - - - - /** - * testLoad - */ - public function testLoad() - { - $fqcn = '\EventEspresso\core\services\address\formatters\AddressFormatter'; - $formatter = $this->loader->load($fqcn); - $this->assertInstanceOf( - $fqcn, - $formatter, - sprintf( - '%1$s is not an instance of $fqcn', - is_object($formatter) ? get_class($formatter) : print_r($formatter, true), - $fqcn - ) - ); - } - -} - - -// End of file CoreLoaderTest.php -// Location: tests/testcases/core/services/loaders/CoreLoaderTest.php \ No newline at end of file diff --git a/tests/testcases/core/services/loaders/LoaderTest.php b/tests/testcases/core/services/loaders/LoaderTest.php deleted file mode 100644 index 198130a890f..00000000000 --- a/tests/testcases/core/services/loaders/LoaderTest.php +++ /dev/null @@ -1,132 +0,0 @@ -load($fqcn, array(), false); - $this->assertInstanceOf( - $fqcn, - $object, - sprintf( - '%1$s is not an instance of $fqcn', - is_object($object) ? get_class($object) : print_r($object, true), - $fqcn - ) - ); - // none of these objects are getting cached because it is turned off for unit testing - $object2 = self::$loader->load($fqcn, array(), false); - $this->assertFalse($object->sameInstance($object2)); - } - - - /** - * testSharedLoader - * - * @throws \PHPUnit\Framework\AssertionFailedError - * @throws \PHPUnit\Framework\Exception - */ - public function testSharedLoader() - { - // first turn caching on - add_filter('FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache', '__return_false'); - $fqcn = 'EventEspresso\tests\mocks\core\services\loaders\SharedClassToLoad'; - /** @var EventEspresso\tests\mocks\core\services\loaders\SharedClassToLoad $object */ - $object = self::$loader->load($fqcn); - $this->assertInstanceOf( - $fqcn, - $object, - sprintf( - '%1$s is not an instance of $fqcn', - is_object($object) ? get_class($object) : print_r($object, true), - $fqcn - ) - ); - // caching is on and we want a shared instance, so we should get the same object again - $object2 = self::$loader->load($fqcn); - $this->assertTrue($object->sameInstance($object2)); - } - - - /** - * testSharedLoader - * - * @group loaderArgs - * @throws \PHPUnit\Framework\AssertionFailedError - * @throws \PHPUnit\Framework\Exception - */ - public function testSharedLoaderWithArgs() - { - // first turn caching on - add_filter('FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache', '__return_false'); - $fqcn = 'EventEspresso\tests\mocks\core\services\loaders\SharedClassToLoad'; - $original_args = array(1, 2, 3); - /** @var EventEspresso\tests\mocks\core\services\loaders\SharedClassToLoad $object */ - $object = self::$loader->load($fqcn, array($original_args)); - $this->assertInstanceOf( - $fqcn, - $object, - sprintf( - '%1$s is not an instance of $fqcn', - is_object($object) ? get_class($object) : print_r($object, true), - $fqcn - ) - ); - $this->assertEquals($original_args, $object->args()); - // caching is on and we want a shared instance, - // but we are passing new args, so we should get a new object - $object2 = self::$loader->load($fqcn, array(array(4, 5, 6))); - $this->assertFalse($object->sameInstance($object2)); - $this->assertNotEquals($original_args, $object2->args()); - // now let's request another instance but with no args, which *should* return the first instance - $object3 = self::$loader->load($fqcn); - $this->assertTrue($object->sameInstance($object3)); - $this->assertEquals($original_args, $object3->args()); - } -} -// End of file LoaderTest.php -// Location: testcases/core/services/loaders/LoaderTest.php diff --git a/tests/testcases/core/services/loaders/ObjectIdentifierTest.php b/tests/testcases/core/services/loaders/ObjectIdentifierTest.php deleted file mode 100644 index 2bba0ed1dfb..00000000000 --- a/tests/testcases/core/services/loaders/ObjectIdentifierTest.php +++ /dev/null @@ -1,164 +0,0 @@ -object_identifier = LoaderFactory::getLoader()->getShared( - 'EventEspresso\core\services\loaders\ObjectIdentifier' - ); - } - - - /** - * dataProvider for testGetIdentifier() - * @return array[] - */ - public function getIdentifierProvider() - { - $object1 = new stdClass(); - $object1->prop1 = 1234; - $object1->prop2 = 'mom\'s spaghetti'; - $object1hash = spl_object_hash($object1); - return array( - // $fqcn, $arguments, $expected - 0 => array( - 'fully/qualified/class/name/DoesNotNeedToBeReal', - array(), - 'fully/qualified/class/name/DoesNotNeedToBeReal', - ), - 1 => array( - 'fully/qualified/class/name/DoesNotNeedToBeReal', - array(1, 2, 3, 4), - 'fully/qualified/class/name/DoesNotNeedToBeReal' . ObjectIdentifier::DELIMITER . md5('1234'), - ), - 2 => array( - 'fully/qualified/class/name/DoesNotNeedToBeReal', - array($object1), - 'fully/qualified/class/name/DoesNotNeedToBeReal' . ObjectIdentifier::DELIMITER . md5($object1hash), - ), - 3 => array( - 'fully/qualified/class/name/DoesNotNeedToBeReal', - array(1, 2, 3, 4, $object1), - 'fully/qualified/class/name/DoesNotNeedToBeReal' - . ObjectIdentifier::DELIMITER . md5('1234' . $object1hash), - ), - // test class that implements EventEspresso\core\interfaces\ReservedInstanceInterface - 4 => array( - 'EventEspresso\core\services\request\Request', - array(array(1, 2, 3, 4), array(), array(), array()), - 'EventEspresso\core\services\request\Request', - ), - ); - } - - - /** - * @dataProvider getIdentifierProvider - * @param string $fqcn - * @param array $arguments - * @param string $expected - */ - public function testGetIdentifier($fqcn, array $arguments, $expected) - { - $this->assertEquals( - $expected, - $this->object_identifier->getIdentifier($fqcn,$arguments) - ); - } - - - /** - * dataProvider for testHasArguments() - * - * @return array[] - */ - public function hasArgumentsProvider() - { - return array( - array('fully/qualified/class/Name', false), - array('fully/qualified/class/Name' . ObjectIdentifier::DELIMITER . md5('1234'), true), - ); - } - - - /** - * @dataProvider hasArgumentsProvider - * @param string $object_identifier - * @param bool $has_arguments - */ - public function testHasArguments($object_identifier, $has_arguments) - { - $this->assertEquals( - $has_arguments, - $this->object_identifier->hasArguments($object_identifier) - ); - } - - /** - * dataProvider for testFqcnMatchesObjectIdentifier() - * - * @return array[] - */ - public function fqcnMatchesObjectIdentifierProvider() - { - return array( - array('fully/qualified/class/Name', 'fully/qualified/class/Name', true), - array('fully/qualified/class/Name', 'fully/qualified/class/Name' . ObjectIdentifier::DELIMITER . md5('1234'), true), - array('fully/qualified/class/Name', 'fully/qualified/class/OtherName', false), - array('fully/qualified/class/Name', 'fully/qualified/class/OtherName' . ObjectIdentifier::DELIMITER . md5('1234'), false), - ); - } - - - /** - * @dataProvider fqcnMatchesObjectIdentifierProvider - * @param string $fqcn - * @param string $object_identifier - * @param bool $matches - */ - public function testFqcnMatchesObjectIdentifier($fqcn, $object_identifier, $matches) - { - $this->assertEquals( - $matches, - $this->object_identifier->fqcnMatchesObjectIdentifier( - $fqcn, - $object_identifier - ) - ); - } -} -// location: tests/testcases/core/services/loaders/ObjectIdentifierTest.php \ No newline at end of file diff --git a/tests/testcases/core/services/locators/FqcnLocatorTest.php b/tests/testcases/core/services/locators/FqcnLocatorTest.php deleted file mode 100644 index 892a80d81f9..00000000000 --- a/tests/testcases/core/services/locators/FqcnLocatorTest.php +++ /dev/null @@ -1,80 +0,0 @@ -file_locator = new FqcnLocator(); - } - - - public function tearDown() - { - parent::tearDown(); - unset($this->file_locator); - } - - - private function getExpectedFQCNs() - { - $FQCNs = array( - '\EventEspresso\tests\mocks\core\services\locator\test_dir\TestClassA', - '\EventEspresso\tests\mocks\core\services\locator\test_dir\TestClassB', - ); - return sort($FQCNs); - } - - - public function testLocate() - { - $FQCNs = $this->file_locator->locate($this->test_fqcn); - $this->assertEquals($this->getExpectedFQCNs(), sort($FQCNs)); - } - - - public function testCount() - { - $this->file_locator->locate($this->test_fqcn); - $this->assertCount(2, $this->file_locator); - } - - - public function testGetFQCNs() - { - $this->file_locator->locate($this->test_fqcn); - $FQCNs = $this->file_locator->getFQCNs(); - $this->assertEquals($this->getExpectedFQCNs(), sort($FQCNs)); - } -} - -// Location: tests/testcases/core/services/locators/FqcnLocatorTest.php diff --git a/tests/testcases/core/services/notices/AdminNoticeTest.php b/tests/testcases/core/services/notices/AdminNoticeTest.php deleted file mode 100644 index 13e2713d836..00000000000 --- a/tests/testcases/core/services/notices/AdminNoticeTest.php +++ /dev/null @@ -1,147 +0,0 @@ -extraErrorDetails(); - return new Notice( - $type, - $notice, - $dismissible, - $error_details->file, - $error_details->func, - $error_details->line - ); - } - - - public function noticeDetails() - { - return array( - (object)array( - 'type' => Notice::ERROR, - 'class' => 'error', - 'message' => 'this is an error message', - 'dismissible' => false, - ), - (object)array( - 'type' => Notice::ERROR, - 'class' => 'error', - 'message' => 'this is a dismissible error message', - 'dismissible' => true, - ), - (object)array( - 'type' => Notice::SUCCESS, - 'class' => 'success', - 'message' => 'this is a success message', - 'dismissible' => false, - ), - (object)array( - 'type' => Notice::SUCCESS, - 'class' => 'success', - 'message' => 'this is a dismissible success message', - 'dismissible' => true, - ), - (object)array( - 'type' => Notice::ATTENTION, - 'class' => 'warning', - 'message' => 'this is an attention message', - 'dismissible' => false, - ), - (object)array( - 'type' => Notice::ATTENTION, - 'class' => 'warning', - 'message' => 'this is a dismissible attention message', - 'dismissible' => true, - ), - (object)array( - 'type' => Notice::INFORMATION, - 'class' => 'info', - 'message' => 'this is an information message', - 'dismissible' => false, - ), - (object)array( - 'type' => Notice::INFORMATION, - 'class' => 'info', - 'message' => 'this is a dismissible information message', - 'dismissible' => true, - ), - ); - } - - - public function extraErrorDetails() - { - return (object)array( - 'file' => 'path/to/file.php', - 'func' => 'function', - 'line' => 123, - ); - } - - - public function testGetNotice() - { - $all_notice_details = $this->noticeDetails(); - foreach ($all_notice_details as $notice_details) { - $admin_notice = new \EventEspresso\core\services\notices\AdminNotice( - $this->createNotice( - $notice_details->type, - $notice_details->message, - $notice_details->dismissible - ) - ); - $this->assertEquals( - $this->noticeHtml( - $notice_details->type, - $notice_details->message, - $notice_details->dismissible, - $notice_details->class - ), - $admin_notice->getNotice() - ); - } - } - - - private function noticeHtml($type, $message, $dismissible, $class) - { - $notice = '

    '; - $notice .= $message; - if ($type === Notice::ERROR) { - $notice .= '
    file - function - 123'; - } - $notice .= '

    '; - $notice .= '
    '; - return $notice; - } - - -} -// Location: tests/testcases/core/services/notices/AdminNoticeTest.php diff --git a/tests/testcases/core/services/notices/NoticeTest.php b/tests/testcases/core/services/notices/NoticeTest.php deleted file mode 100644 index 33bae671b6a..00000000000 --- a/tests/testcases/core/services/notices/NoticeTest.php +++ /dev/null @@ -1,195 +0,0 @@ - true, - Notice::SUCCESS => true, - Notice::ATTENTION => true, - Notice::INFORMATION => true, - 'INVALID' => false, - ); - foreach ($types as $type => $valid) { - if (! $valid) { - $this->setExceptionExpected('EventEspresso\core\exceptions\InvalidDataTypeException'); - } - $notice = $this->createNotice($type); - $this->assertEquals($type, $notice->type()); - } - } - - - public function testValidMessage() - { - $notice = $this->createNotice(Notice::SUCCESS, 'valid message'); - $this->assertEquals('valid message', $notice->message()); - } - - - public function testMessageWithArray() - { - $this->setExceptionExpected('EventEspresso\core\exceptions\InvalidDataTypeException'); - $this->createNotice(Notice::SUCCESS, array('invalid message')); - } - - - public function testMessageWithObject() - { - $this->setExceptionExpected('EventEspresso\core\exceptions\InvalidDataTypeException'); - $this->createNotice(Notice::SUCCESS, new stdClass()); - } - - - public function testMessageWithInteger() - { - $this->setExceptionExpected('EventEspresso\core\exceptions\InvalidDataTypeException'); - $this->createNotice(Notice::SUCCESS, 12345); - } - - - public function testDismissible() - { - $dismissible_values = array( - true, - false, - 1, - 0, - 'true', - 'false', - 'yes', - 'no', - array(), - new stdClass(), - 12345, - 'nope', - ); - foreach ($dismissible_values as $dismissible) { - $notice = $this->createNotice(Notice::SUCCESS, 'valid message', $dismissible); - $this->assertEquals( - filter_var($dismissible, FILTER_VALIDATE_BOOLEAN), - $notice->isDismissible() - ); - } - } - - - public function testFile() - { - $files = array( - 0 => Notice::SUCCESS, - 1 => Notice::ATTENTION, - '' => Notice::INFORMATION, - 'valid_file.php' => Notice::ERROR, - 4 => Notice::ERROR, - ); - foreach ($files as $file => $type) { - // file is only required for Notice::ERROR types - if ($file === 4) { - $this->setExceptionExpected('EventEspresso\core\exceptions\InvalidDataTypeException'); - } - $notice = new Notice( - $type, - 'valid message', - true, - $file, - __FUNCTION__, - __LINE__ - ); - $this->assertEquals($type, $notice->type()); - } - } - - - public function testFunc() - { - $functions = array( - 0 => Notice::SUCCESS, - 1 => Notice::ATTENTION, - '' => Notice::INFORMATION, - __FUNCTION__ => Notice::ERROR, - 4 => Notice::ERROR, - ); - foreach ($functions as $function => $type) { - // file is only required for Notice::ERROR types - if ($function === 4) { - $this->setExceptionExpected('EventEspresso\core\exceptions\InvalidDataTypeException'); - } - $notice = new Notice( - $type, - 'valid message', - true, - __FILE__, - $function, - __LINE__ - ); - $this->assertEquals($type, $notice->type()); - } - } - - - public function testLine() - { - $lines = array( - '0' => Notice::SUCCESS, - '1' => Notice::ATTENTION, - '' => Notice::INFORMATION, - __LINE__ => Notice::ERROR, - 'number' => Notice::ERROR, - ); - foreach ($lines as $line => $type) { - // file is only required for Notice::ERROR types - if ($line === 'number') { - $this->setExceptionExpected('EventEspresso\core\exceptions\InvalidDataTypeException'); - } - $notice = new Notice( - $type, - 'valid message', - true, - __FILE__, - __FUNCTION__, - $line - ); - $this->assertEquals($type, $notice->type()); - } - } - - -} -// Location: tests/testcases/core/services/notices/NoticeTest.php diff --git a/tests/testcases/core/services/notices/NoticesContainerTest.php b/tests/testcases/core/services/notices/NoticesContainerTest.php deleted file mode 100644 index 08fc3edad7d..00000000000 --- a/tests/testcases/core/services/notices/NoticesContainerTest.php +++ /dev/null @@ -1,118 +0,0 @@ -notices_container = new NoticesContainer(); - } - - - /** - * @see https://stackoverflow.com/a/4356295 - * @return string - */ - public function generateRandomString() - { - $length = mt_rand(10, 50); - $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; - $charactersLength = strlen($characters); - $randomString = ''; - for ($i = 0; $i < $length; $i++) { - $randomString .= $characters[mt_rand(0, $charactersLength - 1)]; - } - return $randomString; - } - - - /** - * @return stdClass - */ - public function extraErrorDetails() - { - return (object)array( - 'file' => 'path/to/file.php', - 'func' => 'function', - 'line' => 123, - ); - } - - - public function containerMethods($type) - { - $add = "add{$type}"; - $count = "count{$type}"; - $get = "get{$type}"; - $has = "has{$type}"; - $error = $this->extraErrorDetails(); - $this->assertEquals(0, $this->notices_container->$count()); - for ($x = 1; $x <= 10; $x++) { - $message = $this->generateRandomString(); - if ($type === 'Error') { - $this->notices_container->$add( - $message, - $x % 2, - $error->file, - $error->func, - $error->line - ); - } else { - $this->notices_container->$add($message, $x % 2); - } - $this->assertTrue($this->notices_container->$has()); - $this->assertEquals($x, $this->notices_container->$count()); - } - $notices = $this->notices_container->$get(); - foreach ($notices as $notice) { - $this->assertInstanceOf('EventEspresso\core\services\notices\Notice', $notice); - } - } - - - public function testInformationMethods() - { - $this->containerMethods('Information'); - } - - - public function testAttentionMethods() - { - $this->containerMethods('Attention'); - } - - - public function testSuccessMethods() - { - $this->containerMethods('Success'); - } - - - public function testErrorMethods() - { - $this->containerMethods('Error'); - } -} -// Location: tests/testcases/core/services/notices/NoticesContainerTest.php diff --git a/tests/testcases/core/services/request/RequestStackBuilderTest.php b/tests/testcases/core/services/request/RequestStackBuilderTest.php deleted file mode 100644 index 0c2947363f0..00000000000 --- a/tests/testcases/core/services/request/RequestStackBuilderTest.php +++ /dev/null @@ -1,259 +0,0 @@ -loader = LoaderFactory::getLoader(); - $this->request_stack_builder = $this->loader->getShared( - 'EventEspresso\tests\mocks\core\services\request\RequestStackBuilderMock', - array($this->loader) - ); - } - - - /** - * @return RequestStackCoreAppMock - */ - public function getCoreApp() - { - return $this->loader->getShared( - 'EventEspresso\tests\mocks\core\services\request\RequestStackCoreAppMock' - ); - } - - - /** - * @return Request - */ - public function getRequest() - { - return $this->loader->getShared( - 'EventEspresso\core\services\request\Request' - ); - } - - - /** - * @return Response - */ - public function getResponse() - { - return $this->loader->getShared( - 'EventEspresso\core\services\request\Response' - ); - } - - - /** - * @return array - */ - public function getNotices() - { - $notices = EE_Error::get_vanilla_notices(); - if(isset($notices['errors']['RequestStackCoreAppMock - handleRequest - 34'])) { - $notices['errors'][] = str_replace( - '
    RequestStackCoreAppMock - handleRequest - 34', - '', - $notices['errors']['RequestStackCoreAppMock - handleRequest - 34'] - ); - unset($notices['errors']['RequestStackCoreAppMock - handleRequest - 34']); - } - return $notices; - } - - - /** - * @return void - */ - public function setMiddlewareFQCNs() - { - $this->obi_wan_kenobi = 'EventEspresso\tests\mocks\core\services\request\ObiWanKenobiWare'; - $this->general_grievous = 'EventEspresso\tests\mocks\core\services\request\GeneralGrievousWare'; - } - - - /** - * @param bool $legacy - * @return void - */ - public function addMiddleware($legacy = false) - { - $this->setMiddlewareFQCNs(); - if($legacy){ - $this->request_stack_builder->push(array(0, $this->general_grievous)); - $this->request_stack_builder->push(array(1, $this->obi_wan_kenobi)); - } else { - $this->request_stack_builder->push(array($this->general_grievous, array())); - $this->request_stack_builder->push(array($this->obi_wan_kenobi, array())); - } - } - - - /** - * @return void - */ - public function testRequestStackBuilderAsSplDoublyLinkedList() - { - $this->addMiddleware(); - // list should be FILO, so first in is at bottom of the stack - $first = $this->request_stack_builder->bottom(); - $first_fqcn = reset($first); - $this->assertEquals($this->general_grievous, $first_fqcn); - $last = $this->request_stack_builder->top(); - $last_fqcn = reset($last); - $this->assertEquals($this->obi_wan_kenobi, $last_fqcn); - } - - - /** - * returns following parameters: - * $middleware_app middleware app class details (FQCN, args array) - * $recurse true may call validateMiddlewareAppDetails() twice - * $expected expected middleware app class - * - * @return array - */ - public function middlewareAppProvider() - { - $this->setMiddlewareFQCNs(); - return array( - // empty array - array(array(), false, null), - // arguments in wrong order - array(array(array(), $this->obi_wan_kenobi), true, $this->obi_wan_kenobi), - // arguments in wrong order, no recurse - array(array(array(), $this->obi_wan_kenobi), false, null), - // legacy middleware - array(array(0, $this->obi_wan_kenobi), true, $this->obi_wan_kenobi), - // legacy middleware, no recurse - array(array(0, $this->obi_wan_kenobi), false, null), - // invalid FQCN - array(array('invalid/FQCN', array()), false, null), - // all good - array(array($this->obi_wan_kenobi, array()), true, $this->obi_wan_kenobi), - array(array($this->general_grievous, array()), true, $this->general_grievous), - ); - } - - - /** - * @dataProvider middlewareAppProvider - * @param array $middleware_app - * @param bool $recurse - * @param string $expected - * @throws \EventEspresso\core\services\request\InvalidRequestStackMiddlewareException - */ - public function testValidateMiddlewareAppDetails(array $middleware_app, $recurse, $expected) - { - if($recurse === false) { - $this->setExpectedException('EventEspresso\core\services\request\InvalidRequestStackMiddlewareException'); - $middleware_app_class = $this->request_stack_builder->validateMiddlewareAppDetails( - $middleware_app - ); - $this->assertEquals( - null, - $middleware_app_class, - 'An InvalidRequestStackMiddlewareException was expected but not thrown!' - ); - return; - } - $middleware_app = $this->request_stack_builder->validateMiddlewareAppDetails( - $middleware_app, - true - ); - $middleware_app_class = array_shift($middleware_app); - $this->assertEquals($expected, $middleware_app_class); - } - - - /** - * @return void - * @throws \Exception - */ - public function testRequestStackBuilderResolve() - { - $this->addMiddleware(); - $this->TheBattleOfUtapau(); - } - - /** - * @return void - * @throws \Exception - */ - public function testRequestStackBuilderResolveWithLegacyMiddleware() - { - $this->addMiddleware(true); - $this->TheBattleOfUtapau(); - } - - - /** - * @return void - * @throws \Exception - */ - public function TheBattleOfUtapau() - { - $request_stack = $this->request_stack_builder->resolve($this->getCoreApp()); - $this->assertInstanceOf( - 'EventEspresso\core\services\request\RequestStack', - $request_stack - ); - $this->assertEquals(0, EE_Error::has_notices()); - $request_stack->handleRequest($this->getRequest(), $this->getResponse()); - $notices = $this->getNotices(); - $this->assertCount(1, $notices['success']); - $this->assertEquals('Hello There!', $notices['success'][0]); - $this->assertCount(1, $notices['attention']); - $this->assertEquals('General Kenobi!', $notices['attention'][0]); - $this->assertCount(1, $notices['errors']); - $this->assertEquals('Back away! I will deal with this Jedi slime myself!', $notices['errors'][0]); - $request_stack->handleResponse(); - $notices = $this->getNotices(); - $this->assertCount(2, $notices['success']); - $this->assertEquals('Now, let\'s get a move on. We\'ve got a battle to win here.', $notices['success'][1]); - // now clear all notices - EE_Error::reset_notices(); - } -} -// location: tests/testcases/core/services/requests/RequestStackBuilderTest.php diff --git a/tests/testcases/core/services/request/files/FileSubmissionTest.php b/tests/testcases/core/services/request/files/FileSubmissionTest.php deleted file mode 100644 index 7d46f0fe6d2..00000000000 --- a/tests/testcases/core/services/request/files/FileSubmissionTest.php +++ /dev/null @@ -1,82 +0,0 @@ -assertEquals($filename, $file->getName()); - $this->assertEquals($filepath, $file->getTmpFile()); - $this->assertEquals('php', $file->getExtension()); - $this->assertEquals('text/x-php', $file->getType()); - $this->assertEquals($filesize, $file->getSize()); - $this->assertEquals($error, $file->getErrorCode()); - } - - public function testFileError() - { - $filename = ''; - $filepath = ''; - $filesize = 0; - $error = UPLOAD_ERR_INI_SIZE; - $file = new FileSubmission($filename, $filepath, $filesize, $error); - $this->assertEquals($filename, $file->getName()); - $this->assertEquals($filepath, $file->getTmpFile()); - $this->assertEquals('', $file->getExtension()); - $this->assertEquals('', $file->getType()); - $this->assertEquals($filesize, $file->getSize()); - $this->assertEquals($error, $file->getErrorCode()); - } - - public function testFileExtensionDifferentOnTmpFile() - { - $filename = 'foobar.csv'; - $filepath = __FILE__; - $filesize = 1234; - $error = UPLOAD_ERR_OK; - $file = new FileSubmission($filename, $filepath, $filesize, $error); - $this->assertEquals($filename, $file->getName()); - $this->assertEquals($filepath, $file->getTmpFile()); - $this->assertEquals('csv', $file->getExtension()); - $this->assertEquals('text/x-php', $file->getType()); - $this->assertEquals($filesize, $file->getSize()); - $this->assertEquals($error, $file->getErrorCode()); - } - - public function testFileNpExtension() - { - $filename = 'foobar'; - $filepath = __FILE__; - $filesize = 1234; - $error = UPLOAD_ERR_OK; - $file = new FileSubmission($filename, $filepath, $filesize, $error); - $this->assertEquals($filename, $file->getName()); - $this->assertEquals($filepath, $file->getTmpFile()); - $this->assertEquals('', $file->getExtension()); - $this->assertEquals('text/x-php', $file->getType()); - $this->assertEquals($filesize, $file->getSize()); - $this->assertEquals($error, $file->getErrorCode()); - } -} -// End of file FileSubmissionTest.php -// Location: EventEspresso\tests\testcases\core\services\request\files/FileSubmissionTest.php diff --git a/tests/testcases/core/services/request/files/FilesDataHandlerTest.php b/tests/testcases/core/services/request/files/FilesDataHandlerTest.php deleted file mode 100644 index 19d95944914..00000000000 --- a/tests/testcases/core/services/request/files/FilesDataHandlerTest.php +++ /dev/null @@ -1,238 +0,0 @@ -assertNull($files_data_handler->getFileObject('doesnt-exist')); - } - - /** - * @since 4.9.80.p - */ - public function testGetOrganizedFiles2dArray() - { - $request = new Request( - [], - [], - [], - [], - [ - 'file_input' => [ - 'name' => 'funnycatphoto.gif', - 'size' => 1234, - 'tmp_name' => '/srv/tmp/something/greegtd.gif', - 'error' => UPLOAD_ERR_OK - ] - ] - ); - $files_data_handler = new FilesDataHandler($request); - $this->assertInstanceOf( - 'EventEspresso\core\services\request\files\FileSubmission', - $files_data_handler->getFileObjectFromNameParts(['file_input']) - ); - $this->assertInstanceOf( - 'EventEspresso\core\services\request\files\FileSubmission', - $files_data_handler->getFileObject('file_input') - ); - } - - /** - * @since 4.9.80.p - */ - public function testGetOrganizedFiles3dArray() - { - $request = new Request( - [], - [], - [], - [], - [ - 'my' => [ - 'name' => [ - 'file' => [ - 'input1' => 'funnycatphoto.gif', - 'input2' => 'registrations.csv', - 'input3' => 'piratedvideo.mov' - ] - ], - 'size' => [ - 'file' => [ - 'input1' => 123, - 'input2' => 456, - 'input3' => 1234567890 - ] - ], - 'tmp_name' => [ - 'file' => [ - 'input1' => 'fewgrgfew.gif', - 'input2' => 'gbegr/rgrer.csv', - 'input3' => 'grgt/wef/wegr.mov' - ] - ], - 'error' => [ - 'file' => [ - 'input1' => UPLOAD_ERR_OK, - 'input2' => UPLOAD_ERR_OK, - 'input3' => UPLOAD_ERR_INI_SIZE - ] - ] - ] - ] - ); - $files_data_handler = new FilesDataHandler($request); - $this->assertInstanceOf( - 'EventEspresso\core\services\request\files\FileSubmission', - $files_data_handler->getFileObjectFromNameParts( - ['my', 'file', 'input1'] - ) - ); - $this->assertInstanceOf( - 'EventEspresso\core\services\request\files\FileSubmission', - $files_data_handler->getFileObject('my[file][input1]') - ); - } - - /** - * @since 4.9.80.p - */ - public function testGetOrganizedFiles2dAnd3dArray() - { - $request = new Request( - [], - [], - [], - [], - [ - 'my' => [ - 'name' => [ - 'file' => [ - 'input1' => 'funnycatphoto.gif', - 'input2' => 'registrations.csv', - 'input3' => 'piratedvideo.mov' - ], - 'input4' => 'unexpected.gif' - ], - 'size' => [ - 'file' => [ - 'input1' => 123, - 'input2' => 456, - 'input3' => 1234567890 - ], - 'input4' => 123, - ], - 'tmp_name' => [ - 'file' => [ - 'input1' => 'fewgrgfew.gif', - 'input2' => 'gbegr/rgrer.csv', - 'input3' => 'grgt/wef/wegr.mov' - ], - 'input4' => 'ougif/iyv.gif' - ], - 'error' => [ - 'file' => [ - 'input1' => UPLOAD_ERR_OK, - 'input2' => UPLOAD_ERR_OK, - 'input3' => UPLOAD_ERR_INI_SIZE - ], - 'input4'=> UPLOAD_ERR_OK - ] - ] - ] - ); - $files_data_handler = new FilesDataHandler($request); - $this->assertInstanceOf( - 'EventEspresso\core\services\request\files\FileSubmission', - $files_data_handler->getFileObject('my[file][input1]') - ); - $this->assertInstanceOf( - 'EventEspresso\core\services\request\files\FileSubmission', - $files_data_handler->getFileObject('my[input4]') - ); - } - - /** - * @since 4.9.80.p - */ - public function testGetOrganizedFiles4dArray() - { - $request = new Request( - [], - [], - [], - [], - [ - 'my' => [ - 'name' => [ - 'great' => [ - 'file' => [ - 'input1' => 'funnycatphoto.gif', - ] - ] - ], - 'size' => [ - 'great' => [ - 'file' => [ - 'input1' => 123, - ] - ] - ], - 'tmp_name' => [ - 'great' => [ - 'file' => [ - 'input1' => 'fewgrgfew.gif', - ] - ] - ], - 'error' => [ - 'great' => [ - 'file' => [ - 'input1' => UPLOAD_ERR_OK, - ] - ] - ] - ] - ] - ); - $files_data_handler = new FilesDataHandler($request); - $this->assertInstanceOf( - 'EventEspresso\core\services\request\files\FileSubmission', - $files_data_handler->getFileObjectFromNameParts(['my', 'great', 'file', 'input1']) - ); - $this->assertInstanceOf( - 'EventEspresso\core\services\request\files\FileSubmission', - $files_data_handler->getFileObject('my[great][file][input1]') - ); - } -} -// End of file FilesDataHandlerTest.php -// Location: EventEspresso\tests\testcases\core\services\request\files/FilesDataHandlerTest.php diff --git a/tests/testcases/core/services/route_match/RouteMatchSpecificationCollectionTest.php b/tests/testcases/core/services/route_match/RouteMatchSpecificationCollectionTest.php deleted file mode 100644 index 7d1609ac707..00000000000 --- a/tests/testcases/core/services/route_match/RouteMatchSpecificationCollectionTest.php +++ /dev/null @@ -1,118 +0,0 @@ -assertInstanceOf( - 'EventEspresso\core\services\route_match\RouteMatchSpecificationCollection', - $this->getCollection() - ); - } - - /** - * @since 4.9.71.p - * @throws \EventEspresso\core\exceptions\InvalidEntityException - * @throws \EventEspresso\core\exceptions\InvalidInterfaceException - * @throws \EventEspresso\core\services\collections\DuplicateCollectionIdentifierException - * @throws \PHPUnit\Framework\AssertionFailedError - * @throws \PHPUnit\Framework\Exception - */ - public function testAdd() - { - $request = $this->getRequest(); - $route_fqcn = 'EventEspresso\core\domain\entities\route_match\specifications\admin\EspressoEventEditorEdit'; - $collection = $this->getCollection(); - $this->assertFalse($collection->has($route_fqcn)); - $route = $this->getRoute($request); - $this->assertTrue($collection->add($route)); - $this->assertTrue($collection->has($route_fqcn)); - // and now for something completely different.. and something invalid - $oof_ouch_owie_fqcn = 'EventEspresso\tests\mocks\core\services\dependencies\composites\Oof'; - $this->assertFalse($collection->has($oof_ouch_owie_fqcn)); - $oof_ouch_owie = new Oof($request); - $exception = 'EventEspresso\core\exceptions\InvalidEntityException'; - if (method_exists($this, 'expectException')) { - $this->expectException($exception); - } elseif (method_exists($this, 'setExpectedException')) { - $this->setExpectedException($exception); - } - $collection->add($oof_ouch_owie); - $this->assertFalse($collection->has($oof_ouch_owie_fqcn)); - } - - /** - * @since 4.9.71.p - * @throws \EventEspresso\core\exceptions\InvalidEntityException - * @throws \EventEspresso\core\exceptions\InvalidInterfaceException - * @throws \EventEspresso\core\services\collections\DuplicateCollectionIdentifierException - * @throws \PHPUnit\Framework\AssertionFailedError - */ - public function testGetIdentifier() - { - $request = $this->getRequest(); - $collection = $this->getCollection(); - $route = $this->getRoute($request); - $this->assertTrue($collection->add($route)); - $this->assertEquals( - 'EventEspresso\core\domain\entities\route_match\specifications\admin\EspressoEventEditorEdit', - $collection->getIdentifier($route) - ); - $this->assertEquals( - 'custom_identifier', - $collection->getIdentifier($route, 'custom_identifier') - ); - } -} - -// location: /tests/testcases/core/services/route_match/RouteMatchSpecificationCollectionTest.php diff --git a/tests/testcases/core/services/route_match/RouteMatchSpecificationDependencyResolverTest.php b/tests/testcases/core/services/route_match/RouteMatchSpecificationDependencyResolverTest.php deleted file mode 100644 index 594572385c8..00000000000 --- a/tests/testcases/core/services/route_match/RouteMatchSpecificationDependencyResolverTest.php +++ /dev/null @@ -1,84 +0,0 @@ -loader = LoaderFactory::getLoader(); - $this->dependency_map = $this->loader->getShared('EE_Dependency_Map'); - $class = new ReflectionClass($this->dependency_map); - $property = $class->getProperty('_dependency_map'); - $property->setAccessible(true); - $registered_dependencies = $property->getValue($this->dependency_map); - $fqcn = 'EventEspresso\core\domain\entities\route_match\specifications\admin\EspressoEventEditorEdit'; - unset($registered_dependencies[ $fqcn ]); - $property->setValue($this->dependency_map, $registered_dependencies); - $this->assertFalse($this->dependency_map->has($fqcn)); - } - - /** - * @since 4.9.71.p - * @return RouteMatchSpecificationDependencyResolver - */ - public function getDependencyResolver() - { - return new RouteMatchSpecificationDependencyResolver( - $this->loader->getShared('EventEspresso\core\services\container\Mirror'), - $this->loader->getShared('EventEspresso\core\services\loaders\ClassInterfaceCache'), - $this->dependency_map - ); - } - - /** - * @since 4.9.71.p - * @throws \EventEspresso\core\exceptions\InvalidDataTypeException - * @throws \PHPUnit\Framework\AssertionFailedError - * @throws \ReflectionException - */ - public function testResolveDependenciesForClass() - { - $fqcn = 'EventEspresso\core\domain\entities\route_match\specifications\admin\EspressoEventEditorEdit'; - $this->assertFalse($this->dependency_map->has($fqcn)); - $DependencyResolver = $this->getDependencyResolver(); - $DependencyResolver->resolveDependenciesForClass($fqcn); - $this->assertTrue($this->dependency_map->has($fqcn)); - } -} - -// location: /tests/testcases/core/services/route_match/RouteMatchSpecificationDependencyResolverTest.php \ No newline at end of file diff --git a/tests/testcases/core/services/route_match/RouteMatchSpecificationFactoryTest.php b/tests/testcases/core/services/route_match/RouteMatchSpecificationFactoryTest.php deleted file mode 100644 index d406dddf119..00000000000 --- a/tests/testcases/core/services/route_match/RouteMatchSpecificationFactoryTest.php +++ /dev/null @@ -1,95 +0,0 @@ -loader = LoaderFactory::getLoader(); - } - - /** - * @since 4.9.71.p - * @return RouteMatchSpecificationFactory - */ - public function getFactory() - { - return new RouteMatchSpecificationFactory( - $this->loader->getShared( - 'EventEspresso\core\services\route_match\RouteMatchSpecificationDependencyResolver' - ), - $this->loader - ); - } - - /** - * @since 4.9.71.p - * @throws \PHPUnit\Framework\Exception - */ - public function test__construct() - { - $this->assertInstanceOf( - 'EventEspresso\core\services\route_match\RouteMatchSpecificationFactory', - $this->getFactory() - ); - } - - /** - * @since 4.9.71.p - * @throws \EventEspresso\core\exceptions\InvalidDataTypeException - * @throws \PHPUnit\Framework\Exception - * @throws \ReflectionException - */ - public function testCreateNewRouteMatchSpecification() - { - $fqcn = 'EventEspresso\core\domain\entities\route_match\specifications\admin\EspressoEventEditorEdit'; - $this->assertInstanceOf( - $fqcn, - $this->getFactory()->createNewRouteMatchSpecification($fqcn) - ); - } - - /** - * @since 4.9.71.p - * @throws \EventEspresso\core\exceptions\InvalidDataTypeException - * @throws \EventEspresso\core\exceptions\InvalidInterfaceException - * @throws \InvalidArgumentException - * @throws \PHPUnit\Framework\Exception - * @throws \ReflectionException - */ - public function testCreate() - { - $fqcn = 'EventEspresso\core\domain\entities\route_match\specifications\admin\EspressoEventEditorEdit'; - $this->assertInstanceOf( - $fqcn, - RouteMatchSpecificationFactory::create($fqcn) - ); - } -} -// location: /tests/testcases/core/services/route_match/RouteMatchSpecificationFactoryTest.php \ No newline at end of file diff --git a/tests/testcases/core/services/validators/URLValidatorTest.php b/tests/testcases/core/services/validators/URLValidatorTest.php deleted file mode 100644 index 3929e1199ff..00000000000 --- a/tests/testcases/core/services/validators/URLValidatorTest.php +++ /dev/null @@ -1,63 +0,0 @@ - array('http://localhost', true), - 'http' => array('http://eventespresso.com', true), - 'https' => array('https://eventespresso.com', true), - 'underscore' => array('http://event_espresso.com', true), - 'subsite' => array('http://dev.eventespresso.com', true), - 'querystring' => array('http://foo.bar?foo=bar&other=thing', true), - 'slashquerystring' => array('http://foob.bar/?foo=bar', true), - 'with_path' => array('http://foo.bar/some/path', true), - 'with_file' => array('http://foo.bar/some/file.txt', true), - 'port' => array('http://foo.bar:80', true), - 'unicode' => array('http://์Šคํƒ€๋ฒ…์Šค์ฝ”๋ฆฌ์•„.com', true), - 'encoded_unicode' => array('http://%EC%8A%A4%ED%83%80%EB%B2%85%EC%8A%A4%EC%BD%94%EB%A6%AC%EC%95%84_foobar.com', true), - 'xss' => array('http://example.com/">', false), - 'bad_scheme' => array('php://filter/read=convert.base64-encode/resource=/etc/passw', false), - 'bad_scheme_2' => array('foo://bar', false), - 'javascript' => array('javascript://test%0Aalert(321)', false), - 'www' => array('www', false), - 'relative_url' => array('some/path', false), - ); - } - - /** - * @dataProvider urlsToTest - * @since 4.9.68.p - * - */ - public function testIsValid($url, $should_be_valid) - { - $validator = new URLValidator(); - $this->assertEquals($should_be_valid,$validator->isValid($url)); - } - - -} -// End of file URLValidatorTest.php -// Location: ${NAMESPACE}/URLValidatorTest.php diff --git a/tests/testcases/espresso_Tests.php b/tests/testcases/espresso_Tests.php deleted file mode 100644 index adcaad8d5a3..00000000000 --- a/tests/testcases/espresso_Tests.php +++ /dev/null @@ -1,96 +0,0 @@ -assertTrue( defined('EVENT_ESPRESSO_VERSION') ); - $this->assertTrue( defined('EE_MIN_WP_VER_REQUIRED') ); - $this->assertTrue( defined('EE_MIN_WP_VER_RECOMMENDED') ); - $this->assertTrue( defined('EE_MIN_PHP_VER_RECOMMENDED') ); - $this->assertTrue( defined('EVENT_ESPRESSO_MAIN_FILE') ); - $this->assertTrue( defined('DS') ); - $this->assertTrue( defined('PS') ); - $this->assertTrue( defined('SP') ); - $this->assertTrue( defined('EE_SUPPORT_EMAIL') ); - $this->assertTrue( defined('EE_PLUGIN_BASENAME') ); - $this->assertTrue( defined('EE_PLUGIN_DIR_PATH') ); - $this->assertTrue( defined('EE_PLUGIN_DIR_URL') ); - $this->assertTrue( defined('EE_ADMIN_PAGES') ); - $this->assertTrue( defined('EE_CORE') ); - $this->assertTrue( defined('EE_MODULES') ); - $this->assertTrue( defined('EE_SHORTCODES') ); - $this->assertTrue( defined('EE_TEMPLATES') ); - $this->assertTrue( defined('EE_WIDGETS') ); - $this->assertTrue( defined('EE_CAFF_PATH') ); - $this->assertTrue( defined('EE_ADMIN') ); - $this->assertTrue( defined('EE_CPTS') ); - $this->assertTrue( defined('EE_CLASSES') ); - $this->assertTrue( defined('EE_MODELS') ); - $this->assertTrue( defined('EE_HELPERS') ); - $this->assertTrue( defined('EE_LIBRARIES') ); - $this->assertTrue( defined('EE_THIRD_PARTY') ); - $this->assertTrue( defined('EE_GLOBAL_ASSETS') ); - $this->assertTrue( defined('EE_GATEWAYS') ); - $this->assertTrue( defined('EE_GATEWAYS_URL') ); - $this->assertTrue( defined('EE_TEMPLATES_URL') ); - $this->assertTrue( defined('EE_GLOBAL_ASSETS_URL') ); - $this->assertTrue( defined('EE_IMAGES_URL') ); - $this->assertTrue( defined('EE_THIRD_PARTY_URL') ); - $this->assertTrue( defined('EE_HELPERS_ASSETS') ); - $this->assertTrue( defined('EVENT_ESPRESSO_UPLOAD_DIR') ); - $this->assertTrue( defined('EVENT_ESPRESSO_UPLOAD_URL') ); - $this->assertTrue( defined('EVENT_ESPRESSO_TEMPLATE_DIR') ); - $this->assertTrue( defined('EVENT_ESPRESSO_TEMPLATE_URL') ); - $this->assertTrue( defined('EVENT_ESPRESSO_GATEWAY_DIR') ); - $this->assertTrue( defined('EVENT_ESPRESSO_GATEWAY_URL') ); - $this->assertTrue( defined('EE_LANGUAGES_SAFE_LOC') ); - $this->assertTrue( defined('EE_LANGUAGES_SAFE_DIR') ); - $this->assertTrue( defined('EE_FRONT_AJAX') ); - $this->assertTrue( defined('EE_ADMIN_AJAX') ); - $this->assertTrue( defined('EE_INF_IN_DB') ); - } - - - /** - * espresso_load_required is run automatically when the plugin is loaded. - * - * That means we should have the following files already loaded: - * - EE_System - * - EE_Debug_Tools - * - EE_Error - * - * @since 4.3.0 - */ - function test_espresso_load_required() { - $this->assertTrue( class_exists( 'EE_System') ); - - //depends on WP_DEBUG - if( defined('WP_DEBUG') && WP_DEBUG ) - $this->assertTrue( class_exists( 'EEH_Debug_Tools') ); - else - $this->assertFalse( class_exists( 'EEH_Debug_Tools') ); - - $this->assertTrue( class_exists( 'EE_Error' ) ); - } -} diff --git a/tests/testcases/integration/EE_Line_Item__EE_Single_Registration_Line_Item_Filter__Integration_Test.php b/tests/testcases/integration/EE_Line_Item__EE_Single_Registration_Line_Item_Filter__Integration_Test.php deleted file mode 100644 index 6f80dd95428..00000000000 --- a/tests/testcases/integration/EE_Line_Item__EE_Single_Registration_Line_Item_Filter__Integration_Test.php +++ /dev/null @@ -1,153 +0,0 @@ -new_typical_transaction( array( 'ticket_types' => 2 ) ); - //add another ticket purchase for one of the same events - $event1 = EEM_Event::instance()->get_one( - array( array( 'Registration.TXN_ID' => $transaction->ID() ) ) - ); - $event_line_item = EEM_Line_Item::instance()->get_one( - array( - array( - 'TXN_ID' => $transaction->ID(), - 'OBJ_type' => 'Event', - 'OBJ_ID' => $event1->ID(), - ), - ) - ); - $this->new_model_obj_with_dependencies( - 'Line_Item', - array( - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_name' => 'event discount', - 'LIN_total' => -8, - 'LIN_unit_price' => -8, - 'LIN_quantity' => 1, - 'LIN_parent' => $event_line_item->ID(), - 'LIN_percent' => null, - 'LIN_order' => count( $event_line_item->children() ) - ) - ); - $total_line_item = $transaction->total_line_item(); - $total_line_item->recalculate_total_including_taxes(); - //and add an unrelated purchase - EEH_Line_Item::add_unrelated_item( $total_line_item, 'Transaction-Wide Discount', -5 ); - $totals = EEH_Line_Item::calculate_reg_final_prices_per_line_item( $total_line_item ); - // honestly the easiest way to confirm the total was right is to visualize the tree - // echo "\n\n " . __LINE__ . ') : visualize( $total_line_item )'; - // EEH_Line_Item::visualize( $total_line_item ); - // echo "\n\n " . __LINE__ . ') : $totals' . "\n"; - // var_dump( $totals ); - - //for each registration on the transaction, verify the REG_final_price - //indicated by EEH_Line_Item::calculate_reg_final_prices_per_line_item matches - //what the line item filters would have returned - EEH_Autoloader::register_line_item_filter_autoloaders(); - foreach( $transaction->registrations() as $registration ) { - $ticket_line_item = EEM_Line_Item::instance()->get_line_item_for_registration( $registration ); - $reg_final_price_from_line_item_helper = $totals[ $ticket_line_item->ID() ]; - //now get the line item filter's final price - $filters = new EE_Line_Item_Filter_Collection(); - $filters->add( new EE_Single_Registration_Line_Item_Filter( $registration ) ); - $line_item_filter_processor = new EE_Line_Item_Filter_Processor( $filters, $total_line_item ); - $filtered_line_item_tree = $line_item_filter_processor->process(); - // echo "\n\n " . __LINE__ . ') : visualize( $filtered_line_item_tree )'; - // EEH_Line_Item::visualize( $filtered_line_item_tree ); - $reg_final_price_from_line_item_filter = $filtered_line_item_tree->total(); - $this->assertLessThan( 0.2, abs( $reg_final_price_from_line_item_filter - $reg_final_price_from_line_item_helper ) ); - } - } - - /** - * like test_REG_final_price_matches_total_of_filtering_line_item_tree, - * but makes sure the tickets have sub-prices, because that has shown to have some - * bugs with calculations so far - */ - function test_REG_final_price_matches_total_of_filtering_line_item_tree__with_sub_line_items() { - $transaction = $this->new_typical_transaction( - array( - 'ticket_types' => 2, - 'fixed_ticket_price_modifiers' => 2, - ) - ); - //add another ticket purchase for one of the same events - $event1 = EEM_Event::instance()->get_one( - array( array( 'Registration.TXN_ID' => $transaction->ID() ) ) - ); - $event_line_item = EEM_Line_Item::instance()->get_one( - array( - array( - 'TXN_ID' => $transaction->ID(), - 'OBJ_type' => 'Event', - 'OBJ_ID' => $event1->ID() - ) - ) - ); - $this->new_model_obj_with_dependencies( - 'Line_Item', - array( - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_name' => 'event discount', - 'LIN_total' => -8, - 'LIN_unit_price' => -8, - 'LIN_quantity' => 1, - 'LIN_parent' => $event_line_item->ID(), - 'LIN_percent' => null, - 'LIN_order' => count( $event_line_item->children() ) - ) - ); - $total_line_item = $transaction->total_line_item(); - $total_line_item->recalculate_total_including_taxes(); - //and add an unrelated purchase - EEH_Line_Item::add_unrelated_item( $total_line_item, 'Transaction-Wide Discount', -5 ); - - $totals = EEH_Line_Item::calculate_reg_final_prices_per_line_item( $total_line_item ); - - // honestly the easiest way to confirm the total was right is to visualize the tree -// var_dump( $totals ); -// EEH_Line_Item::visualize( $total_line_item ); - - //for each registration on the transaction, verify the REG_final_price - //indicated by EEH_Line_Item::calculate_reg_final_prices_per_line_item matches - //what the line item filters would have returned - EEH_Autoloader::register_line_item_filter_autoloaders(); - foreach( $transaction->registrations() as $registration ) { - $ticket_line_item = EEM_Line_Item::instance()->get_line_item_for_registration( $registration ); - $reg_final_price_from_line_item_helper = $totals[ $ticket_line_item->ID() ]; - - //now get the line item filter's final price - $filters = new EE_Line_Item_Filter_Collection(); - $filters->add( new EE_Single_Registration_Line_Item_Filter( $registration ) ); - $line_item_filter_processor = new EE_Line_Item_Filter_Processor( $filters, $total_line_item ); - $filtered_line_item_tree = $line_item_filter_processor->process(); - $reg_final_price_from_line_item_filter = $filtered_line_item_tree->total(); - - $this->assertLessThan( 0.2, abs( $reg_final_price_from_line_item_filter - $reg_final_price_from_line_item_helper ) ); - } - } - - - -} - -// End of file EE_Line_Item__EE_Single_Registration_Line_Item_Filter__Integration_Test.php -// Location: testcases/integration/EE_Line_Item__EE_Single_Registration_Line_Item_Filter__Integration_Test.php \ No newline at end of file diff --git a/tests/testcases/misc/EE_Tests_Miscellaneous.php b/tests/testcases/misc/EE_Tests_Miscellaneous.php deleted file mode 100644 index 01d44644e4d..00000000000 --- a/tests/testcases/misc/EE_Tests_Miscellaneous.php +++ /dev/null @@ -1,27 +0,0 @@ -assertTrue( $EE_SYS instanceof EE_System ); - } -} diff --git a/tests/testcases/misc/EE_UnitTestCase_Test.php b/tests/testcases/misc/EE_UnitTestCase_Test.php deleted file mode 100644 index 9dc179c8470..00000000000 --- a/tests/testcases/misc/EE_UnitTestCase_Test.php +++ /dev/null @@ -1,128 +0,0 @@ -get_all_prices_that_are_taxes(); - $this->assertEquals(1, count( $taxes ) ); - $taxes_at_top_priority = array_shift( $taxes );//array shift twice because 2d array - $tax = array_shift( $taxes_at_top_priority ); - - //make transaction - $txn = $this->new_typical_transaction(); - - $this->assertEquals( 1.5, $taxable = $txn->tax_total() ); - //verify everything - $regs = $txn->registrations(); - $this->assertEquals(1, count( $regs ) ); - $reg = array_shift( $regs ); - $this->assertEquals( $txn->total(), $reg->final_price() ); - - $tkt = $reg->ticket(); - $this->assertEquals( $tkt->price() * ( 100 + $tax->amount()) / 100, $reg->final_price() ); - $this->assertTrue( $tkt->taxable() ); - - $total_line_item = $txn->total_line_item(); - $this->assertEquals( $txn->total(), $total_line_item->total() ); - - $this->_ensure_txn_on_line_item_and_children( $txn, $total_line_item ); - $this->assertNotEmpty( $txn->tax_total() ); - $this->assertEquals( $txn->ID(), $total_line_item->TXN_ID() ); - } - /** - * repeats the test because it originally failed when the test was repeated - * (because when we reset EE_Cart, it fetches the same one from the session, - * ie there was a bug in EE_Cart::reset) - */ - public function test_new_typical_transaction_again(){ - //there should be a tax in the system by default - $taxes = EEM_Price::instance()->get_all_prices_that_are_taxes(); - $this->assertEquals(1, count( $taxes ) ); - $taxes_at_top_priority = array_shift( $taxes );//array shift twice because 2d array - $tax = array_shift( $taxes_at_top_priority ); - - //make transaction - $txn = $this->new_typical_transaction(); - - //verify everything - $regs = $txn->registrations(); - $this->assertEquals(1, count( $regs ) ); - $reg = array_shift( $regs ); - $this->assertEquals( $txn->total(), $reg->final_price() ); - - $tkt = $reg->ticket(); - $this->assertEquals( $tkt->price() * ( 100 + $tax->amount()) / 100, $reg->final_price() ); - $this->assertTrue( $tkt->taxable() ); - - $total_line_item = $txn->total_line_item(); - $this->assertEquals( $txn->total(), $total_line_item->total() ); - - $this->_ensure_txn_on_line_item_and_children( $txn, $total_line_item ); - $this->assertNotEmpty( $txn->tax_total() ); - $this->assertEquals( $txn->ID(), $total_line_item->TXN_ID() ); - } - - public function test_new_typical_transaction__ticket_types_3(){ - $different_tickets_purchased = 3; - //there should be a tax in the system by default - $taxes = EEM_Price::instance()->get_all_prices_that_are_taxes(); - $this->assertEquals(1, count( $taxes ) ); - $taxes_at_top_priority = array_shift( $taxes );//array shift twice because 2d array - $tax = array_shift( $taxes_at_top_priority ); - - //make transaction - $txn = $this->new_typical_transaction( array('ticket_types'=>$different_tickets_purchased)); - - //verify everything - $regs = $txn->registrations(); - $this->assertEquals($different_tickets_purchased, count( $regs ) ); - - $sum_of_regs = 0; - foreach( $regs as $reg){ - $sum_of_regs += $reg->final_price(); - $reg = array_shift( $regs ); - $tkt = $reg->ticket(); - $this->assertEquals( $tkt->price() * ( 100 + $tax->amount()) / 100, $reg->final_price() ); - $this->assertTrue( $tkt->taxable() ); - } - $this->assertEquals( $txn->total(), $sum_of_regs ); - - - - $total_line_item = $txn->total_line_item(); - $this->assertEquals( $txn->total(), $total_line_item->total() ); - - $this->_ensure_txn_on_line_item_and_children( $txn, $total_line_item ); - $this->assertNotEmpty( $txn->tax_total() ); - $this->assertEquals( $txn->ID(), $total_line_item->TXN_ID() ); - } - - /** - * Checks line item and children list $txn as their transaction. - * Used by E_UnitTestCase_Test::test_new_typical_transaction() - * @param EE_Transaction $txn - * @param EE_Line_Item $line_item - */ - private function _ensure_txn_on_line_item_and_children( $txn, $line_item ){ - $this->assertEquals($txn->ID(), $line_item->TXN_ID() ); - foreach($line_item->children() as $child_line_item ){ - $this->_ensure_txn_on_line_item_and_children( $txn, $child_line_item ); - } - } -} -// End of file EE_UnitTestCase_Test.php \ No newline at end of file diff --git a/tests/testcases/misc/WP_Filesystem_permissions_UnitTestCases.php b/tests/testcases/misc/WP_Filesystem_permissions_UnitTestCases.php deleted file mode 100644 index 9bbce1c0140..00000000000 --- a/tests/testcases/misc/WP_Filesystem_permissions_UnitTestCases.php +++ /dev/null @@ -1,175 +0,0 @@ -assertTrue(is_a($wp_filesystem, 'WP_Filesystem_MockEEFS')); - $wp_filesystem->init('/'); - // Test creation/exists checks - $this->assertFalse($wp_filesystem->is_dir('/test/')); - $wp_filesystem->mkdir('/test'); - $this->assertTrue($wp_filesystem->exists('/test')); - $this->assertTrue($wp_filesystem->is_dir('/test/')); - $this->assertFalse($wp_filesystem->is_file('/test')); - //$this->assertFalse( true ); - } - - - - function test_mkdir() - { - global $wp_filesystem; - $wp_filesystem->init('/'); - $folder_path = '/test/'; - $wp_filesystem->mkdir($folder_path); - $this->assertTrue($wp_filesystem->exists($folder_path)); - $this->assertEquals(WP_Filesystem_MockFS_default_perms, $wp_filesystem->getchmod($folder_path)); - $this->assertEquals(WP_Filesystem_MockFS_default_owner, $wp_filesystem->owner($folder_path)); - $this->assertEquals(WP_Filesystem_MockFS_default_group, $wp_filesystem->group($folder_path)); - } - - - - function test_chmod() - { - global $wp_filesystem; - $wp_filesystem->init('/'); - $folder_path = '/test/'; - $wp_filesystem->mkdir($folder_path); - $this->assertEquals(WP_Filesystem_MockFS_default_perms, $wp_filesystem->getchmod($folder_path)); - $wp_filesystem->chmod($folder_path, 664); - $this->assertEquals(664, $wp_filesystem->getchmod($folder_path)); - } - - - - function test_chown() - { - global $wp_filesystem; - $wp_filesystem->init('/'); - $folder_path = '/test/'; - $wp_filesystem->mkdir($folder_path); - $this->assertEquals(WP_Filesystem_MockFS_default_owner, $wp_filesystem->owner($folder_path)); - $wp_filesystem->chown($folder_path, 'stranger'); - $this->assertEquals('stranger', $wp_filesystem->owner($folder_path)); - } - - - - function test_chgroup() - { - global $wp_filesystem; - $wp_filesystem->init('/'); - $folder_path = '/test/'; - $wp_filesystem->mkdir($folder_path); - $this->assertEquals(WP_Filesystem_MockFS_default_group, $wp_filesystem->group($folder_path)); - $success = $wp_filesystem->chgrp($folder_path, 'globe-trotters'); - $this->assertEquals('globe-trotters', $wp_filesystem->group($folder_path)); - } - - - - function test_is_readable() - { - global $wp_filesystem; - $wp_filesystem->init('/'); - $folder_path = '/test/'; - $wp_filesystem->mkdir($folder_path); - $this->assertEquals(WP_Filesystem_MockFS_default_perms, $wp_filesystem->getchmod($folder_path)); - $this->assertTrue($wp_filesystem->is_readable($folder_path)); - //switch to another user, although they should be able to read it too - $other_user_same_group = $wp_filesystem->add_system_user('other_user_same_group', WP_Filesystem_MockFS_default_group); - $other_user_other_group = $wp_filesystem->add_system_user('other_user_other_group', 'other_group'); - $wp_filesystem->change_current_system_user($other_user_other_group->username); - $this->assertTrue($wp_filesystem->is_readable($folder_path)); - $wp_filesystem->change_current_system_user(WP_Filesystem_MockFS_default_owner); - //change the permissions soo only someone in the same group can read - $wp_filesystem->chmod($folder_path, '770'); - $this->assertEquals('770', $wp_filesystem->getchmod($folder_path)); - $this->assertTrue($wp_filesystem->is_readable($folder_path)); - //and now check the user in the same group can still read... - $wp_filesystem->change_current_system_user($other_user_same_group->username); - $this->assertTrue($wp_filesystem->is_readable($folder_path)); - //..bu tthe user in a differeng group can't - $wp_filesystem->change_current_system_user($other_user_other_group->username); - $this->assertFalse($wp_filesystem->is_readable($folder_path)); - } - - - - function test_is_writable() - { - global $wp_filesystem; - $wp_filesystem->init('/'); - $folder_path = '/test/'; - $wp_filesystem->mkdir($folder_path); - $this->assertEquals(WP_Filesystem_MockFS_default_perms, $wp_filesystem->getchmod($folder_path)); - $this->assertTrue($wp_filesystem->is_writable($folder_path)); - //switch to another user, although they should be able to write it too - $other_user_same_group = $wp_filesystem->add_system_user('other_user_same_group', WP_Filesystem_MockFS_default_group); - $other_user_other_group = $wp_filesystem->add_system_user('other_user_other_group', 'other_group'); - $wp_filesystem->change_current_system_user($other_user_other_group->username); - $this->assertTrue($wp_filesystem->is_writable($folder_path)); - $wp_filesystem->change_current_system_user(WP_Filesystem_MockFS_default_owner); - //change the permissions soo only someone in the same group can read - $wp_filesystem->chmod($folder_path, '770'); - $this->assertEquals('770', $wp_filesystem->getchmod($folder_path)); - $this->assertTrue($wp_filesystem->is_writable($folder_path)); - //and now check the user in the same group can still write... - $wp_filesystem->change_current_system_user($other_user_same_group->username); - $this->assertTrue($wp_filesystem->is_writable($folder_path)); - //..bu tthe user in a differeng group can't - $wp_filesystem->change_current_system_user($other_user_other_group->username); - $this->assertFalse($wp_filesystem->is_writable($folder_path)); - } - -} - - diff --git a/tests/testcases/modules/EEDCoreRestApiTest.php b/tests/testcases/modules/EEDCoreRestApiTest.php deleted file mode 100644 index 5e3359e9a83..00000000000 --- a/tests/testcases/modules/EEDCoreRestApiTest.php +++ /dev/null @@ -1,536 +0,0 @@ - $ee_routes) { - foreach (EED_Core_Rest_Api::model_names_with_plural_routes('4.8.36') as $model_name => $model_classname) { - $model = EE_Registry::instance()->load_model($model_name); - $plural_model_route = EED_Core_Rest_Api::get_collection_route($model); - $singular_model_route = EED_Core_Rest_Api::get_entity_route($model, '(?P[^\/]+)'); - //currently, we expose models even for wp core routes to reading (we have plans to change this though) - //on https://events.codebasehq.com/projects/event-espresso/tickets/9583 - $this->assertArrayHasKey( - 0, - $ee_routes[$plural_model_route], - $plural_model_route - ); - //now let's double-check the singular routes too - $this->assertArrayHasKey( - 0, - $ee_routes[$singular_model_route], - $singular_model_route - ); - //wp core models should NOT have write endpoints - if ($model->is_wp_core_model()) { - //make sure there is no insert endpoint - $this->AssertArrayNotHasKey( - 1, - $ee_routes[$plural_model_route] - ); - //make sure there is no update or delete endpoints - $this->AssertArrayNotHasKey( - 1, - $ee_routes[$singular_model_route] - ); - $this->AssertArrayNotHasKey( - 2, - $ee_routes[$singular_model_route] - ); - } else { - //make sure there is an insert endpoint - $this->AssertArrayHasKey( - 1, - $ee_routes[$plural_model_route] - ); - //make sure there is update and delete endpoints - $this->assertArrayHasKey( - 1, - $ee_routes[$singular_model_route] - ); - $this->assertArrayHasKey( - 2, - $ee_routes[$singular_model_route] - ); - } - } - } - } - - - - /** - * @return array{ - * @type EEM_Base $model - * } - */ - public function dataProviderForTestGetAllCollectionRoutes() - { - $unit_test_data = array(); - foreach (array_keys(EED_Core_Rest_Api::model_names_with_plural_routes('4.8.36')) as $model_name) { - $model = EE_Registry::instance()->load_model($model_name); - //lets only verify requests for models with primary keys - if ($model->has_primary_key_field()) { - $unit_test_data[$model_name] = array($model); - } - } - return $unit_test_data; - } - - - - /** - * Verifies that, for each model from the data provider, we can query its GET routes - * - * @dataProvider dataProviderForTestGetAllCollectionRoutes - * @param EEM_Base $model - * @group big_rest_tests - */ - public function testGetAllCollectionRoutes(EEM_Base $model) - { - $this->authenticate_as_admin(); - //make sure there's an entry for this model. We will use it in an assertion later - $model_obj = $this->getAModelObjOfType($model); - $route = EED_Core_Rest_Api::get_versioned_route_to( - EED_Core_Rest_Api::get_collection_route($model), - '4.8.36' - ); - $response = rest_do_request( - new WP_REST_Request( - 'GET', - $route - ) - ); - $response_data = $response->get_data(); - $this->assertNotFalse($response_data); - $this->assertArrayNotHasKey( - 'code', - $response_data, - sprintf( - 'Got error response "%1$s" while querying route "%2$s"', - wp_json_encode($response_data), - $route - ) - ); - //verify we find the item we identified using the models - $contains_item = false; - foreach ($response_data as $datum) { - if ($datum[$model->primary_key_name()] == $model_obj->ID()) { - $contains_item = true; - break; - } - } - $this->assertTrue($contains_item); - } - - - - /** - * Verifies that all our models' singular GET routes work - * - * @dataProvider dataProviderForTestGetAllCollectionRoutes - * @param EEM_Base $model - * @group big_rest_tests - */ - public function testGetAllEntityRoutes(EEM_Base $model) - { - $this->authenticate_as_admin(); - //make sure there's an entry for this model. We will use it in an assertion later - $model_obj = $this->getAModelObjOfType($model); - $route = EED_Core_Rest_Api::get_versioned_route_to( - EED_Core_Rest_Api::get_entity_route($model, $model_obj->ID()), - '4.8.36' - ); - $response = rest_do_request( - new WP_REST_Request( - 'GET', - $route - ) - ); - $response_data = $response->get_data(); - $this->assertNotFalse($response_data); - $this->assertArrayNotHasKey( - 'code', - $response_data, - sprintf( - 'Got error response "%1$s" while querying route "%2$s"', - wp_json_encode($response_data), - $route - ) - ); - //verify we find the item we identified using the models - $this->assertEquals($model_obj->ID(), $response_data[$model->primary_key_name()]); - } - - - - /** - * @return array{ - * @type EEM_Base $model - * @type EE_Model_Relation_Base $relation_obj - * } - */ - public function dataProviderForTestGetAllRelatedRoutes() - { - $unit_test_data = array(); - $models_with_plural_routes = array_keys(EED_Core_Rest_Api::model_names_with_plural_routes('4.8.36')); - foreach ($models_with_plural_routes as $model_name) { - $model = EE_Registry::instance()->load_model($model_name); - foreach ($model->relation_settings() as $relation_name => $relation_obj) { - //lets only verify requests for models with primary keys - if ($model->has_primary_key_field()) { - $unit_test_data[$model_name] = array($model, $relation_obj); - } - } - } - return $unit_test_data; - } - - - - /** - * Verifies that all the existing related routes are queryable - * - * @dataProvider dataProviderForTestGetAllRelatedRoutes - * @param EEM_Base $model - * @param EE_Model_Relation_Base $relation_obj - * @group big_rest_tests - */ - public function testGetAllRelatedRoutes(EEM_Base $model, EE_Model_Relation_Base $relation_obj) - { - $related_model = $relation_obj->get_other_model(); - $this->authenticate_as_admin(); - $model_obj = $this->getAModelObjOfType($model); - $related_model_obj = $this->getAModelObjOfType($related_model); - $model_obj->_add_relation_to($related_model_obj, $related_model->get_this_model_name()); - - $route = EED_Core_Rest_Api::get_versioned_route_to( - EED_Core_Rest_Api::get_relation_route_via( - $model, - $model_obj->ID(), - $relation_obj - ), - '4.8.36' - ); - $response = rest_do_request( - new WP_REST_Request( - 'GET', - $route - ) - ); - $response_data = $response->get_data(); - $this->assertNotFalse($response_data); - $this->assertNotEmpty($response_data); - $this->assertNotNull($response_data); - $this->assertArrayNotHasKey( - 'code', - $response_data, - sprintf( - 'Got error response "%1$s" while querying route "%2$s"', - wp_json_encode($response_data), - $route - ) - ); - if ($relation_obj instanceof EE_Belongs_To_Relation){ - //only expect one result - $this->assertEquals($related_model_obj->ID(), $response_data[$related_model->primary_key_name()]); - } else { - //verify we find the item we identified using the models - $contains_item = false; - foreach ($response_data as $datum) { - if ($datum[$related_model->primary_key_name()] == $related_model_obj->ID()) { - $contains_item = true; - break; - } - } - $this->assertTrue($contains_item); - } - } - - - - /** - * Returns an array of model names which an object of type $model - * needs in order for queries for that model to return anything. - * (Because there are default model conditions that always join to that model - * when capabilities are being applied). - * - * @param string $model_name - * @return array - */ - protected function requiredRelationsInOrderToQuery($model_name) - { - $requirements = array( - 'Ticket_Template' => array('Ticket'), - ); - if (isset($requirements[$model_name])) { - return $requirements[$model_name]; - } else { - return array(); - } - } - - - - /** - * Fetches a model object of the specified type, or if none exists creates one. - * Also, verifies that model object has any related model objects which are - * needed in order to find that method object when applying caps - * (because capability conditions might join to that table) - * - * @param EEM_Base $model - * @param boolean $reuse_existing_objs whether to use existing model objects of this type, - * or always create a new one - * @return EE_Base_Class - */ - protected function getAModelObjOfType(EEM_Base $model, $reuse_existing_objs = true) - { - $model_obj = null; - if ($reuse_existing_objs) { - $model_obj = $model->get_one( - array( - 'caps' => EEM_Base::caps_read, - ) - ); - } - if (! $model_obj instanceof EE_Base_Class) { - $model_obj = $this->new_model_obj_with_dependencies($model->get_this_model_name()); - } - //add any data they might require in order to be queried - $required_relations = $this->requiredRelationsInOrderToQuery($model->get_this_model_name()); - foreach ($required_relations as $required_dependent_model_name) { - $related_model_obj = $this->new_model_obj_with_dependencies($required_dependent_model_name); - $model_obj->_add_relation_to($related_model_obj, $required_dependent_model_name); - } - return $model_obj; - } - - - - /** - * @return array{ - * @type EEM_Base $model - * } - */ - public function dataProviderForTestInsertsRoutes() - { - $unit_test_data = array(); - foreach (array_keys(EED_Core_Rest_Api::model_names_with_plural_routes('4.8.36')) as $model_name) { - $model = EE_Registry::instance()->load_model($model_name); - if (EED_Core_Rest_Api::should_have_write_endpoints($model)) { - //lets only verify requests for models with primary keys - if ($model->has_primary_key_field()) { - $unit_test_data[$model_name] = array($model); - } - } - } - return $unit_test_data; - } - - - - /** - * Verifies that, for each model from the data provider, we can use its INSERT routes - * - * @dataProvider dataProviderForTestInsertsRoutes - * @param EEM_Base $model - * @group big_rest_tests - */ - public function testInsertsRoutes(EEM_Base $model) - { - $this->authenticate_as_admin(); - $unsaved_model_obj = $this->new_model_obj_with_dependencies( - $model->get_this_model_name(), - array(), - false - ); - - $route = EED_Core_Rest_Api::get_versioned_route_to( - EED_Core_Rest_Api::get_collection_route($model), - '4.8.36' - ); - $insert_values = array(); - foreach ($unsaved_model_obj->get_model()->field_settings() as $field_name => $field_obj) { - $value_to_use = $field_obj instanceof EE_Datetime_Field - ? $unsaved_model_obj->get_DateTime_object($field_name) - : $unsaved_model_obj->get_raw($field_name); - $insert_values[$field_name] = ModelDataTranslator::prepareFieldValuesForJson( - $field_obj, - $value_to_use, - '4.8.36' - ); - } - $request = new WP_REST_Request( - 'POST', - $route - ); - $request->set_body_params($insert_values); - $response = rest_do_request( - $request - ); - $response_data = $response->get_data(); - $this->assertNotFalse($response_data); - $this->assertArrayNotHasKey( - 'code', - $response_data, - sprintf( - 'Got error response "%1$s" while POSTing to route "%2$s"', - wp_json_encode($response_data), - $route - ) - ); - } - - - - /** - * Verifies that, for each model from the data provider, we can use its DELETE routes - * - * @dataProvider dataProviderForTestInsertsRoutes - * @param EEM_Base $model - * @group big_rest_tests - */ - public function testDeleteRoutes(EEM_Base $model) - { - $this->authenticate_as_admin(); - $model_obj = $this->getAModelObjOfType($model, false); - $route = EED_Core_Rest_Api::get_versioned_route_to( - EED_Core_Rest_Api::get_entity_route($model, $model_obj->ID()), - '4.8.36' - ); - - $request = new WP_REST_Request( - 'DELETE', - $route - ); - $request->set_body_params( - array( - 'force' => true, - 'allow_blocking' => false - ) - ); - - $response = rest_do_request( - $request - ); - $response_data = $response->get_data(); - $this->assertNotFalse($response_data); - $this->assertArrayNotHasKey( - 'code', - $response_data, - sprintf( - 'Got error response "%1$s" while DELETEing on route "%2$s"', - wp_json_encode($response_data), - $route - ) - ); - $this->assertEquals(true, $response_data['deleted']); - $this->assertEquals($model_obj->ID(), $response_data['previous'][$model->primary_key_name()]); - } - - - /** - * Verifies that, for each model from the data provider, we can use its DELETE routes - * - * @dataProvider dataProviderForTestInsertsRoutes - * @param EEM_Base $model - * @group big_rest_tests - */ - public function testUpdateRoutes(EEM_Base $model) - { - $this->authenticate_as_admin(); - $model_obj = $this->getAModelObjOfType($model, false); - $route = EED_Core_Rest_Api::get_versioned_route_to( - EED_Core_Rest_Api::get_entity_route($model, $model_obj->ID()), - '4.8.36' - ); - - $request = new WP_REST_Request( - 'PUT', - $route - ); - $field_to_update = null; - foreach ($model->field_settings() as $field_obj) { - if (! $field_obj instanceof EE_Primary_Key_Field_Base) { - $field_to_update = $field_obj; - break; - } - } - if ($field_to_update instanceof EE_Boolean_Field) { - $set_value = ! $model_obj->get($field_to_update->get_name()); - } elseif ($field_to_update instanceof EE_Integer_Field - || $field_to_update instanceof EE_Float_Field - || $field_to_update instanceof EE_Foreign_Key_Int_Field) { - $set_value = $model_obj->get($field_to_update->get_name()) + 1; - } elseif ($field_to_update instanceof EE_Datetime_Field) { - $set_value = $model_obj->get_DateTime_object($field_to_update->get_name())->modify('+1 day'); - } elseif ($field_to_update instanceof EE_All_Caps_Text_Field - || $field_to_update instanceof EE_Foreign_Key_String_Field) { - $set_value = 'NEW'; - } else { - $set_value = 'new'; - } - //double check the new value won't be the same as the old one - $this->assertNotEquals( - $set_value, - $model_obj->get($field_to_update->get_name()), - $field_to_update->get_name() - ); - $request->set_body_params( - array( - $field_to_update->get_name() => ModelDataTranslator::prepareFieldValuesForJson( - $field_to_update, - $set_value, - '4.8.36' - ) - ) - ); - $response = rest_do_request( - $request - ); - $response_data = $response->get_data(); - $this->assertNotFalse($response_data); - $this->assertArrayNotHasKey( - 'code', - $response_data, - sprintf( - 'Got error response "%1$s" while PUTing on route "%2$s"', - wp_json_encode($response_data), - $route - ) - ); - if ($field_to_update instanceof EE_Datetime_Field) { - $current_value = $model_obj->get_DateTime_object($field_to_update->get_name()); - } else { - $current_value = $model_obj->get($field_to_update->get_name()); - } - $this->assertEquals($set_value, $current_value); - $this->assertEquals($model_obj->ID(), $response_data[$model->primary_key_name()]); - } -} -// End of file EEDCoreRestApiTest.php -// Location: /EEDCoreRestApiTest.php diff --git a/tests/testcases/modules/EED_Single_Page_Checkout_Test.php b/tests/testcases/modules/EED_Single_Page_Checkout_Test.php deleted file mode 100644 index fd4c0bfcdae..00000000000 --- a/tests/testcases/modules/EED_Single_Page_Checkout_Test.php +++ /dev/null @@ -1,112 +0,0 @@ -loadModuleMocks( array( 'EED_Single_Page_Checkout' ) ); - $this->spco_mock = EED_Single_Page_Checkout_Mock::instance(); - //add filter on permalink to add some noise - add_filter( 'page_link', array( $this, 'add_dummy_query_args' ) ); - // for some reason, whatever the reg_page_id is set on EE_Config is not an actual page in the db. - // so we first setup a page and set it as the reg page for the purpose of this test - $this->new_page_id = $this->factory->post->create( array( 'post_type' => 'page' ) ); - // then swap out existing reg page id with the new one - $this->original_reg_page_id = EE_Config::instance()->core->reg_page_id; - EE_Config::instance()->core->reg_page_id = $this->new_page_id; - } - - - - public function tearDown() { - EE_Config::instance()->core->reg_page_id = $this->original_reg_page_id; - // remove filter on permalink - remove_filter( 'page_link', array( $this, 'add_dummy_query_args' ) ); - parent::tearDown(); - } - - - - public function add_dummy_query_args( $link ) { - return add_query_arg( array( 'some_dummy_arg' => 'crazy' ), $link ); - } - - - - /** - * because older versions of WP don't have \WP_UnitTestCase::set_permalink_structure() - * - * @param string $structure - */ - public function set_permalink_structure( $structure = '' ) { - global $wp_rewrite; - $wp_rewrite->init(); - $wp_rewrite->set_permalink_structure( $structure ); - $wp_rewrite->flush_rules(); - } - - - - /** - * @group 10220 - * @group spco - */ - public function test_is_reg_page() { - $permalink_structures = array( - // plain /?p=123 - 'plain' => '', - // Day and name 2016/11/07/sample-post/ - 'day_name' => '/%year%/%monthnum%/%day%/%postname%/', - // Month and name http://local.wordpress.dev/2016/11/sample-post/ - 'month_name' => '/%year%/%monthnum%/%postname%/', - // Numeric http://local.wordpress.dev/archives/123 - 'numeric' => '/archives/%post_id%', - // Post name http://local.wordpress.dev/sample-post/ - 'post_name' => '/%postname%/', - ); - foreach ( $permalink_structures as $permalink_structure ) { - $this->set_permalink_structure( $permalink_structure ); - // example reg_page_permalink where a plugin or theme adds query params - // to links clicked by users for additional functionality that is NOT - // generated via filtering get_permalink. - $this->go_to( - add_query_arg( - array( - 'utm' => '5677', - 'campaign' => 'analytics_campaign', - ), - get_permalink( EE_Config::instance()->core->reg_page_id ) - ) - ); - //so we SHOULD be on the reg page - $this->assertTrue( $this->spco_mock->is_reg_checkout() ); - } - } - - -} -// End of file EED_Single_Page_Checkout_Test.php -// Location: tests/testcases/modules/EED_Single_Page_Checkout_Test.php \ No newline at end of file diff --git a/tests/testcases/modules/EED_Ticket_Sales_Monitor_Test.php b/tests/testcases/modules/EED_Ticket_Sales_Monitor_Test.php deleted file mode 100644 index e2366a60bd2..00000000000 --- a/tests/testcases/modules/EED_Ticket_Sales_Monitor_Test.php +++ /dev/null @@ -1,661 +0,0 @@ -set('TXN_ID', 0); - $this->assertEquals(0, $total_line_item->total()); - $ticket = $this->new_ticket(); - $ticket_line_item = EEH_Line_Item::add_ticket_purchase($total_line_item, $ticket, $ticket_count); - $this->assertInstanceOf('EE_Line_Item', $ticket_line_item); - $this->assertEquals($ticket_count, $ticket_line_item->quantity()); - $timestamp = time(); - if ($expired) { - $timestamp -= DAY_IN_SECONDS; - $this->fake_expired_cart($total_line_item, $timestamp); - } - $saved = $total_line_item->save_this_and_descendants_to_txn(); - // total, pretax, tax total, tax, event, ticket, price - $this->assertEquals(7, $saved); - $this->assertDateWithinOneMinute( - date('Y-m-d h:i a', $timestamp), - date('Y-m-d h:i a', $total_line_item->timestamp(true)), - 'Y-m-d h:i a' - ); - return $ticket_line_item; - } - - - /** - * sets timestamp for line item and descendants to past date - * - * @param EE_Line_Item $line_item - * @param int $timestamp - * @return void - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - */ - protected function fake_expired_cart(EE_Line_Item $line_item, $timestamp = 0) - { - $line_item->set('LIN_timestamp', $timestamp); - $children = $line_item->children(); - foreach ($children as $child_line_item) { - if ($child_line_item instanceof EE_Line_Item) { - $this->fake_expired_cart($child_line_item, $timestamp); - } - } - } - - - /** - * @param int $ticket_count - * @param int $line_item_count - * @return void - * @throws EE_Error - * @throws InvalidArgumentException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws \PHPUnit\Framework\Exception - */ - protected function confirm_ticket_line_item_counts($ticket_count = 1, $line_item_count = 1) - { - $ticket_line_items = EEM_Line_Item::instance()->get_all(array(array('OBJ_type' => 'Ticket'))); - $this->assertCount( - $line_item_count, - $ticket_line_items, - sprintf( - 'Line item count was %1$d when it should have been %2$d', - count($ticket_line_items), - $line_item_count - ) - ); - $qty = 0; - foreach ($ticket_line_items as $ticket_line_item) { - /** @var EE_Line_Item $ticket_line_item */ - $this->assertInstanceOf('EE_Line_Item', $ticket_line_item); - $qty += $ticket_line_item->quantity(); - } - $this->assertEquals( - $ticket_count, - $qty, - sprintf( - 'Ticket count was %1$d when it should have been %2$d', - $qty, - $ticket_count - ) - ); - } - - - /** - * generates all objects for each test and verifies all initial counts are correct - * - * @param array $cart_details - * @return array - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws UnexpectedEntityException - * @throws \PHPUnit\Framework\Exception - */ - protected function setup_and_validate_tickets_for_carts(array $cart_details) - { - $cart_count = 0; - $total_ticket_count = 0; - foreach ($cart_details as $cart => $details) { - $cart_count++; - $total_ticket_count += $details['ticket_count']; - // simulate a couple of tickets that were added to the cart in the past - $ticket_line_item = $this->setup_cart_and_get_ticket_line_item( - $details['ticket_count'], - $details['expired'] - ); - // get ticket from line item - $ticket = $ticket_line_item->ticket(); - $this->assertInstanceOf('EE_Ticket', $ticket); - // confirm number of line items && tickets - $this->confirm_ticket_line_item_counts($total_ticket_count, $cart_count); - // this will increment ticket reserved count - EED_Ticket_Sales_Monitor::validate_ticket_sale($details['ticket_count'], $ticket); - $this->assertEquals( - $details['ticket_count'], - $ticket->reserved(), - sprintf( - 'The reserved ticket count for the %1$s ticket was %2$d when it should have been %3$d', - $cart, - $ticket->reserved(), - $details['ticket_count'] - ) - ); - // if cart is expired, the reserved count should get releases and end up as zero - $cart_details[$cart]['final_reserved_count'] = ! $details['expired'] ? $details['ticket_count'] : 0; - $cart_details[$cart]['ticket'] = $ticket; - } - return $cart_details; - } - - - /** - * Confirms that each ticket's reserved count matches what is expected - * - * @param array $cart_details - * @throws EE_Error - */ - protected function process_cart_results(array $cart_details) - { - foreach ($cart_details as $cart => $details) { - if ($details['ticket'] instanceof EE_Ticket) { - $this->assertEquals( - $details['final_reserved_count'], - $details['ticket']->reserved(), - sprintf( - 'The final reserved ticket count for the %1$s ticket after expired tickets were released, was %2$d when it should have been %3$d.', - $cart, - $details['ticket']->reserved(), - $details['final_reserved_count'] - ) - ); - } - } - } - - - /** - * @throws DomainException - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws UnexpectedEntityException - * @throws \PHPUnit\Framework\Exception - */ - public function test_release_tickets_with_expired_carts() - { - $cart_results = $this->setup_and_validate_tickets_for_carts( - array( - 'expired cart' => array( - 'ticket_count' => 2, - 'expired' => true, - ), - 'valid cart' => array( - 'ticket_count' => 2, - 'expired' => false, - ), - ) - ); - EED_Ticket_Sales_Monitor::release_tickets_for_expired_carts(); - $this->process_cart_results($cart_results); - } - - - /** - * @throws DomainException - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws UnexpectedEntityException - * @throws \PHPUnit\Framework\Exception - */ - public function test_release_tickets_for_multiple_valid_carts() - { - $cart_results = $this->setup_and_validate_tickets_for_carts( - array( - 'first cart' => array( - 'ticket_count' => 4, - 'expired' => false, - ), - 'second cart' => array( - 'ticket_count' => 2, - 'expired' => false, - ), - ) - ); - EED_Ticket_Sales_Monitor::release_tickets_for_expired_carts(); - $this->process_cart_results($cart_results); - } - - - /** - * Validates EED_Ticket_Sales_Monitor::validate_ticket_sale properly detects when a sale is ok. - * @since 4.9.80.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws UnexpectedEntityException - * @group current - */ - public function testValidateTicketSaleTruePositive() - { - $e = $this->new_model_obj_with_dependencies( - 'Event', - [ - 'status' => EEM_Event::post_status_publish - ] - ); - $d1 = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $e->ID(), - 'DTT_reserved' => 0, - 'DTT_sold' => 0 - )); - $d2 = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $e->ID(), - 'DTT_reserved' => 0, - 'DTT_sold' => 0 - )); - $t = $this->new_model_obj_with_dependencies( - 'Ticket', - [ - 'TKT_qty' => 1, - 'TKT_reserved' => 0, - 'TKT_sold' => 0, - 'TKT_max' => 1, - 'TKT_min' => 0 - ] - ); - $d1->_add_relation_to($t, 'Ticket'); - $d2->_add_relation_to($t, 'Ticket'); - $ticket_reserved = EED_Ticket_Sales_Monitor::validate_ticket_sale(1, $t); - $this->assertEquals(1, $ticket_reserved); - $d1->refresh_from_db(); - $d2->refresh_from_db(); - $t->refresh_from_db(); - $this->assertEquals(1, $d1->reserved()); - $this->assertEquals(1, $d2->reserved()); - $this->assertEquals(1, $t->reserved()); - } - - - /** - * Validates EED_Ticket_Sales_Monitor::validate_ticket_sale properly detects when a sale shouldn't occur. - * @since 4.9.80.p - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws UnexpectedEntityException - * @group current - */ - public function testValidateTicketSaleTrueNegative() - { - $e = $this->new_model_obj_with_dependencies( - 'Event', - [ - 'status' => EEM_Event::post_status_publish - ] - ); - $d1 = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $e->ID(), - 'DTT_reserved' => 1, - 'DTT_sold' => 0 - )); - $d2 = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $e->ID(), - 'DTT_reserved' => 0, - 'DTT_sold' => 0 - )); - $t = $this->new_model_obj_with_dependencies( - 'Ticket', - [ - 'TKT_qty' => 1, - // this next line is important: that one ticket is reserved! - 'TKT_reserved' => 1, - 'TKT_sold' => 0, - 'TKT_max' => 1, - 'TKT_min' => 0 - ] - ); - $d1->_add_relation_to($t, 'Ticket'); - $d2->_add_relation_to($t, 'Ticket'); - $ticket_reserved = EED_Ticket_Sales_Monitor::validate_ticket_sale(1, $t); - $this->assertEquals(0, $ticket_reserved); - $d1->refresh_from_db(); - $d2->refresh_from_db(); - $t->refresh_from_db(); - // Validate the reserved counts were unchanged. - $this->assertEquals(1, $d1->reserved()); - $this->assertEquals(0, $d2->reserved()); - $this->assertEquals(1, $t->reserved()); - } - - /** - * Simulates two simultaneous requests arriving to validate ticket sales. - * Normally, this runs into a concurrency problem because we first READ to verify the ticket sale is ok, and afterwards update. - * A problematic request is one where the DB is updated between when we read and update the DB because we will update the - * DB based on stale data. - * @since 4.9.80.p - * @group current - */ - public function testValidateTicketSaleConcurrentRequestTicketLimitReached() - { - $e = $this->new_model_obj_with_dependencies( - 'Event', - [ - 'status' => EEM_Event::post_status_publish - ] - ); - $d1 = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $e->ID(), - 'DTT_reserved' => 0, - 'DTT_sold' => 0 - )); - $d2 = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $e->ID(), - 'DTT_reserved' => 0, - 'DTT_sold' => 0 - )); - $t = $this->new_model_obj_with_dependencies( - 'Ticket', - [ - 'TKT_qty' => 1, - 'TKT_reserved' => 0, - 'TKT_sold' => 0, - 'TKT_max' => 1, - 'TKT_min' => 0 - ] - ); - $d1->_add_relation_to($t, 'Ticket'); - $d2->_add_relation_to($t, 'Ticket'); - - // Setup an action to simulate a simultaneous request that will swoop in during the ticket validation - // (after we read from the DB but before writing to it) and add a ticket reservation. - add_action( - 'AHEE__EE_Ticket__increase_reserved__begin', - function($ticket, $quantity, $source) use ($t) { - EEM_Ticket::instance()->update( - [ - 'TKT_reserved' => 1, - ], - [ - [ - 'TKT_ID' => $t->ID() - ] - ] - ); - }, - 10, - 3 - ); - $ticket_reserved = EED_Ticket_Sales_Monitor::validate_ticket_sale(1, $t); - // Now we should NOT reserve the ticket (alternatively we could at least keep the DB accurate - // about how many tickets were oversold.) - $this->assertEquals(0, $ticket_reserved); - $d1->refresh_from_db(); - $d2->refresh_from_db(); - $t->refresh_from_db(); - // Validate the reserved counts were unchanged. - $this->assertEquals(0, $d1->reserved()); - $this->assertEquals(0, $d2->reserved()); - $this->assertEquals(1, $t->reserved()); - } - - /** - * Simulates two simultaneous requests arriving to validate ticket sales. - * Normally, this runs into a concurrency problem because we first READ to verify the ticket sale is ok, and afterwards update. - * A problematic request is one where the DB is updated between when we read and update the DB because we will update the - * DB based on stale data. - * @since 4.9.80.p - * @group current - */ - public function testValidateTicketSaleConcurrentRequestDatetimeLimitReached() - { - $e = $this->new_model_obj_with_dependencies( - 'Event', - [ - 'status' => EEM_Event::post_status_publish - ] - ); - $d1 = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $e->ID(), - 'DTT_reserved' => 0, - 'DTT_sold' => 0, - )); - $d2 = $this->new_model_obj_with_dependencies( - 'Datetime', - array( - 'EVT_ID' => $e->ID(), - 'DTT_reserved' => 1, - 'DTT_sold' => 1, - // Note this datetime only has one more space! - 'DTT_reg_limit' => 3, - )); - $t = $this->new_model_obj_with_dependencies( - 'Ticket', - [ - 'TKT_qty' => EE_INF, - 'TKT_reserved' => 0, - 'TKT_sold' => 0, - 'TKT_max' => EE_INF, - 'TKT_min' => 0 - ] - ); - $d1->_add_relation_to($t, 'Ticket'); - $d2->_add_relation_to($t, 'Ticket'); - - // Setup an action to simulate a simultaneous request that will swoop in during the ticket validation - // (after we read from the DB but before writing to it) and add a datetime reservation. - add_action( - 'AHEE__EE_Ticket__increase_reserved__begin', - function($ticket, $quantity, $source) use ($d2) { - EEM_Datetime::instance()->update( - [ - 'DTT_reserved' => 2, - ], - [ - [ - 'DTT_ID' => $d2->ID() - ] - ] - ); - }, - 10, - 3 - ); - $ticket_reserved = EED_Ticket_Sales_Monitor::validate_ticket_sale(1, $t); - // Now we should NOT reserve the ticket (alternatively we could at least keep the DB accurate - // about how many tickets were oversold.) - $this->assertEquals(0, $ticket_reserved); - $d1->refresh_from_db(); - $d2->refresh_from_db(); - $t->refresh_from_db(); - // Validate the reserved counts were unchanged. - $this->assertEquals(0, $d1->reserved()); - $this->assertEquals(2, $d2->reserved()); - $this->assertEquals(0, $t->reserved()); - } - - /** - * @since 4.10.4.p - * @throws DomainException - * @throws EE_Error - * @throws InvalidArgumentException - * @throws ReflectionException - * @throws InvalidDataTypeException - * @throws InvalidInterfaceException - * @throws UnexpectedEntityException - */ - public function testResetReservationCounts() - { - $this->assertEquals(0, EEM_Transaction::instance()->count()); - // need some transactions - $old_transactions_count = 10; - for($i=0; $i<$old_transactions_count; $i++){ - $transaction = $this->new_typical_transaction( - [ - 'tkt_qty' => 5, - 'reg_status' => EEM_Registration::status_id_pending_payment, - 'setup_reg' => true, - 'timestamp' => current_time('timestamp') - WEEK_IN_SECONDS * 2 - ] - ); - } - $new_transaction_count = 1; - // And let's make a new transaction, just to verify its reservations don't get released - $new_transaction = $this->new_typical_transaction( - [ - 'tkt_qty' => 5, - 'reg_status' => EEM_Registration::status_id_pending_payment, - 'setup_reg' => true, - ] - ); - $this->assertEquals($old_transactions_count + $new_transaction_count, EEM_Transaction::instance()->count()); - $a_ticket = $transaction->primary_registration()->ticket(); - $this->assertEquals(1, $a_ticket->reserved()); - $tickets_released = EED_Ticket_Sales_Monitor::reset_reservation_counts(); - // We should report that all the old transactions' tickets were released... - $this->assertEquals($old_transactions_count, $tickets_released); - // And that their reserved count goes back down to 0. - $this->assertEquals(0, $a_ticket->reserved()); - // But, the new transactions' ticket should still be reserved. - $this->assertEquals(1, $new_transaction->primary_registration()->ticket()->reserved()); - } - - /** - * Try to release reservations for the ticket, but there is a valid reservation for it. - * @since 4.10.4.p - * @throws DomainException - * @throws EE_Error - * @throws UnexpectedEntityException - */ - public function testReleaseReservationForTicketsAllValid() - { - EEM_Ticket::instance()->delete_permanently( - [ - [ - 'TKT_ID' => ['>',0] - ] - ], - false - ); - $this->assertEquals(0, EEM_Ticket::instance()->count()); - $t1 = $this->factory->ticket_chained->create( - [ - 'TKT_name' => 'ticket reservations all valid', - 'TKT_qty' => 10, - 'TKT_reserved' => 5 - ] - ); - $t2 = $this->factory->ticket_chained->create( - [ - 'TKT_name' => 'ticket SOME reservation still valid', - 'TKT_qty' => 10, - 'TKT_reserved' => 5 - ] - ); - $t3 = $this->factory->ticket_chained->create( - [ - 'TKT_name' => 'ticket NO reservations are still valid', - 'TKT_qty' => 10, - 'TKT_reserved' => 5 - ] - ); - $this->assertEquals(3, EEM_Ticket::instance()->count()); - $li1 = $this->new_model_obj_with_dependencies( - 'Line_Item', - [ - 'OBJ_type' => 'Ticket', - 'OBJ_ID' => $t1->ID(), - 'LIN_quantity' => 5 // ie, all the ticket's reservations are valid. - ] - ); - $li2 = $this->new_model_obj_with_dependencies( - 'Line_Item', - [ - 'OBJ_type' => 'Ticket', - 'OBJ_ID' => $t2->ID(), - 'LIN_quantity' => 3 // ie, three of this ticket's reservations are valid. The other two are not. - ] - ); - // No valid reservations for ticket 3, so no ticket line items for it will be provided - $this->assertEquals(3, EEM_Ticket::instance()->count()); - $num_released = EED_Ticket_Sales_Monitor_Mock::release_reservations_for_tickets( - [$t1, $t2, $t3], - [$li1, $li2], - 'test' - ); - // two tickets for t2 and 5 tickets for t3 should have had tickets released. - $this->assertEquals(7, $num_released); - // t1's reserved count should be unaffected - $this->assertEquals( - 5, - $t1->reserved() - ); - // t2's reserved count should be reduced - $this->assertEquals( - 3, - $t2->reserved() - ); - // None of t3's reserved count were valid (because we provided no line items indicating they were valid). - // So all its reservations should have been released. - $this->assertEquals( - 0, - $t3->reserved() - ); - } - -} -// End of file EED_Ticket_Sales_Monitor_Test.php -// Location: /tests/testcases/modules/EED_Ticket_Sales_Monitor_Test.php diff --git a/tests/testcases/modules/EE_CheckoutTest.php b/tests/testcases/modules/EE_CheckoutTest.php deleted file mode 100644 index 445d83c8bb8..00000000000 --- a/tests/testcases/modules/EE_CheckoutTest.php +++ /dev/null @@ -1,37 +0,0 @@ -_test_settings = array( - 'login_id' => '534NmsVS', - 'transaction_key' => '9u64QUm4VzZ9x66d', - 'test_transactions' => FALSE, - 'debug_mode' => TRUE - ); - $this->_test_billing_info = array( - 'first_name' => 'auto', - 'last_name' => 'tester', - 'email' => 'few@ew.few', - 'address' => '2090 Nowhere Rd', - 'address2' => '', - 'city' => 'Whoville', - 'state' => 'Arkansas', - 'country' => 'US', - 'zip' => '84604', - 'credit_card' => '4007000000027', - 'cvv' => '123', - 'exp_month' => '05', - 'exp_year' => '2024', - 'company' => 'Event Espresso', - 'fax' => '1231231231', - 'phone' => '1231231231', - ); - } - public function setUp(){ - parent::setUp(); - EE_Payment_Method_Manager::reset(); - } - public function test_do_direct_payment__success(){ - $ppm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Aim' ) ); - $ppg = $ppm->type_obj()->get_gateway(); - $ppg->set_settings( $this->_test_settings ); - $t = $this->new_typical_transaction(); - $p = $this->new_model_obj_with_dependencies( 'Payment', array('TXN_ID'=>$t->ID(), 'PMD_ID' => $ppm->ID(), 'PAY_amount' => $t->total() ) ); - $this->assertNotEquals( EEM_Payment::status_id_approved, $p->status() ); - - $p_processed = $ppg->do_direct_payment( $p, $this->_test_billing_info ); - $this->assertEquals( $p, $p_processed ); - $this->assertEquals( EEM_Payment::status_id_approved, $p_processed->status(), 'If this fails, verify the accounts transaction key hasntbeen updated. Here is the raw response from aim: ' . var_export( $p_processed->details(), true ) ); - $this->assertEquals( $t->total(), $p_processed->amount() ); - } - public function test_do_direct_payment__fail(){ - $ppm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Aim' ) ); - $ppg = $ppm->type_obj()->get_gateway(); - $ppg->set_settings( $this->_test_settings ); - $t = $this->new_typical_transaction(); - $p = $this->new_model_obj_with_dependencies( 'Payment', array('TXN_ID'=>$t->ID(), 'PMD_ID' => $ppm->ID(), 'PAY_amount' => $t->total() ) ); - $this->assertNotEquals( EEM_Payment::status_id_declined, $p->status() ); - - $fail_billing_info = $this->_test_billing_info; - $fail_billing_info[ 'credit_card' ] = '4222222222222'; - $fail_billing_info[ 'zip' ] = '46282'; - - $p_processed = $ppg->do_direct_payment( $p, $fail_billing_info ); - $this->assertEquals( $p, $p_processed ); - $this->assertEquals( EEM_Payment::status_id_declined, $p_processed->status() ); - $this->assertEquals( $t->total(), $p_processed->amount() ); - } - public function test_do_direct_payment__partial_payment(){ - $ppm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Aim' ) ); - $ppg = $ppm->type_obj()->get_gateway(); - $ppg->set_settings( $this->_test_settings ); - $paid_so_far = 1.00; - $t = $this->new_typical_transaction(); - $t->set_paid( $paid_so_far ); - $previous_payment = $this->new_model_obj_with_dependencies( 'Payment', array('TXN_ID'=>$t->ID(), 'PMD_ID' => $ppm->ID(), 'PAY_amount' => $paid_so_far ) ); - $p = $this->new_model_obj_with_dependencies( 'Payment', array('TXN_ID'=>$t->ID(), 'PMD_ID' => $ppm->ID(), 'PAY_amount' => $t->total() - $paid_so_far ) ); - $this->assertNotEquals( EEM_Payment::status_id_approved, $p->status() ); - - $p_processed = $ppg->do_direct_payment( $p, $this->_test_billing_info ); - $this->assertEquals( EEM_Payment::status_id_approved, $p_processed->status() ); - $this->assertEquals( $t->total() - $paid_so_far, $p_processed->amount() ); - } - /** - * tests that even if the line items are too complicated for the gateway to handle, - * it can at least send the total payable - */ - public function test_do_direct_payment__total_mismatch(){ - $ppm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Aim' ) ); - $ppg = $ppm->type_obj()->get_gateway(); - $ppg->set_settings( $this->_test_settings ); - $t = $this->new_typical_transaction(); - $t->set_total( $t->total() / 2 ); - $t->total_line_item()->set_total ( $t->total() ); - $t->save(); - $t->total_line_item()->save(); - $p = $this->new_model_obj_with_dependencies( 'Payment', array('TXN_ID'=>$t->ID(), 'PMD_ID' => $ppm->ID(), 'PAY_amount' => $t->total() ) ); - $this->assertNotEquals( EEM_Payment::status_id_approved, $p->status() ); - - $p_processed = $ppg->do_direct_payment( $p, $this->_test_billing_info ); - $this->assertEquals( EEM_Payment::status_id_approved, $p_processed->status() ); - $this->assertEquals( $t->total(), $p_processed->amount() ); - } -} - -// End of file EE_PMT_Aim_Test.php \ No newline at end of file diff --git a/tests/testcases/payment_methods/EE_PMT_Paypal_Pro_Test.php b/tests/testcases/payment_methods/EE_PMT_Paypal_Pro_Test.php deleted file mode 100644 index baae4670de8..00000000000 --- a/tests/testcases/payment_methods/EE_PMT_Paypal_Pro_Test.php +++ /dev/null @@ -1,184 +0,0 @@ -_test_settings = array( - 'username' => 'sell_1359059457_biz_api1.eventespresso.com', - 'password' => '1359059477', - 'signature' => 'At4QgLNCqDfsw218JPKQWyb74X3HAicxDti5ZoS2qp01O8izJtunMnkZ', - 'debug_mode' => TRUE - ); - $this->_test_billing_info = array( - 'first_name' => 'auto', - 'last_name' => 'tester', - 'email' => 'few@ew.few', - 'address' => '2090 Nowhere Rd', - 'address2' => '', - 'city' => 'Whoville', - 'state' => 'Arkansas', - 'country' => 'US', - 'zip' => '84604', - 'phone' => '123-123-1234', - 'credit_card_type' => 'Visa', - 'credit_card' => '4127143344648082', - 'cvv' => '115', - 'exp_month' => '01', - 'exp_year' => '2018' - ); - } - - /** - * setUp - */ - public function setUp(){ - parent::setUp(); - //EEG_Paypal_Pro uses $_SERVER at some point, so we need to pretend this is a regular request - $this->go_to( 'http://localhost/' ); - //just set a random address - $_SERVER[ 'REMOTE_ADDR' ] = '192.0.0.1'; - add_filter('FHEE__EEG_Paypal_Pro__CurlRequest__CURLOPT_VERBOSE', '__return_false' ); - //make sure caf payment methods are registered - EE_Payment_Method_Manager::reset(); - } - - /** - * test_do_direct_payment__success - */ - public function test_do_direct_payment__success(){ - $ppm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Paypal_Pro' ) ); - $ppg = $ppm->type_obj()->get_gateway(); - $ppg->set_settings( $this->_test_settings ); - $t = $this->new_typical_transaction(); - $p = $this->new_model_obj_with_dependencies( 'Payment', array('TXN_ID'=>$t->ID(), 'PMD_ID' => $ppm->ID(), 'PAY_amount' => $t->total() ) ); - $this->assertNotEquals( EEM_Payment::status_id_approved, $p->status() ); - - $p_processed = $ppg->do_direct_payment( $p, $this->_test_billing_info ); - $this->assertEquals( $p, $p_processed ); - $this->assertEquals( EEM_Payment::status_id_approved, $p_processed->status(), 'If this test fails, verify the paypal sandbox account HAS ENOUGH FUNDS and that we are still using the correct test credit card. Here is the payments details: ' . var_export( $p_processed->details(), true ) ); - $this->assertEquals( $t->total(), $p_processed->amount() ); - } - - /** - * test_do_direct_payment__fail - */ - public function test_do_direct_payment__fail(){ - $ppm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Paypal_Pro' ) ); - $ppg = $ppm->type_obj()->get_gateway(); - $ppg->set_settings( array( - 'username' => 'seller_with_fail_api1.eventespresso.com', - 'password' => '1405373725', - 'signature' => 'AySrU3tYAnUcGB87EC84g-FvwSiGA7pL1gPqq1ZS-ITCs1Sea8oAG2.e', - 'debug_mode' => TRUE - ) ); - $t = $this->new_typical_transaction( array('ticket_types' => 8 ) ); - ///set the payment amount to a specific error code (yes it's a partial payment that will be failing). See - //https://developer.paypal.com/docs/classic/lifecycle/sb_error-conditions/ for details - $amount_to_pay = 107.55; - $p = $this->new_model_obj_with_dependencies( 'Payment', array('TXN_ID'=>$t->ID(), 'PMD_ID' => $ppm->ID(), 'PAY_amount' => $amount_to_pay ) ); - $this->assertNotEquals( EEM_Payment::status_id_declined, $p->status() ); - - $billing_info = $this->_test_billing_info; - $billing_info['credit_card'] = '6011779094237966'; - $billing_info['credit_card_type'] = 'Discover'; - $billing_info['exp_month'] = '07'; - $billing_info['exp_year'] = '2019'; - $p_processed = $ppg->do_direct_payment( $p, $billing_info ); - - $this->assertEquals( $p, $p_processed ); - $this->assertEquals( EEM_Payment::status_id_declined, $p_processed->status(), 'transaction was for ' . $t->total() . ' and payment details were: ' . var_export( $p->details(), true ) ); - $this->assertEquals( $amount_to_pay, $p_processed->amount() ); - } - - /** - * test_do_direct_payment__partial_payment - */ - public function test_do_direct_payment__partial_payment(){ - $ppm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Paypal_Pro' ) ); - $ppg = $ppm->type_obj()->get_gateway(); - $ppg->set_settings( $this->_test_settings ); - $paid_so_far = 1.00; - $t = $this->new_typical_transaction(); - $t->set_paid( $paid_so_far ); - $previous_payment = $this->new_model_obj_with_dependencies( 'Payment', array('TXN_ID'=>$t->ID(), 'PMD_ID' => $ppm->ID(), 'PAY_amount' => $paid_so_far ) ); - $p = $this->new_model_obj_with_dependencies( 'Payment', array('TXN_ID'=>$t->ID(), 'PMD_ID' => $ppm->ID(), 'PAY_amount' => $t->total() - $paid_so_far ) ); - $this->assertNotEquals( EEM_Payment::status_id_approved, $p->status() ); - - $p_processed = $ppg->do_direct_payment( $p, $this->_test_billing_info ); - $this->assertEquals( EEM_Payment::status_id_approved, $p_processed->status() ); - $this->assertEquals( $t->total() - $paid_so_far, $p_processed->amount() ); - } - - /** - * test_do_direct_payment__total_mismatch - * - * tests that even if the line items are too complicated for the gateway to handle, - * it can at least send the total payable - */ - public function test_do_direct_payment__total_mismatch(){ - $ppm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Paypal_Pro' ) ); - $ppg = $ppm->type_obj()->get_gateway(); - $ppg->set_settings( $this->_test_settings ); - $t = $this->new_typical_transaction(); - $t->set_total( $t->total() / 2 ); - $t->total_line_item()->set_total ( $t->total() ); - $t->save(); - $t->total_line_item()->save(); - $p = $this->new_model_obj_with_dependencies( 'Payment', array('TXN_ID'=>$t->ID(), 'PMD_ID' => $ppm->ID(), 'PAY_amount' => $t->total() ) ); - $this->assertNotEquals( EEM_Payment::status_id_approved, $p->status() ); - - $p_processed = $ppg->do_direct_payment( $p, $this->_test_billing_info ); - $this->assertEquals( EEM_Payment::status_id_approved, $p_processed->status() ); - $this->assertEquals( $t->total(), $p_processed->amount() ); - } - - /** - * test_generate_new_billing_form - */ - public function test_generate_new_billing_form(){ - $ppm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Paypal_Pro', 'PMD_debug_mode' => TRUE ) ); - $t = $this->new_typical_transaction(); - $ppm->type_obj()->generate_new_billing_form( $t ); - } -} - -// End of file EE_PMT_Paypal_Pro_Test.php \ No newline at end of file diff --git a/tests/testcases/payment_methods/EE_PMT_Paypal_Standard_Test.php b/tests/testcases/payment_methods/EE_PMT_Paypal_Standard_Test.php deleted file mode 100644 index 294e5635cad..00000000000 --- a/tests/testcases/payment_methods/EE_PMT_Paypal_Standard_Test.php +++ /dev/null @@ -1,642 +0,0 @@ -_paypal_id = 'sell_1359059457_biz@eventespresso.com'; - $this->_test_settings = array( - 'paypal_id' => $this->_paypal_id, - 'shipping_details' => 1,//none - 'paypal_shipping'=> FALSE, - 'paypal_taxes'=> FALSE, - ); - } - public function test_set_redirection_info__success(){ - //make sure paypal gateway is included - $ppm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Paypal_Standard' ) ); - $ppg = $ppm->type_obj()->get_gateway(); - $ppg->set_settings( $this->_test_settings ); - $t = $this->new_typical_transaction( array( 'ticket_types' => 2) ); - $p = $this->new_model_obj_with_dependencies( 'Payment', array('TXN_ID'=>$t->ID(), 'PMD_ID' => $ppm->ID(), 'PAY_amount' => $t->total() ) ); - $this->assertEmpty( $p->redirect_url() ); - - - $p = $ppg->set_redirection_info( $p, NULL, self::return_url, self::notify_url, self::cancel_url ); - $this->assertNotEmpty( $p->redirect_url() ); - $this->assertEquals( self::paypal_url, $p->redirect_url() ); - $this->assertNotEmpty( $p->redirect_args() ); - $rargs = $p->redirect_args(); - $items_purchased = $t->items_purchased(); - $first_item = array_shift( $items_purchased ); - $second_item = array_shift( $items_purchased ); - $this->assertEquals( sprintf( '%s for %s', $first_item->ticket()->name(), $first_item->ticket_event_name() ), $rargs[ 'item_name_1' ] ); - $this->assertEquals( $first_item->ticket()->price(), $rargs[ 'amount_1' ] ); - $this->assertEquals( sprintf( '%s for %s', $second_item->ticket()->name(), $second_item->ticket_event_name() ), $rargs[ 'item_name_2' ] ); - $this->assertEquals( $second_item->ticket()->price(), $rargs[ 'amount_2' ] ); - $this->assertEquals( 1, $rargs[ 'quantity_1' ] ); - $this->assertEquals( $t->tax_total(), $rargs[ 'tax_cart' ] ); - $this->assertEquals( $this->_paypal_id, $rargs[ 'business' ] ); - $this->assertEquals( self::return_url, $rargs[ 'return' ] ); - $this->assertEquals( self::cancel_url, $rargs[ 'cancel_return' ] ); - $this->assertEquals( self::notify_url, $rargs[ 'notify_url' ] ); - $this->assertEquals( '_cart', $rargs[ 'cmd' ] ); - $this->assertEquals( 1, $rargs[ 'upload' ] ); - $this->assertEquals( 'USD', $rargs[ 'currency_code' ] ); - $this->assertEquals( 2, $rargs[ 'rm' ] );//makes the user return with method=POST - $this->assertEquals( 1, $rargs[ 'no_shipping'] ); - } - - /** - */ - public function test_set_redirection_info__with_paypal_taxes_and_shipping(){ - //make sure paypal gateway is included - $ppm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Paypal_Standard' ) ); - $ppg = $ppm->type_obj()->get_gateway(); - $ppg->set_settings(array( - 'paypal_id' => $this->_paypal_id, - 'paypal_taxes' => TRUE, - 'paypal_shipping' => TRUE - )); - $t = $this->new_typical_transaction( - array( - 'ticket_types' => 2, - 'taxable_tickets' => 1) ); - $original_txn_total = $t->total(); - //pretend we previous used paypal to make a payment. - EEH_Line_Item::add_unrelated_item( - $t->total_line_item(), - 'Shipping', - 8, - 'some shipping', - 1, - false, - 'paypal_shipping_' . $t->ID() ); - EEH_Line_Item::set_total_tax_to( $t->total_line_item(), 4, 'paypal taxes', 'paypal did thi', 'paypal_tax', false ); - $t->total_line_item()->save_this_and_descendants_to_txn( $t->ID() ); - $registration_processor = EE_Registry::instance()->load_class( 'Registration_Processor' ); - $registration_processor->update_registration_final_prices( $t ); - - $p = $this->new_model_obj_with_dependencies( 'Payment', array('TXN_ID'=>$t->ID(), 'PMD_ID' => $ppm->ID(), 'PAY_amount' => $t->total() ) ); - $this->assertEmpty( $p->redirect_url() ); - //set redirection info; we should ignore previously-added paypal tax and shipping - //(so paypal can add calculate them again when we send them) - $p = $ppg->set_redirection_info( $p, NULL, self::return_url, self::notify_url, self::cancel_url ); - $this->assertNotEmpty( $p->redirect_url() ); - $this->assertEquals( self::paypal_url, $p->redirect_url() ); - $this->assertNotEmpty( $p->redirect_args() ); - $rargs = $p->redirect_args(); - $items_purchased = $t->items_purchased(); - $first_item = array_shift( $items_purchased ); - $second_item = array_shift( $items_purchased ); - $this->assertEquals( sprintf( '%s for %s', $first_item->ticket()->name(), $first_item->ticket_event_name() ), $rargs[ 'item_name_1' ] ); - $this->assertEquals( $first_item->ticket()->price(), $rargs[ 'amount_1' ] ); - $this->assertEquals( sprintf( '%s for %s', $second_item->ticket()->name(), $second_item->ticket_event_name() ), $rargs[ 'item_name_2' ] ); - $this->assertEquals( $second_item->ticket()->price(), $rargs[ 'amount_2' ] ); - $this->assertEquals( 1, $rargs[ 'quantity_1' ] ); - //we shouldn't have told paypal how much tax to add. Let paypal decide. - $this->assertFalse( isset( $rargs[ 'tax_cart' ] ) ); - //there should be no 3rd item for shipping - $this->assertFalse( isset( $rargs[ 'amount_3' ] ) ); - } - //@todo test ipn with different tax and shipping - public function test_handle_payment_update(){ - $ppm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Paypal_Standard' ) ); - $ppg = $ppm->type_obj()->get_gateway(); - $ppg->set_settings(array( - 'paypal_id' => $this->_paypal_id - )); - $t = $this->new_typical_transaction(); - $p = $this->new_model_obj_with_dependencies( 'Payment', array('TXN_ID'=>$t->ID(), 'PMD_ID' => $ppm->ID(), 'PAY_amount' => $t->total() ) ); - $p_in_map = EE_Registry::instance()->load_model('Payment')->get_from_entity_map( $p->ID() ); - $this->assertInstanceOf( 'EE_Payment', $p_in_map ); - //skip IPN validation with paypal - add_filter( 'FHEE__EEG_Paypal_Standard__validate_ipn__skip', '__return_true' ); - - $ppg->handle_payment_update( array ( - 'e_reg_url_link' => '1-bfcffeb307c5f5e275643de154fe7192', - 'mc_gross' => $t->total(), - 'protection_eligibility' => 'Eligible', - 'address_status' => 'confirmed', - 'item_number1' => '', - 'item_number2' => '', - 'payer_id' => 'XN873NKAXAAE2', - 'tax' => '0.00', - 'address_street' => '1 Main St', - 'payment_date' => '10:55:09 Jul 03, 2014 PDT', - 'payment_status' => 'Completed', - 'option_selection1_2' => 'http://localhost/wp-develop/src/transactions/?e_reg_url_link=1-bfcffeb307c5f5e275643de154fe7192&ee_payment_method=paypal_standard', - 'charset' => 'windows-1252', - 'address_zip' => '95131', - 'mc_shipping' => '0.00', - 'mc_handling' => '0.00', - 'first_name' => 'Event', - 'mc_fee' => '2.04', - 'address_country_code' => 'US', - 'address_name' => 'Event Espresso', - 'notify_version' => '3.8', - 'custom' => '', - 'payer_status' => 'verified', - 'business' => 'sell_1359059457_biz@eventespresso.com', - 'address_country' => 'United States', - 'num_cart_items' => '2', - 'mc_handling1' => '0.00', - 'mc_handling2' => '0.00', - 'address_city' => 'San Jose', - 'payer_email' => 'buyer_1359059233_per@eventespresso.com', - 'verify_sign' => 'An5ns1Kso7MWUdW4ErQKJJJ4qi4-A7ueXcNiuE.6nTwMSoqIZ1cXOQTF', - 'mc_shipping1' => '0.00', - 'mc_shipping2' => '0.00', - 'tax1' => '0.00', - 'tax2' => '0.00', - 'option_name1_2' => 'NOTIFY URL', - 'txn_id' => '2UT88371J0075792R', - 'payment_type' => 'instant', - 'last_name' => 'Espresso', - 'item_name1' => 'Free Ticket', - 'address_state' => 'CA', - 'receiver_email' => 'sell_1359059457_biz@eventespresso.com', - 'item_name2' => 'DEBUG INFO (this item only added in sandbox mode', - 'payment_fee' => '2.04', - 'quantity1' => '1', - 'quantity2' => '1', - 'receiver_id' => 'M33RRGRH82CUN', - 'txn_type' => 'cart', - 'mc_gross_1' => $t->primary_registration()->ticket()->price(), - 'mc_currency' => 'USD', - 'mc_gross_2' => '0.00', - 'residence_country' => 'US', - 'test_ipn' => '1', - 'transaction_subject' => '', - 'payment_gross' => '60.00', - 'auth' => 'Abp7Rv87UBZqp18HlystBhVYkr5U-wOEufLDnbUuLIli4sta-Jr-4G1kw4uwGLNlopOjLer38dL3Zp-rBnaT3wg', -), $t ); - $this->assertEquals( EEM_Payment::status_id_approved, $p->status() ); - $this->assertEquals( $t->total(), $p->amount() ); - } - - - public function test_handle_payment_update__refund(){ - /** @type EE_Payment_Method $ppm */ - $ppm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Paypal_Standard' ) ); - /** @type EEG_Paypal_Standard $ppg */ - $ppg = $ppm->type_obj()->get_gateway(); - $ppg->set_settings(array( - 'paypal_id' => $this->_paypal_id - )); - $t = $this->new_typical_transaction(); - /** @type EE_Payment $p */ - // PLZ NOTE: refunds have a negative value for their amount - $p = $this->new_model_obj_with_dependencies( 'Payment', array('TXN_ID'=>$t->ID(), 'PMD_ID' => $ppm->ID(), 'PAY_amount' => ( $t->total() * -1 ) ) ); - $p_in_map = EE_Registry::instance()->load_model('Payment')->get_from_entity_map( $p->ID() ); - $this->assertInstanceOf( 'EE_Payment', $p_in_map ); - //skip IPN validation with paypal - add_filter( 'FHEE__EEG_Paypal_Standard__validate_ipn__skip', '__return_true' ); - add_filter( 'FHEE__EEG_Paypal_Standard__handle_payment_update__kill_refund_request', '__return_false' ); - $ppg->handle_payment_update( - array ( - 'e_reg_url_link' => '1-bfcffeb307c5f5e275643de154fe7192', - 'mc_gross' => ( $t->total() * -1 ), - 'protection_eligibility' => 'Eligible', - 'address_status' => 'confirmed', - 'item_number1' => '', - 'item_number2' => '', - 'payer_id' => 'XN873NKAXAAE2', - 'tax' => '0.00', - 'address_street' => '1 Main St', - 'payment_date' => '10:55:09 Jul 03, 2014 PDT', - 'payment_status' => 'Refunded', - 'option_selection1_2' => 'http://localhost/wp-develop/src/transactions/?e_reg_url_link=1-bfcffeb307c5f5e275643de154fe7192&ee_payment_method=paypal_standard', - 'charset' => 'windows-1252', - 'address_zip' => '95131', - 'mc_shipping' => '0.00', - 'mc_handling' => '0.00', - 'first_name' => 'Event', - 'mc_fee' => '2.04', - 'address_country_code' => 'US', - 'address_name' => 'Event Espresso', - 'notify_version' => '3.8', - 'custom' => '', - 'payer_status' => 'verified', - 'business' => 'sell_1359059457_biz@eventespresso.com', - 'address_country' => 'United States', - 'num_cart_items' => '2', - 'mc_handling1' => '0.00', - 'mc_handling2' => '0.00', - 'address_city' => 'San Jose', - 'payer_email' => 'buyer_1359059233_per@eventespresso.com', - 'verify_sign' => 'An5ns1Kso7MWUdW4ErQKJJJ4qi4-A7ueXcNiuE.6nTwMSoqIZ1cXOQTF', - 'mc_shipping1' => '0.00', - 'mc_shipping2' => '0.00', - 'tax1' => '0.00', - 'tax2' => '0.00', - 'option_name1_2' => 'NOTIFY URL', - 'txn_id' => '2UT88371J0075792R', - 'payment_type' => 'instant', - 'last_name' => 'Espresso', - 'item_name1' => 'Free Ticket', - 'address_state' => 'CA', - 'receiver_email' => 'sell_1359059457_biz@eventespresso.com', - 'item_name2' => 'DEBUG INFO (this item only added in sandbox mode', - 'payment_fee' => '2.04', - 'quantity1' => '1', - 'quantity2' => '1', - 'receiver_id' => 'M33RRGRH82CUN', - 'txn_type' => 'cart', - 'mc_gross_1' => $t->primary_registration()->ticket()->price(), - 'mc_currency' => 'USD', - 'mc_gross_2' => '0.00', - 'residence_country' => 'US', - 'test_ipn' => '1', - 'transaction_subject' => '', - 'payment_gross' => '60.00', - 'auth' => 'Abp7Rv87UBZqp18HlystBhVYkr5U-wOEufLDnbUuLIli4sta-Jr-4G1kw4uwGLNlopOjLer38dL3Zp-rBnaT3wg', - ), - $t - ); - $this->assertEquals( EEM_Payment::status_id_approved, $p->status() ); - $this->assertEquals( ( $t->total() * -1 ), $p->amount() ); - } - - /** - * @group 4710 - */ - public function test_handle_payment_update__paypal_adds_taxes_and_shipping(){ - $ppm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Paypal_Standard' ) ); - $ppg = $ppm->type_obj()->get_gateway(); - $ppg->set_settings(array( - 'paypal_id' => $this->_paypal_id, - 'paypal_taxes' => TRUE, - 'paypal_shipping' => TRUE - )); - $t = $this->new_typical_transaction(); - $p = $this->new_model_obj_with_dependencies( 'Payment', array('TXN_ID'=>$t->ID(), 'PMD_ID' => $ppm->ID(), 'PAY_amount' => $t->total() ) ); - $p->update_extra_meta( EEG_Paypal_Standard::itemized_payment_option_name, true ); - $old_pretax_total = EEH_Line_Item::get_pre_tax_subtotal( $t->total_line_item() )->total(); - $old_taxable_total = $t->total_line_item()->taxable_total(); - $this->assertNotEmpty( $old_taxable_total ); - $old_tax_total = $t->tax_total(); - $this->assertNotEmpty( $old_tax_total ); - //skip IPN validation with paypal - add_filter( 'FHEE__EEG_Paypal_Standard__validate_ipn__skip', '__return_true' ); - - //pretend we sent an itemized report to paypal, and thus told them to calculate taxes on it. - $p->update_extra_meta( 'itemized_payment', true ); - $tax_in_ipn = 2.80; - //if the old tax matches what's going to be in the IPN data, we can't verify the IPN data - //updated the tax can we? - $this->assertNotEquals( $tax_in_ipn, $old_tax_total ); - $ipn_args = array ( - 'e_reg_url_link' => '1-203446311152995f326e9ca81b64c95b', - 'mc_gross' => $old_pretax_total + 8 + 2.8,//pretax total plus shipping and tax - 'protection_eligibility' => 'Eligible', - 'address_status' => 'confirmed', - 'item_number1' => '', - 'item_number2' => '', - 'payer_id' => 'DQUX5EF8CFFQ2', - 'tax' => "$tax_in_ipn",//IMPORTANT - 'address_street' => '1 Maire-Victorin', - 'payment_date' => '15:21:18 Jul 04, 2014 PDT', - 'payment_status' => 'Completed', - 'option_selection1_2' => 'http://localhost/wp-develop/src/transactions/?e_reg_url_link=1-203446311152995f326e9ca81b64c95b&ee_payment_method=paypal_standard', - 'charset' => 'windows-1252', - 'address_zip' => 'M5A 1E1', - 'mc_shipping' => '8.00',//IMPORTANT - 'mc_handling' => '0.00',//MAYBE IMPORTANT - 'first_name' => 'canadaman', - 'mc_fee' => '1.50', - 'address_country_code' => 'CA', - 'address_name' => 'canadaman eh', - 'notify_version' => '3.8', - 'custom' => '', - 'payer_status' => 'verified', - 'business' => 'sell_tax_and_ship@eventespresso.com', - 'address_country' => 'Canada', - 'num_cart_items' => '2', - 'mc_handling1' => '0.00', - 'mc_handling2' => '0.00', - 'address_city' => 'Toronto', - 'payer_email' => 'canada_buy_eh@eventespresso.com', - 'verify_sign' => 'Asuc-38eoonqdqSbDHczw6533JekAJTc2w.QEYe.bLdd3C9Sk1FmgQur', - 'mc_shipping1' => '0.00', - 'mc_shipping2' => '0.00', - 'tax1' => '0.00', - 'tax2' => '0.00', - 'option_name1_2' => 'NOTIFY URL', - 'txn_id' => '4W884024TK795542J', - 'payment_type' => 'instant', - 'last_name' => 'eh', - 'item_name1' => 'Free Ticket', - 'address_state' => 'Ontario', - 'receiver_email' => 'sell_tax_and_ship@eventespresso.com', - 'item_name2' => 'DEBUG INFO (this item only added in sandbox mode', - 'payment_fee' => '1.50', - 'shipping_discount' => '0.00', - 'quantity1' => '1', - 'insurance_amount' => '0.00', - 'quantity2' => '1', - 'receiver_id' => '8STUBD4V9ZUUN', - 'txn_type' => 'cart', - 'discount' => '0.00', - 'mc_gross_1' => '20.00', - 'mc_currency' => 'USD', - 'mc_gross_2' => '0.00', - 'residence_country' => 'CA', - 'test_ipn' => '1', - 'shipping_method' => 'International Economy',//IMPORTANT - 'transaction_subject' => '', - 'payment_gross' => '30.80',//IMPORTANT - 'auth' => 'A7v0XCv0MTRMLTC3ib4B4zYtTI7Wt-pU5StpnoQBIGsiMj5pXBoOr8z8kiKzYdNkeTmwiWW3xlus4rZhBUOqj6g', - ); - $ppg->handle_payment_update( $ipn_args, $t ); - $ppg->update_txn_based_on_payment( $p ); - //check the new tax is correct - $this->assertNotEquals( $old_tax_total, $t->tax_total(), 'Its not necessarily wrong for the old tax to match the new tax; but if they match we can\'t be very sure the tax total was updated' ); - $this->assertEquals( floatval( $ipn_args[ 'tax' ] ), $t->tax_total() ); - $tax_line_items = EEH_Line_Item::get_taxes_subtotal( $t->total_line_item() )->children(); - $this->assertEquals( 1, count( $tax_line_items ) ); - $only_tax = array_shift( $tax_line_items ); - $this->assertEquals( __( 'Taxes', 'event_espresso' ), $only_tax->name() ); - $this->assertEquals( EEM_Payment::status_id_approved, $p->status() ); - $this->assertEquals( $t->total(), $p->amount() ); - //check that the shipping surcharge is correct - $items_subtotal = EEH_Line_Item::get_pre_tax_subtotal( $t->total_line_item() ); - $items = $items_subtotal->children(); - $first_item = array_shift( $items ); - $this->assertEquals( 10, $first_item->total() ); - $second_item = array_shift( $items); - $this->assertEquals( 8, $second_item->total() ); - //EEH_Line_Item::visualize($t->total_line_item()); - $this->assertEquals( $old_pretax_total + 8, $items_subtotal->total() ); - //check that the transaction's total got updated to match the total line item's - $this->assertEquals( $t->total_line_item()->total(), $t->total() ); - //check that if we re-calculate all the prices everything is still the same - $updated_line_item_total = $t->total_line_item()->total(); - $t->total_line_item()->recalculate_total_including_taxes(); - $this->assertEquals( $updated_line_item_total, $t->total_line_item()->total() ); - } - - /** - * @group 4710 - */ - public function test_update_txn_based_on_payment__paypal_adds_taxes_and_shipping__twice(){ - $ppm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Paypal_Standard' ) ); - $ppg = $ppm->type_obj()->get_gateway(); - $ppg->set_settings(array( - 'paypal_id' => $this->_paypal_id, - 'paypal_taxes' => TRUE, - 'paypal_shipping' => TRUE - )); - $t = $this->new_typical_transaction(); - $old_taxable_total = $t->total_line_item()->taxable_total(); - $this->assertNotEmpty( $old_taxable_total ); - $old_tax_total = $t->tax_total(); - $this->assertNotEmpty( $old_tax_total ); - - $tax_in_1st_ipn = 1.80; - $ship_in_1st_ipn = 3.00; - $p = $this->new_model_obj_with_dependencies( 'Payment', - array( - 'TXN_ID'=>$t->ID(), - 'STS_ID' => EEM_Payment::status_id_approved, - 'PMD_ID' => $ppm->ID(), - 'PAY_amount' => $t->total() / 2, - 'PAY_details' => array ( - 'tax' => "$tax_in_1st_ipn",//IMPORTANT - 'mc_shipping' => "$ship_in_1st_ipn",//IMPORTANT - ), - ) ); - $p->update_extra_meta( EEG_Paypal_Standard::itemized_payment_option_name, false ); - //taxes shouldn't have been changed, despite whatever paypal says, because - //we didnt send them an itemized total so they cant have calculated taxes right anyways - $this->assertNotEquals( $tax_in_1st_ipn, $old_tax_total, 'Its not necessarily wrong for the old tax to match the new tax; but if they match we can\'t be very sure the tax total wasnt updated' ); - - - $ppg->update_txn_based_on_payment( $p ); - //check the new tax wasnt changed - $this->assertEquals( $old_tax_total, $t->tax_total() ); - $this->assertNotEquals( $tax_in_1st_ipn, $t->tax_total() );//taxes shouldnt have changed - $pre_tax_total = EEH_Line_Item::get_pre_tax_subtotal( $t->total_line_item() ); - $shipping1_line_item = $pre_tax_total->get_child_line_item( 'paypal_shipping_' . $t->ID() ); - $this->assertNull( $shipping1_line_item ); - - //ok now let's pretend they made another payment via paypal and added more onto the taxes. - //but we only update taxes when paypal received an itemized payment from us, which it didn't - $tax_in_2nd_ipn = 1.5; - $ship_in_2nd_ipn = 8.00; - $p2 = $this->new_model_obj_with_dependencies( 'Payment', - array( - 'TXN_ID'=>$t->ID(), - 'STS_ID' => EEM_Payment::status_id_approved, - 'PMD_ID' => $ppm->ID(), - 'PAY_amount' => $t->remaining(), - 'PAY_details' => array( - 'tax' => "$tax_in_2nd_ipn", - 'mc_shipping' => "$ship_in_2nd_ipn")) ); - $p2->update_extra_meta( EEG_Paypal_Standard::itemized_payment_option_name, false ); - $ppg->update_txn_based_on_payment( $p2 ); - //assert that the total tax is now the SUM of both IPN's tax amounts - $this->assertEquals( $tax_in_2nd_ipn, $t->tax_total() ); - //verify the old shipping is still there - $shipping1_line_item = $pre_tax_total->get_child_line_item( 'paypal_shipping_' . $t->ID() ); - $this->assertNull( $shipping1_line_item ); - } - - - /** - * verifies that previous payments get added onto the discount - * @group 4710 - */ - public function test_set_redirect_info__partial_payment_for_remainder(){ - $ppm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Paypal_Standard' ) ); - $ppg = $ppm->type_obj()->get_gateway(); - $ppg->set_settings( $this->_test_settings ); - $paid_so_far = 1.00; - $t = $this->new_typical_transaction( array( 'ticket_types' => 2)); - $t->set_paid( $paid_so_far ); - $previous_payment = $this->new_model_obj_with_dependencies( 'Payment', array('TXN_ID'=>$t->ID(), 'PMD_ID' => $ppm->ID(), 'PAY_amount' => $paid_so_far, 'STS_ID' => EEM_Payment::status_id_approved ) ); - $p = $this->new_model_obj_with_dependencies( 'Payment', array('TXN_ID'=>$t->ID(), 'PMD_ID' => $ppm->ID(), 'PAY_amount' => $t->total() - $paid_so_far ) ); - $this->assertNotEquals( EEM_Payment::status_id_approved, $p->status() ); - - $p = $ppg->set_redirection_info( $p, NULL, self::return_url, self::notify_url, self::cancel_url ); - - $this->assertNotEmpty( $p->redirect_url() ); - $rargs = $p->redirect_args(); - //also check we DID try to enumerat ethe line items - $this->assertFalse( isset( $rargs[ 'discount_amount_cart' ] ) ); - $this->assertTrue( isset( $rargs[ 'item_name_1' ] ) ); - $this->assertTrue( isset( $rargs[ 'amount_1' ] ) ); - $this->assertFalse( isset( $rargs[ 'item_name_2' ] ) ); - $this->assertFalse( isset( $rargs[ 'amount_2' ] ) ); - $this->assertFalse( isset( $rargs[ 'quantity_2' ] ) ); - } - - /** - * This is a legitimate partial payment (different from a total mismatch in that the itemized total - * equals the transaction total as expected, but the payment is for less than the transaction - * and there are no previous payments - * @group 4710 - */ - public function test_set_redirect_info__partial_payment_initial(){ - $ppm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Paypal_Standard' ) ); - $ppg = $ppm->type_obj()->get_gateway(); - $ppg->set_settings( $this->_test_settings ); - $t = $this->new_typical_transaction( array( 'ticket_types' => 2)); - $p = $this->new_model_obj_with_dependencies( 'Payment', array('TXN_ID'=>$t->ID(), 'PMD_ID' => $ppm->ID(), 'PAY_amount' => 10 ) ); - $this->assertNotEquals( EEM_Payment::status_id_approved, $p->status() ); - - $p = $ppg->set_redirection_info( $p, NULL, self::return_url, self::notify_url, self::cancel_url ); - - $this->assertNotEmpty( $p->redirect_url() ); - $rargs = $p->redirect_args(); - //also check we DID NOT try to enumerat ethe line items - $this->assertTrue( isset( $rargs[ 'item_name_1' ] ) ); - $this->assertTrue( isset( $rargs[ 'amount_1' ] ) ); - $this->assertFalse( isset( $rargs[ 'item_name_2' ] ) ); - $this->assertFalse( isset( $rargs[ 'amount_2' ] ) ); - $this->assertFalse( isset( $rargs[ 'quantity_2' ] ) ); - } - /** - * Verifies that we don't re-add shipping if it's already been added - * @group 4710 - */ - public function test_set_redirect_info__with_promotion() { - $ppm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Paypal_Standard' ) ); - $ppg = $ppm->type_obj()->get_gateway(); - $ppg->set_settings( $this->_test_settings ); - $t = $this->new_typical_transaction( array( 'ticket_types' => 2)); - $event = EEM_Event::instance()->get_one( array( array( 'Registration.TXN_ID' => $t->ID() ) ) ); - $event_li = EEH_Line_Item::get_event_line_item( $t->total_line_item(), $event ); - $discount_li = $this->new_model_obj_with_dependencies( - 'Line_Item', - array( - 'LIN_parent' => $event_li->ID(), - 'LIN_name' => 'discount', - 'LIN_code' => 'discount', - 'LIN_unit_price' => -10, - 'LIN_quantity' => 1, - 'LIN_percent' => 0, - 'LIN_type' => EEM_Line_Item::type_line_item, - 'LIN_is_taxable' => false, - 'TXN_ID' => $t->ID() - )); - $t->total_line_item()->recalculate_total_including_taxes(); - $p = $this->new_model_obj_with_dependencies( 'Payment', array('TXN_ID'=>$t->ID(), 'PMD_ID' => $ppm->ID(), 'PAY_amount' => $t->total() ) ); - $this->assertNotEquals( EEM_Payment::status_id_approved, $p->status() ); - - $p = $ppg->set_redirection_info( $p, NULL, self::return_url, self::notify_url, self::cancel_url ); - - $rargs = $p->redirect_args(); - //also check we DID enumerate the line items - $this->assertEquals((float) '10', (float) $rargs['discount_amount_cart']); - $this->assertTrue( isset( $rargs[ 'item_name_1' ] ) ); - $this->assertTrue( isset( $rargs[ 'amount_1' ] ) ); - //although we shouldn't be mentioning how much taxes are per item. leave that to paypal - $this->assertFalse( isset( $rargs[ 'tax_1' ] ) ); - $this->assertTrue( isset( $rargs[ 'item_name_2' ] ) ); - $this->assertTrue( isset( $rargs[ 'amount_2' ] ) ); - $this->assertTrue( isset( $rargs[ 'quantity_2' ] ) ); - $this->assertFalse( isset( $rargs[ 'tax_2' ] ) ); - } - - /** - * tests that even if the line items are too complicated for the gateway to handle, - * it can at least send the total payable - * @group 4710 - */ - public function test_set_redirect_info__total_mismatch__itemized_higher(){ - $ppm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Paypal_Standard' ) ); - $ppg = $ppm->type_obj()->get_gateway(); - $ppg->set_settings( $this->_test_settings ); - $t = $this->new_typical_transaction( array( 'ticket_types' => 2) ); - $t->set_total( $t->total() - 10 ); - $t->total_line_item()->set_total ( $t->total() ); - $t->save(); - $t->total_line_item()->save(); - $p = $this->new_model_obj_with_dependencies( 'Payment', array('TXN_ID'=>$t->ID(), 'PMD_ID' => $ppm->ID(), 'PAY_amount' => $t->total() ) ); - $this->assertNotEquals( EEM_Payment::status_id_approved, $p->status() ); - - $p = $ppg->set_redirection_info( $p, NULL, self::return_url, self::notify_url, self::cancel_url ); - - $this->assertNotEmpty( $p->redirect_url() ); - $rargs = $p->redirect_args(); - //also check we DID manage to enumerat ethe line items, just with a discount - //the amount missing is equal to - $this->assertEquals( 10, intval( $rargs[ 'discount_amount_cart' ] ) ); - $this->assertTrue( isset( $rargs[ 'item_name_1' ] ) ); - $this->assertTrue( isset( $rargs[ 'amount_1' ] ) ); - $this->assertTrue( isset( $rargs[ 'item_name_2' ] ) ); - $this->assertTrue( isset( $rargs[ 'amount_2' ] ) ); - $this->assertTrue( isset( $rargs[ 'quantity_2' ] ) ); - } - - /** - * tests that even if the line items are too complicated for the gateway to handle, - * it can at least send the total payable - * @group 4710 - */ - public function test_set_redirect_info__total_mismatch__itemized_lower(){ - $ppm = $this->new_model_obj_with_dependencies( 'Payment_Method', array( 'PMD_type' => 'Paypal_Standard' ) ); - $ppg = $ppm->type_obj()->get_gateway(); - $ppg->set_settings( $this->_test_settings ); - $t = $this->new_typical_transaction( array( 'ticket_types' => 2) ); - $t->set_total( $t->total() + 5 ); - $t->total_line_item()->set_total ( $t->total() ); - $t->save(); - $t->total_line_item()->save(); - $p = $this->new_model_obj_with_dependencies( 'Payment', array('TXN_ID'=>$t->ID(), 'PMD_ID' => $ppm->ID(), 'PAY_amount' => $t->total() ) ); - $this->assertNotEquals( EEM_Payment::status_id_approved, $p->status() ); - - $p = $ppg->set_redirection_info( $p, NULL, self::return_url, self::notify_url, self::cancel_url ); - - $this->assertNotEmpty( $p->redirect_url() ); - $rargs = $p->redirect_args(); - //also check we DID manage to enumerat ethe line items, just with an extra item for the surplus - $this->assertTrue( isset( $rargs[ 'item_name_1' ] ) ); - $this->assertTrue( isset( $rargs[ 'amount_1' ] ) ); - $this->assertTrue( isset( $rargs[ 'item_name_2' ] ) ); - $this->assertTrue( isset( $rargs[ 'amount_2' ] ) ); - $this->assertTrue( isset( $rargs[ 'quantity_2' ] ) ); - //check that we've also added another item to make up for the difference - $this->assertTrue( isset( $rargs[ 'item_name_3' ] ) ); - $this->assertTrue( isset( $rargs[ 'amount_3' ] ) ); - $this->assertTrue( isset( $rargs[ 'quantity_3' ] ) ); - $this->assertEquals( 5, $rargs[ 'amount_3' ] ); - } -} - -// End of file EE_PMT_Paypal_Standard_Test.php -// Location: /tests/testcases/payment_methods/EE_PMT_Paypal_Standard_Test.php diff --git a/wp-assets/banner-772x250.jpg b/wp-assets/banner-772x250.jpg deleted file mode 100644 index 1309dd13339..00000000000 Binary files a/wp-assets/banner-772x250.jpg and /dev/null differ diff --git a/wp-assets/icon-128x128.png b/wp-assets/icon-128x128.png deleted file mode 100644 index 9347adb78dc..00000000000 Binary files a/wp-assets/icon-128x128.png and /dev/null differ diff --git a/wp-assets/icon-256x256.png b/wp-assets/icon-256x256.png deleted file mode 100644 index 84970f89db8..00000000000 Binary files a/wp-assets/icon-256x256.png and /dev/null differ diff --git a/wp-assets/icon.svg b/wp-assets/icon.svg deleted file mode 100644 index 2bf6cb04d57..00000000000 --- a/wp-assets/icon.svg +++ /dev/null @@ -1,134 +0,0 @@ - - - -image/svg+xml - - - - - - - - - \ No newline at end of file diff --git a/wp-assets/screenshot-1.jpg b/wp-assets/screenshot-1.jpg deleted file mode 100644 index 94377fa87c9..00000000000 Binary files a/wp-assets/screenshot-1.jpg and /dev/null differ diff --git a/wp-assets/screenshot-2.jpg b/wp-assets/screenshot-2.jpg deleted file mode 100644 index 0bc36251602..00000000000 Binary files a/wp-assets/screenshot-2.jpg and /dev/null differ diff --git a/wp-assets/screenshot-3.jpg b/wp-assets/screenshot-3.jpg deleted file mode 100644 index a526361cdd1..00000000000 Binary files a/wp-assets/screenshot-3.jpg and /dev/null differ diff --git a/wp-assets/screenshot-4.jpg b/wp-assets/screenshot-4.jpg deleted file mode 100644 index b1600c8e978..00000000000 Binary files a/wp-assets/screenshot-4.jpg and /dev/null differ diff --git a/wp-assets/screenshot-5.jpg b/wp-assets/screenshot-5.jpg deleted file mode 100644 index 514b9c7203d..00000000000 Binary files a/wp-assets/screenshot-5.jpg and /dev/null differ diff --git a/wp-assets/screenshot-6.jpg b/wp-assets/screenshot-6.jpg deleted file mode 100644 index d53abcf9225..00000000000 Binary files a/wp-assets/screenshot-6.jpg and /dev/null differ diff --git a/wp-assets/screenshot-7.jpg b/wp-assets/screenshot-7.jpg deleted file mode 100644 index 1cfdb13b916..00000000000 Binary files a/wp-assets/screenshot-7.jpg and /dev/null differ diff --git a/wp-assets/screenshot-8.jpg b/wp-assets/screenshot-8.jpg deleted file mode 100644 index 31f1f0641bc..00000000000 Binary files a/wp-assets/screenshot-8.jpg and /dev/null differ