* Tidy up bootstap so it uses autoloaders and works with the known plugin paths

* eslint ignore woocommerce bin

* Use WC from bin in wp-env

* Git ignore woocommerce in bin

* Remove reliance on core framework across phpunit tests

* Simplify bootstrap - since test framework is no longer required, there is no need to pull in woo from github

* Remove unused configs

* Update CI

* Implement PHPunit Polyfill

* Abstract the test case

* Update lock

* remove chown

* experiment: try sudo

* move phpversion to first run

* Remove 7.0 tests :(

* test plugin override for 5.5 test

* Use dev version

* Fix formatting

Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
This commit is contained in:
Mike Jolley 2021-08-20 14:58:32 +01:00 committed by GitHub
parent 7805ea63db
commit 1d79bb6365
37 changed files with 1513 additions and 1554 deletions

View File

@ -58,42 +58,44 @@ jobs:
PHPUnitTests:
name: PHP Unit Tests
needs: Setup
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Get Composer Cache Directory
id: composer-cache
run: |
echo "::set-output name=dir::$(composer config cache-files-dir)"
- uses: actions/cache@v2
- name: Cache node modules
uses: actions/cache@v2
env:
cache-name: cache-node-modules
with:
path: ${{ steps.composer-cache.outputs.dir }}
key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
# npm cache files are stored in `~/.npm` on Linux/macOS
path: ~/.npm
key: ${{ runner.OS }}-build-${{ secrets.CACHE_VERSION }}-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-composer-
- name: Set up PHP
uses: shivammathur/setup-php@v2
${{ runner.OS }}-build-${{ secrets.CACHE_VERSION }}-${{ env.cache-name }}-
${{ runner.OS }}-build-${{ secrets.CACHE_VERSION }}-
- name: Use Node.js 14.x
uses: actions/setup-node@v1
with:
php-version: 7.4
coverage: none
tools: composer
node-version: 14.x
- name: Composer install
- name: Npm install #build is not needed
run: |
composer install
npm ci
- name: blocks.ini setup
run: |
echo -e 'woocommerce_blocks_phase = 3\nwoocommerce_blocks_env = tests' > blocks.ini
- name: Run PHP Unit tests
echo 'woocommerce_blocks_phase = 3' > blocks.ini
- name: Setup Environment
run: |
npm run phpunit
chmod -R 767 ./ #TODO: Might get implemented in wp-env
npm run wp-env start
- name: Run PHPUnit tests
run: npm run test:php
- name: Run PHPUnit tests (WooCommerce Development Version)
run: |
JSON='{"plugins": [".","https://downloads.wordpress.org/plugin/woocommerce.zip"]}'
echo $JSON > .wp-env.override.json
npm run wp-env start
npm run test:php
JSUnitTests:
name: JS Unit Tests

View File

@ -13,6 +13,6 @@
},
"config": {
"JETPACK_AUTOLOAD_DEV": true,
"SCRIPT_DEBUG": false
"SCRIPT_DEBUG": false
}
}

View File

@ -1,2 +0,0 @@
ARG WP_VERSION
FROM wordpress:${WP_VERSION}

View File

@ -0,0 +1,6 @@
#!/bin/sh
BASENAME=$(basename "`pwd`")
npm run wp-env run composer 'install --no-interaction'
npm run wp-env run phpunit 'php -v'
npm run wp-env run phpunit "phpunit -c /var/www/html/wp-content/plugins/${BASENAME}/phpunit.xml.dist --verbose"

View File

@ -16,14 +16,20 @@
"automattic/jetpack-autoloader": "^2.9.1"
},
"require-dev": {
"phpunit/phpunit": "7.5.20",
"woocommerce/woocommerce-sniffs": "0.1.0"
"wp-phpunit/wp-phpunit": "^5.4",
"woocommerce/woocommerce-sniffs": "0.1.0",
"yoast/phpunit-polyfills": "^1.0"
},
"autoload": {
"psr-4": {
"Automattic\\WooCommerce\\Blocks\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Automattic\\WooCommerce\\Blocks\\Tests\\": "tests/php"
}
},
"scripts": {
"phpcs": [
"phpcs --extensions=php -s -p"

File diff suppressed because it is too large Load Diff

View File

@ -8248,9 +8248,9 @@
}
},
"@wordpress/env": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/@wordpress/env/-/env-4.0.3.tgz",
"integrity": "sha512-4gixVn56afkyQE/vBPwdA8F08AWcUXY35SRzAct5LaAvx0WOUn32qtgFITfbJSljaYpLy15Z65O82wd+fPNIeQ==",
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/@wordpress/env/-/env-4.1.0.tgz",
"integrity": "sha512-wp3WP/KuUmdHRwWMRHd6m+3uWqCSRqHvJ56K3B4SjFMS4OZEBTPTcvG4rvw0ECH8x3pVXiua1QJm0acLfiIN4w==",
"dev": true,
"requires": {
"chalk": "^4.0.0",

View File

@ -50,7 +50,6 @@
"package-plugin:dev": "rimraf woocommerce-gutenberg-products-block.zip && ./bin/build-plugin-zip.sh -d",
"package-plugin:zip-only": "rimraf woocommerce-gutenberg-products-block.zip && ./bin/build-plugin-zip.sh -z",
"package-plugin:deploy": "npm run build:deploy && npm run package-plugin:zip-only",
"phpunit": "docker-compose up -d db && docker-compose up -d --build wordpress-unit-tests && docker exec --workdir /var/www/html/wp-content/plugins/woocommerce-gutenberg-products-block wordpress_test php ./vendor/bin/phpunit",
"postinstall": "patch-package",
"reformat-files": "prettier --ignore-path .eslintignore --write \"**/*.{js,jsx,json,ts,tsx}\"",
"release": "sh ./bin/wordpress-deploy.sh",
@ -63,11 +62,13 @@
"test:e2e-dev": "npm run wp-env:config && cross-env NODE_CONFIG_DIR=tests/e2e/config wp-scripts test-e2e --config tests/e2e/config/jest.config.js --puppeteer-interactive",
"test:e2e:update": "npm run wp-env:config && cross-env NODE_CONFIG_DIR=tests/e2e/config wp-scripts test-e2e --config tests/e2e/config/jest.config.js --updateSnapshot",
"test:help": "wp-scripts test-unit-js --help",
"test:php": "npm run wp-env:phpunit-config",
"test:update": "wp-scripts test-unit-js --updateSnapshot --config tests/js/jest.config.json",
"test:watch": "npm run test -- --watch",
"ts:check": "tsc --build",
"wp-env": "wp-env",
"wp-env:config": "./bin/wp-env-pre-config.sh"
"wp-env:config": "./bin/wp-env-pre-config.sh",
"wp-env:phpunit-config": "./bin/wp-env-phpunit-pre-config.sh"
},
"devDependencies": {
"@automattic/color-studio": "2.5.0",
@ -121,7 +122,7 @@
"@wordpress/dom": "3.2.1",
"@wordpress/e2e-test-utils": "5.4.1",
"@wordpress/element": "3.1.0",
"@wordpress/env": "4.0.3",
"@wordpress/env": "4.1.0",
"@wordpress/html-entities": "3.2.1",
"@wordpress/i18n": "4.2.1",
"@wordpress/is-shallow-equal": "4.2.0",

View File

@ -441,7 +441,7 @@ class ProductSchema extends AbstractSchema {
'on_sale' => $product->is_on_sale(),
'prices' => (object) $this->prepare_product_price_response( $product ),
'price_html' => $this->prepare_html_response( $product->get_price_html() ),
'average_rating' => $product->get_average_rating(),
'average_rating' => (string) $product->get_average_rating(),
'review_count' => $product->get_review_count(),
'images' => $this->get_images( $product ),
'categories' => $this->get_term_list( $product, 'product_cat' ),

View File

@ -1,24 +0,0 @@
FROM wordpress:latest
ARG WOO_INSTALL_VERSION=latest
CMD echo "Installing dependencies..."
RUN apt-get update && \
apt-get -y install subversion unzip wget git-all
CMD echo "Installing tests..."
ENV WP_TESTS_DIR=/tmp/wordpress-tests-lib
ENV WP_CORE_DIR=/tmp/src/wordpress
ENV WOO_VERSION=$WOO_INSTALL_VERSION
COPY install-wp-tests.sh /usr/local/bin/dockerInit
RUN chmod +x /usr/local/bin/dockerInit
RUN dockerInit wordpress wordpress wordpress db latest true
# This is the entrypoint script from the WordPress Docker package.
CMD ["docker-entrypoint.sh"]
# Keep container active
CMD ["apache2-foreground"]

View File

@ -1,290 +0,0 @@
#!/bin/bash
set -euo pipefail
# usage: file_env VAR [DEFAULT]
# ie: file_env 'XYZ_DB_PASSWORD' 'example'
# (will allow for "$XYZ_DB_PASSWORD_FILE" to fill in the value of
# "$XYZ_DB_PASSWORD" from a file, especially for Docker's secrets feature)
file_env() {
local var="$1"
local fileVar="${var}_FILE"
local def="${2:-}"
if [ "${!var:-}" ] && [ "${!fileVar:-}" ]; then
echo >&2 "error: both $var and $fileVar are set (but are exclusive)"
exit 1
fi
local val="$def"
if [ "${!var:-}" ]; then
val="${!var}"
elif [ "${!fileVar:-}" ]; then
val="$(< "${!fileVar}")"
fi
export "$var"="$val"
unset "$fileVar"
}
if [[ "$1" == apache2* ]] || [ "$1" == php-fpm ]; then
if [ "$(id -u)" = '0' ]; then
case "$1" in
apache2*)
user="${APACHE_RUN_USER:-www-data}"
group="${APACHE_RUN_GROUP:-www-data}"
# strip off any '#' symbol ('#1000' is valid syntax for Apache)
pound='#'
user="${user#$pound}"
group="${group#$pound}"
;;
*) # php-fpm
user='www-data'
group='www-data'
;;
esac
else
user="$(id -u)"
group="$(id -g)"
fi
if [ ! -e index.php ] && [ ! -e wp-includes/version.php ]; then
# if the directory exists and WordPress doesn't appear to be installed AND the permissions of it are root:root, let's chown it (likely a Docker-created directory)
if [ "$(id -u)" = '0' ] && [ "$(stat -c '%u:%g' .)" = '0:0' ]; then
chown "$user:$group" .
fi
echo >&2 "WordPress not found in $PWD - copying now..."
if [ -n "$(ls -A)" ]; then
echo >&2 "WARNING: $PWD is not empty! (copying anyhow)"
fi
sourceTarArgs=(
--create
--file -
--directory /usr/src/wordpress
--owner "$user" --group "$group"
)
targetTarArgs=(
--extract
--file -
)
if [ "$user" != '0' ]; then
# avoid "tar: .: Cannot utime: Operation not permitted" and "tar: .: Cannot change mode to rwxr-xr-x: Operation not permitted"
targetTarArgs+=( --no-overwrite-dir )
fi
tar "${sourceTarArgs[@]}" . | tar "${targetTarArgs[@]}"
echo >&2 "Complete! WordPress has been successfully copied to $PWD"
if [ ! -e .htaccess ]; then
# NOTE: The "Indexes" option is disabled in the php:apache base image
cat > .htaccess <<-'EOF'
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
EOF
chown "$user:$group" .htaccess
fi
fi
# allow any of these "Authentication Unique Keys and Salts." to be specified via
# environment variables with a "WORDPRESS_" prefix (ie, "WORDPRESS_AUTH_KEY")
uniqueEnvs=(
AUTH_KEY
SECURE_AUTH_KEY
LOGGED_IN_KEY
NONCE_KEY
AUTH_SALT
SECURE_AUTH_SALT
LOGGED_IN_SALT
NONCE_SALT
)
envs=(
WORDPRESS_DB_HOST
WORDPRESS_DB_USER
WORDPRESS_DB_PASSWORD
WORDPRESS_DB_NAME
WORDPRESS_DB_CHARSET
WORDPRESS_DB_COLLATE
"${uniqueEnvs[@]/#/WORDPRESS_}"
WORDPRESS_TABLE_PREFIX
WORDPRESS_DEBUG
WORDPRESS_CONFIG_EXTRA
)
haveConfig=
for e in "${envs[@]}"; do
file_env "$e"
if [ -z "$haveConfig" ] && [ -n "${!e}" ]; then
haveConfig=1
fi
done
# linking backwards-compatibility
if [ -n "${!MYSQL_ENV_MYSQL_*}" ]; then
haveConfig=1
# host defaults to "mysql" below if unspecified
: "${WORDPRESS_DB_USER:=${MYSQL_ENV_MYSQL_USER:-root}}"
if [ "$WORDPRESS_DB_USER" = 'root' ]; then
: "${WORDPRESS_DB_PASSWORD:=${MYSQL_ENV_MYSQL_ROOT_PASSWORD:-}}"
else
: "${WORDPRESS_DB_PASSWORD:=${MYSQL_ENV_MYSQL_PASSWORD:-}}"
fi
: "${WORDPRESS_DB_NAME:=${MYSQL_ENV_MYSQL_DATABASE:-}}"
fi
# only touch "wp-config.php" if we have environment-supplied configuration values
if [ "$haveConfig" ]; then
: "${WORDPRESS_DB_HOST:=mysql}"
: "${WORDPRESS_DB_USER:=root}"
: "${WORDPRESS_DB_PASSWORD:=}"
: "${WORDPRESS_DB_NAME:=wordpress}"
: "${WORDPRESS_DB_CHARSET:=utf8}"
: "${WORDPRESS_DB_COLLATE:=}"
# version 4.4.1 decided to switch to windows line endings, that breaks our seds and awks
# https://github.com/docker-library/wordpress/issues/116
# https://github.com/WordPress/WordPress/commit/1acedc542fba2482bab88ec70d4bea4b997a92e4
sed -ri -e 's/\r$//' wp-config*
if [ ! -e wp-config.php ]; then
awk '
/^\/\*.*stop editing.*\*\/$/ && c == 0 {
c = 1
system("cat")
if (ENVIRON["WORDPRESS_CONFIG_EXTRA"]) {
print "// WORDPRESS_CONFIG_EXTRA"
print ENVIRON["WORDPRESS_CONFIG_EXTRA"] "\n"
}
}
{ print }
' wp-config-sample.php > wp-config.php <<'EOPHP'
// If we're behind a proxy server and using HTTPS, we need to alert WordPress of that fact
// see also http://codex.wordpress.org/Administration_Over_SSL#Using_a_Reverse_Proxy
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
$_SERVER['HTTPS'] = 'on';
}
EOPHP
chown "$user:$group" wp-config.php
elif [ -e wp-config.php ] && [ -n "$WORDPRESS_CONFIG_EXTRA" ] && [[ "$(< wp-config.php)" != *"$WORDPRESS_CONFIG_EXTRA"* ]]; then
# (if the config file already contains the requested PHP code, don't print a warning)
echo >&2
echo >&2 'WARNING: environment variable "WORDPRESS_CONFIG_EXTRA" is set, but "wp-config.php" already exists'
echo >&2 ' The contents of this variable will _not_ be inserted into the existing "wp-config.php" file.'
echo >&2 ' (see https://github.com/docker-library/wordpress/issues/333 for more details)'
echo >&2
fi
# see http://stackoverflow.com/a/2705678/433558
sed_escape_lhs() {
echo "$@" | sed -e 's/[]\/$*.^|[]/\\&/g'
}
sed_escape_rhs() {
echo "$@" | sed -e 's/[\/&]/\\&/g'
}
php_escape() {
local escaped="$(php -r 'var_export(('"$2"') $argv[1]);' -- "$1")"
if [ "$2" = 'string' ] && [ "${escaped:0:1}" = "'" ]; then
escaped="${escaped//$'\n'/"' + \"\\n\" + '"}"
fi
echo "$escaped"
}
set_config() {
key="$1"
value="$2"
var_type="${3:-string}"
start="(['\"])$(sed_escape_lhs "$key")\2\s*,"
end="\);"
if [ "${key:0:1}" = '$' ]; then
start="^(\s*)$(sed_escape_lhs "$key")\s*="
end=";"
fi
sed -ri -e "s/($start\s*).*($end)$/\1$(sed_escape_rhs "$(php_escape "$value" "$var_type")")\3/" wp-config.php
}
set_config 'DB_HOST' "$WORDPRESS_DB_HOST"
set_config 'DB_USER' "$WORDPRESS_DB_USER"
set_config 'DB_PASSWORD' "$WORDPRESS_DB_PASSWORD"
set_config 'DB_NAME' "$WORDPRESS_DB_NAME"
set_config 'DB_CHARSET' "$WORDPRESS_DB_CHARSET"
set_config 'DB_COLLATE' "$WORDPRESS_DB_COLLATE"
for unique in "${uniqueEnvs[@]}"; do
uniqVar="WORDPRESS_$unique"
if [ -n "${!uniqVar}" ]; then
set_config "$unique" "${!uniqVar}"
else
# if not specified, let's generate a random value
currentVal="$(sed -rn -e "s/define\(\s*(([\'\"])$unique\2\s*,\s*)(['\"])(.*)\3\s*\);/\4/p" wp-config.php)"
if [ "$currentVal" = 'put your unique phrase here' ]; then
set_config "$unique" "$(head -c1m /dev/urandom | sha1sum | cut -d' ' -f1)"
fi
fi
done
if [ "$WORDPRESS_TABLE_PREFIX" ]; then
set_config '$table_prefix' "$WORDPRESS_TABLE_PREFIX"
fi
if [ "$WORDPRESS_DEBUG" ]; then
set_config 'WP_DEBUG' 1 boolean
fi
if ! TERM=dumb php -- <<'EOPHP'
<?php
// database might not exist, so let's try creating it (just to be safe)
$stderr = fopen('php://stderr', 'w');
// https://codex.wordpress.org/Editing_wp-config.php#MySQL_Alternate_Port
// "hostname:port"
// https://codex.wordpress.org/Editing_wp-config.php#MySQL_Sockets_or_Pipes
// "hostname:unix-socket-path"
list($host, $socket) = explode(':', getenv('WORDPRESS_DB_HOST'), 2);
$port = 0;
if (is_numeric($socket)) {
$port = (int) $socket;
$socket = null;
}
$user = getenv('WORDPRESS_DB_USER');
$pass = getenv('WORDPRESS_DB_PASSWORD');
$dbName = getenv('WORDPRESS_DB_NAME');
$maxTries = 10;
do {
$mysql = new mysqli($host, $user, $pass, '', $port, $socket);
if ($mysql->connect_error) {
fwrite($stderr, "\n" . 'MySQL Connection Error: (' . $mysql->connect_errno . ') ' . $mysql->connect_error . "\n");
--$maxTries;
if ($maxTries <= 0) {
exit(1);
}
sleep(3);
}
} while ($mysql->connect_error);
if (!$mysql->query('CREATE DATABASE IF NOT EXISTS `' . $mysql->real_escape_string($dbName) . '`')) {
fwrite($stderr, "\n" . 'MySQL "CREATE DATABASE" Error: ' . $mysql->error . "\n");
$mysql->close();
exit(1);
}
$mysql->close();
EOPHP
then
echo >&2
echo >&2 "WARNING: unable to establish a database connection to '$WORDPRESS_DB_HOST'"
echo >&2 ' continuing anyways (which might have unexpected results)'
echo >&2
fi
fi
# now that we're definitely done writing configuration, let's clear out the relevant envrionment variables (so that stray "phpinfo()" calls don't leak secrets from our code)
for e in "${envs[@]}"; do
unset "$e"
done
fi
exec "$@"

View File

@ -1,178 +0,0 @@
#!/usr/bin/env bash
if [ $# -lt 3 ]; then
echo "usage: $0 <db-name> <db-user> <db-pass> [db-host] [wp-version] [skip-database-creation]"
exit 1
fi
DB_NAME=$1
DB_USER=$2
DB_PASS=$3
DB_HOST=${4-localhost}
WP_VERSION=${5-latest}
SKIP_DB_CREATE=${6-false}
WOO_VERSION=${WOO_VERSION-latest}
# directories
TMPDIR=${TMPDIR-/tmp}
TMPDIR=$(echo $TMPDIR | sed -e "s/\/$//")
WP_TESTS_DIR=${WP_TESTS_DIR-$TMPDIR/wordpress-tests-lib}
WP_CORE_DIR=${WP_CORE_DIR-$TMPDIR/wordpress/}
download() {
if [ `which curl` ]; then
curl -s -L "$1" > "$2";
elif [ `which wget` ]; then
wget -nv -O "$2" "$1"
fi
}
if [[ $WP_VERSION =~ ^[0-9]+\.[0-9]+$ ]]; then
WP_TESTS_TAG="branches/$WP_VERSION"
elif [[ $WP_VERSION =~ [0-9]+\.[0-9]+\.[0-9]+ ]]; then
if [[ $WP_VERSION =~ [0-9]+\.[0-9]+\.[0] ]]; then
# version x.x.0 means the first release of the major version, so strip off the .0 and download version x.x
WP_TESTS_TAG="tags/${WP_VERSION%??}"
else
WP_TESTS_TAG="tags/$WP_VERSION"
fi
elif [[ $WP_VERSION == 'nightly' || $WP_VERSION == 'trunk' ]]; then
WP_TESTS_TAG="trunk"
else
# http serves a single offer, whereas https serves multiple. we only want one
download http://api.wordpress.org/core/version-check/1.7/ /tmp/wp-latest.json
grep '[0-9]+\.[0-9]+(\.[0-9]+)?' /tmp/wp-latest.json
LATEST_VERSION=$(grep -o '"version":"[^"]*' /tmp/wp-latest.json | sed 's/"version":"//')
if [[ -z "$LATEST_VERSION" ]]; then
echo "Latest WordPress version could not be found"
exit 1
fi
WP_TESTS_TAG="tags/$LATEST_VERSION"
fi
set -ex
install_wp() {
if [ -d $WP_CORE_DIR ]; then
return;
fi
mkdir -p $WP_CORE_DIR
if [[ $WP_VERSION == 'nightly' || $WP_VERSION == 'trunk' ]]; then
mkdir -p $TMPDIR/wordpress-nightly
download https://wordpress.org/nightly-builds/wordpress-latest.zip $TMPDIR/wordpress-nightly/wordpress-nightly.zip
unzip -q $TMPDIR/wordpress-nightly/wordpress-nightly.zip -d $TMPDIR/wordpress-nightly/
mv $TMPDIR/wordpress-nightly/wordpress/* $WP_CORE_DIR
else
if [ $WP_VERSION == 'latest' ]; then
local ARCHIVE_NAME='latest'
elif [[ $WP_VERSION =~ [0-9]+\.[0-9]+ ]]; then
# https serves multiple offers, whereas http serves single.
download https://api.wordpress.org/core/version-check/1.7/ $TMPDIR/wp-latest.json
if [[ $WP_VERSION =~ [0-9]+\.[0-9]+\.[0] ]]; then
# version x.x.0 means the first release of the major version, so strip off the .0 and download version x.x
LATEST_VERSION=${WP_VERSION%??}
else
# otherwise, scan the releases and get the most up to date minor version of the major release
local VERSION_ESCAPED=`echo $WP_VERSION | sed 's/\./\\\\./g'`
LATEST_VERSION=$(grep -o '"version":"'$VERSION_ESCAPED'[^"]*' $TMPDIR/wp-latest.json | sed 's/"version":"//' | head -1)
fi
if [[ -z "$LATEST_VERSION" ]]; then
local ARCHIVE_NAME="wordpress-$WP_VERSION"
else
local ARCHIVE_NAME="wordpress-$LATEST_VERSION"
fi
else
local ARCHIVE_NAME="wordpress-$WP_VERSION"
fi
download https://wordpress.org/${ARCHIVE_NAME}.tar.gz $TMPDIR/wordpress.tar.gz
tar --strip-components=1 -zxmf $TMPDIR/wordpress.tar.gz -C $WP_CORE_DIR
fi
download https://raw.github.com/markoheijnen/wp-mysqli/master/db.php $WP_CORE_DIR/wp-content/db.php
}
install_test_suite() {
# portable in-place argument for both GNU sed and Mac OSX sed
if [[ $(uname -s) == 'Darwin' ]]; then
local ioption='-i .bak'
else
local ioption='-i'
fi
# set up testing suite if it doesn't yet exist
if [ ! -d $WP_TESTS_DIR ]; then
# set up testing suite
mkdir -p $WP_TESTS_DIR
svn co --quiet https://develop.svn.wordpress.org/${WP_TESTS_TAG}/tests/phpunit/includes/ $WP_TESTS_DIR/includes
svn co --quiet https://develop.svn.wordpress.org/${WP_TESTS_TAG}/tests/phpunit/data/ $WP_TESTS_DIR/data
fi
if [ ! -f wp-tests-config.php ]; then
download https://develop.svn.wordpress.org/${WP_TESTS_TAG}/wp-tests-config-sample.php "$WP_TESTS_DIR"/wp-tests-config.php
# remove all forward slashes in the end
WP_CORE_DIR=$(echo $WP_CORE_DIR | sed "s:/\+$::")
sed $ioption "s:dirname( __FILE__ ) . '/src/':'$WP_CORE_DIR/':" "$WP_TESTS_DIR"/wp-tests-config.php
sed $ioption "s/youremptytestdbnamehere/$DB_NAME/" "$WP_TESTS_DIR"/wp-tests-config.php
sed $ioption "s/yourusernamehere/$DB_USER/" "$WP_TESTS_DIR"/wp-tests-config.php
sed $ioption "s/yourpasswordhere/$DB_PASS/" "$WP_TESTS_DIR"/wp-tests-config.php
sed $ioption "s|localhost|${DB_HOST}|" "$WP_TESTS_DIR"/wp-tests-config.php
fi
}
install_db() {
if [ ${SKIP_DB_CREATE} = "true" ]; then
return 0
fi
# parse DB_HOST for port or socket references
local PARTS=(${DB_HOST//\:/ })
local DB_HOSTNAME=${PARTS[0]};
local DB_SOCK_OR_PORT=${PARTS[1]};
local EXTRA=""
if ! [ -z $DB_HOSTNAME ] ; then
if [ $(echo $DB_SOCK_OR_PORT | grep -e '^[0-9]\{1,\}$') ]; then
EXTRA=" --host=$DB_HOSTNAME --port=$DB_SOCK_OR_PORT --protocol=tcp"
elif ! [ -z $DB_SOCK_OR_PORT ] ; then
EXTRA=" --socket=$DB_SOCK_OR_PORT"
elif ! [ -z $DB_HOSTNAME ] ; then
EXTRA=" --host=$DB_HOSTNAME --protocol=tcp"
fi
fi
# create database
mysqladmin create $DB_NAME --user="$DB_USER" --password="$DB_PASS"$EXTRA
}
install_woocommerce() {
WOO_INSTALL_VERSION=$WOO_VERSION
echo "Woo Version: $WOO_VERSION"
if [ $WOO_VERSION == 'latest' ] ; then
WOO_INSTALL_VERSION=latest-stable
fi
echo "Woo Install Version: $WOO_INSTALL_VERSION";
# get built plugin from .org
download "https://downloads.wordpress.org/plugin/woocommerce.$WOO_INSTALL_VERSION.zip" "$TMPDIR/woocommerce.zip"
unzip -q $TMPDIR/woocommerce.zip -d "$WP_CORE_DIR/wp-content/plugins"
git clone "https://github.com/woocommerce/woocommerce.git" "$TMPDIR/woocommerce-git"
# if specific version, then checkout the tag
if [ $WOO_VERSION != 'latest' ] ; then
echo "Checking out specific Woo Version test suite (tag)"
cd "$TMPDIR/woocommerce-git"
git checkout ${WOO_VERSION}
cd ..
fi
mv "$TMPDIR/woocommerce-git/tests" "$WP_CORE_DIR/wp-content/plugins/woocommerce"
}
install_wp
install_test_suite
install_db
install_woocommerce

View File

@ -1,153 +1,52 @@
<?php
use Automattic\WooCommerce\Proxies\LegacyProxy;
use Automattic\WooCommerce\Testing\Tools\DependencyManagement\MockableLegacyProxy;
/**
* PHPUnit bootstrap file
*
* @package WooCommerce\Blocks
*/
namespace Automattic\WooCommerce\Blocks\Tests;
// Require composer dependencies.
require_once dirname( __DIR__ ) . '/vendor/autoload.php';
// Determine the tests directory (from a WP dev checkout).
// Try the WP_TESTS_DIR environment variable first.
$_wc_tests_framework_dir = dirname( dirname( __DIR__ ) ) . '/woocommerce/tests/legacy';
$_tests_dir = getenv( 'WP_TESTS_DIR' );
// Next, try the WP_PHPUNIT composer package.
if ( ! $_tests_dir ) {
$_tests_dir = rtrim( sys_get_temp_dir(), '/\\' ) . '/wordpress-tests-lib';
$_tests_dir = getenv( 'WP_PHPUNIT__DIR' );
}
if ( ! file_exists( $_tests_dir . '/includes/functions.php' ) ) {
echo "Could not find $_tests_dir/includes/functions.php, have you run tests/bin/install-wp-tests.sh ?";
exit( 1 );
// See if we're installed inside an existing WP dev instance.
if ( ! $_tests_dir ) {
$_try_tests_dir = __DIR__ . '/../../../../../tests/phpunit';
if ( file_exists( $_try_tests_dir . '/includes/functions.php' ) ) {
$_tests_dir = $_try_tests_dir;
}
}
// Fallback.
if ( ! $_tests_dir ) {
$_tests_dir = '/tmp/wordpress-tests-lib';
}
// Give access to tests_add_filter() function.
require_once $_tests_dir . '/includes/functions.php';
/**
* Returns WooCommerce main directory.
*
* @return string
* Manually load the plugin being tested.
*/
function wc_dir() {
static $dir = '';
if ( $dir === '' ) {
if ( file_exists( WP_CONTENT_DIR . '/plugins/woocommerce/woocommerce.php' ) ) {
$dir = WP_CONTENT_DIR . '/plugins/woocommerce';
echo "Found WooCommerce plugin in content dir." . PHP_EOL;
} elseif ( file_exists( dirname( dirname( __DIR__ ) ) . '/woocommerce/woocommerce.php' ) ) {
$dir = dirname( dirname( __DIR__ ) ) . '/woocommerce';
echo "Found WooCommerce plugin in relative dir." . PHP_EOL;
} elseif ( file_exists( '/tmp/wordpress/wp-content/plugins/woocommerce/woocommerce.php' ) ) {
$dir = '/tmp/wordpress/wp-content/plugins/woocommerce';
echo "Found WooCommerce plugin in tmp dir." . PHP_EOL;
} else {
echo "Could not find WooCommerce plugin." . PHP_EOL;
exit( 1 );
}
}
return $dir;
}
/**
* Install WC Blocks
*/
function wc_blocks_install() {
echo esc_html( 'Loading WooCommerce Blocks plugin' . PHP_EOL );
function manually_load_plugins() {
require dirname( dirname( __DIR__ ) ) . '/woocommerce/woocommerce.php';
require dirname( __DIR__ ) . '/woocommerce-gutenberg-products-block.php';
}
/**
* Adds WooCommerce testing framework classes.
*/
function wc_test_includes() {
$wc_tests_framework_base_dir = wc_dir() . '/tests/legacy';
// WooCommerce test classes.
// Framework.
require_once $wc_tests_framework_base_dir . '/framework/class-wc-unit-test-factory.php';
require_once $wc_tests_framework_base_dir . '/framework/class-wc-mock-session-handler.php';
require_once $wc_tests_framework_base_dir . '/framework/class-wc-mock-wc-data.php';
require_once $wc_tests_framework_base_dir . '/framework/class-wc-mock-wc-object-query.php';
require_once $wc_tests_framework_base_dir . '/framework/class-wc-mock-payment-gateway.php';
require_once $wc_tests_framework_base_dir . '/framework/class-wc-payment-token-stub.php';
require_once $wc_tests_framework_base_dir . '/framework/vendor/class-wp-test-spy-rest-server.php';
// Test cases.
require_once $wc_tests_framework_base_dir . '/includes/wp-http-testcase.php';
require_once $wc_tests_framework_base_dir . '/framework/class-wc-unit-test-case.php';
require_once $wc_tests_framework_base_dir . '/framework/class-wc-api-unit-test-case.php';
require_once $wc_tests_framework_base_dir . '/framework/class-wc-rest-unit-test-case.php';
// Helpers.
require_once $wc_tests_framework_base_dir . '/framework/helpers/class-wc-helper-product.php';
require_once $wc_tests_framework_base_dir . '/framework/helpers/class-wc-helper-coupon.php';
require_once $wc_tests_framework_base_dir . '/framework/helpers/class-wc-helper-fee.php';
require_once $wc_tests_framework_base_dir . '/framework/helpers/class-wc-helper-shipping.php';
require_once $wc_tests_framework_base_dir . '/framework/helpers/class-wc-helper-customer.php';
require_once $wc_tests_framework_base_dir . '/framework/helpers/class-wc-helper-order.php';
require_once $wc_tests_framework_base_dir . '/framework/helpers/class-wc-helper-shipping-zones.php';
require_once $wc_tests_framework_base_dir . '/framework/helpers/class-wc-helper-payment-token.php';
require_once $wc_tests_framework_base_dir . '/framework/helpers/class-wc-helper-settings.php';
}
tests_add_filter( 'muplugins_loaded', __NAMESPACE__ . '\\manually_load_plugins' );
/**
* Re-initialize the dependency injection engine.
*
* The dependency injection engine has been already initialized as part of the Woo initialization, but we need
* to replace the registered read-only container with a fully configurable one for testing.
* To this end we hack a bit and use reflection to grab the underlying container that the read-only one stores
* in a private property.
*
* Additionally, we replace the legacy/function proxies with mockable versions to easily replace anything
* in tests as appropriate.
*
* @throws \Exception The Container class doesn't have a 'container' property.
* Manually install plugins being tested.
*/
function wc_blocks_initialize_dependency_injection() {
try {
$inner_container_property = new \ReflectionProperty( \Automattic\WooCommerce\Container::class, 'container' );
} catch ( ReflectionException $ex ) {
throw new \Exception( "Error when trying to get the private 'container' property from the " . \Automattic\WooCommerce\Container::class . ' class using reflection during unit testing bootstrap, has the property been removed or renamed?' );
}
$inner_container_property->setAccessible( true );
$inner_container = $inner_container_property->getValue( wc_get_container() );
$inner_container->replace( LegacyProxy::class, MockableLegacyProxy::class );
$inner_container->reset_all_resolved();
$GLOBALS['wc_container'] = $inner_container;
}
function wc_load_core() {
define( 'WC_TAX_ROUNDING_MODE', 'auto' );
define( 'WC_USE_TRANSACTIONS', false );
echo esc_html( 'Loading WooCommerce plugin' . PHP_EOL );
require_once wc_dir() . '/woocommerce.php';
}
function wc_install_core() {
// Clean existing install first.
define( 'WP_UNINSTALL_PLUGIN', true );
define( 'WC_REMOVE_ALL_DATA', true );
include wc_dir() . '/uninstall.php';
$GLOBALS['wp_roles'] = null; // WPCS: override ok.
wp_roles();
echo esc_html( 'Installing WooCommerce Blocks...' . PHP_EOL );
function manually_install_plugins() {
\Automattic\WooCommerce\Blocks\Package::container()->get( \Automattic\WooCommerce\Blocks\Installer::class )->maybe_create_tables();
}
/**
* Manually load the plugin being tested.
*/
tests_add_filter(
'muplugins_loaded',
function() {
define( 'JETPACK_AUTOLOAD_DEV', true );
wc_load_core();
// install blocks plugin
wc_blocks_install();
}
);
tests_add_filter( 'setup_theme', 'wc_install_core' );
tests_add_filter( 'setup_theme', __NAMESPACE__ . '\\manually_install_plugins' );
// Start up the WP testing environment.
require $_tests_dir . '/includes/bootstrap.php';
wc_test_includes();
wc_blocks_initialize_dependency_injection();

View File

@ -2,7 +2,7 @@
namespace Automattic\WooCommerce\Blocks\Tests\Assets;
use \WP_UnitTestCase;
use Yoast\PHPUnitPolyfills\Polyfills\ExpectException;
use Automattic\WooCommerce\Blocks\Assets\Api;
use Automattic\WooCommerce\Blocks\Tests\Mocks\AssetDataRegistryMock;
use Automattic\WooCommerce\Blocks\Package;
@ -13,7 +13,9 @@ use InvalidArgumentException;
*
* @since $VID:$
*/
class AssetDataRegistry extends WP_UnitTestCase {
class AssetDataRegistry extends \WP_UnitTestCase {
use ExpectException;
private $registry;
public function setUp() {

View File

@ -2,7 +2,7 @@
namespace Automattic\WooCommerce\Blocks\Tests\Library;
use \WP_UnitTestCase;
use Yoast\PHPUnitPolyfills\Polyfills\ExpectException;
use Automattic\WooCommerce\Blocks\Package;
use Automattic\WooCommerce\Blocks\Domain\Package as NewPackage;
use Automattic\WooCommerce\Blocks\Domain\Services\FeatureGating;
@ -20,7 +20,9 @@ use Automattic\WooCommerce\Blocks\Domain\Services\CreateAccount as TestedCreateA
*
* @since $VID:$
*/
class CreateAccount extends WP_UnitTestCase {
class CreateAccount extends \WP_UnitTestCase {
use ExpectException;
private function get_test_instance() {
return new TestedCreateAccount( new NewPackage( 'test', './', new FeatureGating( 2 ) ) );
}

View File

@ -2,7 +2,7 @@
namespace Automattic\WooCommerce\Blocks\Tests\Library;
use PHPUnit\Framework\TestCase;
use Yoast\PHPUnitPolyfills\TestCases\TestCase;
use \WC_Order;
use Automattic\WooCommerce\Blocks\Domain\Services\DraftOrders;
use Automattic\WooCommerce\Blocks\Domain\Services\FeatureGating;

View File

@ -3,6 +3,7 @@
namespace Automattic\WooCommerce\Blocks\Tests\Library;
use Yoast\PHPUnitPolyfills\TestCases\TestCase;
use Automattic\WooCommerce\Blocks\Domain\Services\ExtendRestApi;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\CurrencyFormatter;
@ -10,7 +11,6 @@ use Automattic\WooCommerce\Blocks\StoreApi\Formatters\HtmlFormatter;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\MoneyFormatter;
use Automattic\WooCommerce\Blocks\StoreApi\Routes\RouteException;
use Exception;
use PHPUnit\Framework\TestCase;
use Automattic\WooCommerce\Blocks\Domain\Services\FeatureGating;
use Automattic\WooCommerce\Blocks\Domain\Package as DomainPackage;

View File

@ -0,0 +1,276 @@
<?php
/**
* Helper used to create fixture data for tests.
*/
namespace Automattic\WooCommerce\Blocks\Tests\Helpers;
/**
* FixtureData class.
*/
class FixtureData {
/**
* Create a simple product and return the result.
*
* @param array $props Product props.
* @return \WC_Product
*/
public function get_simple_product( $props ) {
$product = new \WC_Product_Simple();
$product->set_props(
wp_parse_args(
$props,
[
'name' => 'Simple Product',
]
)
);
$product->save();
return wc_get_product( $product->get_id() );
}
/**
* Create a variable product and return the result.
*
* @param array $props Product props.
* @param array $attributes Product attributes from which to create variations.
* @return \WC_Product
*/
public function get_variable_product( $props, $attributes = [] ) {
$product = new \WC_Product_Variable();
$product->set_props(
wp_parse_args(
$props,
[
'name' => 'Variable Product',
]
)
);
$product->save();
if ( $attributes ) {
$product_attributes = [];
foreach ( $attributes as $attribute ) {
$product_attribute = new \WC_Product_Attribute();
$product_attribute->set_id( $attribute['attribute_id'] );
$product_attribute->set_name( $attribute['attribute_taxonomy'] );
$product_attribute->set_options( $attribute['term_ids'] );
$product_attribute->set_position( 1 );
$product_attribute->set_visible( true );
$product_attribute->set_variation( true );
$product_attributes[] = $product_attribute;
}
$product->set_attributes( $product_attributes );
$product->save();
}
return wc_get_product( $product->get_id() );
}
/**
* Create and return a variation of a product.
*
* @param integer $parent_id Parent product ID.
* @param array $attributes Variation attributes.
* @param array $props Product props.
* @return \WC_Product_Variation
*/
public function get_variation_product( $parent_id, $attributes = [], $props = [] ) {
$variation = new \WC_Product_Variation();
$variation->set_props(
array_merge(
wp_parse_args(
$props,
[
'name' => 'Variation of ' . $parent_id,
'regular_price' => '10',
]
),
array(
'parent_id' => $parent_id,
)
)
);
$variation->set_attributes( $attributes );
$variation->save();
return wc_get_product( $variation->get_id() );
}
/**
* Create a product attribute.
*
* @param string $raw_name Name of attribute to create.
* @param array $terms Terms to create for the attribute.
* @return array Attribute data and created terms.
*/
public static function get_product_attribute( $raw_name = 'size', $terms = array( 'small' ) ) {
global $wpdb, $wc_product_attributes;
// Make sure caches are clean.
delete_transient( 'wc_attribute_taxonomies' );
\WC_Cache_Helper::invalidate_cache_group( 'woocommerce-attributes' );
// These are exported as labels, so convert the label to a name if possible first.
$attribute_labels = wp_list_pluck( wc_get_attribute_taxonomies(), 'attribute_label', 'attribute_name' );
$attribute_name = array_search( $raw_name, $attribute_labels, true );
if ( ! $attribute_name ) {
$attribute_name = wc_sanitize_taxonomy_name( $raw_name );
}
$attribute_id = wc_attribute_taxonomy_id_by_name( $attribute_name );
if ( ! $attribute_id ) {
$taxonomy_name = wc_attribute_taxonomy_name( $attribute_name );
// Unregister taxonomy which other tests may have created...
unregister_taxonomy( $taxonomy_name );
$attribute_id = wc_create_attribute(
array(
'name' => $raw_name,
'slug' => $attribute_name,
'type' => 'select',
'order_by' => 'menu_order',
'has_archives' => 0,
)
);
// Register as taxonomy.
register_taxonomy(
$taxonomy_name,
apply_filters( 'woocommerce_taxonomy_objects_' . $taxonomy_name, array( 'product' ) ),
apply_filters(
'woocommerce_taxonomy_args_' . $taxonomy_name,
array(
'labels' => array(
'name' => $raw_name,
),
'hierarchical' => false,
'show_ui' => false,
'query_var' => true,
'rewrite' => false,
)
)
);
// Set product attributes global.
$wc_product_attributes = array();
foreach ( wc_get_attribute_taxonomies() as $taxonomy ) {
$wc_product_attributes[ wc_attribute_taxonomy_name( $taxonomy->attribute_name ) ] = $taxonomy;
}
}
$attribute = wc_get_attribute( $attribute_id );
$return = array(
'attribute_name' => $attribute->name,
'attribute_taxonomy' => $attribute->slug,
'attribute_id' => $attribute_id,
'term_ids' => array(),
);
foreach ( $terms as $term ) {
$result = term_exists( $term, $attribute->slug );
if ( ! $result ) {
$result = wp_insert_term(
$term,
$attribute->slug,
[
'slug' => $term . '-slug',
'description' => 'Description of ' . $term,
]
);
$return['term_ids'][] = $result['term_id'];
} else {
$return['term_ids'][] = $result['term_id'];
}
}
return $return;
}
/**
* Create a coupon and return the result.
*
* @param array $props Product props.
* @return \WC_Coupon
*/
public function get_coupon( $props ) {
$coupon = new \WC_Coupon();
$coupon->set_props( $props );
$coupon->save();
return new \WC_Coupon( $coupon->get_id() );
}
/**
* Upload a sample image and return it's ID.
*
* @param integer $product_id
* @return void
*/
public function sideload_image( $product_id = 0 ) {
global $wpdb;
$image_url = media_sideload_image( 'http://cldup.com/Dr1Bczxq4q.png', $product_id, '', 'src' );
return $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE guid = %s", $image_url ) )[0];
}
/**
* Add a review to a product and flush cache.
*
* @param integer $product_id Product ID.
* @param integer $rating Review rating.
* @param string $content Review content.
* @param array $props Review props.
* @return void
*/
public function add_product_review( $product_id, $rating = 5, $content = 'Product review.', $props = [] ) {
wp_insert_comment(
array_merge(
wp_parse_args(
$props,
[
'comment_author' => 'admin',
'comment_author_email' => 'woo@woo.local',
'comment_author_url' => '',
'comment_approved' => 1,
'comment_type' => 'review',
]
),
[
'comment_post_ID' => $product_id,
'comment_content' => $content,
'comment_meta' => [
'rating' => $rating,
],
]
)
);
\WC_Comments::clear_transients( $product_id );
}
/**
* Create a simple flat rate at the cost of 10.
*
* @param float $cost Optional. Cost of flat rate method.
*/
public function shipping_add_flat_rate( $cost = 10 ) {
$flat_rate_settings = array(
'enabled' => 'yes',
'title' => 'Flat rate',
'availability' => 'all',
'countries' => '',
'tax_status' => 'taxable',
'cost' => $cost,
);
update_option( 'woocommerce_flat_rate_settings', $flat_rate_settings );
update_option( 'woocommerce_flat_rate', array() );
\WC_Cache_Helper::get_transient_version( 'shipping', true );
WC()->shipping()->load_shipping_methods();
}
}

View File

@ -7,12 +7,10 @@ namespace Automattic\WooCommerce\Blocks\Tests\Helpers;
require_once 'ValidateSchema.php';
use \WC_REST_Unit_Test_Case as TestCase;
/**
* Test Validate schema.
*/
class TestValidateSchema extends TestCase {
class TestValidateSchema extends \WP_UnitTestCase {
/**
* ValidateSchema instance.
*

View File

@ -5,7 +5,7 @@ namespace Automattic\WooCommerce\Blocks\Tests\Registry;
use Automattic\WooCommerce\Blocks\Registry\Container as ContainerTest;
use Automattic\WooCommerce\Blocks\Registry\FactoryType;
use Automattic\WooCommerce\Blocks\Tests\Mocks\MockTestDependency;
use PHPUnit\Framework\TestCase;
use Yoast\PHPUnitPolyfills\TestCases\TestCase;
/**
* Tests the Container functionality

View File

@ -5,13 +5,12 @@
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Formatters;
use \WC_REST_Unit_Test_Case as TestCase;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\CurrencyFormatter;
/**
* TestCurrencyFormatter tests.
*/
class TestCurrencyFormatter extends TestCase {
class TestCurrencyFormatter extends \WP_UnitTestCase {
private $mock_formatter;

View File

@ -5,7 +5,6 @@
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Formatters;
use \WC_REST_Unit_Test_Case as TestCase;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\MoneyFormatter;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\HtmlFormatter;
@ -15,7 +14,7 @@ use Automattic\WooCommerce\Blocks\StoreApi\Formatters\CurrencyFormatter;
/**
* TestFormatters tests.
*/
class TestFormatters extends TestCase {
class TestFormatters extends \WP_UnitTestCase {
private $mock_formatters;

View File

@ -5,13 +5,12 @@
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Formatters;
use \WC_REST_Unit_Test_Case as TestCase;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\HtmlFormatter;
/**
* TestHtmlFormatter tests.
*/
class TestHtmlFormatter extends TestCase {
class TestHtmlFormatter extends \WP_UnitTestCase {
private $mock_formatter;

View File

@ -5,13 +5,12 @@
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Formatters;
use \WC_REST_Unit_Test_Case as TestCase;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\MoneyFormatter;
/**
* TestMoneyFormatter tests.
*/
class TestMoneyFormatter extends TestCase {
class TestMoneyFormatter extends \WP_UnitTestCase {
private $mock_formatter;

View File

@ -3,29 +3,15 @@
* Controller Tests.
*/
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Controllers;
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes;
use \WP_REST_Request;
use \WC_REST_Unit_Test_Case as TestCase;
use \WC_Helper_Product as ProductHelper;
use \WC_Helper_Coupon as CouponHelper;
use \WC_Helper_Shipping;
use Automattic\WooCommerce\Blocks\Domain\Services\ExtendRestApi;
use Automattic\WooCommerce\Blocks\Package;
use Automattic\WooCommerce\Blocks\Domain\Package as DomainPackage;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\MoneyFormatter;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\HtmlFormatter;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\CurrencyFormatter;
use Automattic\WooCommerce\Blocks\Registry\Container;
use Automattic\WooCommerce\Blocks\Domain\Services\FeatureGating;
use Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes\ControllerTestCase;
use Automattic\WooCommerce\Blocks\Tests\Helpers\FixtureData;
/**
* Batch Controller Tests.
*/
class Batch extends TestCase {
private $mock_extend;
class Batch extends ControllerTestCase {
/**
* Setup test products data. Called before every test.
@ -33,38 +19,25 @@ class Batch extends TestCase {
public function setUp() {
parent::setUp();
wp_set_current_user( 0 );
update_option( 'woocommerce_weight_unit', 'g' );
$fixtures = new FixtureData();
$this->products = [];
$formatters = new Formatters();
$formatters->register( 'money', MoneyFormatter::class );
$formatters->register( 'html', HtmlFormatter::class );
$formatters->register( 'currency', CurrencyFormatter::class );
$this->mock_extend = new ExtendRestApi( new DomainPackage( '', '', new FeatureGating( 2 ) ), $formatters );
// Create some test products.
$this->products[0] = ProductHelper::create_simple_product( false );
$this->products[0]->set_weight( 10 );
$this->products[0]->set_regular_price( 10 );
$this->products[0]->save();
$this->products[1] = ProductHelper::create_simple_product( false );
$this->products[1]->set_weight( 10 );
$this->products[1]->set_regular_price( 10 );
$this->products[1]->save();
$this->coupon = CouponHelper::create_coupon();
WC_Helper_Shipping::create_simple_flat_rate();
wc_empty_cart();
$this->products = [
$fixtures->get_simple_product( [
'name' => 'Test Product 1',
'regular_price' => 10,
] ),
$fixtures->get_simple_product( [
'name' => 'Test Product 2',
'regular_price' => 10,
] ),
];
}
/**
* Test route registration.
*/
public function test_register_routes() {
$routes = $this->server->get_routes();
$routes = rest_get_server()->get_routes();
$this->assertArrayHasKey( '/wc/store/batch', $routes );
}
@ -72,7 +45,7 @@ class Batch extends TestCase {
* Test that a batch of requests are successful.
*/
public function test_success_cart_route_batch() {
$request = new WP_REST_Request( 'POST', '/wc/store/batch' );
$request = new \WP_REST_Request( 'POST', '/wc/store/batch' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$request->set_body_params(
array(
@ -102,7 +75,7 @@ class Batch extends TestCase {
),
)
);
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$response_data = $response->get_data();
// Assert that there were 2 successful results from the batch.
@ -115,7 +88,7 @@ class Batch extends TestCase {
* Test for a mixture of successful and non-successful requests in a batch.
*/
public function test_mix_cart_route_batch() {
$request = new WP_REST_Request( 'POST', '/wc/store/batch' );
$request = new \WP_REST_Request( 'POST', '/wc/store/batch' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$request->set_body_params(
array(
@ -145,7 +118,7 @@ class Batch extends TestCase {
),
)
);
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$response_data = $response->get_data();
$this->assertEquals( 2, count( $response_data['responses'] ) );
@ -157,7 +130,7 @@ class Batch extends TestCase {
* Get Requests not supported by batch.
*/
public function test_get_cart_route_batch() {
$request = new WP_REST_Request( 'POST', '/wc/store/batch' );
$request = new \WP_REST_Request( 'POST', '/wc/store/batch' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$request->set_body_params(
array(
@ -173,7 +146,7 @@ class Batch extends TestCase {
),
)
);
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$response_data = $response->get_data();
$this->assertEquals( 'rest_invalid_param', $response_data['code'], print_r( $response_data, true ) );

View File

@ -3,30 +3,16 @@
* Controller Tests.
*/
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Controllers;
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes;
use \WP_REST_Request;
use \WC_REST_Unit_Test_Case as TestCase;
use \WC_Helper_Product as ProductHelper;
use \WC_Helper_Coupon as CouponHelper;
use \WC_Helper_Shipping;
use Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes\ControllerTestCase;
use Automattic\WooCommerce\Blocks\Tests\Helpers\FixtureData;
use Automattic\WooCommerce\Blocks\Tests\Helpers\ValidateSchema;
use Automattic\WooCommerce\Blocks\Domain\Services\ExtendRestApi;
use Automattic\WooCommerce\Blocks\Package;
use Automattic\WooCommerce\Blocks\Domain\Package as DomainPackage;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\MoneyFormatter;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\HtmlFormatter;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\CurrencyFormatter;
use Automattic\WooCommerce\Blocks\Registry\Container;
use Automattic\WooCommerce\Blocks\Domain\Services\FeatureGating;
/**
* Cart Controller Tests.
*/
class Cart extends TestCase {
private $mock_extend;
class Cart extends ControllerTestCase {
/**
* Setup test products data. Called before every test.
@ -34,46 +20,44 @@ class Cart extends TestCase {
public function setUp() {
parent::setUp();
wp_set_current_user( 0 );
$fixtures = new FixtureData();
$fixtures->shipping_add_flat_rate();
update_option( 'woocommerce_weight_unit', 'g' );
$this->products = [
$fixtures->get_simple_product( [
'name' => 'Test Product 1',
'stock_status' => 'instock',
'regular_price' => 10,
'weight' => 10,
] ),
$fixtures->get_simple_product( [
'name' => 'Test Product 2',
'stock_status' => 'instock',
'regular_price' => 10,
'weight' => 10,
] ),
];
$this->products = [];
$formatters = new Formatters();
$formatters->register( 'money', MoneyFormatter::class );
$formatters->register( 'html', HtmlFormatter::class );
$formatters->register( 'currency', CurrencyFormatter::class );
$this->mock_extend = new ExtendRestApi( new DomainPackage( '', '', new FeatureGating( 2 ) ), $formatters );
// Create some test products.
$this->products[0] = ProductHelper::create_simple_product( false );
$this->products[0]->set_weight( 10 );
$this->products[0]->set_regular_price( 10 );
$this->products[0]->save();
$this->products[1] = ProductHelper::create_simple_product( false );
$this->products[1]->set_weight( 10 );
$this->products[1]->set_regular_price( 10 );
$this->products[1]->save();
$this->coupon = CouponHelper::create_coupon();
$this->coupon = $fixtures->get_coupon(
[
'code' => 'test_coupon',
'discount_type' => 'fixed_cart',
'amount' => 1
]
);
wc_empty_cart();
$this->keys = [];
$this->keys[] = wc()->cart->add_to_cart( $this->products[0]->get_id(), 2 );
$this->keys[] = wc()->cart->add_to_cart( $this->products[1]->get_id(), 1 );
wc()->cart->apply_coupon( $this->coupon->get_code() );
WC_Helper_Shipping::create_simple_flat_rate();
}
/**
* Test route registration.
*/
public function test_register_routes() {
$routes = $this->server->get_routes();
$routes = rest_get_server()->get_routes();
$this->assertArrayHasKey( '/wc/store/cart', $routes );
$this->assertArrayHasKey( '/wc/store/cart/apply-coupon', $routes );
$this->assertArrayHasKey( '/wc/store/cart/remove-coupon', $routes );
@ -85,7 +69,7 @@ class Cart extends TestCase {
* Test getting cart.
*/
public function test_get_item() {
$response = $this->server->dispatch( new WP_REST_Request( 'GET', '/wc/store/cart' ) );
$response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc/store/cart' ) );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
@ -114,14 +98,14 @@ class Cart extends TestCase {
*/
public function test_remove_bad_cart_item() {
// Test removing a bad cart item - should return 404.
$request = new WP_REST_Request( 'POST', '/wc/store/cart/remove-item' );
$request = new \WP_REST_Request( 'POST', '/wc/store/cart/remove-item' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$request->set_body_params(
array(
'key' => 'bad_item_key_123',
)
);
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 409, $response->get_status() );
@ -133,14 +117,14 @@ class Cart extends TestCase {
*/
public function test_remove_cart_item() {
// Test removing a valid cart item - should return updated cart.
$request = new WP_REST_Request( 'POST', '/wc/store/cart/remove-item' );
$request = new \WP_REST_Request( 'POST', '/wc/store/cart/remove-item' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$request->set_body_params(
array(
'key' => $this->keys[0],
)
);
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
@ -150,7 +134,7 @@ class Cart extends TestCase {
$this->assertEquals( '1000', $data['totals']->total_items );
// Test removing same item again - should return 404 (item is already removed).
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 409, $response->get_status() );
@ -161,7 +145,7 @@ class Cart extends TestCase {
* Test changing the quantity of a cart item.
*/
public function test_update_item() {
$request = new WP_REST_Request( 'POST', '/wc/store/cart/update-item' );
$request = new \WP_REST_Request( 'POST', '/wc/store/cart/update-item' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$request->set_body_params(
array(
@ -169,7 +153,7 @@ class Cart extends TestCase {
'quantity' => 10,
)
);
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
@ -182,7 +166,7 @@ class Cart extends TestCase {
* Test getting updated shipping.
*/
public function test_update_customer() {
$request = new WP_REST_Request( 'POST', '/wc/store/cart/update-customer' );
$request = new \WP_REST_Request( 'POST', '/wc/store/cart/update-customer' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$request->set_body_params(
array(
@ -191,7 +175,7 @@ class Cart extends TestCase {
)
)
);
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status(), print_r( $response, true ) );
@ -210,7 +194,7 @@ class Cart extends TestCase {
*/
public function test_update_customer_address() {
// US address.
$request = new WP_REST_Request( 'POST', '/wc/store/cart/update-customer' );
$request = new \WP_REST_Request( 'POST', '/wc/store/cart/update-customer' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$request->set_body_params(
array(
@ -226,7 +210,7 @@ class Cart extends TestCase {
)
)
);
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
@ -238,7 +222,7 @@ class Cart extends TestCase {
$this->assertEquals( 'US', $data['shipping_rates'][0]['destination']->country );
// Address with invalid country.
$request = new WP_REST_Request( 'POST', '/wc/store/cart/update-customer' );
$request = new \WP_REST_Request( 'POST', '/wc/store/cart/update-customer' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$request->set_body_params(
array(
@ -254,13 +238,13 @@ class Cart extends TestCase {
)
)
);
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 400, $response->get_status() );
// US address with named state.
$request = new WP_REST_Request( 'POST', '/wc/store/cart/update-customer' );
$request = new \WP_REST_Request( 'POST', '/wc/store/cart/update-customer' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$request->set_body_params(
array(
@ -276,7 +260,7 @@ class Cart extends TestCase {
)
)
);
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
@ -284,7 +268,7 @@ class Cart extends TestCase {
$this->assertEquals( 'US', $data['shipping_rates'][0]['destination']->country );
// US address with invalid state.
$request = new WP_REST_Request( 'POST', '/wc/store/cart/update-customer' );
$request = new \WP_REST_Request( 'POST', '/wc/store/cart/update-customer' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$request->set_body_params(
array(
@ -300,13 +284,13 @@ class Cart extends TestCase {
)
)
);
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 400, $response->get_status() );
// US address with invalid postcode.
$request = new WP_REST_Request( 'POST', '/wc/store/cart/update-customer' );
$request = new \WP_REST_Request( 'POST', '/wc/store/cart/update-customer' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$request->set_body_params(
array(
@ -322,7 +306,7 @@ class Cart extends TestCase {
)
)
);
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 400, $response->get_status() );
@ -335,41 +319,43 @@ class Cart extends TestCase {
public function test_apply_coupon() {
wc()->cart->remove_coupon( $this->coupon->get_code() );
$request = new WP_REST_Request( 'POST', '/wc/store/cart/apply-coupon' );
$request = new \WP_REST_Request( 'POST', '/wc/store/cart/apply-coupon' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$request->set_body_params(
array(
'code' => $this->coupon->get_code(),
)
);
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
$this->assertEquals( '100', $data['totals']->total_discount );
$fixtures = new FixtureData();
// Test coupons with different case.
$newcoupon = CouponHelper::create_coupon( 'testCoupon' );
$request = new WP_REST_Request( 'POST', '/wc/store/cart/apply-coupon' );
$newcoupon = $fixtures->get_coupon( [ 'code' => 'testCoupon' ] );
$request = new \WP_REST_Request( 'POST', '/wc/store/cart/apply-coupon' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$request->set_body_params(
array(
'code' => 'testCoupon',
)
);
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
// Test coupons with special chars in the code.
$newcoupon = CouponHelper::create_coupon( '$5 off' );
$request = new WP_REST_Request( 'POST', '/wc/store/cart/apply-coupon' );
$newcoupon = $fixtures->get_coupon( [ 'code' => '$5 off' ] );
$request = new \WP_REST_Request( 'POST', '/wc/store/cart/apply-coupon' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$request->set_body_params(
array(
'code' => '$5 off',
)
);
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
}
@ -379,26 +365,26 @@ class Cart extends TestCase {
*/
public function test_remove_coupon() {
// Invalid coupon.
$request = new WP_REST_Request( 'POST', '/wc/store/cart/remove-coupon' );
$request = new \WP_REST_Request( 'POST', '/wc/store/cart/remove-coupon' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$request->set_body_params(
array(
'code' => 'doesnotexist',
)
);
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 400, $response->get_status() );
// Applied coupon.
$request = new WP_REST_Request( 'POST', '/wc/store/cart/remove-coupon' );
$request = new \WP_REST_Request( 'POST', '/wc/store/cart/remove-coupon' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$request->set_body_params(
array(
'code' => $this->coupon->get_code(),
)
);
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
$this->assertEquals( '0', $data['totals']->total_discount );
@ -407,7 +393,7 @@ class Cart extends TestCase {
/**
* Test conversion of cart item to rest response.
*/
public function test_prepare_item_for_response() {
public function test_prepare_item() {
$routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController( $this->mock_extend ) );
$controller = $routes->get( 'cart' );
$cart = wc()->cart;
@ -427,7 +413,7 @@ class Cart extends TestCase {
/**
* Test schema matches responses.
*/
public function test_schema_matches_response() {
public function test_get_item_schema() {
$routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController( $this->mock_extend ) );
$controller = $routes->get( 'cart' );
$schema = $controller->get_item_schema();

View File

@ -3,29 +3,16 @@
* Controller Tests.
*/
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Controllers;
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes;
use \WP_REST_Request;
use \WC_REST_Unit_Test_Case as TestCase;
use \WC_Helper_Product as ProductHelper;
use \WC_Helper_Coupon as CouponHelper;
use Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes\ControllerTestCase;
use Automattic\WooCommerce\Blocks\Tests\Helpers\FixtureData;
use Automattic\WooCommerce\Blocks\Tests\Helpers\ValidateSchema;
use Automattic\WooCommerce\Blocks\Domain\Services\ExtendRestApi;
use Automattic\WooCommerce\Blocks\Package;
use Automattic\WooCommerce\Blocks\Domain\Package as DomainPackage;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\MoneyFormatter;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\HtmlFormatter;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\CurrencyFormatter;
use Automattic\WooCommerce\Blocks\Registry\Container;
use Automattic\WooCommerce\Blocks\Domain\Services\FeatureGating;
/**
* Cart Coupons Controller Tests.
*/
class CartCoupons extends TestCase {
private $mock_extend;
class CartCoupons extends ControllerTestCase {
/**
* Setup test products data. Called before every test.
@ -33,15 +20,13 @@ class CartCoupons extends TestCase {
public function setUp() {
parent::setUp();
wp_set_current_user( 0 );
$fixtures = new FixtureData();
$formatters = new Formatters();
$formatters->register( 'money', MoneyFormatter::class );
$formatters->register( 'html', HtmlFormatter::class );
$formatters->register( 'currency', CurrencyFormatter::class );
$this->mock_extend = new ExtendRestApi( new DomainPackage( '', '', new FeatureGating( 2 ) ), $formatters );
$this->product = ProductHelper::create_simple_product( false );
$this->coupon = CouponHelper::create_coupon();
$this->product = $fixtures->get_simple_product( [
'name' => 'Test Product 1',
'regular_price' => 10,
] );
$this->coupon = $fixtures->get_coupon( ['code' => 'test_coupon'] );
wc_empty_cart();
@ -53,7 +38,7 @@ class CartCoupons extends TestCase {
* Test route registration.
*/
public function test_register_routes() {
$routes = $this->server->get_routes();
$routes = rest_get_server()->get_routes();
$this->assertArrayHasKey( '/wc/store/cart/coupons', $routes );
$this->assertArrayHasKey( '/wc/store/cart/coupons/(?P<code>[\w-]+)', $routes );
}
@ -62,7 +47,7 @@ class CartCoupons extends TestCase {
* Test getting cart.
*/
public function test_get_items() {
$response = $this->server->dispatch( new WP_REST_Request( 'GET', '/wc/store/cart/coupons' ) );
$response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc/store/cart/coupons' ) );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
@ -73,7 +58,7 @@ class CartCoupons extends TestCase {
* Test getting cart item by key.
*/
public function test_get_item() {
$response = $this->server->dispatch( new WP_REST_Request( 'GET', '/wc/store/cart/coupons/' . $this->coupon->get_code() ) );
$response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc/store/cart/coupons/' . $this->coupon->get_code() ) );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
@ -88,14 +73,14 @@ class CartCoupons extends TestCase {
public function test_create_item() {
wc()->cart->remove_coupons();
$request = new WP_REST_Request( 'POST', '/wc/store/cart/coupons' );
$request = new \WP_REST_Request( 'POST', '/wc/store/cart/coupons' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$request->set_body_params(
array(
'code' => $this->coupon->get_code(),
)
);
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 201, $response->get_status() );
@ -108,14 +93,14 @@ class CartCoupons extends TestCase {
public function test_invalid_create_item() {
wc()->cart->remove_coupons();
$request = new WP_REST_Request( 'POST', '/wc/store/cart/coupons' );
$request = new \WP_REST_Request( 'POST', '/wc/store/cart/coupons' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$request->set_body_params(
array(
'code' => 'IDONOTEXIST',
)
);
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 400, $response->get_status() );
@ -125,24 +110,24 @@ class CartCoupons extends TestCase {
* Test delete item.
*/
public function test_delete_item() {
$request = new WP_REST_Request( 'DELETE', '/wc/store/cart/coupons/' . $this->coupon->get_code() );
$request = new \WP_REST_Request( 'DELETE', '/wc/store/cart/coupons/' . $this->coupon->get_code() );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 204, $response->get_status() );
$this->assertEmpty( $data );
$request = new WP_REST_Request( 'DELETE', '/wc/store/cart/coupons/' . $this->coupon->get_code() );
$request = new \WP_REST_Request( 'DELETE', '/wc/store/cart/coupons/' . $this->coupon->get_code() );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 404, $response->get_status() );
$request = new WP_REST_Request( 'DELETE', '/wc/store/cart/coupons/i-do-not-exist' );
$request = new \WP_REST_Request( 'DELETE', '/wc/store/cart/coupons/i-do-not-exist' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 404, $response->get_status() );
@ -152,15 +137,15 @@ class CartCoupons extends TestCase {
* Test delete all items.
*/
public function test_delete_items() {
$request = new WP_REST_Request( 'DELETE', '/wc/store/cart/coupons' );
$request = new \WP_REST_Request( 'DELETE', '/wc/store/cart/coupons' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
$this->assertEquals( [], $data );
$response = $this->server->dispatch( new WP_REST_Request( 'GET', '/wc/store/cart/coupons' ) );
$response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc/store/cart/coupons' ) );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
@ -170,7 +155,7 @@ class CartCoupons extends TestCase {
/**
* Test conversion of cart item to rest response.
*/
public function test_prepare_item_for_response() {
public function test_prepare_item() {
$routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController( $this->mock_extend ) );
$controller = $routes->get( 'cart-coupons' );
@ -184,7 +169,7 @@ class CartCoupons extends TestCase {
/**
* Test schema matches responses.
*/
public function test_schema_matches_response() {
public function test_get_item_schema() {
$routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController( $this->mock_extend ) );
$controller = $routes->get( 'cart-coupons' );
$schema = $controller->get_item_schema();

View File

@ -3,78 +3,22 @@
* Cart extensions route tests.
*/
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Controllers;
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes;
use Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes\ControllerTestCase;
use Automattic\WooCommerce\Blocks\StoreApi\Routes\RouteException;
use \WP_REST_Request;
use \WC_REST_Unit_Test_Case as TestCase;
use \WC_Helper_Product as ProductHelper;
use \WC_Helper_Coupon as CouponHelper;
use \WC_Helper_Shipping;
use Automattic\WooCommerce\Blocks\Tests\Helpers\ValidateSchema;
use Automattic\WooCommerce\Blocks\Domain\Services\ExtendRestApi;
use Automattic\WooCommerce\Blocks\Package;
use Automattic\WooCommerce\Blocks\Domain\Package as DomainPackage;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\MoneyFormatter;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\HtmlFormatter;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\CurrencyFormatter;
use Automattic\WooCommerce\Blocks\Registry\Container;
use Automattic\WooCommerce\Blocks\Domain\Services\FeatureGating;
/**
* Cart Controller Tests.
*/
class CartExtensions extends TestCase {
private $mock_extend;
/**
* Setup test products data. Called before every test.
*/
public function setUp() {
parent::setUp();
wp_set_current_user( 0 );
update_option( 'woocommerce_weight_unit', 'g' );
$this->products = [];
$formatters = new Formatters();
$formatters->register( 'money', MoneyFormatter::class );
$formatters->register( 'html', HtmlFormatter::class );
$formatters->register( 'currency', CurrencyFormatter::class );
$this->mock_extend = new ExtendRestApi( new DomainPackage( '', '', new FeatureGating( 2 ) ), $formatters );
// Create some test products.
$this->products[0] = ProductHelper::create_simple_product( false );
$this->products[0]->set_weight( 10 );
$this->products[0]->set_regular_price( 10 );
$this->products[0]->save();
$this->products[1] = ProductHelper::create_simple_product( false );
$this->products[1]->set_weight( 10 );
$this->products[1]->set_regular_price( 10 );
$this->products[1]->save();
$this->coupon = CouponHelper::create_coupon();
wc_empty_cart();
$this->keys = [];
$this->keys[] = wc()->cart->add_to_cart( $this->products[0]->get_id(), 2 );
$this->keys[] = wc()->cart->add_to_cart( $this->products[1]->get_id(), 1 );
wc()->cart->apply_coupon( $this->coupon->get_code() );
WC_Helper_Shipping::create_simple_flat_rate();
}
class CartExtensions extends ControllerTestCase {
/**
* Test route registration.
*/
public function test_register_routes() {
$routes = $this->server->get_routes();
$routes = rest_get_server()->get_routes();
$this->assertArrayHasKey( '/wc/store/cart/extensions', $routes );
}
@ -82,14 +26,14 @@ class CartExtensions extends TestCase {
* Test getting cart with invalid namespace.
*/
public function test_post() {
$request = new WP_REST_Request( 'POST', '/wc/store/cart/extensions' );
$request = new \WP_REST_Request( 'POST', '/wc/store/cart/extensions' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$request->set_body_params(
array(
'namespace' => 'test-plugin',
)
);
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$this->assertEquals( 400, $response->get_status() );
}
}

View File

@ -3,77 +3,62 @@
* Controller Tests.
*/
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Controllers;
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes;
use \WP_REST_Request;
use \WC_REST_Unit_Test_Case as TestCase;
use \WC_Helper_Product as ProductHelper;
use Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes\ControllerTestCase;
use Automattic\WooCommerce\Blocks\Tests\Helpers\FixtureData;
use Automattic\WooCommerce\Blocks\Tests\Helpers\ValidateSchema;
use Automattic\WooCommerce\Blocks\Domain\Services\ExtendRestApi;
use Automattic\WooCommerce\Blocks\Package;
use Automattic\WooCommerce\Blocks\Domain\Package as DomainPackage;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\MoneyFormatter;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\HtmlFormatter;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\CurrencyFormatter;
use Automattic\WooCommerce\Blocks\Registry\Container;
use Automattic\WooCommerce\Blocks\Domain\Services\FeatureGating;
/**
* Cart Controller Tests.
*/
class CartItems extends TestCase {
private $mock_extend;
class CartItems extends ControllerTestCase {
/**
* Setup test products data. Called before every test.
*/
public function setUp() {
global $wpdb;
parent::setUp();
$formatters = new Formatters();
$formatters->register( 'money', MoneyFormatter::class );
$formatters->register( 'html', HtmlFormatter::class );
$formatters->register( 'currency', CurrencyFormatter::class );
$this->mock_extend = new ExtendRestApi( new DomainPackage( '', '', new FeatureGating( 2 ) ), $formatters );
$fixtures = new FixtureData();
wp_set_current_user( 0 );
$this->products = [
$fixtures->get_simple_product( [
'name' => 'Test Product 1',
'stock_status' => 'instock',
'regular_price' => 10,
'weight' => 10,
'image_id' => $fixtures->sideload_image(),
] ),
];
update_option( 'woocommerce_weight_unit', 'g' );
$variable_product = $fixtures->get_variable_product(
[
'name' => 'Test Product 2',
'stock_status' => 'instock',
'regular_price' => 10,
'weight' => 10,
'image_id' => $fixtures->sideload_image(),
],
[
$fixtures->get_product_attribute( 'color', [ 'red', 'green', 'blue' ] ),
$fixtures->get_product_attribute( 'size', [ 'small', 'medium', 'large' ] )
]
);
$variation = $fixtures->get_variation_product( $variable_product->get_id(), [ 'pa_color' => 'red', 'pa_size' => 'small' ] );
$this->products = [];
// Create a test simple product.
$this->products[0] = ProductHelper::create_simple_product( false );
$this->products[0]->set_weight( 10 );
$this->products[0]->set_regular_price( 10 );
$this->products[0]->save();
$image_url = media_sideload_image( 'http://cldup.com/Dr1Bczxq4q.png', $this->products[0]->get_id(), '', 'src' );
$image_id = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE guid = %s", $image_url ) );
$this->products[0]->set_image_id( $image_id[0] );
$this->products[0]->save();
// Create a test variable product.
$this->products[1] = ProductHelper::create_variation_product();
$this->products[1]->set_weight( 10 );
$this->products[1]->set_regular_price( 10 );
$this->products[1]->save();
$this->products[] = $variable_product;
wc_empty_cart();
$this->keys = [];
$this->keys[] = wc()->cart->add_to_cart( $this->products[0]->get_id(), 2 );
$this->keys[] = wc()->cart->add_to_cart(
$this->products[1]->get_id(),
1,
current( $this->products[1]->get_children() ),
$variation->get_id(),
array(
'attribute_pa_colour' => 'red',
'attribute_pa_number' => '2',
'attribute_pa_color' => 'red',
'attribute_pa_size' => 'small',
)
);
}
@ -82,7 +67,7 @@ class CartItems extends TestCase {
* Test route registration.
*/
public function test_register_routes() {
$routes = $this->server->get_routes();
$routes = rest_get_server()->get_routes();
$this->assertArrayHasKey( '/wc/store/cart/items', $routes );
$this->assertArrayHasKey( '/wc/store/cart/items/(?P<key>[\w-]{32})', $routes );
}
@ -91,7 +76,7 @@ class CartItems extends TestCase {
* Test getting cart.
*/
public function test_get_items() {
$response = $this->server->dispatch( new WP_REST_Request( 'GET', '/wc/store/cart/items' ) );
$response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc/store/cart/items' ) );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
@ -102,7 +87,7 @@ class CartItems extends TestCase {
* Test getting cart item by key.
*/
public function test_get_item() {
$response = $this->server->dispatch( new WP_REST_Request( 'GET', '/wc/store/cart/items/' . $this->keys[0] ) );
$response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc/store/cart/items/' . $this->keys[0] ) );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
@ -115,9 +100,9 @@ class CartItems extends TestCase {
$this->assertEquals( '2000', $data['totals']->line_subtotal );
$this->assertEquals( '2000', $data['totals']->line_total );
$request = new WP_REST_Request( 'DELETE', '/wc/store/cart/items/XXX815416f775098fe977004015c6193' );
$request = new \WP_REST_Request( 'DELETE', '/wc/store/cart/items/XXX815416f775098fe977004015c6193' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 404, $response->get_status() );
@ -129,7 +114,7 @@ class CartItems extends TestCase {
public function test_create_item() {
wc_empty_cart();
$request = new WP_REST_Request( 'POST', '/wc/store/cart/items' );
$request = new \WP_REST_Request( 'POST', '/wc/store/cart/items' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$request->set_body_params(
array(
@ -137,14 +122,14 @@ class CartItems extends TestCase {
'quantity' => '10',
)
);
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 201, $response->get_status() );
$this->assertEquals( $this->products[0]->get_id(), $data['id'] );
$this->assertEquals( 10, $data['quantity'] );
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 201, $response->get_status() );
@ -158,11 +143,13 @@ class CartItems extends TestCase {
public function test_invalid_create_item() {
wc_empty_cart();
$invalid_product = ProductHelper::create_simple_product( false );
$invalid_product->set_regular_price( '' );
$invalid_product->save();
$fixtures = new FixtureData();
$invalid_product = $fixtures->get_simple_product( [
'name' => 'Invalid Product',
'regular_price' => '',
] );
$request = new WP_REST_Request( 'POST', '/wc/store/cart/items' );
$request = new \WP_REST_Request( 'POST', '/wc/store/cart/items' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$request->set_body_params(
array(
@ -170,7 +157,7 @@ class CartItems extends TestCase {
'quantity' => '10',
)
);
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$this->assertEquals( 400, $response->get_status() );
}
@ -179,14 +166,14 @@ class CartItems extends TestCase {
* Test updating an item.
*/
public function test_update_item() {
$request = new WP_REST_Request( 'PUT', '/wc/store/cart/items/' . $this->keys[0] );
$request = new \WP_REST_Request( 'PUT', '/wc/store/cart/items/' . $this->keys[0] );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$request->set_body_params(
array(
'quantity' => '10',
)
);
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
@ -197,17 +184,17 @@ class CartItems extends TestCase {
* Test delete item.
*/
public function test_delete_item() {
$request = new WP_REST_Request( 'DELETE', '/wc/store/cart/items/' . $this->keys[0] );
$request = new \WP_REST_Request( 'DELETE', '/wc/store/cart/items/' . $this->keys[0] );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 204, $response->get_status() );
$this->assertEmpty( $data );
$request = new WP_REST_Request( 'DELETE', '/wc/store/cart/items/' . $this->keys[0] );
$request = new \WP_REST_Request( 'DELETE', '/wc/store/cart/items/' . $this->keys[0] );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 404, $response->get_status() );
@ -217,15 +204,15 @@ class CartItems extends TestCase {
* Test delete all items.
*/
public function test_delete_items() {
$request = new WP_REST_Request( 'DELETE', '/wc/store/cart/items' );
$request = new \WP_REST_Request( 'DELETE', '/wc/store/cart/items' );
$request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
$this->assertEquals( [], $data );
$response = $this->server->dispatch( new WP_REST_Request( 'GET', '/wc/store/cart/items' ) );
$response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc/store/cart/items' ) );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
@ -235,7 +222,7 @@ class CartItems extends TestCase {
/**
* Test conversion of cart item to rest response.
*/
public function test_prepare_item_for_response() {
public function test_prepare_item() {
$routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController( $this->mock_extend ) );
$controller = $routes->get( 'cart-items' );
$cart = wc()->cart->get_cart();
@ -264,7 +251,7 @@ class CartItems extends TestCase {
*
* Tests schema of both products in cart to cover as much schema as possible.
*/
public function test_schema_matches_response() {
public function test_get_item_schema() {
$routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController( $this->mock_extend ) );
$controller = $routes->get( 'cart-items' );
$schema = $controller->get_item_schema();

View File

@ -0,0 +1,49 @@
<?php
/**
* OrderController Tests.
*/
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes;
use Automattic\WooCommerce\Blocks\Domain\Services\ExtendRestApi;
use Automattic\WooCommerce\Blocks\Domain\Package as DomainPackage;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\MoneyFormatter;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\HtmlFormatter;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\CurrencyFormatter;
use Automattic\WooCommerce\Blocks\Domain\Services\FeatureGating;
abstract class ControllerTestCase extends \WP_Test_REST_TestCase {
protected $mock_extend;
/**
* Setup Rest API server.
*/
public function setUp() {
parent::setUp();
/** @var \WP_REST_Server $wp_rest_server */
global $wp_rest_server;
$wp_rest_server = new \Spy_REST_Server;
do_action( 'rest_api_init', $wp_rest_server );
wp_set_current_user( 0 );
update_option( 'woocommerce_weight_unit', 'g' );
$formatters = new Formatters();
$formatters->register( 'money', MoneyFormatter::class );
$formatters->register( 'html', HtmlFormatter::class );
$formatters->register( 'currency', CurrencyFormatter::class );
$this->mock_extend = new ExtendRestApi( new DomainPackage( '', '', new FeatureGating( 2 ) ), $formatters );
}
/**
* Tear down Rest API server.
*/
public function tearDown() {
parent::tearDown();
/** @var \WP_REST_Server $wp_rest_server */
global $wp_rest_server;
$wp_rest_server = null;
}
}

View File

@ -3,28 +3,16 @@
* Controller Tests.
*/
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Controllers;
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes;
use \WP_REST_Request;
use \WC_REST_Unit_Test_Case as TestCase;
use \WC_Helper_Product as ProductHelper;
use Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes\ControllerTestCase;
use Automattic\WooCommerce\Blocks\Tests\Helpers\FixtureData;
use Automattic\WooCommerce\Blocks\Tests\Helpers\ValidateSchema;
use Automattic\WooCommerce\Blocks\Domain\Services\ExtendRestApi;
use Automattic\WooCommerce\Blocks\Package;
use Automattic\WooCommerce\Blocks\Domain\Package as DomainPackage;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\MoneyFormatter;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\HtmlFormatter;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\CurrencyFormatter;
use Automattic\WooCommerce\Blocks\Registry\Container;
use Automattic\WooCommerce\Blocks\Domain\Services\FeatureGating;
/**
* Product Attributes Controller Tests.
*/
class ProductAttributeTerms extends TestCase {
private $mock_extend;
class ProductAttributeTerms extends ControllerTestCase {
/**
* Setup test products data. Called before every test.
@ -32,32 +20,19 @@ class ProductAttributeTerms extends TestCase {
public function setUp() {
parent::setUp();
wp_set_current_user( 0 );
$formatters = new Formatters();
$formatters->register( 'money', MoneyFormatter::class );
$formatters->register( 'html', HtmlFormatter::class );
$formatters->register( 'currency', CurrencyFormatter::class );
$this->mock_extend = new ExtendRestApi( new DomainPackage( '', '', new FeatureGating( 2 ) ), $formatters );
$fixtures = new FixtureData();
$this->attributes = [];
$this->attributes[0] = ProductHelper::create_attribute( 'color', [ 'red', 'green', 'blue' ] );
$this->attributes[1] = ProductHelper::create_attribute( 'size', [ 'small', 'medium', 'large' ] );
wp_insert_term(
'test',
'pa_size',
[
'description' => 'This is a test description',
'slug' => 'test-slug',
]
);
$this->attributes = [
$fixtures->get_product_attribute( 'color', [ 'red', 'green', 'blue' ] ),
$fixtures->get_product_attribute( 'size', [ 'small', 'medium', 'large' ] )
];
}
/**
* Test route registration.
*/
public function test_register_routes() {
$routes = $this->server->get_routes();
$routes = rest_get_server()->get_routes();
$this->assertArrayHasKey( '/wc/store/products/attributes/(?P<attribute_id>[\d]+)/terms', $routes );
}
@ -65,9 +40,9 @@ class ProductAttributeTerms extends TestCase {
* Test getting items.
*/
public function test_get_items() {
$request = new WP_REST_Request( 'GET', '/wc/store/products/attributes/' . $this->attributes[0]['attribute_id'] . '/terms' );
$request = new \WP_REST_Request( 'GET', '/wc/store/products/attributes/' . $this->attributes[0]['attribute_id'] . '/terms' );
$request->set_param( 'hide_empty', false );
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
@ -82,16 +57,16 @@ class ProductAttributeTerms extends TestCase {
/**
* Test conversion of product to rest response.
*/
public function test_prepare_item_for_response() {
public function test_prepare_item() {
$schema = new \Automattic\WooCommerce\Blocks\StoreApi\Schemas\TermSchema( $this->mock_extend );
$controller = new \Automattic\WooCommerce\Blocks\StoreApi\Routes\ProductAttributeTerms( $schema );
$response = $controller->prepare_item_for_response( get_term_by( 'name', 'test', 'pa_size' ), new \WP_REST_Request() );
$response = $controller->prepare_item_for_response( get_term_by( 'name', 'small', 'pa_size' ), new \WP_REST_Request() );
$data = $response->get_data();
$this->assertArrayHasKey( 'id', $data );
$this->assertEquals( 'test', $data['name'] );
$this->assertEquals( 'test-slug', $data['slug'] );
$this->assertEquals( 'This is a test description', $data['description'] );
$this->assertEquals( 'small', $data['name'] );
$this->assertEquals( 'small-slug', $data['slug'] );
$this->assertEquals( 'Description of small', $data['description'] );
$this->assertEquals( 0, $data['count'] );
}
@ -111,11 +86,11 @@ class ProductAttributeTerms extends TestCase {
/**
* Test schema matches responses.
*/
public function test_schema_matches_response() {
public function test_get_item_schema() {
$routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController( $this->mock_extend ) );
$controller = $routes->get( 'product-attribute-terms' );
$schema = $controller->get_item_schema();
$response = $controller->prepare_item_for_response( get_term_by( 'name', 'test', 'pa_size' ), new \WP_REST_Request() );
$response = $controller->prepare_item_for_response( get_term_by( 'name', 'small', 'pa_size' ), new \WP_REST_Request() );
$validate = new ValidateSchema( $schema );
$diff = $validate->get_diff_from_object( $response->get_data() );

View File

@ -3,28 +3,16 @@
* Controller Tests.
*/
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Controllers;
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes;
use \WP_REST_Request;
use \WC_REST_Unit_Test_Case as TestCase;
use \WC_Helper_Product as ProductHelper;
use Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes\ControllerTestCase;
use Automattic\WooCommerce\Blocks\Tests\Helpers\FixtureData;
use Automattic\WooCommerce\Blocks\Tests\Helpers\ValidateSchema;
use Automattic\WooCommerce\Blocks\Domain\Services\ExtendRestApi;
use Automattic\WooCommerce\Blocks\Package;
use Automattic\WooCommerce\Blocks\Domain\Package as DomainPackage;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\MoneyFormatter;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\HtmlFormatter;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\CurrencyFormatter;
use Automattic\WooCommerce\Blocks\Registry\Container;
use Automattic\WooCommerce\Blocks\Domain\Services\FeatureGating;
/**
* Product Attributes Controller Tests.
*/
class ProductAttributes extends TestCase {
private $mock_extend;
class ProductAttributes extends ControllerTestCase {
/**
* Setup test products data. Called before every test.
@ -32,26 +20,19 @@ class ProductAttributes extends TestCase {
public function setUp() {
parent::setUp();
wp_set_current_user( 0 );
$formatters = new Formatters();
$formatters->register( 'money', MoneyFormatter::class );
$formatters->register( 'html', HtmlFormatter::class );
$formatters->register( 'currency', CurrencyFormatter::class );
$this->mock_extend = new ExtendRestApi( new DomainPackage( '', '', new FeatureGating( 2 ) ), $formatters );
$fixtures = new FixtureData();
$color_attribute = ProductHelper::create_attribute( 'color', [ 'red', 'green', 'blue' ] );
$size_attribute = ProductHelper::create_attribute( 'size', [ 'small', 'medium', 'large' ] );
$this->attributes = [];
$this->attributes[] = wc_get_attribute( $color_attribute['attribute_id'] );
$this->attributes[] = wc_get_attribute( $size_attribute['attribute_id'] );
$this->attributes = [
$fixtures->get_product_attribute( 'color', [ 'red', 'green', 'blue' ] ),
$fixtures->get_product_attribute( 'size', [ 'small', 'medium', 'large' ] )
];
}
/**
* Test route registration.
*/
public function test_register_routes() {
$routes = $this->server->get_routes();
$routes = rest_get_server()->get_routes();
$this->assertArrayHasKey( '/wc/store/products/attributes', $routes );
$this->assertArrayHasKey( '/wc/store/products/attributes/(?P<id>[\d]+)', $routes );
}
@ -60,23 +41,24 @@ class ProductAttributes extends TestCase {
* Test getting item.
*/
public function test_get_item() {
$response = $this->server->dispatch( new WP_REST_Request( 'GET', '/wc/store/products/attributes/' . $this->attributes[0]->id ) );
$data = $response->get_data();
$attribute = wc_get_attribute( $this->attributes[0]['attribute_id'] );
$response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc/store/products/attributes/' . $attribute->id ) );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
$this->assertEquals( $this->attributes[0]->id, $data['id'] );
$this->assertEquals( $this->attributes[0]->name, $data['name'] );
$this->assertEquals( $this->attributes[0]->slug, $data['taxonomy'] );
$this->assertEquals( $this->attributes[0]->type, $data['type'] );
$this->assertEquals( $this->attributes[0]->order_by, $data['order'] );
$this->assertEquals( $this->attributes[0]->has_archives, $data['has_archives'] );
$this->assertEquals( $attribute->id, $data['id'] );
$this->assertEquals( $attribute->name, $data['name'] );
$this->assertEquals( $attribute->slug, $data['taxonomy'] );
$this->assertEquals( $attribute->type, $data['type'] );
$this->assertEquals( $attribute->order_by, $data['order'] );
$this->assertEquals( $attribute->has_archives, $data['has_archives'] );
}
/**
* Test getting items.
*/
public function test_get_items() {
$response = $this->server->dispatch( new WP_REST_Request( 'GET', '/wc/store/products/attributes' ) );
$response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc/store/products/attributes' ) );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
@ -92,10 +74,11 @@ class ProductAttributes extends TestCase {
/**
* Test conversion of product to rest response.
*/
public function test_prepare_item_for_response() {
public function test_prepare_item() {
$routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController( $this->mock_extend ) );
$controller = $routes->get( 'product-attributes' );
$response = $controller->prepare_item_for_response( $this->attributes[0], new \WP_REST_Request() );
$attribute = wc_get_attribute( $this->attributes[0]['attribute_id'] );
$response = $controller->prepare_item_for_response( $attribute, new \WP_REST_Request() );
$data = $response->get_data();
$this->assertArrayHasKey( 'id', $data );
@ -109,11 +92,12 @@ class ProductAttributes extends TestCase {
/**
* Test schema matches responses.
*/
public function test_schema_matches_response() {
public function test_get_item_schema() {
$routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController( $this->mock_extend ) );
$controller = $routes->get( 'product-attributes' );
$schema = $controller->get_item_schema();
$response = $controller->prepare_item_for_response( $this->attributes[0], new \WP_REST_Request() );
$attribute = wc_get_attribute( $this->attributes[0]['attribute_id'] );
$response = $controller->prepare_item_for_response( $attribute, new \WP_REST_Request() );
$schema = $controller->get_item_schema();
$validate = new ValidateSchema( $schema );

View File

@ -3,27 +3,16 @@
* Controller Tests.
*/
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Controllers;
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes;
use \WP_REST_Request;
use \WC_REST_Unit_Test_Case as TestCase;
use \WC_Helper_Product as ProductHelper;
use Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes\ControllerTestCase;
use Automattic\WooCommerce\Blocks\Tests\Helpers\FixtureData;
use Automattic\WooCommerce\Blocks\Tests\Helpers\ValidateSchema;
use Automattic\WooCommerce\Blocks\Domain\Services\ExtendRestApi;
use Automattic\WooCommerce\Blocks\Package;
use Automattic\WooCommerce\Blocks\Domain\Package as DomainPackage;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\MoneyFormatter;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\HtmlFormatter;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\CurrencyFormatter;
use Automattic\WooCommerce\Blocks\Registry\Container;
use Automattic\WooCommerce\Blocks\Domain\Services\FeatureGating;
/**
* Controller Tests.
*/
class ProductCollectionData extends TestCase {
private $mock_extend;
class ProductCollectionData extends ControllerTestCase {
/**
* Setup test products data. Called before every test.
@ -31,62 +20,28 @@ class ProductCollectionData extends TestCase {
public function setUp() {
parent::setUp();
wp_set_current_user( 0 );
$fixtures = new FixtureData();
$formatters = new Formatters();
$formatters->register( 'money', MoneyFormatter::class );
$formatters->register( 'html', HtmlFormatter::class );
$formatters->register( 'currency', CurrencyFormatter::class );
$this->mock_extend = new ExtendRestApi( new DomainPackage( '', '', new FeatureGating( 2 ) ), $formatters );
$this->products = [
$fixtures->get_simple_product( [
'name' => 'Test Product 1',
'regular_price' => 10,
] ),
$fixtures->get_simple_product( [
'name' => 'Test Product 2',
'regular_price' => 100,
] ),
];
$this->products = [];
$this->products[0] = ProductHelper::create_simple_product( false );
$this->products[0]->set_regular_price( 10 );
$this->products[0]->save();
$this->products[1] = ProductHelper::create_simple_product( false );
$this->products[1]->set_regular_price( 100 );
$this->products[1]->save();
wp_insert_comment(
[
'comment_post_ID' => $this->products[0]->get_id(),
'comment_author' => 'admin',
'comment_author_email' => 'woo@woo.local',
'comment_author_url' => '',
'comment_content' => 'Good product.',
'comment_approved' => 1,
'comment_type' => 'review',
'comment_meta' => [
'rating' => 5,
],
]
);
wp_insert_comment(
[
'comment_post_ID' => $this->products[1]->get_id(),
'comment_author' => 'admin',
'comment_author_email' => 'woo@woo.local',
'comment_author_url' => '',
'comment_content' => 'Another very good product.',
'comment_approved' => 1,
'comment_type' => 'review',
'comment_meta' => [
'rating' => 4,
],
]
);
\WC_Comments::clear_transients( $this->products[0]->get_id() );
\WC_Comments::clear_transients( $this->products[1]->get_id() );
$fixtures->add_product_review( $this->products[0]->get_id(), 5 );
$fixtures->add_product_review( $this->products[1]->get_id(), 4 );
}
/**
* Test route registration.
*/
public function test_register_routes() {
$routes = $this->server->get_routes();
$routes = rest_get_server()->get_routes();
$this->assertArrayHasKey( '/wc/store/products/collection-data', $routes );
}
@ -94,7 +49,7 @@ class ProductCollectionData extends TestCase {
* Test getting items.
*/
public function test_get_items() {
$response = $this->server->dispatch( new WP_REST_Request( 'GET', '/wc/store/products/collection-data' ) );
$response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc/store/products/collection-data' ) );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
@ -107,9 +62,9 @@ class ProductCollectionData extends TestCase {
* Test calculation method.
*/
public function test_calculate_price_range() {
$request = new WP_REST_Request( 'GET', '/wc/store/products/collection-data' );
$request = new \WP_REST_Request( 'GET', '/wc/store/products/collection-data' );
$request->set_param( 'calculate_price_range', true );
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
@ -124,9 +79,15 @@ class ProductCollectionData extends TestCase {
* Test calculation method.
*/
public function test_calculate_attribute_counts() {
ProductHelper::create_variation_product();
$fixtures = new FixtureData();
$product = $fixtures->get_variable_product(
[],
[
$fixtures->get_product_attribute( 'size', [ 'small', 'medium', 'large' ] )
]
);
$request = new WP_REST_Request( 'GET', '/wc/store/products/collection-data' );
$request = new \WP_REST_Request( 'GET', '/wc/store/products/collection-data' );
$request->set_param(
'calculate_attribute_counts',
[
@ -136,7 +97,7 @@ class ProductCollectionData extends TestCase {
],
]
);
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
@ -151,9 +112,9 @@ class ProductCollectionData extends TestCase {
* Test calculation method.
*/
public function test_calculate_rating_counts() {
$request = new WP_REST_Request( 'GET', '/wc/store/products/collection-data' );
$request = new \WP_REST_Request( 'GET', '/wc/store/products/collection-data' );
$request->set_param( 'calculate_rating_counts', true );
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
@ -190,14 +151,20 @@ class ProductCollectionData extends TestCase {
/**
* Test schema matches responses.
*/
public function test_schema_matches_response() {
ProductHelper::create_variation_product();
public function test_get_item_schema() {
$fixtures = new FixtureData();
$product = $fixtures->get_variable_product(
[],
[
$fixtures->get_product_attribute( 'size', [ 'small', 'medium', 'large' ] )
]
);
$routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController( $this->mock_extend ) );
$controller = $routes->get( 'product-collection-data' );
$schema = $controller->get_item_schema();
$request = new WP_REST_Request( 'GET', '/wc/store/products/collection-data' );
$request = new \WP_REST_Request( 'GET', '/wc/store/products/collection-data' );
$request->set_param( 'calculate_price_range', true );
$request->set_param(
'calculate_attribute_counts',
@ -209,7 +176,7 @@ class ProductCollectionData extends TestCase {
]
);
$request->set_param( 'calculate_rating_counts', true );
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$validate = new ValidateSchema( $schema );
$diff = $validate->get_diff_from_object( $response->get_data() );

View File

@ -3,63 +3,46 @@
* Controller Tests.
*/
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Controllers;
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes;
use \WP_REST_Request;
use \WC_REST_Unit_Test_Case as TestCase;
use \WC_Helper_Product as ProductHelper;
use Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes\ControllerTestCase;
use Automattic\WooCommerce\Blocks\Tests\Helpers\FixtureData;
use Automattic\WooCommerce\Blocks\Tests\Helpers\ValidateSchema;
use Automattic\WooCommerce\Blocks\Domain\Services\ExtendRestApi;
use Automattic\WooCommerce\Blocks\Package;
use Automattic\WooCommerce\Blocks\Domain\Package as DomainPackage;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\MoneyFormatter;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\HtmlFormatter;
use Automattic\WooCommerce\Blocks\StoreApi\Formatters\CurrencyFormatter;
use Automattic\WooCommerce\Blocks\Registry\Container;
use Automattic\WooCommerce\Blocks\Domain\Services\FeatureGating;
/**
* Products Controller Tests.
*/
class Products extends TestCase {
class Products extends ControllerTestCase {
private $mock_extend;
/**
* Setup test products data. Called before every test.
*/
public function setUp() {
global $wpdb;
parent::setUp();
wp_set_current_user( 0 );
$formatters = new Formatters();
$formatters->register( 'money', MoneyFormatter::class );
$formatters->register( 'html', HtmlFormatter::class );
$formatters->register( 'currency', CurrencyFormatter::class );
$this->mock_extend = new ExtendRestApi( new DomainPackage( '', '', new FeatureGating( 2 ) ), $formatters );
$fixtures = new FixtureData();
$this->products = [];
$this->products[0] = ProductHelper::create_simple_product( true );
$this->products[1] = ProductHelper::create_simple_product( true );
$image_url = media_sideload_image( 'http://cldup.com/Dr1Bczxq4q.png', $this->products[0]->get_id(), '', 'src' );
$image_id = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE guid = %s", $image_url ) );
$this->products[0]->set_image_id( $image_id[0] );
$this->products[0]->save();
$image_url = media_sideload_image( 'http://cldup.com/Dr1Bczxq4q.png', $this->products[1]->get_id(), '', 'src' );
$image_id = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE guid = %s", $image_url ) );
$this->products[1]->set_image_id( $image_id[0] );
$this->products[1]->save();
$this->products = [
$fixtures->get_simple_product( [
'name' => 'Test Product 1',
'stock_status' => 'instock',
'regular_price' => 10,
'image_id' => $fixtures->sideload_image(),
] ),
$fixtures->get_simple_product( [
'name' => 'Test Product 2',
'stock_status' => 'instock',
'regular_price' => 10,
'image_id' => $fixtures->sideload_image(),
] ),
];
}
/**
* Test route registration.
*/
public function test_register_routes() {
$routes = $this->server->get_routes();
$routes = rest_get_server()->get_routes();
$this->assertArrayHasKey( '/wc/store/products', $routes );
$this->assertArrayHasKey( '/wc/store/products/(?P<id>[\d]+)', $routes );
}
@ -68,7 +51,7 @@ class Products extends TestCase {
* Test getting item.
*/
public function test_get_item() {
$response = $this->server->dispatch( new WP_REST_Request( 'GET', '/wc/store/products/' . $this->products[0]->get_id() ) );
$response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc/store/products/' . $this->products[0]->get_id() ) );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
@ -91,7 +74,7 @@ class Products extends TestCase {
* Test getting items.
*/
public function test_get_items() {
$response = $this->server->dispatch( new WP_REST_Request( 'GET', '/wc/store/products' ) );
$response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc/store/products' ) );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
@ -117,12 +100,14 @@ class Products extends TestCase {
* Test searching by SKU
*/
public function test_search_by_sku() {
ProductHelper::create_simple_product( true, [ 'sku' => 'search-for-this-value' ] );
$product = new \WC_Product_Simple();
$product->set_sku( 'search-for-this-value' );
$product->save();
$request = new WP_REST_Request( 'GET', '/wc/store/products' );
$request = new \WP_REST_Request( 'GET', '/wc/store/products' );
$request->set_param( 'search', 'search-for-this' );
$response = $this->server->dispatch( $request );
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
@ -132,9 +117,9 @@ class Products extends TestCase {
}
/**
* Test conversion of prdouct to rest response.
* Test conversion of product to rest response.
*/
public function test_prepare_item_for_response() {
public function test_prepare_item() {
$schemas = new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController( $this->mock_extend );
$routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( $schemas );
$schema = $schemas->get( 'product' );
@ -200,7 +185,7 @@ class Products extends TestCase {
/**
* Test schema matches responses.
*/
public function test_schema_matches_response() {
public function test_get_item_schema() {
$routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController($this->mock_extend) );
$controller = $routes->get( 'products' );
$schema = $controller->get_item_schema();

View File

@ -5,27 +5,37 @@
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Utilities;
use Automattic\WooCommerce\Blocks\Tests\Helpers\FixtureData;
use Automattic\WooCommerce\Blocks\StoreApi\Utilities\CartController;
use PHPUnit\Framework\TestCase;
use \WC_Helper_Product as ProductHelper;
use Yoast\PHPUnitPolyfills\TestCases\TestCase;
class OrderControllerTests extends TestCase {
public function test_get_cart_item_errors() {
$class = new CartController();
$class = new CartController();
$fixtures = new FixtureData();
// This product will simply be in/out of stock.
$out_of_stock_product = ProductHelper::create_simple_product();
$out_of_stock_product = $fixtures->get_simple_product( [
'name' => 'Test Product 1',
'regular_price' => 10,
] );
$out_of_stock_product_key = wc()->cart->add_to_cart( $out_of_stock_product->get_id(), 2 );
$out_of_stock_in_cart = wc()->cart->get_cart_item( $out_of_stock_product_key )['data'];
// This product will have exact levels of stock known
$partially_out_of_stock_product = ProductHelper::create_simple_product();
$partially_out_of_stock_product = $fixtures->get_simple_product( [
'name' => 'Test Product 2',
'regular_price' => 10,
] );
$partially_out_of_stock_key = wc()->cart->add_to_cart( $partially_out_of_stock_product->get_id(), 4 );
$partially_out_of_stock_in_cart = wc()->cart->get_cart_item( $partially_out_of_stock_key )['data'];
// This product will have exact levels of stock known
$too_many_in_cart_product = ProductHelper::create_simple_product();
$too_many_in_cart_product = $fixtures->get_simple_product( [
'name' => 'Test Product 3',
'regular_price' => 10,
] );
$too_many_in_cart_product_key = wc()->cart->add_to_cart( $too_many_in_cart_product->get_id(), 4 );
$too_many_in_cart_in_cart = wc()->cart->get_cart_item( $too_many_in_cart_product_key )['data'];
@ -35,7 +45,10 @@ class OrderControllerTests extends TestCase {
$too_many_in_cart_in_cart->set_sold_individually( true );
// This product will not be purchasable
$not_purchasable_product = ProductHelper::create_simple_product();
$not_purchasable_product = $fixtures->get_simple_product( [
'name' => 'Test Product 4',
'regular_price' => 10,
] );
wc()->cart->add_to_cart( $not_purchasable_product->get_id(), 2 );
// This function will force the $product->is_purchasable() function to return false for our $not_purchasable_product

View File

@ -8,11 +8,9 @@ namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Utilities;
use Automattic\WooCommerce\Blocks\StoreApi\Routes\RouteException;
use Automattic\WooCommerce\Blocks\StoreApi\Utilities\CartController;
use Automattic\WooCommerce\Blocks\StoreApi\Utilities\NoticeHandler;
use PHPUnit\Framework\TestCase;
use \WC_Helper_Product as ProductHelper;
use Yoast\PHPUnitPolyfills\TestCases\TestCase;
class NoticeHandlerTests extends TestCase {
public function test_convert_notices_to_exceptions() {
$this->expectException( RouteException::class );
$this->expectExceptionMessage( 'This is an error message with Some HTML in it.' );

View File

@ -1,90 +0,0 @@
<?php
/**
* Utility Tests.
*/
namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Utilities;
use PHPUnit\Framework\TestCase;
use \WC_Helper_Order as OrderHelper;
use \WC_Helper_Product as ProductHelper;
use Automattic\WooCommerce\Checkout\Helpers\ReserveStock;
/**
* ReserveStock Utility Tests.
*/
class ReserveStockTests extends TestCase {
/**
* Test that stock is reserved for draft orders.
*/
public function test_reserve_stock_for_order() {
$class = new ReserveStock();
$product = ProductHelper::create_simple_product();
$product->set_manage_stock( true );
// this also saves product
wc_update_product_stock( $product, 10 );
$order = OrderHelper::create_order( 1, $product ); // Note this adds 4 to the order.
$order->set_status( 'checkout-draft' );
$order->save();
$class->reserve_stock_for_order( $order );
$this->assertEquals( 4, $this->get_reserved_stock_by_product_id( $product->get_stock_managed_by_id() ) );
// Repeat.
$order = OrderHelper::create_order( 1, $product );
$order->set_status( 'checkout-draft' );
$order->save();
$class->reserve_stock_for_order( $order );
$this->assertEquals( 8, $this->get_reserved_stock_by_product_id( $product->get_stock_managed_by_id() ) );
}
/**
* Test that trying to reserve stock too much throws an exception.
*
* @expectedException Automattic\WooCommerce\Checkout\Helpers\ReserveStockException
*/
public function test_reserve_stock_for_order_throws_exception() {
$class = new ReserveStock();
$product = ProductHelper::create_simple_product();
$product->set_manage_stock( true );
// this also saves product
wc_update_product_stock( $product, 10 );
$order = OrderHelper::create_order( 1, $product ); // Note this adds 4 to the order.
$order->set_status( 'checkout-draft' );
$order->save();
$order2 = OrderHelper::create_order( 1, $product );
$order2->set_status( 'checkout-draft' );
$order2->save();
$order3 = OrderHelper::create_order( 1, $product );
$order3->set_status( 'checkout-draft' );
$order3->save();
$class->reserve_stock_for_order( $order );
$class->reserve_stock_for_order( $order2 );
$class->reserve_stock_for_order( $order3 );
}
/**
* Helper to get the count of reserved stock.
*
* @param integer $product_id
* @return integer
*/
protected function get_reserved_stock_by_product_id( $product_id ) {
global $wpdb;
return $wpdb->get_var(
$wpdb->prepare(
"SELECT SUM( stock_table.`stock_quantity` ) FROM $wpdb->wc_reserved_stock stock_table WHERE stock_table.`product_id` = %d",
$product_id
)
);
}
}