diff --git a/Dockerfile b/Dockerfile index ea175cf81..f090b7bf8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -39,21 +39,20 @@ ENV PATH "$PATH:~/.composer/vendor/bin" ARG PHPUNIT_VERSION="<=8.1" # Install wp-browser globally RUN composer global require --optimize-autoloader \ - wp-cli/wp-cli-bundle \ + wp-cli/wp-cli-bundle:* \ lucatume/wp-browser \ - codeception/module-asserts \ - codeception/module-cli \ - codeception/module-db \ - codeception/module-filesystem \ - codeception/module-phpbrowser \ - codeception/module-rest \ - codeception/module-webdriver \ - codeception/util-universalframework \ + codeception/module-asserts:^1.0 \ + codeception/module-cli:^1.0 \ + codeception/module-db:^1.0 \ + codeception/module-filesystem:^1.0 \ + codeception/module-phpbrowser:^1.0 \ + codeception/module-rest:^1.0 \ + codeception/module-webdriver:^1.0 \ + codeception/util-universalframework:^1.0 \ league/factory-muffin \ league/factory-muffin-faker \ stripe/stripe-php \ - wp-graphql/wp-graphql-testcase \ - "phpunit/phpunit:${PHPUNIT_VERSION}" + wp-graphql/wp-graphql-testcase # Remove exec statement from base entrypoint script. RUN sed -i '$d' /usr/local/bin/docker-entrypoint.sh diff --git a/access-functions.php b/access-functions.php index 200864e92..ead8ca458 100644 --- a/access-functions.php +++ b/access-functions.php @@ -173,3 +173,44 @@ function wc_graphql_price_range( $from, $to ) { return apply_filters( 'graphql_woocommerce_format_price_range', $price, $from, $to ); } + + /** + * Converts a camel case formatted string to a underscore formatted string. + * + * @param string $string String to be formatted. + * @param boolean $capitalize Capitalize first letter of string. + * + * @return string + */ +function wc_graphql_underscore_to_camel_case( $string, $capitalize = false ) { + $str = str_replace( ' ', '', ucwords( str_replace( '-', ' ', $string ) ) ); + + if ( ! $capitalize ) { + $str[0] = strtolower( $str[0] ); + } + + return $str; +} + + /** + * Converts a camel case formatted string to a underscore formatted string. + * + * @param string $string String to be formatted. + * + * @return string + */ +function wc_graphql_camel_case_to_underscore( $string ) { + preg_match_all( + '!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', + $string, + $matches + ); + + $ret = $matches[0]; + + foreach ( $ret as &$match ) { + $match = strtoupper( $match ) === $match ? strtolower( $match ) : lcfirst( $match ); + } + + return implode( '_', $ret ); +} diff --git a/bin/_lib.sh b/bin/_lib.sh index 3bc43acac..abb7570ac 100644 --- a/bin/_lib.sh +++ b/bin/_lib.sh @@ -29,12 +29,16 @@ install_wordpress() { wpackagist-plugin/woocommerce-gateway-stripe \ wpackagist-plugin/wp-graphql \ wpackagist-theme/twentytwentyone \ - wp-cli/wp-cli-bundle + wp-cli/wp-cli-bundle:* } remove_wordpress() { - # Remove Wordpress + integrated plugins. - wp plugin uninstall woocommerce --deactivate --path=${WP_CORE_DIR} + # Uninstall woocommerce plugins. + if [ -f $WP_CORE_DIR/wp-config.php ]; then + wp plugin uninstall woocommerce --deactivate --path=${WP_CORE_DIR} + fi + + # Remove WordPress dependencies composer remove --dev wp-graphql/wp-graphql-jwt-authentication \ wpackagist-plugin/woocommerce-gateway-stripe \ wpackagist-plugin/wp-graphql \ @@ -43,18 +47,16 @@ remove_wordpress() { johnpbloch/wordpress \ composer/installers \ wp-cli/wp-cli-bundle - - composer update } install_local_test_library() { # Install testing library dependencies. composer install - composer require --dev phpunit/phpunit:${PHPUNIT_VERSION} \ + composer require --dev \ lucatume/wp-browser \ - codeception/module-asserts \ - codeception/module-rest \ - codeception/util-universalframework \ + codeception/module-asserts:^1.0 \ + codeception/module-rest:^1.0 \ + codeception/util-universalframework:^1.0 \ wp-graphql/wp-graphql-testcase \ stripe/stripe-php } @@ -66,10 +68,7 @@ remove_local_test_library() { codeception/module-rest \ codeception/util-universalframework \ lucatume/wp-browser \ - phpunit/phpunit \ stripe/stripe-php - - composer update } install_db() { diff --git a/class-woographql-inflect.php b/class-woographql-inflect.php deleted file mode 100644 index 20ced6f43..000000000 --- a/class-woographql-inflect.php +++ /dev/null @@ -1,237 +0,0 @@ - '$1zes', - '/^(ox)$/i' => '$1en', - '/([m|l])ouse$/i' => '$1ice', - '/(matr|vert|ind)ix|ex$/i' => '$1ices', - '/(x|ch|ss|sh)$/i' => '$1es', - '/([^aeiouy]|qu)y$/i' => '$1ies', - '/(hive)$/i' => '$1s', - '/(?:([^f])fe|([lr])f)$/i' => '$1$2ves', - '/(shea|lea|loa|thie)f$/i' => '$1ves', - '/sis$/i' => 'ses', - '/([ti])um$/i' => '$1a', - '/(tomat|potat|ech|her|vet)o$/i' => '$1oes', - '/(bu)s$/i' => '$1ses', - '/(alias)$/i' => '$1es', - '/(octop)us$/i' => '$1i', - '/(ax|test)is$/i' => '$1es', - '/(us)$/i' => '$1es', - '/s$/i' => 's', - '/$/' => 's', - ); - - /** - * Stores singular suffixes - * - * @var array $singular - */ - private static $singular = array( - '/(quiz)zes$/i' => '$1', - '/(matr)ices$/i' => '$1ix', - '/(vert|ind)ices$/i' => '$1ex', - '/^(ox)en$/i' => '$1', - '/(alias)es$/i' => '$1', - '/(octop|vir)i$/i' => '$1us', - '/(cris|ax|test)es$/i' => '$1is', - '/(shoe)s$/i' => '$1', - '/(o)es$/i' => '$1', - '/(bus)es$/i' => '$1', - '/([m|l])ice$/i' => '$1ouse', - '/(x|ch|ss|sh)es$/i' => '$1', - '/(m)ovies$/i' => '$1ovie', - '/(s)eries$/i' => '$1eries', - '/([^aeiouy]|qu)ies$/i' => '$1y', - '/([lr])ves$/i' => '$1f', - '/(tive)s$/i' => '$1', - '/(hive)s$/i' => '$1', - '/(li|wi|kni)ves$/i' => '$1fe', - '/(shea|loa|lea|thie)ves$/i' => '$1f', - '/(^analy)ses$/i' => '$1sis', - '/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i' => '$1$2sis', - '/([ti])a$/i' => '$1um', - '/(n)ews$/i' => '$1ews', - '/(h|bl)ouses$/i' => '$1ouse', - '/(corpse)s$/i' => '$1', - '/(us)es$/i' => '$1', - '/s$/i' => '', - ); - - /** - * Stores irregular words - * - * @var array $irregular - */ - private static $irregular = array( - 'move' => 'moves', - 'foot' => 'feet', - 'goose' => 'geese', - 'sex' => 'sexes', - 'child' => 'children', - 'man' => 'men', - 'tooth' => 'teeth', - 'person' => 'people', - 'valve' => 'valves', - ); - - /** - * Stores words without plural tenses - * - * @var array $uncountable - */ - private static $uncountable = array( - 'sheep', - 'fish', - 'deer', - 'series', - 'species', - 'money', - 'rice', - 'information', - 'equipment', - ); - - /** - * Return plural tense of provide string - * - * @param string $string - word to be pluralized. - * @return string - */ - public static function pluralize( $string ) { - // save some time in the case that singular and plural are the same. - if ( in_array( strtolower( $string ), self::$uncountable, true ) ) { - return $string; - } - - // check for irregular singular forms. - foreach ( self::$irregular as $pattern => $result ) { - $pattern = '/' . $pattern . '$/i'; - - if ( preg_match( $pattern, $string ) ) { - return preg_replace( $pattern, $result, $string ); - } - } - - // check for matches using regular expressions. - foreach ( self::$plural as $pattern => $result ) { - if ( preg_match( $pattern, $string ) ) { - return preg_replace( $pattern, $result, $string ); - } - } - - return $string; - } - - /** - * Return singular tense of provided string - * - * @param string $string String to be singularized. - * @return string - */ - public static function singularize( $string ) { - // save some time in the case that singular and plural are the same. - if ( in_array( strtolower( $string ), self::$uncountable, true ) ) { - return $string; - } - - // check for irregular plural forms. - foreach ( self::$irregular as $result => $pattern ) { - $pattern = '/' . $pattern . '$/i'; - - if ( preg_match( $pattern, $string ) ) { - return preg_replace( $pattern, $result, $string ); - } - } - - // check for matches using regular expressions. - foreach ( self::$singular as $pattern => $result ) { - if ( preg_match( $pattern, $string ) ) { - return preg_replace( $pattern, $result, $string ); - } - } - - return $string; - } - - /** - * Return plural tense if provided count is greater than 1 - * - * @param int $count Count to be evaluated. - * @param string $string String potentially pluralized. - */ - public static function pluralize_if( $count, $string ) { - if ( 1 === $count ) { - return '1 $string'; - } - - return $count . ' ' . self::pluralize( $string ); - } - - /** - * Converts a camel case formatted string to a underscore formatted string. - * - * @param string $string String to be formatted. - * @param boolean $capitalize Capitalize first letter of string. - * - * @return string - */ - public static function underscore_to_camel_case( $string, $capitalize = false ) { - $str = str_replace( ' ', '', ucwords( str_replace( '-', ' ', $string ) ) ); - - if ( ! $capitalize ) { - $str[0] = strtolower( $str[0] ); - } - - return $str; - } - - /** - * Converts a camel case formatted string to a underscore formatted string. - * - * @param string $string String to be formatted. - * - * @return string - */ - public static function camel_case_to_underscore( $string ) { - preg_match_all( - '!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', - $string, - $matches - ); - - $ret = $matches[0]; - - foreach ( $ret as &$match ) { - $match = strtoupper( $match ) === $match ? strtolower( $match ) : lcfirst( $match ); - } - - return implode( '_', $ret ); - } - } -endif; diff --git a/composer.json b/composer.json index 10e45a702..70749c33f 100644 --- a/composer.json +++ b/composer.json @@ -37,7 +37,11 @@ "config": { "optimize-autoloader": true, "process-timeout": 0, - "sort-packages": true + "sort-packages": true, + "allow-plugins": { + "composer/installers": true, + "johnpbloch/wordpress-core-installer": true + } }, "autoload": { "files": [ diff --git a/composer.lock b/composer.lock index a1d4baa7e..4f8d8732c 100644 --- a/composer.lock +++ b/composer.lock @@ -8,16 +8,16 @@ "packages": [ { "name": "firebase/php-jwt", - "version": "v5.5.0", + "version": "v5.5.1", "source": { "type": "git", "url": "https://github.com/firebase/php-jwt.git", - "reference": "cf814442ce0e9eebe5317d61b63ccda4b85de67a" + "reference": "83b609028194aa042ea33b5af2d41a7427de80e6" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/firebase/php-jwt/zipball/cf814442ce0e9eebe5317d61b63ccda4b85de67a", - "reference": "cf814442ce0e9eebe5317d61b63ccda4b85de67a", + "url": "https://api.github.com/repos/firebase/php-jwt/zipball/83b609028194aa042ea33b5af2d41a7427de80e6", + "reference": "83b609028194aa042ea33b5af2d41a7427de80e6", "shasum": "" }, "require": { @@ -59,24 +59,24 @@ ], "support": { "issues": "https://github.com/firebase/php-jwt/issues", - "source": "https://github.com/firebase/php-jwt/tree/v5.5.0" + "source": "https://github.com/firebase/php-jwt/tree/v5.5.1" }, - "time": "2021-11-04T16:21:41+00:00" + "time": "2021-11-08T20:18:51+00:00" } ], "packages-dev": [ { "name": "squizlabs/php_codesniffer", - "version": "3.6.1", + "version": "3.6.2", "source": { "type": "git", "url": "https://github.com/squizlabs/PHP_CodeSniffer.git", - "reference": "f268ca40d54617c6e06757f83f699775c9b3ff2e" + "reference": "5e4e71592f69da17871dba6e80dd51bce74a351a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/f268ca40d54617c6e06757f83f699775c9b3ff2e", - "reference": "f268ca40d54617c6e06757f83f699775c9b3ff2e", + "url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/5e4e71592f69da17871dba6e80dd51bce74a351a", + "reference": "5e4e71592f69da17871dba6e80dd51bce74a351a", "shasum": "" }, "require": { @@ -119,7 +119,7 @@ "source": "https://github.com/squizlabs/PHP_CodeSniffer", "wiki": "https://github.com/squizlabs/PHP_CodeSniffer/wiki" }, - "time": "2021-10-11T04:00:11+00:00" + "time": "2021-12-12T21:44:58+00:00" }, { "name": "wp-coding-standards/wpcs", diff --git a/docker-compose.yml b/docker-compose.yml index 42edc9209..970075169 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -33,7 +33,7 @@ services: build: context: . args: - PHP_VERSION: ${PHP_VERSION:-7.3} + PHP_VERSION: ${PHP_VERSION:-8.0} volumes: - .:/var/www/html/wp-content/plugins/wp-graphql-woocommerce - ./codeception.dist.yml:/var/www/html/wp-content/plugins/wp-graphql-woocommerce/codeception.yml diff --git a/includes/class-core-schema-filters.php b/includes/class-core-schema-filters.php index ab406776c..806da6f33 100644 --- a/includes/class-core-schema-filters.php +++ b/includes/class-core-schema-filters.php @@ -226,7 +226,7 @@ public static function register_taxonomy_args( $args, $taxonomy ) { $singular_name = graphql_format_field_name( $taxonomy ); $args['show_in_graphql'] = true; $args['graphql_single_name'] = $singular_name; - $args['graphql_plural_name'] = \WooGraphQL_Inflect::pluralize( $singular_name ); + $args['graphql_plural_name'] = 'all' . ucFirst( $singular_name ); } return $args; diff --git a/includes/class-wp-graphql-woocommerce.php b/includes/class-wp-graphql-woocommerce.php index 0590875d2..dfa73d751 100644 --- a/includes/class-wp-graphql-woocommerce.php +++ b/includes/class-wp-graphql-woocommerce.php @@ -178,12 +178,11 @@ function () { ); return false; - } - } + }//end if + }//end if // Required non-autoloaded classes. require_once WPGRAPHQL_WOOCOMMERCE_PLUGIN_DIR . 'access-functions.php'; - require_once WPGRAPHQL_WOOCOMMERCE_PLUGIN_DIR . 'class-woographql-inflect.php'; require_once WPGRAPHQL_WOOCOMMERCE_PLUGIN_DIR . 'includes/functions.php'; return true; diff --git a/includes/connection/class-orders.php b/includes/connection/class-orders.php index 8dc4fdfc3..32fe234ee 100644 --- a/includes/connection/class-orders.php +++ b/includes/connection/class-orders.php @@ -259,7 +259,7 @@ public static function get_connection_args( $access = 'public' ): array { 'description' => __( 'Filter the connection based on dates.', 'wp-graphql-woocommerce' ), ), ); - } + }//end switch } /** @@ -364,10 +364,11 @@ public static function map_input_fields_to_wp_query( $query_args, $where_args, $ } } } - } + }//end foreach if ( ! empty( $meta_query ) ) { - $query_args['meta_query'] = $meta_query; // WPCS: slow query ok. + $query_args['meta_query'] = $meta_query; + // WPCS: slow query ok. } $key_mapping = array( diff --git a/includes/connection/class-products.php b/includes/connection/class-products.php index 840cb38ec..6d79280a5 100644 --- a/includes/connection/class-products.php +++ b/includes/connection/class-products.php @@ -230,10 +230,11 @@ function() { $resolver = new PostObjectConnectionResolver( $source, $args, $context, $info, 'product' ); $tax_query = array( - array( // WPCS: slow query ok. - 'taxonomy' => $source->taxonomyName, // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase - 'field' => 'term_id', - 'terms' => $source->term_id, + array( + // WPCS: slow query ok. + 'taxonomy' => $source->taxonomyName, // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + 'field' => 'term_id', + 'terms' => $source->term_id, ), ); $resolver->set_query_arg( 'tax_query', $tax_query ); @@ -307,7 +308,7 @@ function() { ) ) ); - } + }//end foreach } /** @@ -370,8 +371,8 @@ public static function set_ordering_query_args( $resolver, $args ) { $resolver->set_query_arg( 'meta_type', 'NUMERIC' ); break 2; } - } - } + }//end foreach + }//end if return $resolver; } @@ -622,9 +623,9 @@ public static function map_input_fields_to_wp_query( $query_args, $where_args, $ 'operator' => $operator, ); break; - } - } - } + }//end switch + }//end if + }//end foreach if ( 1 < count( $tax_query ) ) { $tax_query['relation'] = 'AND'; @@ -676,7 +677,7 @@ public static function map_input_fields_to_wp_query( $query_args, $where_args, $ 'operator' => 'NOT IN', ); } - } + }//end if // Handle visibility. $post_type_obj = get_post_type_object( $post_type ); @@ -714,8 +715,8 @@ public static function map_input_fields_to_wp_query( $query_args, $where_args, $ 'operator' => 'AND', ); break; - } - } + }//end switch + }//end if // Process "taxonomyFilter". if ( ! empty( $where_args['taxonomyFilter'] ) ) { @@ -749,7 +750,7 @@ public static function map_input_fields_to_wp_query( $query_args, $where_args, $ ) ); } - } + }//end foreach if ( ! empty( $tax_groups ) ) { array_push( $tax_query, ...$tax_groups ); @@ -758,11 +759,12 @@ public static function map_input_fields_to_wp_query( $query_args, $where_args, $ if ( 1 < count( $tax_groups ) ) { $tax_query['relation'] = $relation; } - } - } + }//end if + }//end if if ( ! empty( $tax_query ) ) { - $query_args['tax_query'] = $tax_query; // WPCS: slow query ok. + $query_args['tax_query'] = $tax_query; + // WPCS: slow query ok. } $meta_query = array(); @@ -804,7 +806,8 @@ public static function map_input_fields_to_wp_query( $query_args, $where_args, $ } if ( ! empty( $meta_query ) ) { - $query_args['meta_query'] = $meta_query; // WPCS: slow query ok. + $query_args['meta_query'] = $meta_query; + // WPCS: slow query ok. } if ( ! empty( $where_args['onSale'] ) && is_bool( $where_args['onSale'] ) ) { diff --git a/includes/connection/class-wc-terms.php b/includes/connection/class-wc-terms.php index 1c474d358..94595a9fc 100644 --- a/includes/connection/class-wc-terms.php +++ b/includes/connection/class-wc-terms.php @@ -60,11 +60,11 @@ public static function register_connections() { ) ) ); - } - } - } - } - } + }//end if + }//end foreach + }//end if + }//end foreach + }//end if // From Coupons to ProductCategory connections. $tax_object = get_taxonomy( 'product_cat' ); diff --git a/includes/connection/wc-cpt-connection-args.php b/includes/connection/wc-cpt-connection-args.php index 0c5d5f796..da200466c 100644 --- a/includes/connection/wc-cpt-connection-args.php +++ b/includes/connection/wc-cpt-connection-args.php @@ -106,14 +106,15 @@ function map_shared_input_fields_to_wp_query( array $input, $ordering_meta = arr // Handle meta fields. } elseif ( in_array( $orderby_input['field'], $ordering_meta, true ) ) { $args['orderby']['meta_value_num'] = $orderby_input['order']; - $args['meta_key'] = esc_sql( $orderby_input['field'] ); // WPCS: slow query ok. + $args['meta_key'] = esc_sql( $orderby_input['field'] ); + // WPCS: slow query ok. // Handle post object fields. } elseif ( ! empty( $orderby_input['field'] ) ) { $args['orderby'][ esc_sql( $orderby_input['field'] ) ] = esc_sql( $orderby_input['order'] ); } - } - } + }//end foreach + }//end if if ( ! empty( $input['dateQuery'] ) ) { $args['date_query'] = $input['dateQuery']; diff --git a/includes/data/class-factory.php b/includes/data/class-factory.php index 36a24cd66..ce30e9d7c 100644 --- a/includes/data/class-factory.php +++ b/includes/data/class-factory.php @@ -290,7 +290,7 @@ public static function resolve_node_type( $type, $node ) { case is_a( $node, Tax_Rate::class ): $type = 'TaxRate'; break; - } + }//end switch return $type; } diff --git a/includes/data/connection/class-customer-connection-resolver.php b/includes/data/connection/class-customer-connection-resolver.php index 15d63a247..d9314b22c 100644 --- a/includes/data/connection/class-customer-connection-resolver.php +++ b/includes/data/connection/class-customer-connection-resolver.php @@ -117,7 +117,8 @@ public function get_query_args() { */ if ( isset( $query_args['orderby'] ) && 'meta_value_num' === $query_args['orderby'] ) { $query_args['orderby'] = array( - 'meta_value' => empty( $query_args['order'] ) ? 'DESC' : $query_args['order'], // WPCS: slow query OK. + 'meta_value' => empty( $query_args['order'] ) ? 'DESC' : $query_args['order'], + // WPCS: slow query OK. ); unset( $query_args['order'] ); $query_args['meta_type'] = 'NUMERIC'; diff --git a/includes/data/connection/class-downloadable-item-connection-resolver.php b/includes/data/connection/class-downloadable-item-connection-resolver.php index aa05fc663..4bc8583f6 100644 --- a/includes/data/connection/class-downloadable-item-connection-resolver.php +++ b/includes/data/connection/class-downloadable-item-connection-resolver.php @@ -88,7 +88,7 @@ public function get_query_args() { return $has_downloads_remaining === $downloads_remaining; }; } - } + }//end if /** * Filter the $query_args to allow folks to customize queries programmatically. diff --git a/includes/data/connection/class-product-attribute-connection-resolver.php b/includes/data/connection/class-product-attribute-connection-resolver.php index 7b3c76a79..c36d507df 100644 --- a/includes/data/connection/class-product-attribute-connection-resolver.php +++ b/includes/data/connection/class-product-attribute-connection-resolver.php @@ -69,7 +69,7 @@ function( $item ) { default: throw new UserError( __( 'Invalid product attribute type provided', 'wp-graphql-woocommerce' ) ); } - } + }//end if return $items; } diff --git a/includes/data/connection/class-product-connection-resolver.php b/includes/data/connection/class-product-connection-resolver.php index 917252eef..2be741800 100644 --- a/includes/data/connection/class-product-connection-resolver.php +++ b/includes/data/connection/class-product-connection-resolver.php @@ -162,7 +162,8 @@ public function get_query_args() { if ( ! current_user_can( $post_type_obj->cap->read_private_posts ) ) { if ( empty( $query_args['tax_query'] ) ) { - $query_args['tax_query'] = array(); // WPCS: slow query ok. + $query_args['tax_query'] = array(); + // WPCS: slow query ok. } /** @@ -188,7 +189,7 @@ public function get_query_args() { if ( ! empty( $catalog_visibility ) ) { $query_args['tax_query'][] = $catalog_visibility; } - } + }//end if /** * If the query is a search, the source is not another Post, and the parent input $arg is not @@ -351,9 +352,9 @@ public function sanitize_input_fields( array $where_args ) { 'operator' => $operator, ); break; - } - } - } + }//end switch + }//end if + }//end foreach if ( 1 < count( $tax_query ) ) { $tax_query['relation'] = 'AND'; @@ -405,7 +406,7 @@ public function sanitize_input_fields( array $where_args ) { 'operator' => 'NOT IN', ); } - } + }//end if // Handle visibility. $post_type_obj = get_post_type_object( $this->post_type ); @@ -443,8 +444,8 @@ public function sanitize_input_fields( array $where_args ) { 'operator' => 'AND', ); break; - } - } + }//end switch + }//end if // Process "taxonomyFilter". if ( ! empty( $where_args['taxonomyFilter'] ) ) { @@ -474,15 +475,16 @@ public function sanitize_input_fields( array $where_args ) { } $tax_query[] = $sub_tax_query; - } - } + }//end foreach + }//end if if ( ! empty( $tax_query ) && 1 > count( $tax_query ) ) { $tax_query['relation'] = 'AND'; } if ( ! empty( $tax_query ) ) { - $args['tax_query'] = $tax_query; // WPCS: slow query ok. + $args['tax_query'] = $tax_query; + // WPCS: slow query ok. } $meta_query = array(); @@ -524,7 +526,8 @@ public function sanitize_input_fields( array $where_args ) { } if ( ! empty( $meta_query ) ) { - $args['meta_query'] = $meta_query; // WPCS: slow query ok. + $args['meta_query'] = $meta_query; + // WPCS: slow query ok. } if ( ! empty( $where_args['onSale'] ) && is_bool( $where_args['onSale'] ) ) { diff --git a/includes/data/connection/class-refund-connection-resolver.php b/includes/data/connection/class-refund-connection-resolver.php index 7e3f0b2ec..4543ffd15 100644 --- a/includes/data/connection/class-refund-connection-resolver.php +++ b/includes/data/connection/class-refund-connection-resolver.php @@ -159,7 +159,7 @@ public function get_query_args() { break; default: break; - } + }//end switch /** * If there's no orderby params in the inputArgs, set order based on the first/last argument diff --git a/includes/data/connection/class-tax-rate-connection-resolver.php b/includes/data/connection/class-tax-rate-connection-resolver.php index b64f534af..ccc72d1d8 100644 --- a/includes/data/connection/class-tax-rate-connection-resolver.php +++ b/includes/data/connection/class-tax-rate-connection-resolver.php @@ -133,7 +133,7 @@ public function get_query() { $this->query_args['order'] ) ); // @codingStandardsIgnoreEnd - } + }//end if $results = array_map( function( $rate ) { diff --git a/includes/data/connection/class-variation-attribute-connection-resolver.php b/includes/data/connection/class-variation-attribute-connection-resolver.php index fa97ba817..9a42b2d27 100644 --- a/includes/data/connection/class-variation-attribute-connection-resolver.php +++ b/includes/data/connection/class-variation-attribute-connection-resolver.php @@ -52,8 +52,8 @@ public static function to_data_array( $attrs = array(), $parent_id = 0 ) { 'value' => $term->name, ); } - } - } + }//end foreach + }//end if return $attributes; } diff --git a/includes/data/connection/trait-wc-cpt-loader-common.php b/includes/data/connection/trait-wc-cpt-loader-common.php index 754d7b24b..b83afc13a 100644 --- a/includes/data/connection/trait-wc-cpt-loader-common.php +++ b/includes/data/connection/trait-wc-cpt-loader-common.php @@ -88,14 +88,15 @@ public function sanitize_common_inputs( array $input ) { // Handle meta fields. } elseif ( in_array( $orderby_input['field'], $this->ordering_meta(), true ) ) { $args['orderby']['meta_value_num'] = $orderby_input['order']; - $args['meta_key'] = esc_sql( $orderby_input['field'] ); // WPCS: slow query ok. + $args['meta_key'] = esc_sql( $orderby_input['field'] ); + // WPCS: slow query ok. // Handle post object fields. } elseif ( ! empty( $orderby_input['field'] ) ) { $args['orderby'][ esc_sql( $orderby_input['field'] ) ] = esc_sql( $orderby_input['order'] ); } - } - } + }//end foreach + }//end if if ( ! empty( $input['dateQuery'] ) ) { $args['date_query'] = $input['dateQuery']; diff --git a/includes/data/loader/class-wc-cpt-loader.php b/includes/data/loader/class-wc-cpt-loader.php index d0e7d03e0..276753f16 100644 --- a/includes/data/loader/class-wc-cpt-loader.php +++ b/includes/data/loader/class-wc-cpt-loader.php @@ -66,7 +66,7 @@ public static function resolve_model( $post_type, $id, $fatal = true ) { /* translators: no model assigned error message */ throw new UserError( sprintf( __( 'No Model is register to the custom post-type "%s"', 'wp-graphql-woocommerce' ), $post_type ) ); - } + }//end switch } /** @@ -202,7 +202,7 @@ function() use ( $post_type, $key ) { return self::resolve_model( $post_type, $key ); } ); - } + }//end foreach return ! empty( $loaded_posts ) ? $loaded_posts : array(); } diff --git a/includes/data/loader/class-wc-db-loader.php b/includes/data/loader/class-wc-db-loader.php index 0702a2e50..1117e7ecd 100644 --- a/includes/data/loader/class-wc-db-loader.php +++ b/includes/data/loader/class-wc-db-loader.php @@ -88,7 +88,7 @@ public function loadKeys( array $keys ) { sprintf( __( 'Loader type invalid: %s', 'wp-graphql-woocommerce' ), $this->loader_type ) ); } - } + }//end switch $loaded_items = array(); @@ -157,7 +157,7 @@ public function load_tax_rate_from_id( $id ) { return new Tax_Rate( $rate ); } else { return null; - } + }//end if } /** diff --git a/includes/data/mutation/class-checkout-mutation.php b/includes/data/mutation/class-checkout-mutation.php index d020f5a46..e2f5dfd89 100644 --- a/includes/data/mutation/class-checkout-mutation.php +++ b/includes/data/mutation/class-checkout-mutation.php @@ -101,7 +101,7 @@ public static function prepare_checkout_args( $input, $context, $info ) { $data[ $key ] = self::get_value( $key ); } } - } + }//end foreach if ( in_array( 'shipping', $skipped, true ) && ( \WC()->cart->needs_shipping_address() || \wc_ship_to_billing_address_only() ) ) { foreach ( self::get_checkout_fields( 'shipping' ) as $field => $input_key ) { @@ -290,7 +290,7 @@ protected static function process_customer( $data ) { // Also, recalculate cart totals to reveal any role-based discounts that were unavailable before registering. WC()->cart->calculate_totals(); - } + }//end if // On multisite, ensure user exists on current site, if not add them before allowing login. if ( $customer_id && is_multisite() && is_user_logged_in() && ! is_user_member_of_blog() ) { @@ -331,7 +331,7 @@ protected static function process_customer( $data ) { do_action( 'woocommerce_checkout_update_customer', $customer, $data ); $customer->save(); - } + }//end if // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound do_action( 'woocommerce_checkout_update_user_meta', $customer_id, $data ); @@ -439,8 +439,8 @@ protected static function validate_data( &$data ) { } } } - } - } + }//end foreach + }//end foreach } /** @@ -485,7 +485,7 @@ protected static function validate_checkout( &$data ) { } } } - } + }//end if if ( WC()->cart->needs_payment() ) { $available_gateways = WC()->payment_gateways->get_available_payment_gateways(); @@ -649,7 +649,7 @@ public static function process_checkout( $data, $input, $context, $info, &$resul ), ); } - } + }//end if return $order_id; } diff --git a/includes/data/mutation/class-order-mutation.php b/includes/data/mutation/class-order-mutation.php index 87f5d5d5a..a0e1d5d18 100644 --- a/includes/data/mutation/class-order-mutation.php +++ b/includes/data/mutation/class-order-mutation.php @@ -153,8 +153,8 @@ public static function add_items( $input, $order_id, $context, $info ) { * @param ResolveInfo $info Request ResolveInfo instance. */ do_action( "graphql_woocommerce_after_{$type}s_added_to_order", $items, $order_id, $context, $info ); - } - } + }//end if + }//end foreach } /** @@ -236,7 +236,7 @@ protected static function get_order_item_keys( $type ) { 'taxClass' => 'tax_class', 'taxStatus' => 'tax_status', ); - } + }//end switch } /** @@ -315,13 +315,13 @@ public static function add_order_meta( $order_id, $input, $context, $info ) { } break; default: - $prop = \WooGraphQL_Inflect::camel_case_to_underscore( $key ); + $prop = \wc_graphql_camel_case_to_underscore( $key ); if ( is_callable( array( $order, "set_{$prop}" ) ) ) { $order->{"set_{$prop}"}( $value ); } break; - } - } + }//end switch + }//end foreach /** * Action called before changes to order meta are saved. diff --git a/includes/model/class-coupon.php b/includes/model/class-coupon.php index 805e50957..e6a11d821 100644 --- a/includes/model/class-coupon.php +++ b/includes/model/class-coupon.php @@ -115,6 +115,6 @@ protected function init() { ); $this->fields = array_merge( $this->fields, $fields ); - } + }//end if } } diff --git a/includes/model/class-customer.php b/includes/model/class-customer.php index b84ee44ff..538cecae4 100644 --- a/includes/model/class-customer.php +++ b/includes/model/class-customer.php @@ -126,7 +126,7 @@ protected function init() { return ( ! empty( $this->data->get_last_order() ) ) ? $this->data->get_last_order()->get_id() : null; }, ); - } + }//end if parent::prepare_fields(); } diff --git a/includes/model/class-order-item.php b/includes/model/class-order-item.php index ca467cd38..dcae34cfd 100644 --- a/includes/model/class-order-item.php +++ b/includes/model/class-order-item.php @@ -251,8 +251,8 @@ protected function init() { ) ); break; - } - } + }//end switch + }//end if parent::prepare_fields(); } diff --git a/includes/model/class-order.php b/includes/model/class-order.php index 4cb378f5c..fc0c84eb3 100644 --- a/includes/model/class-order.php +++ b/includes/model/class-order.php @@ -393,6 +393,6 @@ protected function init() { ); $this->fields = array_merge( $this->fields, $fields ); - } + }//end if } } diff --git a/includes/model/class-product-variation.php b/includes/model/class-product-variation.php index 3d99cab55..d11d2c6db 100644 --- a/includes/model/class-product-variation.php +++ b/includes/model/class-product-variation.php @@ -195,6 +195,6 @@ protected function init() { ); $this->fields = array_merge( $this->fields, $fields ); - } + }//end if } } diff --git a/includes/model/class-product.php b/includes/model/class-product.php index ef5cbb4ae..77cbfe6fd 100644 --- a/includes/model/class-product.php +++ b/includes/model/class-product.php @@ -266,7 +266,7 @@ protected function init() { return ! is_null( $this->wc_data->get_tax_class() ) ? $this->wc_data->get_tax_class() : ''; }, ); - } + }//end if if ( apply_filters( @@ -320,7 +320,7 @@ protected function init() { return ! empty( $this->wc_data->get_stock_status() ) ? $this->wc_data->get_stock_status() : null; }, ); - } + }//end if switch ( true ) { case apply_filters( "graphql_{$type}_product_model_use_virtual_data_fields", 'simple' === $type ): @@ -396,7 +396,7 @@ protected function init() { }, ); break; - } + }//end switch /** * Defines aliased fields @@ -416,6 +416,6 @@ protected function init() { ); $this->fields = array_merge( $this->fields, $fields ); - } + }//end if } } diff --git a/includes/model/class-refund.php b/includes/model/class-refund.php index 18a5338b7..16d8a03bd 100644 --- a/includes/model/class-refund.php +++ b/includes/model/class-refund.php @@ -58,6 +58,6 @@ protected function init() { ); $this->fields = array_merge( $this->fields, $fields ); - } + }//end if } } diff --git a/includes/model/class-tax-rate.php b/includes/model/class-tax-rate.php index d76b56ec2..9a1411e2a 100644 --- a/includes/model/class-tax-rate.php +++ b/includes/model/class-tax-rate.php @@ -97,6 +97,6 @@ protected function init() { return ! is_null( $this->data->tax_rate_class ) ? $this->data->tax_rate_class : ''; }, ); - } + }//end if } } diff --git a/includes/mutation/class-cart-add-item.php b/includes/mutation/class-cart-add-item.php index d6618a21e..88366a7ee 100644 --- a/includes/mutation/class-cart-add-item.php +++ b/includes/mutation/class-cart-add-item.php @@ -98,7 +98,8 @@ public static function mutate_and_get_payload() { // Add item to cart and get item key. try { $cart_item_key = \WC()->cart->add_to_cart( ...$cart_item_args ); - } catch ( \Exception $e ) { // Repackage any errors. + } catch ( \Exception $e ) { + // Repackage any errors. throw new UserError( $e->getMessage() ); } diff --git a/includes/mutation/class-cart-add-items.php b/includes/mutation/class-cart-add-items.php index 21ce77985..94cdcca5b 100644 --- a/includes/mutation/class-cart-add-items.php +++ b/includes/mutation/class-cart-add-items.php @@ -137,8 +137,8 @@ public static function mutate_and_get_payload() { // Capture error. $failure[] = compact( 'cart_item_data', 'reason' ); - } - } + }//end try + }//end foreach // Log captured errors. if ( ! empty( $failure ) ) { diff --git a/includes/mutation/class-cart-fill.php b/includes/mutation/class-cart-fill.php index 34b06b5bb..50e675646 100644 --- a/includes/mutation/class-cart-fill.php +++ b/includes/mutation/class-cart-fill.php @@ -124,7 +124,7 @@ public static function get_output_fields() { } $errors[] = $cart_error; - } + }//end foreach return $errors; }, @@ -181,8 +181,8 @@ public static function mutate_and_get_payload() { // Capture error. $invalid_cart_items[] = compact( 'cart_item_data', 'reason' ); - } - } + }//end try + }//end foreach // Log captured errors. if ( ! empty( $invalid_cart_items ) ) { @@ -217,12 +217,12 @@ public static function mutate_and_get_payload() { } $invalid_coupons[] = compact( 'code', 'reason' ); - } + }//end foreach if ( ! empty( $invalid_coupons ) ) { graphql_debug( $invalid_coupons, array( 'type' => 'INVALID_COUPONS' ) ); } - } + }//end if $chosen_shipping_methods = array(); if ( ! empty( $input['shippingMethods'] ) ) { @@ -253,7 +253,7 @@ public static function mutate_and_get_payload() { if ( ! empty( $invalid_shipping_methods ) ) { graphql_debug( $invalid_shipping_methods, array( 'type' => 'INVALID_SHIPPING_METHODS' ) ); } - } + }//end if // Recalculate totals. \WC()->cart->calculate_totals(); diff --git a/includes/mutation/class-cart-update-item-quantities.php b/includes/mutation/class-cart-update-item-quantities.php index f306c0a81..f3021bcbd 100644 --- a/includes/mutation/class-cart-update-item-quantities.php +++ b/includes/mutation/class-cart-update-item-quantities.php @@ -152,7 +152,7 @@ function( $value ) { } } catch ( Exception $e ) { throw new UserError( $e->getMessage() ); - } + }//end try do_action( 'graphql_woocommerce_before_set_item_quantities', diff --git a/includes/mutation/class-checkout.php b/includes/mutation/class-checkout.php index 69cc7f05d..76f1c4cfe 100644 --- a/includes/mutation/class-checkout.php +++ b/includes/mutation/class-checkout.php @@ -164,7 +164,7 @@ public static function mutate_and_get_payload() { } catch ( Exception $e ) { Order_Mutation::purge( $order ); throw new UserError( $e->getMessage() ); - } + }//end try }; } } diff --git a/includes/mutation/class-coupon-create.php b/includes/mutation/class-coupon-create.php index 5b853d734..f8799c697 100644 --- a/includes/mutation/class-coupon-create.php +++ b/includes/mutation/class-coupon-create.php @@ -214,8 +214,8 @@ public static function mutate_and_get_payload( $input, AppContext $context, Reso $coupon->{"set_{$key}"}( $value ); } break; - } - } + }//end switch + }//end foreach return array( 'id' => $coupon->save() ); } diff --git a/includes/mutation/class-order-create.php b/includes/mutation/class-order-create.php index 37007a66b..e82b3caaf 100644 --- a/includes/mutation/class-order-create.php +++ b/includes/mutation/class-order-create.php @@ -199,7 +199,7 @@ public static function mutate_and_get_payload() { } catch ( Exception $e ) { Order_Mutation::purge( $order ); throw new UserError( $e->getMessage() ); - } + }//end try }; } } diff --git a/includes/type/enum/class-id-type-enums.php b/includes/type/enum/class-id-type-enums.php index 9e465b6d8..99acd0854 100644 --- a/includes/type/enum/class-id-type-enums.php +++ b/includes/type/enum/class-id-type-enums.php @@ -149,6 +149,6 @@ private static function get_value( $value ) { 'value' => 'uri', 'description' => __( 'Identify a resource by the URI.', 'wp-graphql-woocommerce' ), ); - } + }//end switch } } diff --git a/includes/type/object/class-cart-type.php b/includes/type/object/class-cart-type.php index bfa171ddc..4bfcfa3cd 100644 --- a/includes/type/object/class-cart-type.php +++ b/includes/type/object/class-cart-type.php @@ -363,14 +363,16 @@ public static function register_cart_item() { // Check if "key" argument set and assigns to target "keys" array. if ( ! empty( $args['key'] ) && ! empty( $source[ $args['key'] ] ) ) { $keys = array( $args['key'] ); - } elseif ( ! empty( $args['keysIn'] ) ) { // Check if "keysIn" argument set and assigns to target "keys" array. + } elseif ( ! empty( $args['keysIn'] ) ) { + // Check if "keysIn" argument set and assigns to target "keys" array. $keys = array(); foreach ( $args['keysIn'] as $key ) { if ( ! empty( $source[ $key ] ) ) { $keys[] = $key; } } - } else { // If no arguments set, all extra data keys are assigns to target "keys" array. + } else { + // If no arguments set, all extra data keys are assigns to target "keys" array. $keys = array_diff( array_keys( $source ), array( @@ -388,7 +390,7 @@ public static function register_cart_item() { 'line_tax', ) ); - } + }//end if // Create meta ID prefix. $id_prefix = apply_filters( 'graphql_woocommerce_cart_meta_id_prefix', 'cart_' ); diff --git a/includes/type/object/class-meta-data-type.php b/includes/type/object/class-meta-data-type.php index d7dda7e96..758ae3cb5 100644 --- a/includes/type/object/class-meta-data-type.php +++ b/includes/type/object/class-meta-data-type.php @@ -90,7 +90,8 @@ function( $meta ) use ( $data ) { } ); } - } elseif ( ! empty( $args['keysIn'] ) ) { // Check "keysIn" argument and format meta_data objects. + } elseif ( ! empty( $args['keysIn'] ) ) { + // Check "keysIn" argument and format meta_data objects. $keys = $args['keysIn']; $found = array(); @@ -109,7 +110,8 @@ function( $meta ) use ( $keys, $single, &$found ) { } } ); - } else { // If no arguments set return all meta (in accordance with unique flag). + } else { + // If no arguments set return all meta (in accordance with unique flag). $found = array(); $data = array_filter( $source->get_meta_data(), @@ -124,7 +126,7 @@ function( $meta ) use ( $single, &$found ) { return true; } ); - } + }//end if return ! empty( $data ) ? $data : null; }, diff --git a/includes/type/object/class-root-query.php b/includes/type/object/class-root-query.php index 5c39867b5..1deb03a06 100644 --- a/includes/type/object/class-root-query.php +++ b/includes/type/object/class-root-query.php @@ -493,6 +493,6 @@ public static function register_fields() { }, ) ); - } + }//end foreach } } diff --git a/includes/utils/class-ql-session-handler.php b/includes/utils/class-ql-session-handler.php index ad43caaca..dd9a29dc7 100644 --- a/includes/utils/class-ql-session-handler.php +++ b/includes/utils/class-ql-session-handler.php @@ -163,7 +163,7 @@ function( $errors ) use ( $token ) { $this->_customer_id = is_user_logged_in() ? get_current_user_id() : $this->generate_customer_id(); $this->_data = $this->get_session_data(); $this->set_customer_session_token( true ); - } + }//end if } /** @@ -209,7 +209,7 @@ public function get_session_token() { } } catch ( \Exception $error ) { return new \WP_Error( 'invalid_token', $error->getMessage() ); - } + }//end try return $token; } diff --git a/phpcs.xml.dist b/phpcs.xml.dist index 0c9eb71e3..4c548f9bb 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -42,13 +42,35 @@ + + + /tests/ + + + /tests/ + + + /tests/ + + + /tests/ + + + /tests/ + + + /tests/ + + + /tests/ + + wp-graphql-woocommerce.php access-functions.php - class-inflect.php includes/ /vendor/ /node_modules/ local/* - /tests/ + /tests/_support/Helper/crud-helpers diff --git a/tests/_data/config.php b/tests/_data/config.php index e43a5972a..4f126ffc3 100644 --- a/tests/_data/config.php +++ b/tests/_data/config.php @@ -5,22 +5,22 @@ * fatal errors when the autoloader is loaded twice */ if ( ! defined( 'GRAPHQL_DEBUG' ) ) { - define( 'GRAPHQL_DEBUG', true ); + define( 'GRAPHQL_DEBUG', true ); } if ( ! defined( 'WPGRAPHQL_WOOCOMMERCE_AUTOLOAD' ) && false !== getenv( 'WPGRAPHQL_WOOCOMMERCE_AUTOLOAD' ) ) { - define( 'WPGRAPHQL_WOOCOMMERCE_AUTOLOAD', true ); + define( 'WPGRAPHQL_WOOCOMMERCE_AUTOLOAD', true ); } if ( ! defined( 'GRAPHQL_JWT_AUTH_SECRET_KEY' ) ) { - define( 'GRAPHQL_JWT_AUTH_SECRET_KEY', 'testingtesting123' ); + define( 'GRAPHQL_JWT_AUTH_SECRET_KEY', 'testingtesting123' ); } if ( ! defined( 'STRIPE_API_PUBLISHABLE_KEY' ) && false !== getenv( 'STRIPE_API_PUBLISHABLE_KEY' ) ) { - define( 'STRIPE_API_PUBLISHABLE_KEY', getenv( 'STRIPE_API_PUBLISHABLE_KEY' ) ); + define( 'STRIPE_API_PUBLISHABLE_KEY', getenv( 'STRIPE_API_PUBLISHABLE_KEY' ) ); } if ( ! defined( 'STRIPE_API_SECRET_KEY' ) && false !== getenv( 'STRIPE_API_SECRET_KEY' ) ) { - define( 'STRIPE_API_SECRET_KEY', getenv( 'STRIPE_API_SECRET_KEY' ) ); + define( 'STRIPE_API_SECRET_KEY', getenv( 'STRIPE_API_SECRET_KEY' ) ); } diff --git a/tests/_support/Factory/CartFactory.php b/tests/_support/Factory/CartFactory.php index d7324c068..351f54ed0 100644 --- a/tests/_support/Factory/CartFactory.php +++ b/tests/_support/Factory/CartFactory.php @@ -24,7 +24,7 @@ class CartFactory { public function add( ...$products ) { $keys = array(); - foreach( $products as $product ) { + foreach ( $products as $product ) { if ( gettype( $product ) === 'array' ) { if ( empty( $product['product_id'] ) ) { codecept_debug( $product ); diff --git a/tests/_support/Factory/CouponFactory.php b/tests/_support/Factory/CouponFactory.php index b0b392023..469703684 100644 --- a/tests/_support/Factory/CouponFactory.php +++ b/tests/_support/Factory/CouponFactory.php @@ -14,17 +14,19 @@ * Coupon factory class for testing. */ class CouponFactory extends \WP_UnitTest_Factory_For_Thing { - function __construct( $factory = null ) { + public function __construct( $factory = null ) { parent::__construct( $factory ); $this->default_generation_definitions = array( - 'coupon_class' => '\WC_Coupon', + 'coupon_class' => '\WC_Coupon', ); } public function create_object( $args ) { - if ( is_wp_error( $args ) ) codecept_debug( $args ); - $coupon_class = $args['coupon_class' ]; + if ( is_wp_error( $args ) ) { + codecept_debug( $args ); + } + $coupon_class = $args['coupon_class']; unset( $args['coupon_class'] ); $coupon = new $coupon_class(); @@ -56,7 +58,7 @@ public function update_object( $object, $fields ) { $object = $this->get_object_by_id( $object ); } - foreach( $fields as $field => $field_value ) { + foreach ( $fields as $field => $field_value ) { if ( ! is_callable( array( $object, "set_{$field}" ) ) ) { throw new \Exception( sprintf( '"%1$s" is not a valid %2$s coupon field.', $field, $object->get_type() ) diff --git a/tests/_support/Factory/CustomerFactory.php b/tests/_support/Factory/CustomerFactory.php index 8bed7a0e3..cac47a704 100644 --- a/tests/_support/Factory/CustomerFactory.php +++ b/tests/_support/Factory/CustomerFactory.php @@ -14,15 +14,17 @@ * Customer factory class for testing. */ class CustomerFactory extends \WP_UnitTest_Factory_For_Thing { - function __construct( $factory = null ) { + public function __construct( $factory = null ) { parent::__construct( $factory ); $this->default_generation_definitions = array(); - $this->dummy = Dummy::instance(); + $this->dummy = Dummy::instance(); } public function create_object( $args ) { - if ( is_wp_error( $args ) ) codecept_debug( $args ); + if ( is_wp_error( $args ) ) { + codecept_debug( $args ); + } $customer = new \WC_Customer(); @@ -94,7 +96,7 @@ public function update_object( $object, $fields ) { $object = $this->get_object_by_id( $object ); } - foreach( $fields as $field => $field_value ) { + foreach ( $fields as $field => $field_value ) { if ( ! is_callable( array( $object, "set_{$field}" ) ) ) { throw new \Exception( sprintf( '"%1$s" is not a valid %2$s coupon field.', $field, $object->get_type() ) diff --git a/tests/_support/Factory/OrderFactory.php b/tests/_support/Factory/OrderFactory.php index 7184baced..f555778ab 100644 --- a/tests/_support/Factory/OrderFactory.php +++ b/tests/_support/Factory/OrderFactory.php @@ -14,7 +14,7 @@ * Order factory class for testing. */ class OrderFactory extends \WP_UnitTest_Factory_For_Thing { - function __construct( $factory = null ) { + public function __construct( $factory = null ) { parent::__construct( $factory ); $this->default_generation_definitions = array( @@ -30,7 +30,7 @@ function __construct( $factory = null ) { public function create_object( $args ) { $_SERVER['REMOTE_ADDR'] = '127.0.0.1'; // Required, else wc_create_order throws an exception - $order = \wc_create_order( $args ); + $order = \wc_create_order( $args ); if ( is_wp_error( $order ) ) { throw new \Exception( $order->get_error_message( $args->get_error_code() ) ); @@ -49,7 +49,7 @@ public function update_object( $object, $fields ) { $object = $this->get_object_by_id( $object ); } - foreach( $fields as $field => $field_value ) { + foreach ( $fields as $field => $field_value ) { if ( ! is_callable( array( $object, "set_{$field}" ) ) ) { throw new \Exception( sprintf( '"%1$s" is not a valid %2$s coupon field.', $field, $object->get_type() ) @@ -80,11 +80,12 @@ public function createNew( $args = array(), $items = array() ) { try { // Add line items if ( ! empty( $items['line_items'] ) ) { - foreach( $items['line_items'] as $item ) { + foreach ( $items['line_items'] as $item ) { $order = $this->add_line_item( $order, $item, false ); } } else { - for ( $i = 0; $i < rand( 1, 3 ); $i++ ) { + $random_amount = rand( 1, 3 ); + for ( $i = 0; $i < $random_amount; $i++ ) { $order = $this->add_line_item( $order, array( @@ -105,12 +106,14 @@ public function createNew( $args = array(), $items = array() ) { $shipping_taxes = \WC_Tax::calc_shipping_tax( '10', \WC_Tax::get_shipping_tax_rates() ); $rate = new \WC_Shipping_Rate( 'flat_rate_shipping', 'Flat rate shipping', '10', $shipping_taxes, 'flat_rate' ); $item = new \WC_Order_Item_Shipping(); - $item->set_props( array( - 'method_title' => $rate->label, - 'method_id' => $rate->id, - 'total' => \wc_format_decimal( $rate->cost ), - 'taxes' => $rate->taxes, - ) ); + $item->set_props( + array( + 'method_title' => $rate->label, + 'method_id' => $rate->id, + 'total' => \wc_format_decimal( $rate->cost ), + 'taxes' => $rate->taxes, + ) + ); foreach ( $rate->get_meta_data() as $key => $value ) { $item->add_meta_data( $key, $value, true ); } @@ -130,7 +133,7 @@ public function createNew( $args = array(), $items = array() ) { // Save and return ID. return $order->save(); - } catch( \Exception $e ) { + } catch ( \Exception $e ) { $order->delete( true ); throw new \Exception( $e->getMessage() ); @@ -221,8 +224,8 @@ public function add_coupon_line( $order, $coupon_id = 0, $save = true ) { if ( empty( $coupon_id ) ) { // Get order product IDs $product_ids = array(); - foreach( $order->get_items() as $item ) { - if ( ! in_array( $item->get_product_id(), $product_ids ) ) { + foreach ( $order->get_items() as $item ) { + if ( ! in_array( $item->get_product_id(), $product_ids, true ) ) { $product_ids[] = $item->get_product_id(); } } @@ -254,17 +257,17 @@ public function add_fee( $order, $args = array(), $save = true ) { // Set the array for tax calculations. $calculate_tax_for = array( - 'country' => $country_code, - 'state' => '', + 'country' => $country_code, + 'state' => '', 'postcode' => '', - 'city' => '' + 'city' => '', ); $imported_total_fee = 8.4342; // Create and add fee to order. $item = new \WC_Order_Item_Fee(); - $item->set_name( "Fee" ); // Generic fee name + $item->set_name( 'Fee' ); // Generic fee name $item->set_amount( $imported_total_fee ); // Fee amount $item->set_tax_class( '' ); // default for '' $item->set_tax_status( 'taxable' ); // or 'none' @@ -334,11 +337,11 @@ public function add_tax( $order, $args = array(), $save = true ) { $order->save(); } - public function set_to_customer_billing_address( $order, $customer, $save = true ) { - $order = \wc_get_order( $order ); + public function set_to_customer_billing_address( $order, $customer, $save = true ) { + $order = \wc_get_order( $order ); $customer = new \WC_Customer( $customer ); - // Set billing address + // Set billing address $order->set_billing_first_name( $customer->get_first_name() ); $order->set_billing_last_name( $customer->get_last_name() ); $order->set_billing_company( $customer->get_billing_company() ); @@ -349,20 +352,20 @@ public function set_to_customer_billing_address( $order, $customer, $save = true $order->set_billing_postcode( $customer->get_billing_postcode() ); $order->set_billing_country( $customer->get_billing_country() ); $order->set_billing_email( $customer->get_billing_email() ); - $order->set_billing_phone( $customer->get_billing_phone() ); + $order->set_billing_phone( $customer->get_billing_phone() ); - if ( $save ) { - return $order->save(); + if ( $save ) { + return $order->save(); } return $order; - } + } - public function set_to_customer_shipping_address( $order, $customer, $save = true ) { - $order = \wc_get_order( $order ); + public function set_to_customer_shipping_address( $order, $customer, $save = true ) { + $order = \wc_get_order( $order ); $customer = new \WC_Customer( $customer ); - // Set shipping address + // Set shipping address $order->set_shipping_first_name( $customer->get_first_name() ); $order->set_shipping_last_name( $customer->get_last_name() ); $order->set_shipping_company( $customer->get_shipping_company() ); @@ -371,14 +374,14 @@ public function set_to_customer_shipping_address( $order, $customer, $save = tru $order->set_shipping_city( $customer->get_shipping_city() ); $order->set_shipping_state( $customer->get_shipping_state() ); $order->set_shipping_postcode( $customer->get_shipping_postcode() ); - $order->set_shipping_country( $customer->get_shipping_country() ); + $order->set_shipping_country( $customer->get_shipping_country() ); - if ( $save ) { - return $order->save(); + if ( $save ) { + return $order->save(); } return $order; - } + } public function delete_order( $id ) { $object = $this->get_object_by_id( $id ); diff --git a/tests/_support/Factory/ProductFactory.php b/tests/_support/Factory/ProductFactory.php index a65f50c7a..2499d73b8 100644 --- a/tests/_support/Factory/ProductFactory.php +++ b/tests/_support/Factory/ProductFactory.php @@ -14,7 +14,7 @@ * Product factory class for testing. */ class ProductFactory extends \WP_UnitTest_Factory_For_Thing { - function __construct( $factory = null ) { + public function __construct( $factory = null ) { parent::__construct( $factory ); $this->default_generation_definitions = array( @@ -23,9 +23,11 @@ function __construct( $factory = null ) { } public function create_object( $args ) { - if ( is_wp_error( $args ) ) codecept_debug( $args ); - $product_class = $args['product_class' ]; - unset( $args['product_class'] );; + if ( is_wp_error( $args ) ) { + codecept_debug( $args ); + } + $product_class = $args['product_class']; + unset( $args['product_class'] ); $product = new $product_class(); @@ -47,7 +49,7 @@ public function update_object( $object, $fields ) { $object = $this->get_object_by_id( $object ); } - foreach( $fields as $field => $field_value ) { + foreach ( $fields as $field => $field_value ) { if ( ! is_callable( array( $object, "set_{$field}" ) ) ) { throw new \Exception( sprintf( '"%1$s" is not a valid %2$s product field.', $field, $object->get_type() ) @@ -100,7 +102,7 @@ public function createExternal( $args = array() ) { 'sku' => uniqid(), 'product_url' => 'http://woocommerce.com', 'button_text' => 'Buy external product', - 'product_class' => '\WC_Product_External', + 'product_class' => '\WC_Product_External', ); return $this->create( $args, $generation_definitions ); @@ -128,10 +130,10 @@ public function createVariable( $args = array() ) { $name = Dummy::instance()->product(); $generation_definitions = array( - 'name' => $name, - 'slug' => $this->slugify( $name ), - 'sku' => uniqid(), - 'product_class' => '\WC_Product_Variable', + 'name' => $name, + 'slug' => $this->slugify( $name ), + 'sku' => uniqid(), + 'product_class' => '\WC_Product_Variable', ); $args = array_merge( @@ -215,7 +217,7 @@ public function createAttribute( $raw_name = 'size', $terms = array( 'small' ) ) $result = term_exists( $term, $attribute->slug ); if ( ! $result ) { - $result = wp_insert_term( $term, $attribute->slug ); + $result = wp_insert_term( $term, $attribute->slug ); $return['term_ids'][] = absint( $result['term_id'] ); } else { $return['term_ids'][] = absint( $result['term_id'] ); @@ -227,7 +229,7 @@ public function createAttribute( $raw_name = 'size', $terms = array( 'small' ) ) private function setVariationAttributes( \WC_Product_Variable $product, array $attribute_data = array() ) { $attributes = array(); - foreach( $attribute_data as $index => $data ) { + foreach ( $attribute_data as $index => $data ) { $attribute = new \WC_Product_Attribute(); $attribute->set_id( $data['attribute_id'] ); $attribute->set_name( $data['attribute_taxonomy'] ); @@ -261,7 +263,7 @@ public function createRelated( $args = array() ) { 'upsell_ids' => $upsell_ids, ) ), - 'related' => array( $related_product_id ), + 'related' => array( $related_product_id ), 'cross_sell' => $cross_sell_ids, 'upsell' => $upsell_ids, ); @@ -284,7 +286,7 @@ public function getStockStatusEnum( $status ) { 'onbackorder' => 'ON_BACKORDER', ); - if ( in_array( $status, array_keys( $statuses ) ) ) { + if ( in_array( $status, array_keys( $statuses ), true ) ) { return $statuses[ $status ]; } @@ -295,7 +297,7 @@ public function createProductCategory( $term, $parent_id = 0 ) { if ( term_exists( $term, 'product_cat' ) ) { $term = get_term( $term, 'product_cat', ARRAY_A ); } else { - $args = []; + $args = array(); if ( $parent_id ) { $args['parent'] = $parent_id; } @@ -347,6 +349,7 @@ public function createReview( $product_id, $args = array() ) { * Simple slugify function * * Copied and cleaned up from + * * @link https://stackoverflow.com/questions/2955251/php-function-to-make-slug-url-string * * @param string $text diff --git a/tests/_support/Factory/ProductVariationFactory.php b/tests/_support/Factory/ProductVariationFactory.php index 1b583f7e4..e3ccbb9e8 100644 --- a/tests/_support/Factory/ProductVariationFactory.php +++ b/tests/_support/Factory/ProductVariationFactory.php @@ -14,7 +14,7 @@ * Product variation factory class for testing. */ class ProductVariationFactory extends \WP_UnitTest_Factory_For_Thing { - function __construct( $factory = null ) { + public function __construct( $factory = null ) { parent::__construct( $factory ); $this->default_generation_definitions = array( @@ -23,7 +23,9 @@ function __construct( $factory = null ) { } public function create_object( $args ) { - if ( is_wp_error( $args ) ) codecept_debug( $args ); + if ( is_wp_error( $args ) ) { + codecept_debug( $args ); + } $variation_class = $args['variation_class']; unset( $args['variation_class'] ); @@ -46,7 +48,7 @@ public function update_object( $object, $fields ) { $object = $this->get_object_by_id( $object ); } - foreach( $fields as $field => $field_value ) { + foreach ( $fields as $field => $field_value ) { if ( ! is_callable( array( $object, "set_{$field}" ) ) ) { throw new \Exception( sprintf( '"%1$s" is not a valid %2$s product field.', $field, $object->get_type() ) @@ -71,7 +73,7 @@ public function createSome( $product = null, $args = array() ) { // Create variation stub data. $variation_data = array( array( - 'attributes' => array( 'pa_size' => 'small' ), + 'attributes' => array( 'pa_size' => 'small' ), 'image_id' => null, 'downloads' => array( $this->factory->product->createDownload() ), 'regular_price' => 10, @@ -93,12 +95,12 @@ public function createSome( $product = null, $args = array() ) { 'image_id' => null, 'downloads' => array(), 'regular_price' => 20, - ) + ), ); $variations = array(); - foreach( $variation_data as $data ) { - $args = array_merge( $data, $args ); + foreach ( $variation_data as $data ) { + $args = array_merge( $data, $args ); $variation = $this->create_and_get( $args, array( diff --git a/tests/_support/Factory/RefundFactory.php b/tests/_support/Factory/RefundFactory.php index 21b56fd17..d831310bc 100644 --- a/tests/_support/Factory/RefundFactory.php +++ b/tests/_support/Factory/RefundFactory.php @@ -14,7 +14,7 @@ * Refund factory class for testing. */ class RefundFactory extends \WP_UnitTest_Factory_For_Thing { - function __construct( $factory = null ) { + public function __construct( $factory = null ) { parent::__construct( $factory ); $this->default_generation_definitions = array( @@ -42,7 +42,7 @@ public function update_object( $object, $fields ) { $object = $this->get_object_by_id( $object ); } - foreach( $fields as $field => $field_value ) { + foreach ( $fields as $field => $field_value ) { if ( ! is_callable( array( $object, "set_{$field}" ) ) ) { throw new \Exception( sprintf( '"%1$s" is not a valid %2$s coupon field.', $field, $object->get_type() ) diff --git a/tests/_support/Factory/ShippingZoneFactory.php b/tests/_support/Factory/ShippingZoneFactory.php index 75d8e5477..7521b5804 100644 --- a/tests/_support/Factory/ShippingZoneFactory.php +++ b/tests/_support/Factory/ShippingZoneFactory.php @@ -14,17 +14,19 @@ * Shipping method factory class for testing. */ class ShippingZoneFactory extends \WP_UnitTest_Factory_For_Thing { - function __construct( $factory = null ) { + public function __construct( $factory = null ) { parent::__construct( $factory ); $this->default_generation_definitions = array( 'zone_name' => '', ); - $this->dummy = Dummy::instance(); + $this->dummy = Dummy::instance(); } public function create_object( $args ) { - if ( is_wp_error( $args ) ) codecept_debug( $args ); + if ( is_wp_error( $args ) ) { + codecept_debug( $args ); + } $object = new \WC_Shipping_Zone(); @@ -41,8 +43,6 @@ public function update_object( $object, $fields ) { if ( ! $object instanceof \WC_Customer && 0 !== absint( $object ) ) { $object = $this->get_object_by_id( $object ); } - - } public function get_object_by_id( $id ) { diff --git a/tests/_support/Factory/TaxRateFactory.php b/tests/_support/Factory/TaxRateFactory.php index dc754d764..9a9500b77 100644 --- a/tests/_support/Factory/TaxRateFactory.php +++ b/tests/_support/Factory/TaxRateFactory.php @@ -14,20 +14,22 @@ * Tax Rate factory class for testing. */ class TaxRateFactory extends \WP_UnitTest_Factory_For_Thing { - function __construct( $factory = null ) { + public function __construct( $factory = null ) { parent::__construct( $factory ); $this->default_generation_definitions = array( 'zone_name' => '', ); - $this->dummy = Dummy::instance(); + $this->dummy = Dummy::instance(); } public function create_object( $args ) { - if ( is_wp_error( $args ) ) codecept_debug( $args ); + if ( is_wp_error( $args ) ) { + codecept_debug( $args ); + } $rate_args = array(); - $fields = array( + $fields = array( 'country' => 'tax_rate_country', 'state' => 'tax_rate_state', 'rate' => 'tax_rate', @@ -39,8 +41,8 @@ public function create_object( $args ) { 'class' => 'tax_rate_class', ); - foreach( $args as $key => $value ) { - if ( in_array( $key, array_keys( $fields ) ) ) { + foreach ( $args as $key => $value ) { + if ( in_array( $key, array_keys( $fields ), true ) ) { $rate_args[ $fields[ $key ] ] = $value; } } @@ -50,7 +52,7 @@ public function create_object( $args ) { 'tax_rate_country' => 'US', 'tax_rate_state' => '*', 'tax_rate' => 20.0000, - 'tax_rate_name' => "VAT", + 'tax_rate_name' => 'VAT', 'tax_rate_priority' => 1, 'tax_rate_compound' => 1, 'tax_rate_shipping' => 1, diff --git a/tests/_support/Helper/GraphQLE2E.php b/tests/_support/Helper/GraphQLE2E.php index 43773d09b..4ca9f2880 100644 --- a/tests/_support/Helper/GraphQLE2E.php +++ b/tests/_support/Helper/GraphQLE2E.php @@ -4,37 +4,37 @@ // here you can define custom actions // all public methods declared in helper class will be available in $I class GraphQLE2E extends \Codeception\Module { - /** - * Asserts existence of and returns an array of HTTP response headers - * - * @param string|array $headers Headers to be evaluated and returned. - * - * @return array - */ - public function wantHTTPResponseHeaders( $headers ) { - $rest = $this->getModule( 'REST' ); - - if ( $headers && ! is_array( $headers ) ) { - $rest->seeHttpHeaderOnce( $headers ); - return $rest->grabHttpHeader( $headers ); - } - - $response_headers = array(); - foreach ( $headers as $header ) { - $rest->seeHttpHeaderOnce( $header ); - $response_headers[] = $rest->grabHttpHeader( $header ); - } - } - - /** - * Authenticates User. - * - * @param array $input - * @param string $session_header - * @return array - */ - public function login( $input, $request_headers = array() ) { - $mutation = ' + /** + * Asserts existence of and returns an array of HTTP response headers + * + * @param string|array $headers Headers to be evaluated and returned. + * + * @return array + */ + public function wantHTTPResponseHeaders( $headers ) { + $rest = $this->getModule( 'REST' ); + + if ( $headers && ! is_array( $headers ) ) { + $rest->seeHttpHeaderOnce( $headers ); + return $rest->grabHttpHeader( $headers ); + } + + $response_headers = array(); + foreach ( $headers as $header ) { + $rest->seeHttpHeaderOnce( $header ); + $response_headers[] = $rest->grabHttpHeader( $header ); + } + } + + /** + * Authenticates User. + * + * @param array $input + * @param string $session_header + * @return array + */ + public function login( $input, $request_headers = array() ) { + $mutation = ' mutation ( $input: LoginInput! ) { login( input: $input ) { clientMutationId @@ -49,24 +49,24 @@ public function login( $input, $request_headers = array() ) { } '; - // Send GraphQL request and get response. - $response = $this->sendGraphQLRequest( $mutation, $input, $request_headers ); - - // Return response. - return $response; - } - - /** - * Adds item to cart. - * - * @param array $input - * @param string $session_header - * - * @return array - */ - public function addToCart( $input, $request_headers = array() ) { - // Add to cart mutation - $mutation = ' + // Send GraphQL request and get response. + $response = $this->sendGraphQLRequest( $mutation, $input, $request_headers ); + + // Return response. + return $response; + } + + /** + * Adds item to cart. + * + * @param array $input + * @param string $session_header + * + * @return array + */ + public function addToCart( $input, $request_headers = array() ) { + // Add to cart mutation + $mutation = ' mutation ( $input: AddToCartInput! ) { addToCart( input: $input ) { clientMutationId @@ -92,24 +92,24 @@ public function addToCart( $input, $request_headers = array() ) { } '; - // Send GraphQL request and get response. - $response = $this->sendGraphQLRequest( $mutation, $input, $request_headers ); - - // Return response. - return $response; - } - - /** - * Update cart items quantities. - * - * @param array $input - * @param string $session_header - * - * @return array - */ - public function updateItemQuantities( $input, $request_headers = array() ) { - // Update cart items mutation - $mutation = ' + // Send GraphQL request and get response. + $response = $this->sendGraphQLRequest( $mutation, $input, $request_headers ); + + // Return response. + return $response; + } + + /** + * Update cart items quantities. + * + * @param array $input + * @param string $session_header + * + * @return array + */ + public function updateItemQuantities( $input, $request_headers = array() ) { + // Update cart items mutation + $mutation = ' mutation updateItemQuantities( $input: UpdateItemQuantitiesInput! ) { updateItemQuantities( input: $input ) { clientMutationId @@ -129,23 +129,23 @@ public function updateItemQuantities( $input, $request_headers = array() ) { } '; - // Send GraphQL request and get response. - $response = $this->sendGraphQLRequest( $mutation, $input, $request_headers ); - - // Return response. - return $response; - } - - /** - * Removes an items from the cart. - * - * @param array $input - * @param string $session_header - * @return array - */ - public function removeItemsFromCart( $input, $request_headers = array() ) { - // Remove item from cart mutation - $mutation = ' + // Send GraphQL request and get response. + $response = $this->sendGraphQLRequest( $mutation, $input, $request_headers ); + + // Return response. + return $response; + } + + /** + * Removes an items from the cart. + * + * @param array $input + * @param string $session_header + * @return array + */ + public function removeItemsFromCart( $input, $request_headers = array() ) { + // Remove item from cart mutation + $mutation = ' mutation ( $input: RemoveItemsFromCartInput! ) { removeItemsFromCart( input: $input ) { clientMutationId @@ -171,22 +171,22 @@ public function removeItemsFromCart( $input, $request_headers = array() ) { } '; - // Send GraphQL request and get response. - $response = $this->sendGraphQLRequest( $mutation, $input, $request_headers ); - - // Return response. - return $response; - } - - /** - * Restores items removed from the cart. - * - * @param array $input - * @param string $session_header - * @return array - */ - public function restoreCartItems( $input, $request_headers = array() ) { - $mutation = ' + // Send GraphQL request and get response. + $response = $this->sendGraphQLRequest( $mutation, $input, $request_headers ); + + // Return response. + return $response; + } + + /** + * Restores items removed from the cart. + * + * @param array $input + * @param string $session_header + * @return array + */ + public function restoreCartItems( $input, $request_headers = array() ) { + $mutation = ' mutation restoreCartItems( $input: RestoreCartItemsInput! ) { restoreCartItems( input: $input ) { clientMutationId @@ -212,22 +212,22 @@ public function restoreCartItems( $input, $request_headers = array() ) { } '; - // Send GraphQL request and get response. - $response = $this->sendGraphQLRequest( $mutation, $input, $request_headers ); - - // Return response. - return $response; - } - - /** - * Removes all items from the cart. - * - * @param array $input - * @param string $session_header - * @return array - */ - public function emptyCart( $input, $request_headers = array() ) { - $mutation = ' + // Send GraphQL request and get response. + $response = $this->sendGraphQLRequest( $mutation, $input, $request_headers ); + + // Return response. + return $response; + } + + /** + * Removes all items from the cart. + * + * @param array $input + * @param string $session_header + * @return array + */ + public function emptyCart( $input, $request_headers = array() ) { + $mutation = ' mutation emptyCart( $input: EmptyCartInput! ) { emptyCart( input: $input ) { clientMutationId @@ -257,22 +257,22 @@ public function emptyCart( $input, $request_headers = array() ) { } '; - // Send GraphQL request and get response. - $response = $this->sendGraphQLRequest( $mutation, $input, $request_headers ); - - // Return response. - return $response; - } - - /** - * Adds fee on cart. - * - * @param array $input - * @param string $session_header - * @return array - */ - public function addFee( $input, $request_headers = array() ) { - $mutation = ' + // Send GraphQL request and get response. + $response = $this->sendGraphQLRequest( $mutation, $input, $request_headers ); + + // Return response. + return $response; + } + + /** + * Adds fee on cart. + * + * @param array $input + * @param string $session_header + * @return array + */ + public function addFee( $input, $request_headers = array() ) { + $mutation = ' mutation addFee( $input: AddFeeInput! ) { addFee( input: $input ) { clientMutationId @@ -288,22 +288,22 @@ public function addFee( $input, $request_headers = array() ) { } '; - // Send GraphQL request and get response. - $response = $this->sendGraphQLRequest( $mutation, $input, $request_headers ); - - // Return response. - return $response; - } - - /** - * Applies coupon to the cart. - * - * @param array $input - * @param string $session_header - * @return array - */ - public function applyCoupon( $input, $request_headers = array() ) { - $mutation = ' + // Send GraphQL request and get response. + $response = $this->sendGraphQLRequest( $mutation, $input, $request_headers ); + + // Return response. + return $response; + } + + /** + * Applies coupon to the cart. + * + * @param array $input + * @param string $session_header + * @return array + */ + public function applyCoupon( $input, $request_headers = array() ) { + $mutation = ' mutation applyCoupon( $input: ApplyCouponInput! ) { applyCoupon( input: $input ) { clientMutationId @@ -331,22 +331,22 @@ public function applyCoupon( $input, $request_headers = array() ) { } '; - // Send GraphQL request and get response. - $response = $this->sendGraphQLRequest( $mutation, $input, $request_headers ); - - // Return response. - return $response; - } - - /** - * Removes coupons on the cart. - * - * @param array $input - * @param string $session_header - * @return array - */ - public function removeCoupons( $input, $request_headers = array() ) { - $mutation = ' + // Send GraphQL request and get response. + $response = $this->sendGraphQLRequest( $mutation, $input, $request_headers ); + + // Return response. + return $response; + } + + /** + * Removes coupons on the cart. + * + * @param array $input + * @param string $session_header + * @return array + */ + public function removeCoupons( $input, $request_headers = array() ) { + $mutation = ' mutation removeCoupons( $input: RemoveCouponsInput! ) { removeCoupons( input: $input ) { clientMutationId @@ -372,23 +372,23 @@ public function removeCoupons( $input, $request_headers = array() ) { } '; - // Send GraphQL request and get response. - $response = $this->sendGraphQLRequest( $mutation, $input, $request_headers ); - - // Return response. - return $response; - } - - /** - * Updates customers chosen shipping method. - * - * @param array $input - * @param string $session_header - * @return array - */ - public function updateShippingMethod( $input, $request_headers = array() ) { - // updateShippingMethod mutation. - $mutation = ' + // Send GraphQL request and get response. + $response = $this->sendGraphQLRequest( $mutation, $input, $request_headers ); + + // Return response. + return $response; + } + + /** + * Updates customers chosen shipping method. + * + * @param array $input + * @param string $session_header + * @return array + */ + public function updateShippingMethod( $input, $request_headers = array() ) { + // updateShippingMethod mutation. + $mutation = ' mutation ($input: UpdateShippingMethodInput!){ updateShippingMethod(input: $input) { cart { @@ -412,24 +412,24 @@ public function updateShippingMethod( $input, $request_headers = array() ) { } '; - // Send GraphQL request and get response. - $response = $this->sendGraphQLRequest( $mutation, $input, $request_headers ); - - // Return response. - return $response; - } - - /** - * Place customer order. - * - * @param array $input - * @param string $session_header - * - * @return array - */ - public function checkout( $input, $request_headers = array() ) { - // Checkout mutation. - $mutation = ' + // Send GraphQL request and get response. + $response = $this->sendGraphQLRequest( $mutation, $input, $request_headers ); + + // Return response. + return $response; + } + + /** + * Place customer order. + * + * @param array $input + * @param string $session_header + * + * @return array + */ + public function checkout( $input, $request_headers = array() ) { + // Checkout mutation. + $mutation = ' mutation checkout( $input: CheckoutInput! ) { checkout( input: $input ) { clientMutationId @@ -590,268 +590,277 @@ public function checkout( $input, $request_headers = array() ) { } '; - // Send GraphQL request and get response. - $response = $this->sendGraphQLRequest( $mutation, $input, $request_headers ); - - // Return response. - return $response; - } - - /** - * Sends GraphQL and returns a response - * - * @param string $mutation - * @param array $input - * @param string|null $session_header - * @param bool $update_header - * - * @return array - */ - public function sendGraphQLRequest( $query, $input, $request_headers = array() ) { - $rest = $this->getModule( 'REST' ); - - // Add item to cart. - $rest->haveHttpHeader( 'Content-Type', 'application/json' ); - - // Set request headers - foreach( $request_headers as $header => $value ) { - $rest->haveHttpHeader( $header, $value ); - } - - // Send request. - $rest->sendPost( - "/graphql", - json_encode( - array( - 'query' => $query, - 'variables' => array( 'input' => $input ), - ) - ) - ); - - // Confirm success. - $rest->seeResponseCodeIs( 200 ); - $rest->seeResponseIsJson(); - - // Get response. + // Send GraphQL request and get response. + $response = $this->sendGraphQLRequest( $mutation, $input, $request_headers ); + + // Return response. + return $response; + } + + /** + * Sends GraphQL and returns a response + * + * @param string $mutation + * @param array $input + * @param string|null $session_header + * @param bool $update_header + * + * @return array + */ + public function sendGraphQLRequest( $query, $input, $request_headers = array() ) { + $rest = $this->getModule( 'REST' ); + + // Add item to cart. + $rest->haveHttpHeader( 'Content-Type', 'application/json' ); + + // Set request headers + foreach ( $request_headers as $header => $value ) { + $rest->haveHttpHeader( $header, $value ); + } + + // Send request. + $rest->sendPost( + '/graphql', + json_encode( + array( + 'query' => $query, + 'variables' => array( 'input' => $input ), + ) + ) + ); + + // Confirm success. + $rest->seeResponseCodeIs( 200 ); + $rest->seeResponseIsJson(); + + // Get response. $response = json_decode( $rest->grabResponse(), true ); // Remove extensions field (temporary fix). unset( $response['extensions'] ); - // use --debug flag to view - codecept_debug( json_encode( $response, JSON_PRETTY_PRINT ) ); - - // Delete request headers - foreach( $request_headers as $header => $value ) { - $rest->deleteHeader( $header ); - } - - return $response; - } - - /** - * Creates store products - * - * @return array - */ - public function getCatalog() { - $this->_setupStore(); - - $product_catalog = array(); - $products = array( - array( - 'post_title' => 't-shirt', - 'meta_input' => array( - '_price' => 45, - '_regular_price' => 45, - ) - ), - array( - 'post_title' => 'jeans', - 'meta_input' => array( - '_price' => 60, - '_regular_price' => 60, - ) - ), - array( - 'post_title' => 'belt', - 'meta_input' => array( - '_price' => 45, - '_regular_price' => 45, - ) - ), - array( - 'post_title' => 'shoes', - 'meta_input' => array( - '_price' => 115, - '_regular_price' => 115, - ) - ), - array( - 'post_title' => 'socks', - 'meta_input' => array( - '_price' => 20, - '_regular_price' => 20, - ) - ), - ); - foreach ( $products as $product ) { - $this->haveAProductInTheDatabase( $product, $product_id ); - $product_catalog[ $product['post_title'] ] = $product_id; - } - - return $product_catalog; - } - - /** - * Initializes store options and actions - * - * @param AcceptanceTester $I - * @return void - */ - public function _setupStore() { - // Turn on tax calculations and store shipping countries. Important! - update_option( 'woocommerce_ship_to_countries', 'all' ); - update_option( 'woocommerce_prices_include_tax', 'no' ); - update_option( 'woocommerce_calc_taxes', 'yes' ); - update_option( 'woocommerce_tax_round_at_subtotal', 'no' ); - - // Enable payment gateway. - update_option( - 'woocommerce_bacs_settings', - array( - 'enabled' => 'yes', - 'title' => 'Direct bank transfer', - 'description' => 'Make your payment directly into our bank account. Please use your Order ID as the payment reference. Your order will not be shipped until the funds have cleared in our account.', - 'instructions' => 'Instructions that will be added to the thank you page and emails.', - 'account' => '', - ) - ); - - - // Additional cart fees. - add_action( - 'woocommerce_cart_calculate_fees', - function() { - $percentage = 0.01; - $surcharge = ( \WC()->cart->cart_contents_total + \WC()->cart->shipping_total ) * $percentage; - \WC()->cart->add_fee( 'Surcharge', $surcharge, true, '' ); - } - ); + // use --debug flag to view + codecept_debug( json_encode( $response, JSON_PRETTY_PRINT ) ); + + // Delete request headers + foreach ( $request_headers as $header => $value ) { + $rest->deleteHeader( $header ); + } - // Create Shipping Zones. + return $response; + } + + /** + * Creates store products + * + * @return array + */ + public function getCatalog() { + $this->_setupStore(); + + $product_catalog = array(); + $products = array( + array( + 'post_title' => 't-shirt', + 'meta_input' => array( + '_price' => 45, + '_regular_price' => 45, + ), + ), + array( + 'post_title' => 'jeans', + 'meta_input' => array( + '_price' => 60, + '_regular_price' => 60, + ), + ), + array( + 'post_title' => 'belt', + 'meta_input' => array( + '_price' => 45, + '_regular_price' => 45, + ), + ), + array( + 'post_title' => 'shoes', + 'meta_input' => array( + '_price' => 115, + '_regular_price' => 115, + ), + ), + array( + 'post_title' => 'socks', + 'meta_input' => array( + '_price' => 20, + '_regular_price' => 20, + ), + ), + ); + foreach ( $products as $product ) { + $this->haveAProductInTheDatabase( $product, $product_id ); + $product_catalog[ $product['post_title'] ] = $product_id; + } + + return $product_catalog; + } + + /** + * Initializes store options and actions + * + * @param AcceptanceTester $I + * @return void + */ + public function _setupStore() { + // Turn on tax calculations and store shipping countries. Important! + update_option( 'woocommerce_ship_to_countries', 'all' ); + update_option( 'woocommerce_prices_include_tax', 'no' ); + update_option( 'woocommerce_calc_taxes', 'yes' ); + update_option( 'woocommerce_tax_round_at_subtotal', 'no' ); + + // Enable payment gateway. + update_option( + 'woocommerce_bacs_settings', + array( + 'enabled' => 'yes', + 'title' => 'Direct bank transfer', + 'description' => 'Make your payment directly into our bank account. Please use your Order ID as the payment reference. Your order will not be shipped until the funds have cleared in our account.', + 'instructions' => 'Instructions that will be added to the thank you page and emails.', + 'account' => '', + ) + ); + + // Additional cart fees. + add_action( + 'woocommerce_cart_calculate_fees', + function() { + $percentage = 0.01; + $surcharge = ( \WC()->cart->cart_contents_total + \WC()->cart->shipping_total ) * $percentage; + \WC()->cart->add_fee( 'Surcharge', $surcharge, true, '' ); + } + ); + + // Create Shipping Zones. $zone = new \WC_Shipping_Zone(); $zone->set_zone_name( 'Local' ); $zone->set_zone_order( 1 ); $zone->add_location( 'GB', 'country' ); $zone->add_location( 'CB*', 'postcode' ); - $zone->save(); - $zone->add_shipping_method( 'flat_rate' ); - $zone->add_shipping_method( 'free_shipping' ); + $zone->save(); + $zone->add_shipping_method( 'flat_rate' ); + $zone->add_shipping_method( 'free_shipping' ); - $zone = new \WC_Shipping_Zone(); + $zone = new \WC_Shipping_Zone(); $zone->set_zone_name( 'Europe' ); $zone->set_zone_order( 2 ); $zone->add_location( 'EU', 'continent' ); - $zone->save(); - $zone->add_shipping_method( 'flat_rate' ); - $zone->add_shipping_method( 'free_shipping' ); + $zone->save(); + $zone->add_shipping_method( 'flat_rate' ); + $zone->add_shipping_method( 'free_shipping' ); - $zone = new \WC_Shipping_Zone(); + $zone = new \WC_Shipping_Zone(); $zone->set_zone_name( 'California' ); $zone->set_zone_order( 3 ); $zone->add_location( 'US:CA', 'state' ); - $zone->save(); - $zone->add_shipping_method( 'flat_rate' ); - $zone->add_shipping_method( 'free_shipping' ); + $zone->save(); + $zone->add_shipping_method( 'flat_rate' ); + $zone->add_shipping_method( 'free_shipping' ); $zone = new \WC_Shipping_Zone(); $zone->set_zone_name( 'US' ); $zone->set_zone_order( 4 ); $zone->add_location( 'US', 'country' ); - $zone->save(); - $zone->add_shipping_method( 'flat_rate' ); - $zone->add_shipping_method( 'free_shipping' ); - } - - /** - * Adds Product in database - * - * @param AcceptanceTester $I - * @param array $args Product args. - * @param integer $product_id ID for product being created. - * @param string $term Product type. Defaults to 'simple'. - * @param integer $term_id Product type term ID. - * @return void - */ - public function haveAProductInTheDatabase( $args, &$product_id, $term = 'simple', &$term_id = 0 ) { - $wpdb = $this->getModule( 'WPDb' ); - // Create Product - $product_id = $wpdb->havePostInDatabase( - array_replace_recursive( - array( - 'post_type' => 'product', - 'post_title' => 't-shirt', - 'meta_input' => array( - '_visibility' => 'visible', - '_sku' => '', - '_price' => '100', - '_regular_price' => '100', - '_sale_price' => '', - '_sale_date_on_sale_from' => null, - '_sale_date_on_sale_to' => null, - 'total_sales' => '0', - '_tax_status' => 'taxable', - '_tax_class' => '', - '_manage_stock' => false, - '_stock_quantity' => null, - '_stock_status' => 'instock', - '_backorders' => 'no', - '_low_stock_amount' => '', - '_sold_individually' => false, - '_weight' => '', - '_length' => '', - '_width' => '', - '_height' => '', - '_upsell_ids' => array(), - '_cross_sell_ids' => array(), - '_purchase_note' => '', - '_default_attributes' => array(), - '_product_attributes' => array(), - '_virtual' => false, - '_downloadable' => false, - '_download_limit' => -1, - '_download_expiry' => -1, - '_featured' => false, - '_wc_rating_counts' => array(), - '_wc_average_rating' => 0, - '_wc_review_count' => 0, - ), - ), - $args - ) - ); - - if ( ! $term_id ) { - $term_id = $wpdb->grabTermIdFromDatabase( [ 'name' => $term, 'slug' => $term ] ); - } - $term_taxonomy_id = $wpdb->grabTermTaxonomyIdFromDatabase( [ 'term_id' => $term_id, 'taxonomy' => 'product_type' ] ); - $wpdb->haveTermRelationshipInDatabase( $product_id, $term_id ); - } - - - public function setupStoreAndUsers() { + $zone->save(); + $zone->add_shipping_method( 'flat_rate' ); + $zone->add_shipping_method( 'free_shipping' ); + } + + /** + * Adds Product in database + * + * @param AcceptanceTester $I + * @param array $args Product args. + * @param integer $product_id ID for product being created. + * @param string $term Product type. Defaults to 'simple'. + * @param integer $term_id Product type term ID. + * @return void + */ + public function haveAProductInTheDatabase( $args, &$product_id, $term = 'simple', &$term_id = 0 ) { + $wpdb = $this->getModule( 'WPDb' ); + // Create Product + $product_id = $wpdb->havePostInDatabase( + array_replace_recursive( + array( + 'post_type' => 'product', + 'post_title' => 't-shirt', + 'meta_input' => array( + '_visibility' => 'visible', + '_sku' => '', + '_price' => '100', + '_regular_price' => '100', + '_sale_price' => '', + '_sale_date_on_sale_from' => null, + '_sale_date_on_sale_to' => null, + 'total_sales' => '0', + '_tax_status' => 'taxable', + '_tax_class' => '', + '_manage_stock' => false, + '_stock_quantity' => null, + '_stock_status' => 'instock', + '_backorders' => 'no', + '_low_stock_amount' => '', + '_sold_individually' => false, + '_weight' => '', + '_length' => '', + '_width' => '', + '_height' => '', + '_upsell_ids' => array(), + '_cross_sell_ids' => array(), + '_purchase_note' => '', + '_default_attributes' => array(), + '_product_attributes' => array(), + '_virtual' => false, + '_downloadable' => false, + '_download_limit' => -1, + '_download_expiry' => -1, + '_featured' => false, + '_wc_rating_counts' => array(), + '_wc_average_rating' => 0, + '_wc_review_count' => 0, + ), + ), + $args + ) + ); + + if ( ! $term_id ) { + $term_id = $wpdb->grabTermIdFromDatabase( + array( + 'name' => $term, + 'slug' => $term, + ) + ); + } + $term_taxonomy_id = $wpdb->grabTermTaxonomyIdFromDatabase( + array( + 'term_id' => $term_id, + 'taxonomy' => 'product_type', + ) + ); + $wpdb->haveTermRelationshipInDatabase( $product_id, $term_id ); + } + + + public function setupStoreAndUsers() { $this->_setupStore(); - $wpdb = $this->getModule( 'WPDb' ); - $userId = $wpdb->haveUserInDatabase( - 'jimbo1234', - 'customer', - [ - 'user_pass' => 'password', - 'user_email' => 'jimbo1234@example.com', - ] - ); - } + $wpdb = $this->getModule( 'WPDb' ); + $userId = $wpdb->haveUserInDatabase( + 'jimbo1234', + 'customer', + array( + 'user_pass' => 'password', + 'user_email' => 'jimbo1234@example.com', + ) + ); + } } diff --git a/tests/_support/Helper/Wpunit.php b/tests/_support/Helper/Wpunit.php index 2da300dec..97017bddb 100644 --- a/tests/_support/Helper/Wpunit.php +++ b/tests/_support/Helper/Wpunit.php @@ -81,7 +81,7 @@ public function tax_rate() { public function get_nodes( $ids, $crud ) { $nodes = array(); - foreach( $ids as $id ) { + foreach ( $ids as $id ) { $nodes[] = $crud->get_query_data( $id ); } diff --git a/tests/_support/TestCase/WooGraphQLTestCase.php b/tests/_support/TestCase/WooGraphQLTestCase.php index 888fd3896..d51275157 100644 --- a/tests/_support/TestCase/WooGraphQLTestCase.php +++ b/tests/_support/TestCase/WooGraphQLTestCase.php @@ -3,6 +3,7 @@ * WPGraphQL test case * * For testing WPGraphQL responses. + * * @since 0.8.0 * @package Tests\WPGraphQL\TestCase */ @@ -45,8 +46,8 @@ public function setUp(): void { ); foreach ( $factories as $factory ) { - $factory_name = strtolower( preg_replace( '/\B([A-Z])/', '_$1', $factory ) ); - $factory_class = '\\Tests\\WPGraphQL\\WooCommerce\\Factory\\' . $factory . 'Factory'; + $factory_name = strtolower( preg_replace( '/\B([A-Z])/', '_$1', $factory ) ); + $factory_class = '\\Tests\\WPGraphQL\\WooCommerce\\Factory\\' . $factory . 'Factory'; $this->factory->{$factory_name} = new $factory_class( $this->factory ); } diff --git a/tests/_support/Utils/Dummy.php b/tests/_support/Utils/Dummy.php index 58e5f8000..7de0173d2 100644 --- a/tests/_support/Utils/Dummy.php +++ b/tests/_support/Utils/Dummy.php @@ -34,232 +34,285 @@ public static function instance() { return self::$instance; } - public function all() { - $un = $this->username(); - $fn = $this->firstname(); - $ln = $this->lastname(); - - $dump = array( - "primaryText" => $this->words(6), - "secondaryText" => $this->sentence(), - "userid" => $this->number(), - "rid" => $this->number(), - - "link" => "http://www.google.com", - "date" => $this->mdy(), - "time" => $this->hm(), - "text" => $this->text(40,140), - "body" => $this->text(140,600), - "number" => $this->number(), - "background" => $this->image(640,480), - "image" => $this->image(), - "thumbnail" => $this->placeholder(150,150), - "price" => $this->price(), - "product" => $this->product(), - "firstname" => $fn, - "lastname" => $ln, - "name" => $fn." ".$ln, - "username" => $un, - "email" => $this->email($un), - "street" => $this->street(), - "city" => $this->city(), - "state" => $this->state(), - "zipcode" => $this->zipcode(), - "telephone" => $this->telephone() - ); - - return($dump); - } - - public function dump( $qty = 5 ) { - $a = array(); - - for($b=0;$b<$qty;$b++) { - $a[] = $this->all(); - } - - return($a); - } - - public function yesno( $w = 5 ) { - if (rand(0,10) > $w) { - return(true); - } else { - return(false); - } - } - - public function mdy() { - return(rand(1,12)."/".rand(1,30)."/".rand(1943,2010)); - } - - public function hm( $s = false ) { - $t = rand(1,12).":".rand(10,59); - - if ($s) { $t = $t.":".rand(10,59); } - - if ($this->yesno()) { $t .= " AM"; } else { $t .= " PM"; } - - return($t); - } - - public function text( $min = 30, $max = 120, $nospaces = false ) { - $s = "Aliquam lectus nulla, eleifend ut tellus in, euismod porttitor arcu. Aliquam erat volutpat. Morbi massa sapien, condimentum ultrices pretium porta, semper ac lacus. Nulla pharetra, urna a lacinia facilisis, neque libero placerat turpis, vel tincidunt massa nunc ac nunc. In nec volutpat ligula. Sed hendrerit ligula vel felis venenatis egestas. Duis sit amet pharetra erat. Interdum et malesuada fames ac ante ipsum primis in faucibus. Morbi rutrum vel magna et tincidunt. Curabitur mattis, sem eget suscipit porta, nibh enim auctor mi, eu lacinia magna velit eu quam. Donec commodo ultrices lorem vel ultrices. Aliquam erat volutpat. Praesent in libero bibendum, euismod dui quis, volutpat purus. Fusce non est egestas, volutpat ipsum ut, cursus augue. In hac habitasse platea dictumst. Mum volutpat."; - $s = explode(" ",$s); - shuffle($s); - $s = implode(" ", $s); - $s = ucfirst(substr($s, 0, rand($min,$max))); - - if ($nospaces) { - $s = str_replace(" ","",$s); - } - - return($s); - } - - public function words( $max = 5, $cmin = 2, $cmax = 6) { - $t = array(); - - for ($a=0; $a <= ($max-1); $a++) { - $t[] = str_replace(array(",","."), array("",""), $this->text($cmin, ($cmax+2), true)); - } - - return(implode(" ",$t)); - } - - public function sentence( $min = 3, $max = 10 ) { - $l = rand($min,$max); - - $w = ucfirst(strtolower($this->words($l)))."."; - return($w); - } - - function number($min=10, $max=1000) { - return(round(rand($min,$max))); - } - - public function image( $w = 300, $h = 300 ) { - $c = array("city","people","animals","food","business","cats","technics","sports"); - shuffle($c); - $u = "http://lorempixel.com/".$w."/".$h."/".current($c); - - return($u); - } - - public function placeholder( $w = 300, $h = 300 ) { - return("http://placehold.it/".$w."x".$h); - } - - public function price( $min = 2, $max = 500 ) { - $c = array("00","99","49","00","50","29"); shuffle($c); - $p = rand($min,$max).".".current($c); - return($p); - } - - public function product() { - $items = "book,exam,hub cap,paperclip,model train,phaser,socks,light saber,lamp,piano,salad,lunch,violin,pony,deoderant,powder,radio,purse,mp3 player,eyeliner,laptop,wheel,glove,boot,pen,slippers,bed,dog,wall,paper,cellular phone,clock,tree,guitar,mullet,dog,cushion,table,ginger,roundabout,cake,teapot,dreadlocks,lampshade,piggy bank,church,eagle,butterfly,keyboard,laptop"; - $adj1 = "original,brand new,mint,new-in-box,trendy,vintage,retro,old,new,gently used,big,small,tarnished,broken,refurbished"; - $adj2 = "hipster,red,blue,green,orange,muddy,waterproof,purple,stainless steel,24k gold,handmade,custom"; - - $a = explode(",",$adj1); - $a2 = explode(",",$adj2); - $i = explode(",",$items); - shuffle($a); - shuffle($a2); - shuffle($i); - - //$t = ucfirst($a[0]." ".$a2[3]." ".$i[1]); - $t = ucfirst($a2[3]." ".$i[1]); - return($t); - } - - public function firstname( $gender = "any" ) { - $m = explode(",","James,John,Robert,Michael,William,David,Richard,Charles,Joseph,Thomas,Christopher,Daniel,Paul,Mark,Donald,George,Kenneth,Steven,Edward,Brian,Ronald,Anthony,Kevin,Jason,Matthew,Gary,Timothy,Jose,Larry,Jeffrey,Frank,Scott,Eric,Stephen,Andrew,Raymond,Gregory,Joshua,Jerry,Dennis,Walter,Patrick,Peter,Harold,Douglas,Henry,Carl,Arthur,Ryan,Roger"); - $fm = explode(",","Mary,Patricia,Linda,Barbara,Elizabeth,Jennifer,Maria,Susan,Margaret,Dorothy,Lisa,Nancy,Karen,Betty,Helen,Sandra,Donna,Carol,Ruth,Sharon,Michelle,Laura,Sarah,Kimberly,Deborah,Jessica,Shirley,Cynthia,Angela,Melissa,Brenda,Amy,Anna,Rebecca,Virginia,Kathleen,Pamela,Martha,Debra,Amanda,Stephanie,Carolyn,Christine,Marie,Janet,Catherine,Frances,Ann,Joyce,Diane"); - $all = array_merge($m, $fm); - - shuffle($m); - shuffle($fm); - shuffle($all); - - switch ($gender) { - default: - return(current($all)); - break; - case "m": - return(current($m)); - break; - case "fm": - return(current($fm)); - break; - } - } - - public function lastname() { - $list = explode(",","Smith,Johnson,Williams,Jones,Brown,Davis,Miller,Wilson,Moore,Taylor,Anderson,Thomas,Jackson,White,Harris,Martin,Thompson,Garcia,Martinez,Robinson,Clark,Rodriguez,Lewis,Lee,Walker,Hall,Allen,Young,Hernandez,King,Wright,Lopez,Hill,Scott,Green,Adams,Baker,Gonzalez,Nelson,Carter,Mitchell,Perez,Roberts,Turner,Phillips,Campbell,Parker,Evans,Edwards,Collins,Dexter,Dennis,Menace,Jesus,Bart,Homer,Dan,Bub,Sparkster,Yanni"); - shuffle($list); - return(current($list)); - } - - public function name() { - $f = $this->firstname(); - $l = $this->lastname(); - return($f." ".$l); - } - - public function username() { - $n = rand(1,300); - $f = substr($this->firstname(),0,1); - $l = $this->lastname() .$n; - - return(strtolower($f.$l)); - - } - - public function email( $u = false ) { - if (!$u) { $u = $this->username(); } - $m = array("@gmail.com","@hotmail.com","@yahoo.com","@aol.com","@redlinederby.com"); - shuffle($m); - $m = current($m); - - - return(strtolower($u.$m)); - } - - public function street() { - $list = explode(",","Second,Third,First,Fourth,Park,Fifth,Main,Sixth,Oak,Seventh,Pine,Maple,Cedar,Eighth,Elm,Washington,Ninth,Lake,Hill"); - $n = rand(700,5500); - shuffle($list); - return($n." ".current($list)." St."); - } - - public function city() { - $list = explode(",","Gotham City,Metropolis,Oz,Smallville,Mos Eisley,Mayberry,Bedrock,Springfield,Vice City,Atlantis,Hill Valley,New New York,Cloud City,Bikini Bottom"); - shuffle($list); - return(current($list)); - } - - public function state( $full = false ) { - $list = array('AL'=>"Alabama",'AK'=>"Alaska", 'AZ'=>"Arizona", 'AR'=>"Arkansas", 'CA'=>"California", 'CO'=>"Colorado", 'CT'=>"Connecticut", 'DE'=>"Delaware", 'DC'=>"District Of Columbia", 'FL'=>"Florida", 'GA'=>"Georgia", 'HI'=>"Hawaii", 'ID'=>"Idaho", 'IL'=>"Illinois", 'IN'=>"Indiana", 'IA'=>"Iowa", 'KS'=>"Kansas", 'KY'=>"Kentucky", 'LA'=>"Louisiana", 'ME'=>"Maine", 'MD'=>"Maryland", 'MA'=>"Massachusetts", 'MI'=>"Michigan", 'MN'=>"Minnesota", 'MS'=>"Mississippi", 'MO'=>"Missouri", 'MT'=>"Montana", 'NE'=>"Nebraska", 'NV'=>"Nevada", 'NH'=>"New Hampshire", 'NJ'=>"New Jersey", 'NM'=>"New Mexico", 'NY'=>"New York", 'NC'=>"North Carolina", 'ND'=>"North Dakota", 'OH'=>"Ohio", 'OK'=>"Oklahoma", 'OR'=>"Oregon", 'PA'=>"Pennsylvania", 'RI'=>"Rhode Island", 'SC'=>"South Carolina", 'SD'=>"South Dakota", 'TN'=>"Tennessee", 'TX'=>"Texas", 'UT'=>"Utah", 'VT'=>"Vermont", 'VA'=>"Virginia", 'WA'=>"Washington", 'WV'=>"West Virginia", 'WI'=>"Wisconsin", 'WY'=>"Wyoming"); - $abbv = array_rand($list, 1); - - if ($full) { - return($list[$abbv]); - } else { - return($abbv); - } - } - - public function zipcode() { - return(rand(12345,98765)); - } - - public function address() { - $a = $this->street()."
".$this->city().", ".$this->state()." ".$this->zipcode(); - return($a); - } - - public function telephone() { - return(rand(123,876)."-".rand(123,987)."-".rand(1234,9876)); - } + public function all() { + $un = $this->username(); + $fn = $this->firstname(); + $ln = $this->lastname(); + + $dump = array( + 'primaryText' => $this->words( 6 ), + 'secondaryText' => $this->sentence(), + 'userid' => $this->number(), + 'rid' => $this->number(), + + 'link' => 'http://www.google.com', + 'date' => $this->mdy(), + 'time' => $this->hm(), + 'text' => $this->text( 40, 140 ), + 'body' => $this->text( 140, 600 ), + 'number' => $this->number(), + 'background' => $this->image( 640, 480 ), + 'image' => $this->image(), + 'thumbnail' => $this->placeholder( 150, 150 ), + 'price' => $this->price(), + 'product' => $this->product(), + 'firstname' => $fn, + 'lastname' => $ln, + 'name' => $fn . ' ' . $ln, + 'username' => $un, + 'email' => $this->email( $un ), + 'street' => $this->street(), + 'city' => $this->city(), + 'state' => $this->state(), + 'zipcode' => $this->zipcode(), + 'telephone' => $this->telephone(), + ); + + return( $dump ); + } + + public function dump( $qty = 5 ) { + $a = array(); + + for ( $b = 0;$b < $qty;$b++ ) { + $a[] = $this->all(); + } + + return( $a ); + } + + public function yesno( $w = 5 ) { + if ( rand( 0, 10 ) > $w ) { + return( true ); + } else { + return( false ); + } + } + + public function mdy() { + return( rand( 1, 12 ) . '/' . rand( 1, 30 ) . '/' . rand( 1943, 2010 ) ); + } + + public function hm( $s = false ) { + $t = rand( 1, 12 ) . ':' . rand( 10, 59 ); + + if ( $s ) { + $t = $t . ':' . rand( 10, 59 ); } + + if ( $this->yesno() ) { + $t .= ' AM'; + } else { + $t .= ' PM'; } + + return( $t ); + } + + public function text( $min = 30, $max = 120, $nospaces = false ) { + $s = 'Aliquam lectus nulla, eleifend ut tellus in, euismod porttitor arcu. Aliquam erat volutpat. Morbi massa sapien, condimentum ultrices pretium porta, semper ac lacus. Nulla pharetra, urna a lacinia facilisis, neque libero placerat turpis, vel tincidunt massa nunc ac nunc. In nec volutpat ligula. Sed hendrerit ligula vel felis venenatis egestas. Duis sit amet pharetra erat. Interdum et malesuada fames ac ante ipsum primis in faucibus. Morbi rutrum vel magna et tincidunt. Curabitur mattis, sem eget suscipit porta, nibh enim auctor mi, eu lacinia magna velit eu quam. Donec commodo ultrices lorem vel ultrices. Aliquam erat volutpat. Praesent in libero bibendum, euismod dui quis, volutpat purus. Fusce non est egestas, volutpat ipsum ut, cursus augue. In hac habitasse platea dictumst. Mum volutpat.'; + $s = explode( ' ', $s ); + shuffle( $s ); + $s = implode( ' ', $s ); + $s = ucfirst( substr( $s, 0, rand( $min, $max ) ) ); + + if ( $nospaces ) { + $s = str_replace( ' ', '', $s ); + } + + return( $s ); + } + + public function words( $max = 5, $cmin = 2, $cmax = 6 ) { + $t = array(); + + for ( $a = 0; $a <= ( $max - 1 ); $a++ ) { + $t[] = str_replace( array( ',', '.' ), array( '', '' ), $this->text( $cmin, ( $cmax + 2 ), true ) ); + } + + return( implode( ' ', $t ) ); + } + + public function sentence( $min = 3, $max = 10 ) { + $l = rand( $min, $max ); + + $w = ucfirst( strtolower( $this->words( $l ) ) ) . '.'; + return( $w ); + } + + public function number( $min = 10, $max = 1000 ) { + return( round( rand( $min, $max ) ) ); + } + + public function image( $w = 300, $h = 300 ) { + $c = array( 'city', 'people', 'animals', 'food', 'business', 'cats', 'technics', 'sports' ); + shuffle( $c ); + $u = 'http://lorempixel.com/' . $w . '/' . $h . '/' . current( $c ); + + return( $u ); + } + + public function placeholder( $w = 300, $h = 300 ) { + return( 'http://placehold.it/' . $w . 'x' . $h ); + } + + public function price( $min = 2, $max = 500 ) { + $c = array( '00', '99', '49', '00', '50', '29' ); + shuffle( $c ); + $p = rand( $min, $max ) . '.' . current( $c ); + return( $p ); + } + + public function product() { + $items = 'book,exam,hub cap,paperclip,model train,phaser,socks,light saber,lamp,piano,salad,lunch,violin,pony,deoderant,powder,radio,purse,mp3 player,eyeliner,laptop,wheel,glove,boot,pen,slippers,bed,dog,wall,paper,cellular phone,clock,tree,guitar,mullet,dog,cushion,table,ginger,roundabout,cake,teapot,dreadlocks,lampshade,piggy bank,church,eagle,butterfly,keyboard,laptop'; + $adj1 = 'original,brand new,mint,new-in-box,trendy,vintage,retro,old,new,gently used,big,small,tarnished,broken,refurbished'; + $adj2 = 'hipster,red,blue,green,orange,muddy,waterproof,purple,stainless steel,24k gold,handmade,custom'; + + $a = explode( ',', $adj1 ); + $a2 = explode( ',', $adj2 ); + $i = explode( ',', $items ); + shuffle( $a ); + shuffle( $a2 ); + shuffle( $i ); + + // $t = ucfirst($a[0]." ".$a2[3]." ".$i[1]); + $t = ucfirst( $a2[3] . ' ' . $i[1] ); + return( $t ); + } + + public function firstname( $gender = 'any' ) { + $m = explode( ',', 'James,John,Robert,Michael,William,David,Richard,Charles,Joseph,Thomas,Christopher,Daniel,Paul,Mark,Donald,George,Kenneth,Steven,Edward,Brian,Ronald,Anthony,Kevin,Jason,Matthew,Gary,Timothy,Jose,Larry,Jeffrey,Frank,Scott,Eric,Stephen,Andrew,Raymond,Gregory,Joshua,Jerry,Dennis,Walter,Patrick,Peter,Harold,Douglas,Henry,Carl,Arthur,Ryan,Roger' ); + $fm = explode( ',', 'Mary,Patricia,Linda,Barbara,Elizabeth,Jennifer,Maria,Susan,Margaret,Dorothy,Lisa,Nancy,Karen,Betty,Helen,Sandra,Donna,Carol,Ruth,Sharon,Michelle,Laura,Sarah,Kimberly,Deborah,Jessica,Shirley,Cynthia,Angela,Melissa,Brenda,Amy,Anna,Rebecca,Virginia,Kathleen,Pamela,Martha,Debra,Amanda,Stephanie,Carolyn,Christine,Marie,Janet,Catherine,Frances,Ann,Joyce,Diane' ); + $all = array_merge( $m, $fm ); + + shuffle( $m ); + shuffle( $fm ); + shuffle( $all ); + + switch ( $gender ) { + default: + return( current( $all ) ); + case 'm': + return( current( $m ) ); + case 'fm': + return( current( $fm ) ); + } + } + + public function lastname() { + $list = explode( ',', 'Smith,Johnson,Williams,Jones,Brown,Davis,Miller,Wilson,Moore,Taylor,Anderson,Thomas,Jackson,White,Harris,Martin,Thompson,Garcia,Martinez,Robinson,Clark,Rodriguez,Lewis,Lee,Walker,Hall,Allen,Young,Hernandez,King,Wright,Lopez,Hill,Scott,Green,Adams,Baker,Gonzalez,Nelson,Carter,Mitchell,Perez,Roberts,Turner,Phillips,Campbell,Parker,Evans,Edwards,Collins,Dexter,Dennis,Menace,Jesus,Bart,Homer,Dan,Bub,Sparkster,Yanni' ); + shuffle( $list ); + return( current( $list ) ); + } + + public function name() { + $f = $this->firstname(); + $l = $this->lastname(); + return( $f . ' ' . $l ); + } + + public function username() { + $n = rand( 1, 300 ); + $f = substr( $this->firstname(), 0, 1 ); + $l = $this->lastname() . $n; + + return( strtolower( $f . $l ) ); + } + + public function email( $u = false ) { + if ( ! $u ) { + $u = $this->username(); } + $m = array( '@gmail.com', '@hotmail.com', '@yahoo.com', '@aol.com', '@redlinederby.com' ); + shuffle( $m ); + $m = current( $m ); + + return( strtolower( $u . $m ) ); + } + + public function street() { + $list = explode( ',', 'Second,Third,First,Fourth,Park,Fifth,Main,Sixth,Oak,Seventh,Pine,Maple,Cedar,Eighth,Elm,Washington,Ninth,Lake,Hill' ); + $n = rand( 700, 5500 ); + shuffle( $list ); + return( $n . ' ' . current( $list ) . ' St.' ); + } + + public function city() { + $list = explode( ',', 'Gotham City,Metropolis,Oz,Smallville,Mos Eisley,Mayberry,Bedrock,Springfield,Vice City,Atlantis,Hill Valley,New New York,Cloud City,Bikini Bottom' ); + shuffle( $list ); + return( current( $list ) ); + } + + public function state( $full = false ) { + $list = array( + 'AL' => 'Alabama', + 'AK' => 'Alaska', + 'AZ' => 'Arizona', + 'AR' => 'Arkansas', + 'CA' => 'California', + 'CO' => 'Colorado', + 'CT' => 'Connecticut', + 'DE' => 'Delaware', + 'DC' => 'District Of Columbia', + 'FL' => 'Florida', + 'GA' => 'Georgia', + 'HI' => 'Hawaii', + 'ID' => 'Idaho', + 'IL' => 'Illinois', + 'IN' => 'Indiana', + 'IA' => 'Iowa', + 'KS' => 'Kansas', + 'KY' => 'Kentucky', + 'LA' => 'Louisiana', + 'ME' => 'Maine', + 'MD' => 'Maryland', + 'MA' => 'Massachusetts', + 'MI' => 'Michigan', + 'MN' => 'Minnesota', + 'MS' => 'Mississippi', + 'MO' => 'Missouri', + 'MT' => 'Montana', + 'NE' => 'Nebraska', + 'NV' => 'Nevada', + 'NH' => 'New Hampshire', + 'NJ' => 'New Jersey', + 'NM' => 'New Mexico', + 'NY' => 'New York', + 'NC' => 'North Carolina', + 'ND' => 'North Dakota', + 'OH' => 'Ohio', + 'OK' => 'Oklahoma', + 'OR' => 'Oregon', + 'PA' => 'Pennsylvania', + 'RI' => 'Rhode Island', + 'SC' => 'South Carolina', + 'SD' => 'South Dakota', + 'TN' => 'Tennessee', + 'TX' => 'Texas', + 'UT' => 'Utah', + 'VT' => 'Vermont', + 'VA' => 'Virginia', + 'WA' => 'Washington', + 'WV' => 'West Virginia', + 'WI' => 'Wisconsin', + 'WY' => 'Wyoming', + ); + $abbv = array_rand( $list, 1 ); + + if ( $full ) { + return( $list[ $abbv ] ); + } else { + return( $abbv ); + } + } + + public function zipcode() { + return( rand( 12345, 98765 ) ); + } + + public function address() { + $a = $this->street() . '
' . $this->city() . ', ' . $this->state() . ' ' . $this->zipcode(); + return( $a ); + } + + public function telephone() { + return( rand( 123, 876 ) . '-' . rand( 123, 987 ) . '-' . rand( 1234, 9876 ) ); + } } diff --git a/tests/_support/Utils/class-wc-product-advanced.php b/tests/_support/Utils/class-wc-product-advanced.php index cfce4b9e5..f492c448a 100644 --- a/tests/_support/Utils/class-wc-product-advanced.php +++ b/tests/_support/Utils/class-wc-product-advanced.php @@ -3,11 +3,12 @@ * Advanced Product Type */ class WC_Product_Advanced extends \WC_Product_Simple { - /** - * Return the product type - * @return string - */ - public function get_type() { - return 'advanced'; - } + /** + * Return the product type + * + * @return string + */ + public function get_type() { + return 'advanced'; + } } diff --git a/tests/acceptance/NewCustomerCheckingOutCept.php b/tests/acceptance/NewCustomerCheckingOutCept.php index 660d1d5b1..4c4cd962b 100644 --- a/tests/acceptance/NewCustomerCheckingOutCept.php +++ b/tests/acceptance/NewCustomerCheckingOutCept.php @@ -1,123 +1,123 @@ -getCatalog(); // Make quick helper for managing the session token. $request_headers = function () use ( $I, &$last_request_headers ) { - $last_request_headers = array ( - 'woocommerce-session' => 'Session ' . $I->wantHTTPResponseHeaders( 'woocommerce-session' ), - ); + $last_request_headers = array( + 'woocommerce-session' => 'Session ' . $I->wantHTTPResponseHeaders( 'woocommerce-session' ), + ); - return $last_request_headers; + return $last_request_headers; }; // Begin test. -$I->wantTo('add items to the cart'); +$I->wantTo( 'add items to the cart' ); /** * Add "T-Shirt" to cart and confirm response data. */ $add_to_cart_input = array( - 'clientMutationId' => 'someId', - 'productId' => $product_catalog['t-shirt'], - 'quantity' => 3, + 'clientMutationId' => 'someId', + 'productId' => $product_catalog['t-shirt'], + 'quantity' => 3, ); $success = $I->addToCart( $add_to_cart_input ); $I->assertArrayNotHasKey( 'errors', $success ); -$I->assertArrayHasKey('data', $success ); -$I->assertArrayHasKey('addToCart', $success['data'] ); -$I->assertArrayHasKey('cartItem', $success['data']['addToCart'] ); -$I->assertArrayHasKey('key', $success['data']['addToCart']['cartItem'] ); +$I->assertArrayHasKey( 'data', $success ); +$I->assertArrayHasKey( 'addToCart', $success['data'] ); +$I->assertArrayHasKey( 'cartItem', $success['data']['addToCart'] ); +$I->assertArrayHasKey( 'key', $success['data']['addToCart']['cartItem'] ); $shirt_key = $success['data']['addToCart']['cartItem']['key']; /** * Add "Belt" to cart and confirm response data. */ $add_to_cart_input = array( - 'clientMutationId' => 'someId', - 'productId' => $product_catalog['belt'], - 'quantity' => 2, + 'clientMutationId' => 'someId', + 'productId' => $product_catalog['belt'], + 'quantity' => 2, ); $success = $I->addToCart( - $add_to_cart_input, - $request_headers() + $add_to_cart_input, + $request_headers() ); $I->assertArrayNotHasKey( 'errors', $success ); -$I->assertArrayHasKey('data', $success ); -$I->assertArrayHasKey('addToCart', $success['data'] ); -$I->assertArrayHasKey('cartItem', $success['data']['addToCart'] ); -$I->assertArrayHasKey('key', $success['data']['addToCart']['cartItem'] ); +$I->assertArrayHasKey( 'data', $success ); +$I->assertArrayHasKey( 'addToCart', $success['data'] ); +$I->assertArrayHasKey( 'cartItem', $success['data']['addToCart'] ); +$I->assertArrayHasKey( 'key', $success['data']['addToCart']['cartItem'] ); $belt_key = $success['data']['addToCart']['cartItem']['key']; /** * Add "Jeans" to cart and confirm response data. */ $add_to_cart_input = array( - 'clientMutationId' => 'someId', - 'productId' => $product_catalog['jeans'], - 'quantity' => 4, + 'clientMutationId' => 'someId', + 'productId' => $product_catalog['jeans'], + 'quantity' => 4, ); $success = $I->addToCart( - $add_to_cart_input, - $request_headers() + $add_to_cart_input, + $request_headers() ); $I->assertArrayNotHasKey( 'errors', $success ); -$I->assertArrayHasKey('data', $success ); -$I->assertArrayHasKey('addToCart', $success['data'] ); -$I->assertArrayHasKey('cartItem', $success['data']['addToCart'] ); -$I->assertArrayHasKey('key', $success['data']['addToCart']['cartItem'] ); +$I->assertArrayHasKey( 'data', $success ); +$I->assertArrayHasKey( 'addToCart', $success['data'] ); +$I->assertArrayHasKey( 'cartItem', $success['data']['addToCart'] ); +$I->assertArrayHasKey( 'key', $success['data']['addToCart']['cartItem'] ); $jeans_key = $success['data']['addToCart']['cartItem']['key']; /** * Add "Socks" to cart and confirm response data. */ $add_to_cart_input = array( - 'clientMutationId' => 'someId', - 'productId' => $product_catalog['socks'], - 'quantity' => 1, + 'clientMutationId' => 'someId', + 'productId' => $product_catalog['socks'], + 'quantity' => 1, ); $success = $I->addToCart( - $add_to_cart_input, - $request_headers() + $add_to_cart_input, + $request_headers() ); $I->assertArrayNotHasKey( 'errors', $success ); -$I->assertArrayHasKey('data', $success ); -$I->assertArrayHasKey('addToCart', $success['data'] ); -$I->assertArrayHasKey('cartItem', $success['data']['addToCart'] ); -$I->assertArrayHasKey('key', $success['data']['addToCart']['cartItem'] ); +$I->assertArrayHasKey( 'data', $success ); +$I->assertArrayHasKey( 'addToCart', $success['data'] ); +$I->assertArrayHasKey( 'cartItem', $success['data']['addToCart'] ); +$I->assertArrayHasKey( 'key', $success['data']['addToCart']['cartItem'] ); $socks_key = $success['data']['addToCart']['cartItem']['key']; -$I->wantTo('remove some items from the cart'); +$I->wantTo( 'remove some items from the cart' ); /** * Remove "Socks" from cart and confirm response data. */ $remove_from_cart_input = array( - 'clientMutationId' => 'someId', - 'keys' => $socks_key, + 'clientMutationId' => 'someId', + 'keys' => $socks_key, ); $success = $I->removeItemsFromCart( - $remove_from_cart_input, - $request_headers() + $remove_from_cart_input, + $request_headers() ); $I->assertArrayNotHasKey( 'errors', $success ); -$I->assertArrayHasKey('data', $success ); -$I->assertArrayHasKey('removeItemsFromCart', $success['data'] ); -$I->assertArrayHasKey('cartItems', $success['data']['removeItemsFromCart'] ); +$I->assertArrayHasKey( 'data', $success ); +$I->assertArrayHasKey( 'removeItemsFromCart', $success['data'] ); +$I->assertArrayHasKey( 'cartItems', $success['data']['removeItemsFromCart'] ); $I->assertCount( 1, $success['data']['removeItemsFromCart']['cartItems'] ); -$I->wantTo('update an item in the cart'); +$I->wantTo( 'update an item in the cart' ); /** * - Change "Belt" quantity to "0" removing it from the cart. @@ -125,81 +125,87 @@ * - Confirm response data. */ $update_quantity_input = array( - 'clientMutationId' => 'someId', - 'items' => array( - array( 'key' => $belt_key, 'quantity' => 0 ), - array( 'key' => $jeans_key, 'quantity' => 1 ), - ), + 'clientMutationId' => 'someId', + 'items' => array( + array( + 'key' => $belt_key, + 'quantity' => 0, + ), + array( + 'key' => $jeans_key, + 'quantity' => 1, + ), + ), ); $success = $I->updateItemQuantities( - $update_quantity_input, - /** - * "removeItemsFromCart" mutation does not update the session token so we can - * use the request headers used on the last request - */ - $last_request_headers + $update_quantity_input, + /** + * "removeItemsFromCart" mutation does not update the session token so we can + * use the request headers used on the last request + */ + $last_request_headers ); $I->assertArrayNotHasKey( 'errors', $success ); -$I->assertArrayHasKey('data', $success ); -$I->assertArrayHasKey('updateItemQuantities', $success['data'] ); -$I->assertArrayHasKey('removed', $success['data']['updateItemQuantities'] ); +$I->assertArrayHasKey( 'data', $success ); +$I->assertArrayHasKey( 'updateItemQuantities', $success['data'] ); +$I->assertArrayHasKey( 'removed', $success['data']['updateItemQuantities'] ); $I->assertCount( 1, $success['data']['updateItemQuantities']['removed'] ); -$I->assertArrayHasKey('updated', $success['data']['updateItemQuantities'] ); +$I->assertArrayHasKey( 'updated', $success['data']['updateItemQuantities'] ); $I->assertCount( 1, $success['data']['updateItemQuantities']['updated'] ); -$I->assertArrayHasKey('items', $success['data']['updateItemQuantities'] ); +$I->assertArrayHasKey( 'items', $success['data']['updateItemQuantities'] ); $I->assertCount( 2, $success['data']['updateItemQuantities']['items'] ); -$I->wantTo('checkout'); +$I->wantTo( 'checkout' ); /** * Place order for items in the cart using the "Checkout" mutation and confirm response data. */ $checkout_input = array( - 'clientMutationId' => 'someId', - 'paymentMethod' => 'bacs', - 'shippingMethod' => array( 'flat rate' ), - 'billing' => array( - 'firstName' => 'May', - 'lastName' => 'Parker', - 'address1' => '20 Ingram St', - 'city' => 'New York City', - 'state' => 'NY', - 'postcode' => '12345', - 'country' => 'US', - 'email' => 'superfreak500@gmail.com', - 'phone' => '555-555-1234', - ), - 'shipping' => array( - 'firstName' => 'May', - 'lastName' => 'Parker', - 'address1' => '20 Ingram St', - 'city' => 'New York City', - 'state' => 'NY', - 'postcode' => '12345', - 'country' => 'US', - ), + 'clientMutationId' => 'someId', + 'paymentMethod' => 'bacs', + 'shippingMethod' => array( 'flat rate' ), + 'billing' => array( + 'firstName' => 'May', + 'lastName' => 'Parker', + 'address1' => '20 Ingram St', + 'city' => 'New York City', + 'state' => 'NY', + 'postcode' => '12345', + 'country' => 'US', + 'email' => 'superfreak500@gmail.com', + 'phone' => '555-555-1234', + ), + 'shipping' => array( + 'firstName' => 'May', + 'lastName' => 'Parker', + 'address1' => '20 Ingram St', + 'city' => 'New York City', + 'state' => 'NY', + 'postcode' => '12345', + 'country' => 'US', + ), ); $success = $I->checkout( - $checkout_input, - /** - * "updateItemQuantities" mutation does not update the session token so we can - * use the request headers used on the last request - */ - $last_request_headers + $checkout_input, + /** + * "updateItemQuantities" mutation does not update the session token so we can + * use the request headers used on the last request + */ + $last_request_headers ); // use --debug flag to view codecept_debug( $success ); $I->assertArrayNotHasKey( 'errors', $success ); -$I->assertArrayHasKey('data', $success ); -$I->assertArrayHasKey('checkout', $success['data'] ); -$I->assertArrayHasKey('order', $success['data']['checkout'] ); -$I->assertArrayHasKey('customer', $success['data']['checkout'] ); -$I->assertArrayHasKey('result', $success['data']['checkout'] ); +$I->assertArrayHasKey( 'data', $success ); +$I->assertArrayHasKey( 'checkout', $success['data'] ); +$I->assertArrayHasKey( 'order', $success['data']['checkout'] ); +$I->assertArrayHasKey( 'customer', $success['data']['checkout'] ); +$I->assertArrayHasKey( 'result', $success['data']['checkout'] ); $I->assertEquals( 'success', $success['data']['checkout']['result'] ); -$I->assertArrayHasKey('redirect', $success['data']['checkout'] ); -$I->assertArrayHasKey('id', $success['data']['checkout']['order'] ); \ No newline at end of file +$I->assertArrayHasKey( 'redirect', $success['data']['checkout'] ); +$I->assertArrayHasKey( 'id', $success['data']['checkout']['order'] ); diff --git a/tests/acceptance/ReturningCustomerSessionCept.php b/tests/acceptance/ReturningCustomerSessionCept.php index 93e8d05ed..651346604 100644 --- a/tests/acceptance/ReturningCustomerSessionCept.php +++ b/tests/acceptance/ReturningCustomerSessionCept.php @@ -1,28 +1,28 @@ setupStoreAndUsers(); // Create products $product_catalog = $I->getCatalog(); // Begin Tests. -$I->wantTo('login'); +$I->wantTo( 'login' ); $login_input = array( - 'clientMutationId' => 'someId', - 'username' => 'jimbo1234', - 'password' => 'password', + 'clientMutationId' => 'someId', + 'username' => 'jimbo1234', + 'password' => 'password', ); $success = $I->login( $login_input ); // Validate response. $I->assertArrayNotHasKey( 'errors', $success ); -$I->assertArrayHasKey('data', $success ); -$I->assertArrayHasKey('login', $success['data'] ); -$I->assertArrayHasKey('customer', $success['data']['login'] ); -$I->assertArrayHasKey('authToken', $success['data']['login'] ); -$I->assertArrayHasKey('refreshToken', $success['data']['login'] ); -$I->assertArrayHasKey('sessionToken', $success['data']['login'] ); +$I->assertArrayHasKey( 'data', $success ); +$I->assertArrayHasKey( 'login', $success['data'] ); +$I->assertArrayHasKey( 'customer', $success['data']['login'] ); +$I->assertArrayHasKey( 'authToken', $success['data']['login'] ); +$I->assertArrayHasKey( 'refreshToken', $success['data']['login'] ); +$I->assertArrayHasKey( 'sessionToken', $success['data']['login'] ); // Retrieve customer ID for later use. $customer_id = $success['data']['login']['customer']['databaseId']; @@ -35,7 +35,7 @@ // You can also retrieve the token from the "woocommerce-session" HTTP response header. $initial_session_token = $success['data']['login']['sessionToken']; -$I->wantTo('Get current username'); +$I->wantTo( 'Get current username' ); $query = ' query { customer { @@ -46,21 +46,21 @@ '; $response = $I->sendGraphQLRequest( - $query, - null, - array( + $query, + null, + array( 'Authorization' => "Bearer {$authToken}", 'woocommerce-session' => "Session {$initial_session_token}", ) ); $expected_results = array( - 'data' => array( - 'customer' => array( - 'databaseId' => $customer_id, - 'username' => 'jimbo1234' - ) - ) + 'data' => array( + 'customer' => array( + 'databaseId' => $customer_id, + 'username' => 'jimbo1234', + ), + ), ); $I->assertEquals( $expected_results, $response ); @@ -71,9 +71,9 @@ * Add "T-Shirt" to cart and confirm response data. */ $add_to_cart_input = array( - 'clientMutationId' => 'someId', - 'productId' => $product_catalog['t-shirt'], - 'quantity' => 3, + 'clientMutationId' => 'someId', + 'productId' => $product_catalog['t-shirt'], + 'quantity' => 3, ); $success = $I->addToCart( @@ -85,10 +85,10 @@ ); $I->assertArrayNotHasKey( 'errors', $success ); -$I->assertArrayHasKey('data', $success ); -$I->assertArrayHasKey('addToCart', $success['data'] ); -$I->assertArrayHasKey('cartItem', $success['data']['addToCart'] ); -$I->assertArrayHasKey('key', $success['data']['addToCart']['cartItem'] ); +$I->assertArrayHasKey( 'data', $success ); +$I->assertArrayHasKey( 'addToCart', $success['data'] ); +$I->assertArrayHasKey( 'cartItem', $success['data']['addToCart'] ); +$I->assertArrayHasKey( 'key', $success['data']['addToCart']['cartItem'] ); $shirt_key = $success['data']['addToCart']['cartItem']['key']; $I->wantTo( 'Check the cart, should contain t-shirts.' ); @@ -110,7 +110,7 @@ } '; -$response = $I->sendGraphQLRequest( +$response = $I->sendGraphQLRequest( $cart_query, null, array( @@ -127,7 +127,7 @@ 'key' => $shirt_key, 'product' => array( 'node' => array( - 'databaseId' => $product_catalog['t-shirt'] + 'databaseId' => $product_catalog['t-shirt'], ), ), ), @@ -140,26 +140,26 @@ $I->assertEquals( $expected_results, $response ); $I->wantTo( 'End session' ); -/* - Simply not sending the previous Authorization or woocommerce-session headers in the next request does the trick. - ¯\_(ツ)_/¯ -*/ +/** + * Simply not sending the previous Authorization or woocommerce-session headers in the next request does the trick. + * ¯\_(ツ)_/¯ + */ $I->wantTo( 'Login and continue previous session.' ); $login_input = array( - 'clientMutationId' => 'someId', - 'username' => 'jimbo1234', - 'password' => 'password', + 'clientMutationId' => 'someId', + 'username' => 'jimbo1234', + 'password' => 'password', ); -$success = $I->login( $login_input ); +$success = $I->login( $login_input ); $I->assertArrayNotHasKey( 'errors', $success ); -$I->assertArrayHasKey('data', $success ); -$I->assertArrayHasKey('login', $success['data'] ); -$I->assertArrayHasKey('customer', $success['data']['login'] ); -$I->assertArrayHasKey('authToken', $success['data']['login'] ); -$I->assertArrayHasKey('refreshToken', $success['data']['login'] ); +$I->assertArrayHasKey( 'data', $success ); +$I->assertArrayHasKey( 'login', $success['data'] ); +$I->assertArrayHasKey( 'customer', $success['data']['login'] ); +$I->assertArrayHasKey( 'authToken', $success['data']['login'] ); +$I->assertArrayHasKey( 'refreshToken', $success['data']['login'] ); $I->assertEquals( $customer_id, $success['data']['login']['customer']['databaseId'] ); // Retrieve new JWT Authorization Token for later use. @@ -184,7 +184,7 @@ } '; -$response = $I->sendGraphQLRequest( $cart_query, null, array( 'Authorization' => "Bearer {$authToken}" ) ); +$response = $I->sendGraphQLRequest( $cart_query, null, array( 'Authorization' => "Bearer {$authToken}" ) ); $expected_results = array( 'data' => array( 'cart' => array( @@ -194,7 +194,7 @@ 'key' => $shirt_key, 'product' => array( 'node' => array( - 'databaseId' => $product_catalog['t-shirt'] + 'databaseId' => $product_catalog['t-shirt'], ), ), ), @@ -212,18 +212,18 @@ * Add "Belt" to cart and confirm response data. */ $add_to_cart_input = array( - 'clientMutationId' => 'someId', - 'productId' => $product_catalog['belt'], - 'quantity' => 2, + 'clientMutationId' => 'someId', + 'productId' => $product_catalog['belt'], + 'quantity' => 2, ); $success = $I->addToCart( $add_to_cart_input, array( 'Authorization' => "Bearer {$authToken}" ) ); $I->assertArrayNotHasKey( 'errors', $success ); -$I->assertArrayHasKey('data', $success ); -$I->assertArrayHasKey('addToCart', $success['data'] ); -$I->assertArrayHasKey('cartItem', $success['data']['addToCart'] ); -$I->assertArrayHasKey('key', $success['data']['addToCart']['cartItem'] ); +$I->assertArrayHasKey( 'data', $success ); +$I->assertArrayHasKey( 'addToCart', $success['data'] ); +$I->assertArrayHasKey( 'cartItem', $success['data']['addToCart'] ); +$I->assertArrayHasKey( 'key', $success['data']['addToCart']['cartItem'] ); $belt_key = $success['data']['addToCart']['cartItem']['key']; // Retrieve refreshed session token created when a new item is added to the cart. @@ -232,7 +232,7 @@ $I->seeHttpHeaderOnce( 'woocommerce-session' ); $refreshed_session_token = $I->grabHttpHeader( 'woocommerce-session' ); -$I->wantTo( 'Check the cart again, should contain t-shirts and belts.'); +$I->wantTo( 'Check the cart again, should contain t-shirts and belts.' ); $cart_query = ' query { @@ -251,7 +251,7 @@ } '; -$response = $I->sendGraphQLRequest( +$response = $I->sendGraphQLRequest( $cart_query, null, array( @@ -268,7 +268,7 @@ 'key' => $shirt_key, 'product' => array( 'node' => array( - 'databaseId' => $product_catalog['t-shirt'] + 'databaseId' => $product_catalog['t-shirt'], ), ), ), @@ -276,7 +276,7 @@ 'key' => $belt_key, 'product' => array( 'node' => array( - 'databaseId' => $product_catalog['belt'] + 'databaseId' => $product_catalog['belt'], ), ), ), @@ -289,27 +289,27 @@ $I->assertEquals( $expected_results, $response ); $I->wantTo( 'End session' ); -/* - Simply not sending the previous Authorization or woocommerce-session headers in the next request does the trick. - ¯\_(ツ)_/¯ -*/ +/** + * Simply not sending the previous Authorization or woocommerce-session headers in the next request does the trick. + * ¯\_(ツ)_/¯ + */ $I->wantTo( 'Login and start a new session.' ); $login_input = array( - 'clientMutationId' => 'someId', - 'username' => 'jimbo1234', - 'password' => 'password', + 'clientMutationId' => 'someId', + 'username' => 'jimbo1234', + 'password' => 'password', ); -$success = $I->login( $login_input ); +$success = $I->login( $login_input ); $I->assertArrayNotHasKey( 'errors', $success ); -$I->assertArrayHasKey('data', $success ); -$I->assertArrayHasKey('login', $success['data'] ); -$I->assertArrayHasKey('customer', $success['data']['login'] ); -$I->assertArrayHasKey('authToken', $success['data']['login'] ); -$I->assertArrayHasKey('refreshToken', $success['data']['login'] ); -$I->assertArrayHasKey('sessionToken', $success['data']['login'] ); +$I->assertArrayHasKey( 'data', $success ); +$I->assertArrayHasKey( 'login', $success['data'] ); +$I->assertArrayHasKey( 'customer', $success['data']['login'] ); +$I->assertArrayHasKey( 'authToken', $success['data']['login'] ); +$I->assertArrayHasKey( 'refreshToken', $success['data']['login'] ); +$I->assertArrayHasKey( 'sessionToken', $success['data']['login'] ); $I->assertEquals( $customer_id, $success['data']['login']['customer']['databaseId'] ); // Retrieve new JWT Authorization Token for later use. @@ -338,7 +338,7 @@ } '; -$response = $I->sendGraphQLRequest( +$response = $I->sendGraphQLRequest( $cart_query, null, array( diff --git a/tests/functional/CartTransactionQueueCest.php b/tests/functional/CartTransactionQueueCest.php index 0e059feda..977e24ad2 100644 --- a/tests/functional/CartTransactionQueueCest.php +++ b/tests/functional/CartTransactionQueueCest.php @@ -3,34 +3,34 @@ class CartTransactionQueueCest { private $product_catalog; - public function _before( FunctionalTester $I ) { - // Create Products - $this->product_catalog = $I->getCatalog(); + public function _before( FunctionalTester $I ) { + // Create Products + $this->product_catalog = $I->getCatalog(); } public function _addTshirtToCart( FunctionalTester $I, $headers = array() ) { /** - * Add t-shirt to the cart - */ - $success = $I->addToCart( - array( - 'clientMutationId' => 'someId', - 'productId' => $this->product_catalog['t-shirt'], - 'quantity' => 5, + * Add t-shirt to the cart + */ + $success = $I->addToCart( + array( + 'clientMutationId' => 'someId', + 'productId' => $this->product_catalog['t-shirt'], + 'quantity' => 5, ), $headers ); $I->assertArrayNotHasKey( 'errors', $success ); - $I->assertArrayHasKey('data', $success ); - $I->assertArrayHasKey('addToCart', $success['data'] ); - $I->assertArrayHasKey('cartItem', $success['data']['addToCart'] ); - $I->assertArrayHasKey('key', $success['data']['addToCart']['cartItem'] ); + $I->assertArrayHasKey( 'data', $success ); + $I->assertArrayHasKey( 'addToCart', $success['data'] ); + $I->assertArrayHasKey( 'cartItem', $success['data']['addToCart'] ); + $I->assertArrayHasKey( 'key', $success['data']['addToCart']['cartItem'] ); $key = $success['data']['addToCart']['cartItem']['key']; /** - * Assert existence and validity of "woocommerce-session" HTTP header. - */ + * Assert existence and validity of "woocommerce-session" HTTP header. + */ $I->seeHttpHeaderOnce( 'woocommerce-session' ); $session_token = $I->grabHttpHeader( 'woocommerce-session' ); @@ -41,7 +41,7 @@ public function _startAuthenticatedSession( $I ) { $I->setupStoreAndUsers(); // Begin Tests. - $I->wantTo('login'); + $I->wantTo( 'login' ); $login_input = array( 'clientMutationId' => 'someId', 'username' => 'jimbo1234', @@ -52,12 +52,12 @@ public function _startAuthenticatedSession( $I ) { // Validate response. $I->assertArrayNotHasKey( 'errors', $success ); - $I->assertArrayHasKey('data', $success ); - $I->assertArrayHasKey('login', $success['data'] ); - $I->assertArrayHasKey('customer', $success['data']['login'] ); - $I->assertArrayHasKey('authToken', $success['data']['login'] ); - $I->assertArrayHasKey('refreshToken', $success['data']['login'] ); - $I->assertArrayHasKey('sessionToken', $success['data']['login'] ); + $I->assertArrayHasKey( 'data', $success ); + $I->assertArrayHasKey( 'login', $success['data'] ); + $I->assertArrayHasKey( 'customer', $success['data']['login'] ); + $I->assertArrayHasKey( 'authToken', $success['data']['login'] ); + $I->assertArrayHasKey( 'refreshToken', $success['data']['login'] ); + $I->assertArrayHasKey( 'sessionToken', $success['data']['login'] ); // Retrieve JWT Authorization Token for later use. $auth_token = $success['data']['login']['authToken']; @@ -77,8 +77,8 @@ public function _startAuthenticatedSession( $I ) { return compact( 'auth_token', 'key', 'session_token' ); } - // tests - public function testCartTransactionQueueWithConcurrentRequest( FunctionalTester $I ) { + // tests + public function testCartTransactionQueueWithConcurrentRequest( FunctionalTester $I ) { $I->wantTo( 'Add Item to cart' ); extract( $this->_startAuthenticatedSession( $I ) ); @@ -132,7 +132,7 @@ public function testCartTransactionQueueWithConcurrentRequest( FunctionalTester } } '; - $cart_query = ' + $cart_query = ' query { cart { contents { @@ -145,14 +145,17 @@ public function testCartTransactionQueueWithConcurrentRequest( FunctionalTester } '; - $requests = array( + $requests = array( array( 'query' => $update_item_quantities_mutation, 'variables' => array( 'input' => array( 'clientMutationId' => 'some_id', 'items' => array( - array( 'key' => $key, 'quantity' => 3 ), + array( + 'key' => $key, + 'quantity' => 3, + ), ), ), ), @@ -163,7 +166,10 @@ public function testCartTransactionQueueWithConcurrentRequest( FunctionalTester 'input' => array( 'clientMutationId' => 'some_id', 'items' => array( - array( 'key' => $key, 'quantity' => 4 ), + array( + 'key' => $key, + 'quantity' => 4, + ), ), ), ), @@ -173,7 +179,7 @@ public function testCartTransactionQueueWithConcurrentRequest( FunctionalTester 'variables' => array( 'input' => array( 'clientMutationId' => 'some_id', - 'keys' => array( $key ) + 'keys' => array( $key ), ), ), ), @@ -185,7 +191,7 @@ public function testCartTransactionQueueWithConcurrentRequest( FunctionalTester 'keys' => array( $key ), ), ), - ) + ), ); $expected_responses = array( array( @@ -195,14 +201,14 @@ public function testCartTransactionQueueWithConcurrentRequest( FunctionalTester array( 'key' => $key, 'quantity' => 3, - ) + ), ), 'removed' => array(), 'items' => array( array( 'key' => $key, 'quantity' => 3, - ) + ), ), ), ), @@ -213,21 +219,21 @@ public function testCartTransactionQueueWithConcurrentRequest( FunctionalTester array( 'key' => $key, 'quantity' => 4, - ) + ), ), 'removed' => array(), 'items' => array( array( 'key' => $key, 'quantity' => 4, - ) + ), ), ), ), array( 'removeItemsFromCart' => array( 'clientMutationId' => 'some_id', - 'cart' => array( + 'cart' => array( 'contents' => array( 'nodes' => array(), ), @@ -237,12 +243,12 @@ public function testCartTransactionQueueWithConcurrentRequest( FunctionalTester array( 'restoreCartItems' => array( 'clientMutationId' => 'some_id', - 'cart' => array( + 'cart' => array( 'contents' => array( 'nodes' => array( array( 'key' => $key, - 'quantity' => 4 + 'quantity' => 4, ), ), ), @@ -262,13 +268,13 @@ public function testCartTransactionQueueWithConcurrentRequest( FunctionalTester $iterator = function( $requests ) use ( $client ) { $stagger = 1000; - foreach( $requests as $index => $payload ) { + foreach ( $requests as $index => $payload ) { yield function() use ( $client, $stagger, $index, $payload ) { $body = json_encode( $payload ); $delay = $stagger * $index + 1; $connected = false; $progress = function( $downloadTotal, $downloadedBytes, $uploadTotal, $uploadedBytes ) use ( $index, &$connected ) { - if ( $uploadTotal === $uploadedBytes && $downloadTotal === 0 && ! $connected ) { + if ( $uploadTotal === $uploadedBytes && 0 === $downloadTotal && ! $connected ) { \codecept_debug( "Session mutation request $index connected @ " . ( new \Carbon\Carbon() )->format( 'Y-m-d H:i:s' ) ); $connected = true; } @@ -283,7 +289,7 @@ public function testCartTransactionQueueWithConcurrentRequest( FunctionalTester $iterator( $requests ), array( 'concurrency' => 5, - 'fulfilled' => function ( $response, $index ) use ( $I, $expected_responses ) { + 'fulfilled' => function ( $response, $index ) use ( $I, $expected_responses ) { \codecept_debug( "Finished session mutation request $index @ " . ( new \Carbon\Carbon() )->format( 'Y-m-d H:i:s' ) ); $expected = $expected_responses[ $index ]; @@ -298,5 +304,5 @@ public function testCartTransactionQueueWithConcurrentRequest( FunctionalTester $promise = $pool->promise(); $promise->wait(); - } + } } diff --git a/tests/functional/QLSessionHandlerCest.php b/tests/functional/QLSessionHandlerCest.php index 4c700d333..dd645ddbd 100644 --- a/tests/functional/QLSessionHandlerCest.php +++ b/tests/functional/QLSessionHandlerCest.php @@ -2,65 +2,65 @@ use Firebase\JWT\JWT; class QLSessionHandlerCest { - private $product_catalog; + private $product_catalog; - public function _before( FunctionalTester $I ) { - // Create products. - $this->product_catalog = $I->getCatalog(); + public function _before( FunctionalTester $I ) { + // Create products. + $this->product_catalog = $I->getCatalog(); if ( ! defined( 'GRAPHQL_WOOCOMMERCE_SECRET_KEY' ) ) { define( 'GRAPHQL_WOOCOMMERCE_SECRET_KEY', 'test' ); } - } - - // tests - public function testCartMutationsWithValidCartSessionToken( FunctionalTester $I ) { - /** - * Add item to the cart - */ - $success = $I->addToCart( - array( - 'clientMutationId' => 'someId', - 'productId' => $this->product_catalog['t-shirt'], - 'quantity' => 5, - ) - ); - - $I->assertArrayNotHasKey( 'errors', $success ); - $I->assertArrayHasKey('data', $success ); - $I->assertArrayHasKey('addToCart', $success['data'] ); - $I->assertArrayHasKey('cartItem', $success['data']['addToCart'] ); - $I->assertArrayHasKey('key', $success['data']['addToCart']['cartItem'] ); - $cart_item_key = $success['data']['addToCart']['cartItem']['key']; - - /** - * Assert existence and validity of "woocommerce-session" HTTP header. - */ - $I->seeHttpHeaderOnce( 'woocommerce-session' ); - $session_token = $I->grabHttpHeader( 'woocommerce-session' ); - - // Decode token - JWT::$leeway = 60; - $token_data = ! empty( $session_token ) - ? JWT::decode( $session_token, GRAPHQL_WOOCOMMERCE_SECRET_KEY, array( 'HS256' ) ) - : null; - - $I->assertNotEmpty( $token_data ); - $I->assertNotEmpty( $token_data->iss ); - $I->assertNotEmpty( $token_data->iat ); - $I->assertNotEmpty( $token_data->nbf ); - $I->assertNotEmpty( $token_data->exp ); - $I->assertNotEmpty( $token_data->data ); - $I->assertNotEmpty( $token_data->data->customer_id ); - - $wp_url = getenv( 'WORDPRESS_URL' ); - $I->assertEquals( $token_data->iss, $wp_url ); - - /** - * Make a cart query request with "woocommerce-session" HTTP Header and confirm - * correct cart contents. - */ - $query = ' + } + + // tests + public function testCartMutationsWithValidCartSessionToken( FunctionalTester $I ) { + /** + * Add item to the cart + */ + $success = $I->addToCart( + array( + 'clientMutationId' => 'someId', + 'productId' => $this->product_catalog['t-shirt'], + 'quantity' => 5, + ) + ); + + $I->assertArrayNotHasKey( 'errors', $success ); + $I->assertArrayHasKey( 'data', $success ); + $I->assertArrayHasKey( 'addToCart', $success['data'] ); + $I->assertArrayHasKey( 'cartItem', $success['data']['addToCart'] ); + $I->assertArrayHasKey( 'key', $success['data']['addToCart']['cartItem'] ); + $cart_item_key = $success['data']['addToCart']['cartItem']['key']; + + /** + * Assert existence and validity of "woocommerce-session" HTTP header. + */ + $I->seeHttpHeaderOnce( 'woocommerce-session' ); + $session_token = $I->grabHttpHeader( 'woocommerce-session' ); + + // Decode token + JWT::$leeway = 60; + $token_data = ! empty( $session_token ) + ? JWT::decode( $session_token, GRAPHQL_WOOCOMMERCE_SECRET_KEY, array( 'HS256' ) ) + : null; + + $I->assertNotEmpty( $token_data ); + $I->assertNotEmpty( $token_data->iss ); + $I->assertNotEmpty( $token_data->iat ); + $I->assertNotEmpty( $token_data->nbf ); + $I->assertNotEmpty( $token_data->exp ); + $I->assertNotEmpty( $token_data->data ); + $I->assertNotEmpty( $token_data->data->customer_id ); + + $wp_url = getenv( 'WORDPRESS_URL' ); + $I->assertEquals( $token_data->iss, $wp_url ); + + /** + * Make a cart query request with "woocommerce-session" HTTP Header and confirm + * correct cart contents. + */ + $query = ' query { cart { contents { @@ -72,45 +72,45 @@ public function testCartMutationsWithValidCartSessionToken( FunctionalTester $I } '; - $actual = $I->sendGraphQLRequest( $query, null, array( 'woocommerce-session' => "Session {$session_token}" ) ); - $expected = array( - 'data' => array( - 'cart' => array( - 'contents' => array( - 'nodes' => array( - array( - 'key' => $cart_item_key, - ), - ), - ), - ), - ), - ); - - $I->assertEquals( $expected, $actual ); - - /** - * Remove item from the cart - */ - $success = $I->removeItemsFromCart( - array( - 'clientMutationId' => 'someId', - 'keys' => $cart_item_key, - ), - array( 'woocommerce-session' => "Session {$session_token}" ) - ); - - $I->assertArrayNotHasKey( 'errors', $success ); - $I->assertArrayHasKey('data', $success ); - $I->assertArrayHasKey('removeItemsFromCart', $success['data'] ); - $I->assertArrayHasKey('cartItems', $success['data']['removeItemsFromCart'] ); - $I->assertCount( 1, $success['data']['removeItemsFromCart']['cartItems'] ); - - /** - * Make a cart query request with "woocommerce-session" HTTP Header and confirm - * correct cart contents. - */ - $query = ' + $actual = $I->sendGraphQLRequest( $query, null, array( 'woocommerce-session' => "Session {$session_token}" ) ); + $expected = array( + 'data' => array( + 'cart' => array( + 'contents' => array( + 'nodes' => array( + array( + 'key' => $cart_item_key, + ), + ), + ), + ), + ), + ); + + $I->assertEquals( $expected, $actual ); + + /** + * Remove item from the cart + */ + $success = $I->removeItemsFromCart( + array( + 'clientMutationId' => 'someId', + 'keys' => $cart_item_key, + ), + array( 'woocommerce-session' => "Session {$session_token}" ) + ); + + $I->assertArrayNotHasKey( 'errors', $success ); + $I->assertArrayHasKey( 'data', $success ); + $I->assertArrayHasKey( 'removeItemsFromCart', $success['data'] ); + $I->assertArrayHasKey( 'cartItems', $success['data']['removeItemsFromCart'] ); + $I->assertCount( 1, $success['data']['removeItemsFromCart']['cartItems'] ); + + /** + * Make a cart query request with "woocommerce-session" HTTP Header and confirm + * correct cart contents. + */ + $query = ' query { cart { contents { @@ -122,41 +122,41 @@ public function testCartMutationsWithValidCartSessionToken( FunctionalTester $I } '; - $actual = $I->sendGraphQLRequest( $query, null, array( 'woocommerce-session' => "Session {$session_token}" ) ); - $expected = array( - 'data' => array( - 'cart' => array( - 'contents' => array( - 'nodes' => array(), - ), - ), - ), - ); - - $I->assertEquals( $expected, $actual ); - - /** - * Restore item to the cart - */ - $success = $I->restoreCartItems( - array( - 'clientMutationId' => 'someId', - 'keys' => array( $cart_item_key ), - ), - array( 'woocommerce-session' => "Session {$session_token}" ) - ); - - $I->assertArrayNotHasKey( 'errors', $success ); - $I->assertArrayHasKey('data', $success ); - $I->assertArrayHasKey('restoreCartItems', $success['data'] ); - $I->assertArrayHasKey('cartItems', $success['data']['restoreCartItems'] ); - $I->assertCount( 1, $success['data']['restoreCartItems']['cartItems'] ); - - /** - * Make a cart query request with "woocommerce-session" HTTP Header and confirm - * correct cart contents. - */ - $query = ' + $actual = $I->sendGraphQLRequest( $query, null, array( 'woocommerce-session' => "Session {$session_token}" ) ); + $expected = array( + 'data' => array( + 'cart' => array( + 'contents' => array( + 'nodes' => array(), + ), + ), + ), + ); + + $I->assertEquals( $expected, $actual ); + + /** + * Restore item to the cart + */ + $success = $I->restoreCartItems( + array( + 'clientMutationId' => 'someId', + 'keys' => array( $cart_item_key ), + ), + array( 'woocommerce-session' => "Session {$session_token}" ) + ); + + $I->assertArrayNotHasKey( 'errors', $success ); + $I->assertArrayHasKey( 'data', $success ); + $I->assertArrayHasKey( 'restoreCartItems', $success['data'] ); + $I->assertArrayHasKey( 'cartItems', $success['data']['restoreCartItems'] ); + $I->assertCount( 1, $success['data']['restoreCartItems']['cartItems'] ); + + /** + * Make a cart query request with "woocommerce-session" HTTP Header and confirm + * correct cart contents. + */ + $query = ' query { cart { contents { @@ -168,204 +168,207 @@ public function testCartMutationsWithValidCartSessionToken( FunctionalTester $I } '; - $actual = $I->sendGraphQLRequest( $query, null, array( 'woocommerce-session' => "Session {$session_token}" ) ); - $expected = array( - 'data' => array( - 'cart' => array( - 'contents' => array( - 'nodes' => array( - array( - 'key' => $cart_item_key, - ), - ), - ), - ), - ), - ); - - $I->assertEquals( $expected, $actual ); - } - - public function testCartMutationsWithInvalidCartSessionToken( FunctionalTester $I ) { - /** - * Add item to cart and retrieve session token to corrupt. - */ - $success = $I->addToCart( - array( - 'clientMutationId' => 'someId', - 'productId' => $this->product_catalog['t-shirt'], - 'quantity' => 1, - ) - ); - - $I->assertArrayNotHasKey( 'errors', $success ); - $I->assertArrayHasKey('data', $success ); - $I->assertArrayHasKey('addToCart', $success['data'] ); - $I->assertArrayHasKey('cartItem', $success['data']['addToCart'] ); - $I->assertArrayHasKey('key', $success['data']['addToCart']['cartItem'] ); - $cart_item_key = $success['data']['addToCart']['cartItem']['key']; - - /** - * Retrieve session token from "woocommerce-session" HTTP response header. - */ - $I->seeHttpHeaderOnce( 'woocommerce-session' ); - $valid_token = $I->grabHttpHeader( 'woocommerce-session' ); - - // Decode token - $token_data = ! empty( $valid_token ) - ? JWT::decode( $valid_token, GRAPHQL_WOOCOMMERCE_SECRET_KEY, array( 'HS256' ) ) - : null; - - /** - * Attempt to add item to the cart with invalid session token. - * GraphQL should throw an error and mutation will fail. - */ - $invalid_token = $token_data; - $invalid_token->data->customer_id = ''; - $invalid_token = JWT::encode( $invalid_token, GRAPHQL_WOOCOMMERCE_SECRET_KEY ); - - $failed = $I->addToCart( - array( - 'clientMutationId' => 'someId', - 'productId' => $this->product_catalog['t-shirt'], - 'quantity' => 1, - ), - array( 'woocommerce-session' => "Session {$invalid_token}" ) - ); - - $I->assertArrayHasKey( 'errors', $failed ); - - /** - * Attempt to remove item from the cart with invalid session token. - * GraphQL should throw an error and mutation will fail. - */ - $invalid_token = $token_data; - $invalid_token->iss = ''; - $invalid_token = JWT::encode( $invalid_token, GRAPHQL_WOOCOMMERCE_SECRET_KEY ); - - $failed = $I->removeItemsFromCart( - array( - 'clientMutationId' => 'someId', - 'keys' => $cart_item_key, - ), - array( 'woocommerce-session' => "Session {$invalid_token}" ) - ); - - $I->assertArrayHasKey( 'errors', $failed ); - - /** - * Attempt to update quantity of item in the cart with invalid session token. - * GraphQL should throw an error and mutation will fail. - */ - $failed = $I->updateItemQuantities( - array( - 'clientMutationId' => 'someId', - 'items' => array( - array( 'key' => $cart_item_key, 'quantity' => 0 ), - ), - ), - array( 'woocommerce-session' => "Session invalid-jwt-token-string" ) - ); - - $I->assertArrayHasKey( 'errors', $failed ); - - /** - * Attempt to empty cart with invalid session token. - * GraphQL should throw an error and mutation will fail. - */ - $failed = $I->emptyCart( - array( 'clientMutationId' => 'someId', ), - array( 'woocommerce-session' => "Session invalid-jwt-token-string" ) - ); - - $I->assertArrayHasKey( 'errors', $failed ); - - /** - * Attempt to add fee on cart with invalid session token. - * GraphQL should throw an error and mutation will fail. - */ - $failed = $I->addFee( - array( - 'clientMutationId' => 'someId', - 'name' => 'extra_fee', - 'amount' => 49.99, - ), - array( 'woocommerce-session' => "Session invalid-jwt-token-string" ) - ); - - $I->assertArrayHasKey( 'errors', $failed ); - - /** - * Attempt to apply coupon on cart with invalid session token. - * GraphQL should throw an error and mutation will fail. - * - * @Note: No coupons exist in the database, but mutation should fail before that becomes a factor. - */ - $failed = $I->applyCoupon( - array( - 'clientMutationId' => 'someId', - 'code' => 'some_coupon', - ), - array( 'woocommerce-session' => "Session invalid-jwt-token-string" ) - ); - - $I->assertArrayHasKey( 'errors', $failed ); - - /** - * Attempt to remove coupon from cart with invalid session token. - * GraphQL should throw an error and mutation will fail. - * - * @Note: No coupons exist on the cart, but mutation should failed before that becomes a factor. - */ - $failed = $I->removeCoupons( - array( - 'clientMutationId' => 'someId', - 'codes' => array( 'some_coupon' ), - ), - array( 'woocommerce-session' => "Session invalid-jwt-token-string" ) - ); - - $I->assertArrayHasKey( 'errors', $failed ); - - /** - * Attempt to restore item to the cart with invalid session token. - * GraphQL should throw an error and mutation will fail. - * - * @Note: No items have been removed from the cart in this session, - * but mutation should failed before that becomes a factor. - */ - $failed = $I->restoreCartItems( - array( - 'clientMutationId' => 'someId', - 'keys' => array( $cart_item_key ), - ), - array( 'woocommerce-session' => "Session invalid-jwt-token-string" ) - ); - - $I->assertArrayHasKey( 'errors', $failed ); - - /** - * Attempt to restore item to the cart with invalid session token. - * GraphQL should throw an error and mutation will fail. - * - * @Note: No items have been removed from the cart in this session, - * but mutation should failed before that becomes a factor. - */ - $failed = $I->updateShippingMethod( - array( - 'clientMutationId' => 'someId', - 'shippingMethods' => array( 'legacy_flat_rate' ), - ), - array( 'woocommerce-session' => "Session invalid-jwt-token-string" ) - ); - - $I->assertArrayHasKey( 'errors', $failed ); - - /** - * Attempt to query cart with invalid session token. - * GraphQL should throw an error and query will fail. - */ - $query = ' + $actual = $I->sendGraphQLRequest( $query, null, array( 'woocommerce-session' => "Session {$session_token}" ) ); + $expected = array( + 'data' => array( + 'cart' => array( + 'contents' => array( + 'nodes' => array( + array( + 'key' => $cart_item_key, + ), + ), + ), + ), + ), + ); + + $I->assertEquals( $expected, $actual ); + } + + public function testCartMutationsWithInvalidCartSessionToken( FunctionalTester $I ) { + /** + * Add item to cart and retrieve session token to corrupt. + */ + $success = $I->addToCart( + array( + 'clientMutationId' => 'someId', + 'productId' => $this->product_catalog['t-shirt'], + 'quantity' => 1, + ) + ); + + $I->assertArrayNotHasKey( 'errors', $success ); + $I->assertArrayHasKey( 'data', $success ); + $I->assertArrayHasKey( 'addToCart', $success['data'] ); + $I->assertArrayHasKey( 'cartItem', $success['data']['addToCart'] ); + $I->assertArrayHasKey( 'key', $success['data']['addToCart']['cartItem'] ); + $cart_item_key = $success['data']['addToCart']['cartItem']['key']; + + /** + * Retrieve session token from "woocommerce-session" HTTP response header. + */ + $I->seeHttpHeaderOnce( 'woocommerce-session' ); + $valid_token = $I->grabHttpHeader( 'woocommerce-session' ); + + // Decode token + $token_data = ! empty( $valid_token ) + ? JWT::decode( $valid_token, GRAPHQL_WOOCOMMERCE_SECRET_KEY, array( 'HS256' ) ) + : null; + + /** + * Attempt to add item to the cart with invalid session token. + * GraphQL should throw an error and mutation will fail. + */ + $invalid_token = $token_data; + $invalid_token->data->customer_id = ''; + $invalid_token = JWT::encode( $invalid_token, GRAPHQL_WOOCOMMERCE_SECRET_KEY ); + + $failed = $I->addToCart( + array( + 'clientMutationId' => 'someId', + 'productId' => $this->product_catalog['t-shirt'], + 'quantity' => 1, + ), + array( 'woocommerce-session' => "Session {$invalid_token}" ) + ); + + $I->assertArrayHasKey( 'errors', $failed ); + + /** + * Attempt to remove item from the cart with invalid session token. + * GraphQL should throw an error and mutation will fail. + */ + $invalid_token = $token_data; + $invalid_token->iss = ''; + $invalid_token = JWT::encode( $invalid_token, GRAPHQL_WOOCOMMERCE_SECRET_KEY ); + + $failed = $I->removeItemsFromCart( + array( + 'clientMutationId' => 'someId', + 'keys' => $cart_item_key, + ), + array( 'woocommerce-session' => "Session {$invalid_token}" ) + ); + + $I->assertArrayHasKey( 'errors', $failed ); + + /** + * Attempt to update quantity of item in the cart with invalid session token. + * GraphQL should throw an error and mutation will fail. + */ + $failed = $I->updateItemQuantities( + array( + 'clientMutationId' => 'someId', + 'items' => array( + array( + 'key' => $cart_item_key, + 'quantity' => 0, + ), + ), + ), + array( 'woocommerce-session' => 'Session invalid-jwt-token-string' ) + ); + + $I->assertArrayHasKey( 'errors', $failed ); + + /** + * Attempt to empty cart with invalid session token. + * GraphQL should throw an error and mutation will fail. + */ + $failed = $I->emptyCart( + array( 'clientMutationId' => 'someId' ), + array( 'woocommerce-session' => 'Session invalid-jwt-token-string' ) + ); + + $I->assertArrayHasKey( 'errors', $failed ); + + /** + * Attempt to add fee on cart with invalid session token. + * GraphQL should throw an error and mutation will fail. + */ + $failed = $I->addFee( + array( + 'clientMutationId' => 'someId', + 'name' => 'extra_fee', + 'amount' => 49.99, + ), + array( 'woocommerce-session' => 'Session invalid-jwt-token-string' ) + ); + + $I->assertArrayHasKey( 'errors', $failed ); + + /** + * Attempt to apply coupon on cart with invalid session token. + * GraphQL should throw an error and mutation will fail. + * + * @Note: No coupons exist in the database, but mutation should fail before that becomes a factor. + */ + $failed = $I->applyCoupon( + array( + 'clientMutationId' => 'someId', + 'code' => 'some_coupon', + ), + array( 'woocommerce-session' => 'Session invalid-jwt-token-string' ) + ); + + $I->assertArrayHasKey( 'errors', $failed ); + + /** + * Attempt to remove coupon from cart with invalid session token. + * GraphQL should throw an error and mutation will fail. + * + * @Note: No coupons exist on the cart, but mutation should failed before that becomes a factor. + */ + $failed = $I->removeCoupons( + array( + 'clientMutationId' => 'someId', + 'codes' => array( 'some_coupon' ), + ), + array( 'woocommerce-session' => 'Session invalid-jwt-token-string' ) + ); + + $I->assertArrayHasKey( 'errors', $failed ); + + /** + * Attempt to restore item to the cart with invalid session token. + * GraphQL should throw an error and mutation will fail. + * + * @Note: No items have been removed from the cart in this session, + * but mutation should failed before that becomes a factor. + */ + $failed = $I->restoreCartItems( + array( + 'clientMutationId' => 'someId', + 'keys' => array( $cart_item_key ), + ), + array( 'woocommerce-session' => 'Session invalid-jwt-token-string' ) + ); + + $I->assertArrayHasKey( 'errors', $failed ); + + /** + * Attempt to restore item to the cart with invalid session token. + * GraphQL should throw an error and mutation will fail. + * + * @Note: No items have been removed from the cart in this session, + * but mutation should failed before that becomes a factor. + */ + $failed = $I->updateShippingMethod( + array( + 'clientMutationId' => 'someId', + 'shippingMethods' => array( 'legacy_flat_rate' ), + ), + array( 'woocommerce-session' => 'Session invalid-jwt-token-string' ) + ); + + $I->assertArrayHasKey( 'errors', $failed ); + + /** + * Attempt to query cart with invalid session token. + * GraphQL should throw an error and query will fail. + */ + $query = ' query { cart { contents { @@ -377,70 +380,70 @@ public function testCartMutationsWithInvalidCartSessionToken( FunctionalTester $ } '; - $failed = $I->sendGraphQLRequest( - $query, - null, - array( 'woocommerce-session' => 'Session invalid-jwt-token-string' ) - ); - - $I->assertArrayHasKey( 'errors', $failed ); - } - - public function testCartSessionDataMutations( FunctionalTester $I ) { - /** - * Add item to the cart - */ - $success = $I->addToCart( - array( - 'clientMutationId' => 'someId', - 'productId' => $this->product_catalog['socks'], - 'quantity' => 2, - ) - ); - - $I->assertArrayNotHasKey( 'errors', $success ); - $I->assertArrayHasKey('data', $success ); - $I->assertArrayHasKey('addToCart', $success['data'] ); - $I->assertArrayHasKey('cartItem', $success['data']['addToCart'] ); - $I->assertArrayHasKey('key', $success['data']['addToCart']['cartItem'] ); - $cart_item_key = $success['data']['addToCart']['cartItem']['key']; - - /** - * Assert existence and validity of "woocommerce-session" HTTP header. - */ - $I->seeHttpHeaderOnce( 'woocommerce-session' ); - $session_token = $I->grabHttpHeader( 'woocommerce-session' ); - - // Decode token - JWT::$leeway = 60; - $token_data = ! empty( $session_token ) - ? JWT::decode( $session_token, GRAPHQL_WOOCOMMERCE_SECRET_KEY, array( 'HS256' ) ) - : null; - - $I->assertNotEmpty( $token_data ); - $I->assertNotEmpty( $token_data->iss ); - $I->assertNotEmpty( $token_data->iat ); - $I->assertNotEmpty( $token_data->nbf ); - $I->assertNotEmpty( $token_data->exp ); - $I->assertNotEmpty( $token_data->data ); - $I->assertNotEmpty( $token_data->data->customer_id ); - - $wp_url = getenv( 'WORDPRESS_URL' ); - $I->assertEquals( $token_data->iss, $wp_url ); - - /** - * Set shipping address, so shipping rates can be calculated - */ - $input = array( - 'clientMutationId' => 'someId', - 'shipping' => array( - 'state' => 'New York', - 'country' => 'US', - 'postcode' => '12345', - ) - ); - - $mutation = ' + $failed = $I->sendGraphQLRequest( + $query, + null, + array( 'woocommerce-session' => 'Session invalid-jwt-token-string' ) + ); + + $I->assertArrayHasKey( 'errors', $failed ); + } + + public function testCartSessionDataMutations( FunctionalTester $I ) { + /** + * Add item to the cart + */ + $success = $I->addToCart( + array( + 'clientMutationId' => 'someId', + 'productId' => $this->product_catalog['socks'], + 'quantity' => 2, + ) + ); + + $I->assertArrayNotHasKey( 'errors', $success ); + $I->assertArrayHasKey( 'data', $success ); + $I->assertArrayHasKey( 'addToCart', $success['data'] ); + $I->assertArrayHasKey( 'cartItem', $success['data']['addToCart'] ); + $I->assertArrayHasKey( 'key', $success['data']['addToCart']['cartItem'] ); + $cart_item_key = $success['data']['addToCart']['cartItem']['key']; + + /** + * Assert existence and validity of "woocommerce-session" HTTP header. + */ + $I->seeHttpHeaderOnce( 'woocommerce-session' ); + $session_token = $I->grabHttpHeader( 'woocommerce-session' ); + + // Decode token + JWT::$leeway = 60; + $token_data = ! empty( $session_token ) + ? JWT::decode( $session_token, GRAPHQL_WOOCOMMERCE_SECRET_KEY, array( 'HS256' ) ) + : null; + + $I->assertNotEmpty( $token_data ); + $I->assertNotEmpty( $token_data->iss ); + $I->assertNotEmpty( $token_data->iat ); + $I->assertNotEmpty( $token_data->nbf ); + $I->assertNotEmpty( $token_data->exp ); + $I->assertNotEmpty( $token_data->data ); + $I->assertNotEmpty( $token_data->data->customer_id ); + + $wp_url = getenv( 'WORDPRESS_URL' ); + $I->assertEquals( $token_data->iss, $wp_url ); + + /** + * Set shipping address, so shipping rates can be calculated + */ + $input = array( + 'clientMutationId' => 'someId', + 'shipping' => array( + 'state' => 'New York', + 'country' => 'US', + 'postcode' => '12345', + ), + ); + + $mutation = ' mutation ( $input: UpdateCustomerInput! ){ updateCustomer ( input: $input ) { customer { @@ -454,28 +457,28 @@ public function testCartSessionDataMutations( FunctionalTester $I ) { } '; - $actual = $I->sendGraphQLRequest( $mutation, $input, array( 'woocommerce-session' => "Session {$session_token}" ) ); - $expected = array( - 'data' => array( - 'updateCustomer' => array( - 'customer' => array( - 'shipping' => array( - 'state' => 'New York', - 'country' => 'US', - 'postcode' => '12345' - ), - ), - ), - ), - ); - - $I->assertEquals( $expected, $actual ); - - /** - * Make a cart query request with "woocommerce-session" HTTP Header and confirm - * correct cart contents and chosen and available shipping methods. - */ - $query = ' + $actual = $I->sendGraphQLRequest( $mutation, $input, array( 'woocommerce-session' => "Session {$session_token}" ) ); + $expected = array( + 'data' => array( + 'updateCustomer' => array( + 'customer' => array( + 'shipping' => array( + 'state' => 'New York', + 'country' => 'US', + 'postcode' => '12345', + ), + ), + ), + ), + ); + + $I->assertEquals( $expected, $actual ); + + /** + * Make a cart query request with "woocommerce-session" HTTP Header and confirm + * correct cart contents and chosen and available shipping methods. + */ + $query = ' query { cart { contents { @@ -496,45 +499,45 @@ public function testCartSessionDataMutations( FunctionalTester $I ) { } '; - $actual = $I->sendGraphQLRequest( $query, null, array( 'woocommerce-session' => "Session {$session_token}" ) ); - $expected = array( - 'data' => array( - 'cart' => array( - 'contents' => array( - 'nodes' => array( - array( - 'key' => $cart_item_key, - ), - ), - ), - 'availableShippingMethods' => array( - array( - 'packageDetails' => \html_entity_decode( 'socks ×2' ), - 'supportsShippingCalculator' => true, - 'rates' => array( - array( - 'id' => 'flat_rate:7', - 'cost' => '0.00', - 'label' => 'Flat rate' - ), - array( - 'id' => 'free_shipping:8', - 'cost' => '0.00', - 'label' => 'Free shipping' - ), - ) - ) - ), - ), - ), - ); - - $I->assertEquals( $expected, $actual ); - - /** - * Update shipping method to 'flat_rate' shipping. - */ - $mutation = ' + $actual = $I->sendGraphQLRequest( $query, null, array( 'woocommerce-session' => "Session {$session_token}" ) ); + $expected = array( + 'data' => array( + 'cart' => array( + 'contents' => array( + 'nodes' => array( + array( + 'key' => $cart_item_key, + ), + ), + ), + 'availableShippingMethods' => array( + array( + 'packageDetails' => \html_entity_decode( 'socks ×2' ), + 'supportsShippingCalculator' => true, + 'rates' => array( + array( + 'id' => 'flat_rate:7', + 'cost' => '0.00', + 'label' => 'Flat rate', + ), + array( + 'id' => 'free_shipping:8', + 'cost' => '0.00', + 'label' => 'Free shipping', + ), + ), + ), + ), + ), + ), + ); + + $I->assertEquals( $expected, $actual ); + + /** + * Update shipping method to 'flat_rate' shipping. + */ + $mutation = ' mutation ($input: UpdateShippingMethodInput!){ updateShippingMethod(input: $input) { cart { @@ -558,21 +561,21 @@ public function testCartSessionDataMutations( FunctionalTester $I ) { } '; - $success = $I->sendGraphQLRequest( - $mutation, - array( - 'clientMutationId' => 'someId', - 'shippingMethods' => array( 'flat_rate:7' ), - ), - array( 'woocommerce-session' => "Session {$session_token}" ) - ); - - $I->assertArrayNotHasKey( 'errors', $success ); - $I->assertNotEmpty( $success['data'] ); - $I->assertNotEmpty( $success['data']['updateShippingMethod'] ); - $I->assertNotEmpty( $success['data']['updateShippingMethod']['cart'] ); - $cart = $success['data']['updateShippingMethod']['cart']; - $I->assertNotEmpty( $cart['availableShippingMethods'] ); - $I->assertEquals( 'flat_rate:7', $cart['chosenShippingMethods'][0] ); - } + $success = $I->sendGraphQLRequest( + $mutation, + array( + 'clientMutationId' => 'someId', + 'shippingMethods' => array( 'flat_rate:7' ), + ), + array( 'woocommerce-session' => "Session {$session_token}" ) + ); + + $I->assertArrayNotHasKey( 'errors', $success ); + $I->assertNotEmpty( $success['data'] ); + $I->assertNotEmpty( $success['data']['updateShippingMethod'] ); + $I->assertNotEmpty( $success['data']['updateShippingMethod']['cart'] ); + $cart = $success['data']['updateShippingMethod']['cart']; + $I->assertNotEmpty( $cart['availableShippingMethods'] ); + $I->assertEquals( 'flat_rate:7', $cart['chosenShippingMethods'][0] ); + } } diff --git a/tests/wpunit/CartMutationsTest.php b/tests/wpunit/CartMutationsTest.php index 70719e265..54f777b13 100644 --- a/tests/wpunit/CartMutationsTest.php +++ b/tests/wpunit/CartMutationsTest.php @@ -1,8 +1,8 @@ factory->product->createSimple(); $query = ' @@ -33,15 +33,15 @@ public function testAddToCartMutationWithProduct() { $variables = array( 'input' => array( - 'clientMutationId' => 'someId', - 'productId' => $product_id, - 'quantity' => 2, - ), + 'clientMutationId' => 'someId', + 'productId' => $product_id, + 'quantity' => 2, + ), ); - $response = $this->graphql( compact( 'query', 'variables' ) ); + $response = $this->graphql( compact( 'query', 'variables' ) ); - // Confirm valid response + // Confirm valid response $this->assertIsValidQueryResponse( $response ); // Get/validate cart item key. @@ -50,8 +50,8 @@ public function testAddToCartMutationWithProduct() { // Get cart item data. $cart = \WC()->cart; - $cart_item = $cart->get_cart_item( $cart_item_key ); - $this->assertNotEmpty( $cart_item ); + $cart_item = $cart->get_cart_item( $cart_item_key ); + $this->assertNotEmpty( $cart_item ); $this->assertQuerySuccessful( $response, @@ -66,12 +66,12 @@ public function testAddToCartMutationWithProduct() { $this->expectedField( 'addToCart.cartItem.tax', wc_graphql_price( $cart_item['line_tax'] ) ), ) ); - } + } - public function testAddToCartMutationWithProductVariation() { - $ids = $this->factory->product_variation->createSome(); + public function testAddToCartMutationWithProductVariation() { + $ids = $this->factory->product_variation->createSome(); - $query = ' + $query = ' mutation( $input: AddToCartInput! ) { addToCart( input: $input ) { clientMutationId @@ -99,9 +99,9 @@ public function testAddToCartMutationWithProductVariation() { $variables = array( 'input' => array( - 'clientMutationId' => 'someId', - 'productId' => $ids['product'], - 'quantity' => 3, + 'clientMutationId' => 'someId', + 'productId' => $ids['product'], + 'quantity' => 3, 'variationId' => $ids['variations'][0], 'variation' => array( array( @@ -109,12 +109,12 @@ public function testAddToCartMutationWithProductVariation() { 'attributeValue' => 'red', ), ), - ) + ), ); - $response = $this->graphql( compact( 'query', 'variables' ) ); + $response = $this->graphql( compact( 'query', 'variables' ) ); - // Confirm valid response + // Confirm valid response $this->assertIsValidQueryResponse( $response ); // Get/validate cart item key. @@ -123,8 +123,8 @@ public function testAddToCartMutationWithProductVariation() { // Get cart item data. $cart = \WC()->cart; - $cart_item = $cart->get_cart_item( $cart_item_key ); - $this->assertNotEmpty( $cart_item ); + $cart_item = $cart->get_cart_item( $cart_item_key ); + $this->assertNotEmpty( $cart_item ); $this->assertQuerySuccessful( $response, @@ -140,30 +140,30 @@ public function testAddToCartMutationWithProductVariation() { $this->expectedField( 'addToCart.cartItem.tax', wc_graphql_price( $cart_item['line_tax'] ) ), ) ); - } + } - public function testUpdateCartItemQuantitiesMutation() { - // Create/add some products to the cart. - $cart_item_data = array( + public function testUpdateCartItemQuantitiesMutation() { + // Create/add some products to the cart. + $cart_item_data = array( array( 'product_id' => $this->factory->product->createSimple(), - 'quantity' => 2, + 'quantity' => 2, ), array( 'product_id' => $this->factory->product->createSimple(), - 'quantity' => 5, + 'quantity' => 5, ), array( 'product_id' => $this->factory->product->createSimple(), - 'quantity' => 1, + 'quantity' => 1, ), ); // Store cart item keys for use in mutation. $keys = $this->factory->cart->add( ...$cart_item_data ); - // Define mutation. - $query = ' + // Define mutation. + $query = ' mutation( $input: UpdateItemQuantitiesInput! ) { updateItemQuantities( input: $input ) { clientMutationId @@ -188,45 +188,90 @@ public function testUpdateCartItemQuantitiesMutation() { 'input' => array( 'clientMutationId' => 'someId', 'items' => array( - array( 'key' => $keys[0], 'quantity' => 4 ), - array( 'key' => $keys[1], 'quantity' => 2 ), - array( 'key' => $keys[2], 'quantity' => 0 ), + array( + 'key' => $keys[0], + 'quantity' => 4, + ), + array( + 'key' => $keys[1], + 'quantity' => 2, + ), + array( + 'key' => $keys[2], + 'quantity' => 0, + ), ), ), ); // Execute mutation. - $response = $this->graphql( compact( 'query', 'variables' ) ); + $response = $this->graphql( compact( 'query', 'variables' ) ); $this->assertQuerySuccessful( $response, array( $this->expectedField( 'updateItemQuantities.clientMutationId', 'someId' ), - $this->expectedNode( 'updateItemQuantities.updated', array( 'key' => $keys[0], 'quantity' => 4 ) ), - $this->expectedNode( 'updateItemQuantities.updated', array( 'key' => $keys[1], 'quantity' => 2 ) ), - $this->expectedNode( 'updateItemQuantities.removed', array( 'key' => $keys[2], 'quantity' => 1 ) ), - $this->expectedNode( 'updateItemQuantities.items', array( 'key' => $keys[0], 'quantity' => 4 ) ), - $this->expectedNode( 'updateItemQuantities.items', array( 'key' => $keys[1], 'quantity' => 2 ) ), - $this->expectedNode( 'updateItemQuantities.items', array( 'key' => $keys[2], 'quantity' => 1 ) ), + $this->expectedNode( + 'updateItemQuantities.updated', + array( + 'key' => $keys[0], + 'quantity' => 4, + ) + ), + $this->expectedNode( + 'updateItemQuantities.updated', + array( + 'key' => $keys[1], + 'quantity' => 2, + ) + ), + $this->expectedNode( + 'updateItemQuantities.removed', + array( + 'key' => $keys[2], + 'quantity' => 1, + ) + ), + $this->expectedNode( + 'updateItemQuantities.items', + array( + 'key' => $keys[0], + 'quantity' => 4, + ) + ), + $this->expectedNode( + 'updateItemQuantities.items', + array( + 'key' => $keys[1], + 'quantity' => 2, + ) + ), + $this->expectedNode( + 'updateItemQuantities.items', + array( + 'key' => $keys[2], + 'quantity' => 1, + ) + ), ) ); - } + } - public function testRemoveItemsFromCartMutation() { + public function testRemoveItemsFromCartMutation() { // Create/add some products to the cart. - $cart_item_data = array( + $cart_item_data = array( array( 'product_id' => $this->factory->product->createSimple(), - 'quantity' => 2, + 'quantity' => 2, ), array( 'product_id' => $this->factory->product->createSimple(), - 'quantity' => 5, + 'quantity' => 5, ), array( 'product_id' => $this->factory->product->createSimple(), - 'quantity' => 1, - ) + 'quantity' => 1, + ), ); // Store cart item keys for use in mutation. @@ -245,24 +290,24 @@ public function testRemoveItemsFromCartMutation() { // Define expected response data. $expected = array( $this->expectedField( 'removeItemsFromCart.clientMutationId', 'someId' ) ); - foreach( $keys as $key ) { + foreach ( $keys as $key ) { $expected[] = $this->expectedNode( 'removeItemsFromCart.cartItems', compact( 'key' ) ); } $variables = array( 'input' => array( - 'clientMutationId' => 'someId', - 'keys' => $keys, - ) + 'clientMutationId' => 'someId', + 'keys' => $keys, + ), ); // Execute mutation w/ "keys" array. - $response = $this->graphql( compact( 'query', 'variables' ) ); + $response = $this->graphql( compact( 'query', 'variables' ) ); $this->assertQuerySuccessful( $response, $expected ); // Confirm none of the items in cart. - foreach( $keys as $key ) { + foreach ( $keys as $key ) { $this->assertEmpty( \WC()->cart->get_cart_item( $key ), "{$key} still in cart after \"removeItemsFromCart\" mutation." @@ -274,9 +319,9 @@ public function testRemoveItemsFromCartMutation() { $variables = array( 'input' => array( - 'clientMutationId' => 'someId', - 'all' => true - ), + 'clientMutationId' => 'someId', + 'all' => true, + ), ); $response = $this->graphql( compact( 'query', 'variables' ) ); @@ -284,31 +329,31 @@ public function testRemoveItemsFromCartMutation() { $this->assertQuerySuccessful( $response, $expected ); // Confirm none of the items in cart. - foreach( $keys as $key ) { + foreach ( $keys as $key ) { $this->assertEmpty( \WC()->cart->get_cart_item( $key ), "{$key} still in cart after \"removeItemsFromCart\" mutation with \"all\" flag." ); } - } + } - public function testRestoreCartItemsMutation() { - // Create/add some products to the cart. + public function testRestoreCartItemsMutation() { + // Create/add some products to the cart. $cart_item_data = array( array( 'product_id' => $this->factory->product->createSimple(), - 'quantity' => 2, + 'quantity' => 2, ), array( 'product_id' => $this->factory->product->createSimple(), - 'quantity' => 5, + 'quantity' => 5, ), array( 'product_id' => $this->factory->product->createSimple(), - 'quantity' => 1, - ) + 'quantity' => 1, + ), ); - $keys = $this->factory->cart->add( ...$cart_item_data ); + $keys = $this->factory->cart->add( ...$cart_item_data ); $this->factory->cart->remove( ...$keys ); $query = ' @@ -324,37 +369,37 @@ public function testRestoreCartItemsMutation() { $variables = array( 'input' => array( - 'clientMutationId' => 'someId', - 'keys' => $keys, - ) + 'clientMutationId' => 'someId', + 'keys' => $keys, + ), ); - $response = $this->graphql( compact( 'query', 'variables' ) ); + $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedField( 'restoreCartItems.clientMutationId', 'someId' ) ); - foreach( $keys as $key ) { + foreach ( $keys as $key ) { $expected[] = $this->expectedNode( 'restoreCartItems.cartItems', compact( 'key' ) ); } $this->assertQuerySuccessful( $response, $expected ); // Confirm items in cart. - foreach( $keys as $key ) { + foreach ( $keys as $key ) { $this->assertNotEmpty( \WC()->cart->get_cart_item( $key ), "{$key} not found in cart after \"restoreCartItems\" mutation." ); } - } + } - public function testEmptyCartMutation() { - // Create/add some products to the cart. + public function testEmptyCartMutation() { + // Create/add some products to the cart. $product_id = $this->factory->product->createSimple(); - $cart = \WC()->cart; - $cart_item_key = $cart->add_to_cart( $product_id, 1 ); + $cart = \WC()->cart; + $cart_item_key = $cart->add_to_cart( $product_id, 1 ); $cart_item = $cart->get_cart_item( $cart_item_key ); - $query = ' + $query = ' mutation( $input: EmptyCartInput! ) { emptyCart( input: $input ) { clientMutationId @@ -384,10 +429,10 @@ public function testEmptyCartMutation() { } '; - $variables = array( - 'input' => array( 'clientMutationId' => 'someId' ), - ); - $response = $this->graphql( compact( 'query', 'variables' ) ); + $variables = array( + 'input' => array( 'clientMutationId' => 'someId' ), + ); + $response = $this->graphql( compact( 'query', 'variables' ) ); $this->assertQuerySuccessful( $response, @@ -413,33 +458,33 @@ public function testEmptyCartMutation() { ) ); - $this->assertTrue( \WC()->cart->is_empty() ); - } + $this->assertTrue( \WC()->cart->is_empty() ); + } - public function testApplyCouponMutation() { - // Create products. - $product_id = $this->factory->product->createSimple( - array( 'regular_price' => 100 ) - ); + public function testApplyCouponMutation() { + // Create products. + $product_id = $this->factory->product->createSimple( + array( 'regular_price' => 100 ) + ); - // Create coupon. - $coupon_code = wc_get_coupon_code_by_id( + // Create coupon. + $coupon_code = wc_get_coupon_code_by_id( $this->factory->coupon->create( - array( - 'amount' => 0.5, - 'product_ids' => array( $product_id ), + array( + 'amount' => 0.5, + 'product_ids' => array( $product_id ), 'description' => 'lorem ipsum dolor', - ) - ) - ); + ) + ) + ); - // Add items to carts. - $cart = \WC()->cart; - $cart_item_key = $cart->add_to_cart( $product_id, 1 ); + // Add items to carts. + $cart = \WC()->cart; + $cart_item_key = $cart->add_to_cart( $product_id, 1 ); - $old_total = \WC()->cart->get_cart_contents_total(); + $old_total = \WC()->cart->get_cart_contents_total(); - $query = ' + $query = ' mutation( $input: ApplyCouponInput! ) { applyCoupon( input: $input ) { clientMutationId @@ -468,16 +513,16 @@ public function testApplyCouponMutation() { } '; - $variables = array( - 'input' => array( - 'clientMutationId' => 'someId', - 'code' => $coupon_code, - ), - ); - $response = $this->graphql( compact( 'query', 'variables' ) ); + $variables = array( + 'input' => array( + 'clientMutationId' => 'someId', + 'code' => $coupon_code, + ), + ); + $response = $this->graphql( compact( 'query', 'variables' ) ); - // Get updated cart item. - $cart_item = $cart->get_cart_item( $cart_item_key ); + // Get updated cart item. + $cart_item = $cart->get_cart_item( $cart_item_key ); $this->assertQuerySuccessful( $response, @@ -493,61 +538,66 @@ public function testApplyCouponMutation() { $this->expectedNode( 'applyCoupon.cart.contents.nodes', array( - 'key' => $cart_item['key'], - 'product' => array( + 'key' => $cart_item['key'], + 'product' => array( 'node' => array( 'id' => $this->toRelayId( 'product', $cart_item['product_id'] ), ), ), - 'quantity' => $cart_item['quantity'], - 'subtotal' => wc_graphql_price( $cart_item['line_subtotal'] ), - 'subtotalTax' => wc_graphql_price( $cart_item['line_subtotal_tax'] ), - 'total' => wc_graphql_price( $cart_item['line_total'] ), - 'tax' => wc_graphql_price( $cart_item['line_tax'] ), + 'quantity' => $cart_item['quantity'], + 'subtotal' => wc_graphql_price( $cart_item['line_subtotal'] ), + 'subtotalTax' => wc_graphql_price( $cart_item['line_subtotal_tax'] ), + 'total' => wc_graphql_price( $cart_item['line_total'] ), + 'tax' => wc_graphql_price( $cart_item['line_tax'] ), ) ), ) ); - $new_total = \WC()->cart->get_cart_contents_total(); - - // Use --debug to view. - codecept_debug( array( 'old' => $old_total, 'new' => $new_total ) ); - - $this->assertTrue( $old_total > $new_total ); - } - - public function testApplyCouponMutationWithInvalidCoupons() { - $cart = WC()->cart; - - // Create products. - $product_id = $this->factory->product->createSimple(); - - // Create invalid coupon codes. - $coupon_id = $this->factory->coupon->create( - array( 'product_ids' => array( $product_id ) ) - ); - $expired_coupon_code = wc_get_coupon_code_by_id( - $this->factory->coupon->create( - array( - 'product_ids' => array( $product_id ), - 'date_expires' => time() - 20, - ) - ) - ); - $applied_coupon_code = wc_get_coupon_code_by_id( - $this->factory->coupon->create( - array( 'product_ids' => array( $product_id ) ) - ) - ); - - // Add items to carts. - $cart_item_key = $cart->add_to_cart( $product_id, 1 ); - $cart->apply_coupon( $applied_coupon_code ); - - $old_total = \WC()->cart->get_cart_contents_total(); - - $query = ' + $new_total = \WC()->cart->get_cart_contents_total(); + + // Use --debug to view. + codecept_debug( + array( + 'old' => $old_total, + 'new' => $new_total, + ) + ); + + $this->assertTrue( $old_total > $new_total ); + } + + public function testApplyCouponMutationWithInvalidCoupons() { + $cart = WC()->cart; + + // Create products. + $product_id = $this->factory->product->createSimple(); + + // Create invalid coupon codes. + $coupon_id = $this->factory->coupon->create( + array( 'product_ids' => array( $product_id ) ) + ); + $expired_coupon_code = wc_get_coupon_code_by_id( + $this->factory->coupon->create( + array( + 'product_ids' => array( $product_id ), + 'date_expires' => time() - 20, + ) + ) + ); + $applied_coupon_code = wc_get_coupon_code_by_id( + $this->factory->coupon->create( + array( 'product_ids' => array( $product_id ) ) + ) + ); + + // Add items to carts. + $cart_item_key = $cart->add_to_cart( $product_id, 1 ); + $cart->apply_coupon( $applied_coupon_code ); + + $old_total = \WC()->cart->get_cart_contents_total(); + + $query = ' mutation( $input: ApplyCouponInput! ) { applyCoupon( input: $input ) { clientMutationId @@ -555,72 +605,72 @@ public function testApplyCouponMutationWithInvalidCoupons() { } '; - /** - * Assertion One - * - * Can't pass coupon ID as coupon 'code'. Mutation should fail. - */ - $variables = array( - 'input' => array( - 'clientMutationId' => 'someId', - 'code' => '$coupon_id', - ), - ); - $response = $this->graphql( compact( 'query', 'variables' ) ); - - $this->assertNotEmpty( $response['errors'] ); - $this->assertEmpty( $response['data']['applyCoupon'] ); - - /** - * Assertion Two - * - * Can't pass expired coupon code. Mutation should fail. - */ - $variables = array( - 'input' => array( - 'clientMutationId' => 'someId', - 'code' => $expired_coupon_code, - ), - ); - $response = $this->graphql( compact( 'query', 'variables' ) ); - - $this->assertNotEmpty( $response['errors'] ); - $this->assertEmpty( $response['data']['applyCoupon'] ); - - /** - * Assertion Three - * - * Can't pass coupon already applied to the cart. Mutation should fail. - */ - $variables = array( - 'input' => array( - 'clientMutationId' => 'someId', - 'code' => $applied_coupon_code, - ), - ); - $response = $this->graphql( compact( 'query', 'variables' ) ); - - $this->assertNotEmpty( $response['errors'] ); - $this->assertEmpty( $response['data']['applyCoupon'] ); - - $this->assertEquals( $old_total, \WC()->cart->get_cart_contents_total() ); - } - - public function testRemoveCouponMutation() { - // Create product and coupon. - $product_id = $this->factory->product->createSimple(); - $coupon_code = wc_get_coupon_code_by_id( - $this->factory->coupon->create( - array( 'product_ids' => array( $product_id ) ) - ) - ); + /** + * Assertion One + * + * Can't pass coupon ID as coupon 'code'. Mutation should fail. + */ + $variables = array( + 'input' => array( + 'clientMutationId' => 'someId', + 'code' => '$coupon_id', + ), + ); + $response = $this->graphql( compact( 'query', 'variables' ) ); + + $this->assertNotEmpty( $response['errors'] ); + $this->assertEmpty( $response['data']['applyCoupon'] ); + + /** + * Assertion Two + * + * Can't pass expired coupon code. Mutation should fail. + */ + $variables = array( + 'input' => array( + 'clientMutationId' => 'someId', + 'code' => $expired_coupon_code, + ), + ); + $response = $this->graphql( compact( 'query', 'variables' ) ); + + $this->assertNotEmpty( $response['errors'] ); + $this->assertEmpty( $response['data']['applyCoupon'] ); + + /** + * Assertion Three + * + * Can't pass coupon already applied to the cart. Mutation should fail. + */ + $variables = array( + 'input' => array( + 'clientMutationId' => 'someId', + 'code' => $applied_coupon_code, + ), + ); + $response = $this->graphql( compact( 'query', 'variables' ) ); + + $this->assertNotEmpty( $response['errors'] ); + $this->assertEmpty( $response['data']['applyCoupon'] ); + + $this->assertEquals( $old_total, \WC()->cart->get_cart_contents_total() ); + } + + public function testRemoveCouponMutation() { + // Create product and coupon. + $product_id = $this->factory->product->createSimple(); + $coupon_code = wc_get_coupon_code_by_id( + $this->factory->coupon->create( + array( 'product_ids' => array( $product_id ) ) + ) + ); // Add item and coupon to cart and get total.. - $cart = \WC()->cart; - $cart_item_key = $cart->add_to_cart( $product_id, 3 ); - $cart->apply_coupon( $coupon_code ); + $cart = \WC()->cart; + $cart_item_key = $cart->add_to_cart( $product_id, 3 ); + $cart->apply_coupon( $coupon_code ); - $query = ' + $query = ' mutation removeCoupons( $input: RemoveCouponsInput! ) { removeCoupons( input: $input ) { clientMutationId @@ -648,15 +698,15 @@ public function testRemoveCouponMutation() { } '; - $variables = array( - 'input' => array( - 'clientMutationId' => 'someId', - 'codes' => array( $coupon_code ), - ), - ); - $response = $this->graphql( compact( 'query', 'variables' ) ); + $variables = array( + 'input' => array( + 'clientMutationId' => 'someId', + 'codes' => array( $coupon_code ), + ), + ); + $response = $this->graphql( compact( 'query', 'variables' ) ); - // Get updated cart item. + // Get updated cart item. $cart_item = \WC()->cart->get_cart_item( $cart_item_key ); $this->assertQuerySuccessful( @@ -667,38 +717,38 @@ public function testRemoveCouponMutation() { $this->expectedNode( 'removeCoupons.cart.contents.nodes', array( - 'key' => $cart_item['key'], - 'product' => array( + 'key' => $cart_item['key'], + 'product' => array( 'node' => array( 'id' => $this->toRelayId( 'product', $cart_item['product_id'] ), - ) + ), ), - 'quantity' => $cart_item['quantity'], - 'subtotal' => wc_graphql_price( $cart_item['line_subtotal'] ), - 'subtotalTax' => wc_graphql_price( $cart_item['line_subtotal_tax'] ), - 'total' => wc_graphql_price( $cart_item['line_total'] ), - 'tax' => wc_graphql_price( $cart_item['line_tax'] ), + 'quantity' => $cart_item['quantity'], + 'subtotal' => wc_graphql_price( $cart_item['line_subtotal'] ), + 'subtotalTax' => wc_graphql_price( $cart_item['line_subtotal_tax'] ), + 'total' => wc_graphql_price( $cart_item['line_total'] ), + 'tax' => wc_graphql_price( $cart_item['line_tax'] ), ) ), ) ); - } - - public function testAddFeeMutation() { - // Create product and coupon. - $product_id = $this->factory->product->createSimple(); - $coupon_code = wc_get_coupon_code_by_id( - $this->factory->coupon->create( - array( 'product_ids' => array( $product_id ) ) - ) - ); - - // Add item and coupon to cart. - $cart = \WC()->cart; - $cart->add_to_cart( $product_id, 3 ); - $cart->apply_coupon( $coupon_code ); - - $query = ' + } + + public function testAddFeeMutation() { + // Create product and coupon. + $product_id = $this->factory->product->createSimple(); + $coupon_code = wc_get_coupon_code_by_id( + $this->factory->coupon->create( + array( 'product_ids' => array( $product_id ) ) + ) + ); + + // Add item and coupon to cart. + $cart = \WC()->cart; + $cart->add_to_cart( $product_id, 3 ); + $cart->apply_coupon( $coupon_code ); + + $query = ' mutation( $input: AddFeeInput! ) { addFee( input: $input ) { clientMutationId @@ -714,18 +764,18 @@ public function testAddFeeMutation() { } '; - $variables = array( - 'input' => array( - 'clientMutationId' => 'someId', - 'name' => 'extra_fee', - 'amount' => 49.99, - ), - ); - $response = $this->graphql( compact( 'query', 'variables' ) ); - $this->assertArrayHasKey( 'errors', $response ); + $variables = array( + 'input' => array( + 'clientMutationId' => 'someId', + 'name' => 'extra_fee', + 'amount' => 49.99, + ), + ); + $response = $this->graphql( compact( 'query', 'variables' ) ); + $this->assertArrayHasKey( 'errors', $response ); - wp_set_current_user( $this->shop_manager ); - $response = $this->graphql( compact( 'query', 'variables' ) ); + wp_set_current_user( $this->shop_manager ); + $response = $this->graphql( compact( 'query', 'variables' ) ); $cart = WC()->cart; $fee = ( $cart->get_fees() )['extra_fee']; @@ -751,7 +801,7 @@ public function testAddFeeMutation() { public function testAddToCartMutationErrors() { // Create products. - $product_id = $this->factory->product->createSimple( + $product_id = $this->factory->product->createSimple( array( 'manage_stock' => true, 'stock_quantity' => 1, @@ -767,12 +817,12 @@ public function testAddToCartMutationErrors() { $attribute->set_position( 3 ); $attribute->set_visible( true ); $attribute->set_variation( true ); - $attributes = array_values( $product->get_attributes() ); + $attributes = array_values( $product->get_attributes() ); $attributes[] = $attribute; $product->set_attributes( $attributes ); $product->save(); - $query = ' + $query = ' mutation( $input: AddToCartInput! ) { addToCart( input: $input ) { clientMutationId @@ -799,7 +849,7 @@ public function testAddToCartMutationErrors() { '; \WC()->session->set( 'wc_notices', null ); - $variables = array( + $variables = array( 'input' => array( 'clientMutationId' => 'someId', 'productId' => $variation_ids['product'], @@ -807,18 +857,18 @@ public function testAddToCartMutationErrors() { 'variationId' => $variation_ids['variations'][0], ), ); - $missing_attributes = $this->graphql( compact( 'query', 'variables' ) ); + $missing_attributes = $this->graphql( compact( 'query', 'variables' ) ); $this->assertArrayHasKey( 'errors', $missing_attributes ); \WC()->session->set( 'wc_notices', null ); - $variables = array( + $variables = array( 'input' => array( - 'clientMutationId' => 'someId', - 'productId' => $product_id, - 'quantity' => 5, - ), + 'clientMutationId' => 'someId', + 'productId' => $product_id, + 'quantity' => 5, + ), ); - $not_enough_stock = $this->graphql( compact( 'query', 'variables' ) ); + $not_enough_stock = $this->graphql( compact( 'query', 'variables' ) ); $this->assertArrayHasKey( 'errors', $not_enough_stock ); } @@ -833,7 +883,7 @@ public function testAddToCartMutationItemEdgeData() { $attribute->set_position( 3 ); $attribute->set_visible( true ); $attribute->set_variation( true ); - $attributes = array_values( $product->get_attributes() ); + $attributes = array_values( $product->get_attributes() ); $attributes[] = $attribute; $product->set_attributes( $attributes ); $product->save(); @@ -871,8 +921,8 @@ public function testAddToCartMutationItemEdgeData() { 'attributeName' => 'color', 'attributeValue' => 'green', ), - ) - ) + ), + ), ); $response = $this->graphql( compact( 'query', 'variables' ) ); @@ -896,7 +946,7 @@ public function testAddToCartMutationItemEdgeData() { ) ), ) - ) + ), ); $this->assertQuerySuccessful( $response, $expected ); @@ -913,7 +963,7 @@ public function testAddCartItemsMutationAndErrors() { $attribute->set_position( 3 ); $attribute->set_visible( true ); $attribute->set_variation( true ); - $attributes = array_values( $product->get_attributes() ); + $attributes = array_values( $product->get_attributes() ); $attributes[] = $attribute; $product->set_attributes( $attributes ); $product->save(); @@ -965,7 +1015,7 @@ public function testAddCartItemsMutationAndErrors() { ), array( 'productId' => $invalid_product, - 'quantity' => 4 + 'quantity' => 4, ), array( 'productId' => $variation_ids['product'], @@ -980,8 +1030,8 @@ public function testAddCartItemsMutationAndErrors() { 'attributeName' => 'color', 'attributeValue' => 'green', ), - ) - ) + ), + ), ), ), ); @@ -996,7 +1046,7 @@ public function testAddCartItemsMutationAndErrors() { 'addCartItems.added', array( 'product' => array( - 'node' => array( 'databaseId' => $product_one ) + 'node' => array( 'databaseId' => $product_one ), ), 'variation' => null, 'quantity' => 2, @@ -1006,10 +1056,10 @@ public function testAddCartItemsMutationAndErrors() { 'addCartItems.added', array( 'product' => array( - 'node' => array( 'databaseId' => $variation_ids['product'] ) + 'node' => array( 'databaseId' => $variation_ids['product'] ), ), 'variation' => array( - 'node' => array( 'databaseId' => $variation_ids['variations'][1] ) + 'node' => array( 'databaseId' => $variation_ids['variations'][1] ), ), 'quantity' => 3, ) @@ -1023,7 +1073,7 @@ public function testAddCartItemsMutationAndErrors() { 'quantity' => 5, 'variationId' => $variation_ids['variations'][0], 'variation' => null, - 'extraData' => null + 'extraData' => null, ) ), $this->expectedNode( @@ -1035,7 +1085,7 @@ public function testAddCartItemsMutationAndErrors() { 'quantity' => 4, 'variationId' => null, 'variation' => null, - 'extraData' => null + 'extraData' => null, ) ), ) @@ -1044,26 +1094,26 @@ public function testAddCartItemsMutationAndErrors() { public function testFillCartMutationAndErrors() { // Create products. - $product_one = $this->factory->product->createSimple( array( 'regular_price' => 100 ) ); + $product_one = $this->factory->product->createSimple( array( 'regular_price' => 100 ) ); $product_two = $this->factory->product->createSimple( array( 'regular_price' => 40 ) ); - // Create coupons. - $coupon_code_one = wc_get_coupon_code_by_id( + // Create coupons. + $coupon_code_one = wc_get_coupon_code_by_id( $this->factory->coupon->create( array( 'amount' => 0.5, - 'product_ids' => array( $product_one ) + 'product_ids' => array( $product_one ), ) ) ); $coupon_code_two = wc_get_coupon_code_by_id( - $this->factory->coupon->create( - array( - 'amount' => 0.2, - 'product_ids' => array( $product_two ) - ) - ) - ); + $this->factory->coupon->create( + array( + 'amount' => 0.2, + 'product_ids' => array( $product_two ), + ) + ) + ); $invalid_product = 1000; $invalid_coupon = 'failed'; @@ -1131,8 +1181,8 @@ public function testFillCartMutationAndErrors() { 'quantity' => 4, ), ), - 'coupons' => array( $coupon_code_one, $coupon_code_two, $invalid_coupon ), - 'shippingMethods' => array( 'legacy_flat_rate', $invalid_shipping_method ), + 'coupons' => array( $coupon_code_one, $coupon_code_two, $invalid_coupon ), + 'shippingMethods' => array( 'legacy_flat_rate', $invalid_shipping_method ), ), ); diff --git a/tests/wpunit/CartQueriesTest.php b/tests/wpunit/CartQueriesTest.php index fd2fe8402..102da4e45 100644 --- a/tests/wpunit/CartQueriesTest.php +++ b/tests/wpunit/CartQueriesTest.php @@ -2,6 +2,7 @@ class CartQueriesTest extends \Tests\WPGraphQL\WooCommerce\TestCase\WooGraphQLTestCase { private function key_to_cursor( $key ) { + // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode return base64_encode( 'arrayconnection:' . $key ); } @@ -33,26 +34,26 @@ public function getExpectedCartItemData( $path, $cart_item_key ) { $this->expectedObject( $path, array( - $this->expectedField( "key", $item['key'] ), - $this->expectedField( "product.node.id", $this->toRelayId( 'product', $item['product_id'] ) ), - $this->expectedField( "product.node.databaseId", $item['product_id'] ), + $this->expectedField( 'key', $item['key'] ), + $this->expectedField( 'product.node.id', $this->toRelayId( 'product', $item['product_id'] ) ), + $this->expectedField( 'product.node.databaseId', $item['product_id'] ), $this->expectedField( - "variation.node.id", + 'variation.node.id', ! empty( $item['variation_id'] ) ? $this->toRelayId( 'product_variation', $item['variation_id'] ) : 'NULL' ), $this->expectedField( - "variation.node.databaseId", + 'variation.node.databaseId', ! empty( $item['variation_id'] ) ? $item['variation_id'] : 'NULL' ), - $this->expectedField( "quantity", $item['quantity'] ), - $this->expectedField( "subtotal", \wc_graphql_price( $item['line_subtotal'] ) ), - $this->expectedField( "subtotalTax", \wc_graphql_price( $item['line_subtotal_tax'] ) ), - $this->expectedField( "total", \wc_graphql_price( $item['line_total'] ) ), - $this->expectedField( "tax", \wc_graphql_price( $item['line_tax'] ) ), + $this->expectedField( 'quantity', $item['quantity'] ), + $this->expectedField( 'subtotal', \wc_graphql_price( $item['line_subtotal'] ) ), + $this->expectedField( 'subtotalTax', \wc_graphql_price( $item['line_subtotal_tax'] ) ), + $this->expectedField( 'total', \wc_graphql_price( $item['line_total'] ) ), + $this->expectedField( 'tax', \wc_graphql_price( $item['line_tax'] ) ), ) - ) + ), ); } @@ -62,11 +63,11 @@ public function testCartQuery() { $this->factory->cart->add( array( 'product_id' => $this->factory->product->createSimple(), - 'quantity' => 2, + 'quantity' => 2, ), array( 'product_id' => $this->factory->product->createSimple(), - 'quantity' => 1, + 'quantity' => 1, ) ); @@ -107,7 +108,7 @@ public function testCartQuery() { } public function testCartItemQuery() { - $cart = \WC()->cart; + $cart = \WC()->cart; $variations = $this->factory->product_variation->createSome(); $key = $cart->add_to_cart( @@ -153,7 +154,7 @@ public function testCartItemQuery() { * Assertion One */ $variables = array( 'key' => $key ); - $response = $this->graphql( compact( 'query', 'variables' ) ); + $response = $this->graphql( compact( 'query', 'variables' ) ); $this->assertQuerySuccessful( $response, $this->getExpectedCartItemData( 'cartItem', $key ) ); } @@ -164,15 +165,15 @@ public function testCartItemConnection() { 'product_id' => $this->factory->product->createSimple( array( 'virtual' => true ) ), - 'quantity' => 2, + 'quantity' => 2, ), array( 'product_id' => $this->factory->product->createSimple(), - 'quantity' => 1, + 'quantity' => 1, ), array( 'product_id' => $this->factory->product->createSimple(), - 'quantity' => 10, + 'quantity' => 10, ) ); @@ -206,7 +207,7 @@ public function testCartItemConnection() { $response = $this->graphql( compact( 'query' ) ); $expected = array(); - foreach( $keys as $key ) { + foreach ( $keys as $key ) { $expected[] = $this->expectedNode( 'cart.contents.nodes', array( 'key' => $key ) ); } @@ -250,7 +251,7 @@ public function testCartFeeQuery() { WC()->cart->add_fee( 'Test fee', 30.50 ); $fee_ids = array_keys( WC()->cart->get_fees() ); - $query = ' + $query = ' query ($id: ID!) { cartFee(id: $id) { id @@ -269,7 +270,7 @@ public function testCartFeeQuery() { $variables = array( 'id' => $fee_ids[0] ); $response = $this->graphql( compact( 'query', 'variables' ) ); - $fee = ( \WC()->cart->get_fees() )[ $fee_ids[0] ]; + $fee = ( \WC()->cart->get_fees() )[ $fee_ids[0] ]; $this->assertQuerySuccessful( $response, @@ -302,10 +303,10 @@ public function testCartToCartFeeQuery() { /** * Assertion One */ - $response = $this->graphql( compact( 'query' ) ); + $response = $this->graphql( compact( 'query' ) ); $expected = array(); - foreach( \WC()->cart->get_fees() as $fee_id => $value ) { + foreach ( \WC()->cart->get_fees() as $fee_id => $value ) { $expected[] = $this->expectedNode( 'cart.fees', array( 'id' => $fee_id ) ); } @@ -362,7 +363,10 @@ public function testCartItemPagination() { * * Tests "first" parameter. */ - $variables = array( 'first' => 2, 'after' => '' ); + $variables = array( + 'first' => 2, + 'after' => '', + ); $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedField( 'cart.contents.itemCount', 6 ), @@ -380,7 +384,7 @@ public function testCartItemPagination() { 'cart.contents.edges', array( $this->expectedField( 'key', $cart_items[1] ) ), 1 - ) + ), ); $this->assertQuerySuccessful( $response, $expected ); @@ -392,7 +396,7 @@ public function testCartItemPagination() { */ $variables = array( 'first' => 2, - 'after' => $this->key_to_cursor( $cart_items[1] ) + 'after' => $this->key_to_cursor( $cart_items[1] ), ); $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( @@ -409,7 +413,7 @@ public function testCartItemPagination() { 'cart.contents.edges', array( $this->expectedField( 'key', $cart_items[3] ) ), 1 - ) + ), ); $this->assertQuerySuccessful( $response, $expected ); @@ -435,7 +439,7 @@ public function testCartItemPagination() { 'cart.contents.edges', array( $this->expectedField( 'key', $cart_items[4] ) ), 1 - ) + ), ); $this->assertQuerySuccessful( $response, $expected ); @@ -446,7 +450,7 @@ public function testCartItemPagination() { * Tests "before" parameter. */ $variables = array( - 'last' => 4, + 'last' => 4, 'before' => $this->key_to_cursor( $cart_items[3] ), ); $response = $this->graphql( compact( 'query', 'variables' ) ); @@ -470,7 +474,7 @@ public function testCartItemPagination() { 'cart.contents.edges', array( $this->expectedField( 'key', $cart_items[2] ) ), 2 - ) + ), ); $this->assertQuerySuccessful( $response, $expected ); diff --git a/tests/wpunit/CheckoutMutationTest.php b/tests/wpunit/CheckoutMutationTest.php index 345503386..53bb08ece 100644 --- a/tests/wpunit/CheckoutMutationTest.php +++ b/tests/wpunit/CheckoutMutationTest.php @@ -3,114 +3,107 @@ use WPGraphQL\Type\WPEnumType; class CheckoutMutationTest extends \Codeception\TestCase\WPTestCase { - public function setUp(): void { - // before - parent::setUp(); - - // Create users. - $this->shop_manager = $this->factory->user->create( array( 'role' => 'shop_manager' ) ); - $this->simple_customer = $this->factory->user->create( array( 'role' => 'customer' ) ); - - // Get helper instances - $this->order = $this->getModule('\Helper\Wpunit')->order(); - $this->coupon = $this->getModule('\Helper\Wpunit')->coupon(); - $this->product = $this->getModule('\Helper\Wpunit')->product(); - $this->variation = $this->getModule('\Helper\Wpunit')->product_variation(); - $this->cart = $this->getModule('\Helper\Wpunit')->cart(); - $this->tax = $this->getModule('\Helper\Wpunit')->tax_rate(); - $this->customer = $this->getModule('\Helper\Wpunit')->customer(); - - // Turn on tax calculations and store shipping countries. Important! - update_option( 'woocommerce_ship_to_countries', 'all' ); - update_option( 'woocommerce_prices_include_tax', 'no' ); + public function setUp(): void { + // before + parent::setUp(); + + // Create users. + $this->shop_manager = $this->factory->user->create( array( 'role' => 'shop_manager' ) ); + $this->simple_customer = $this->factory->user->create( array( 'role' => 'customer' ) ); + + // Get helper instances + $this->order = $this->getModule( '\Helper\Wpunit' )->order(); + $this->coupon = $this->getModule( '\Helper\Wpunit' )->coupon(); + $this->product = $this->getModule( '\Helper\Wpunit' )->product(); + $this->variation = $this->getModule( '\Helper\Wpunit' )->product_variation(); + $this->cart = $this->getModule( '\Helper\Wpunit' )->cart(); + $this->tax = $this->getModule( '\Helper\Wpunit' )->tax_rate(); + $this->customer = $this->getModule( '\Helper\Wpunit' )->customer(); + + // Turn on tax calculations and store shipping countries. Important! + update_option( 'woocommerce_ship_to_countries', 'all' ); + update_option( 'woocommerce_prices_include_tax', 'no' ); update_option( 'woocommerce_calc_taxes', 'yes' ); - update_option( 'woocommerce_tax_round_at_subtotal', 'no' ); - - // Enable payment gateways. - update_option( - 'woocommerce_bacs_settings', - array( - 'enabled' => 'yes', - 'title' => 'Direct bank transfer', - 'description' => 'Make your payment directly into our bank account. Please use your Order ID as the payment reference. Your order will not be shipped until the funds have cleared in our account.', - 'instructions' => 'Instructions that will be added to the thank you page and emails.', - 'account' => '', - ) - ); - - update_option( - 'woocommerce_stripe_settings', - array( - 'enabled' => 'yes', - 'title' => 'Credit Card (Stripe)', - 'description' => 'Pay with your credit card via Stripe', - 'webhook' => '', - 'testmode' => 'yes', - 'test_publishable_key' => defined( 'STRIPE_API_PUBLISHABLE_KEY' ) - ? STRIPE_API_PUBLISHABLE_KEY - : getenv( 'STRIPE_API_PUBLISHABLE_KEY' ), - 'test_secret_key' => defined( 'STRIPE_API_SECRET_KEY' ) - ? STRIPE_API_SECRET_KEY - : getenv( 'STRIPE_API_SECRET_KEY' ), - 'test_webhook_secret' => '', - 'publishable_key' => '', - 'secret_key' => '', - 'webhook_secret' => '', - 'inline_cc_form' => 'no', - 'statement_descriptor' => '', - 'capture' => 'yes', - 'payment_request' => 'yes', - 'payment_request_button_type' => 'buy', - 'payment_request_button_theme' => 'dark', - 'payment_request_button_height' => '44', - 'saved_cards' => 'yes', - 'logging' => 'no', - ) - ); - - // Additional cart fees. - add_action( - 'woocommerce_cart_calculate_fees', - function() { - $percentage = 0.01; - $surcharge = ( WC()->cart->cart_contents_total + WC()->cart->shipping_total ) * $percentage; - WC()->cart->add_fee( 'Surcharge', $surcharge, true, '' ); - } - ); - - // Create a tax rate. - $this->tax->create( - array( - 'country' => '', - 'state' => '', - 'rate' => 20.000, - 'name' => 'VAT', - 'priority' => '1', - 'compound' => '0', - 'shipping' => '1', - 'class' => '' - ) - ); - // Create sample order to be used as a parent order. - $this->order_id = $this->order->create(); - - // Clear cart. - WC()->cart->empty_cart( true ); - wp_logout(); - - \WPGraphQL::clear_schema(); - } - - public function tearDown(): void { - // your tear down methods here - - // then - parent::tearDown(); - } - - private function checkout( $input, $mutation = null ) { - if ( ! $mutation ) { - $mutation = ' + update_option( 'woocommerce_tax_round_at_subtotal', 'no' ); + + // Enable payment gateways. + update_option( + 'woocommerce_bacs_settings', + array( + 'enabled' => 'yes', + 'title' => 'Direct bank transfer', + 'description' => 'Make your payment directly into our bank account. Please use your Order ID as the payment reference. Your order will not be shipped until the funds have cleared in our account.', + 'instructions' => 'Instructions that will be added to the thank you page and emails.', + 'account' => '', + ) + ); + + update_option( + 'woocommerce_stripe_settings', + array( + 'enabled' => 'yes', + 'title' => 'Credit Card (Stripe)', + 'description' => 'Pay with your credit card via Stripe', + 'webhook' => '', + 'testmode' => 'yes', + 'test_publishable_key' => defined( 'STRIPE_API_PUBLISHABLE_KEY' ) + ? STRIPE_API_PUBLISHABLE_KEY + : getenv( 'STRIPE_API_PUBLISHABLE_KEY' ), + 'test_secret_key' => defined( 'STRIPE_API_SECRET_KEY' ) + ? STRIPE_API_SECRET_KEY + : getenv( 'STRIPE_API_SECRET_KEY' ), + 'test_webhook_secret' => '', + 'publishable_key' => '', + 'secret_key' => '', + 'webhook_secret' => '', + 'inline_cc_form' => 'no', + 'statement_descriptor' => '', + 'capture' => 'yes', + 'payment_request' => 'yes', + 'payment_request_button_type' => 'buy', + 'payment_request_button_theme' => 'dark', + 'payment_request_button_height' => '44', + 'saved_cards' => 'yes', + 'logging' => 'no', + ) + ); + + // Additional cart fees. + add_action( + 'woocommerce_cart_calculate_fees', + function() { + $percentage = 0.01; + $surcharge = ( WC()->cart->cart_contents_total + WC()->cart->shipping_total ) * $percentage; + WC()->cart->add_fee( 'Surcharge', $surcharge, true, '' ); + } + ); + + // Create a tax rate. + $this->tax->create( + array( + 'country' => '', + 'state' => '', + 'rate' => 20.000, + 'name' => 'VAT', + 'priority' => '1', + 'compound' => '0', + 'shipping' => '1', + 'class' => '', + ) + ); + // Create sample order to be used as a parent order. + $this->order_id = $this->order->create(); + + // Clear cart. + WC()->cart->empty_cart( true ); + wp_logout(); + + \WPGraphQL::clear_schema(); + } + + private function checkout( $input, $mutation = null ) { + if ( ! $mutation ) { + $mutation = ' mutation checkout( $input: CheckoutInput! ) { checkout( input: $input ) { clientMutationId @@ -279,936 +272,933 @@ private function checkout( $input, $mutation = null ) { } } '; - } - - $actual = graphql( - array( - 'query' => $mutation, - 'operation_name' => 'checkout', - 'variables' => array( 'input' => $input ), - ) - ); - - return $actual; - } - - // tests - public function testCheckoutMutation() { - wp_set_current_user( $this->simple_customer ); - WC()->customer->set_billing_company( 'Harris Teeter' ); - - $variable = $this->variation->create( $this->product->create_variable() ); - $product_ids = array( - $this->product->create_simple(), - $this->product->create_simple(), - $variable['product'], - ); - $coupon = new WC_Coupon( - $this->coupon->create( array( 'product_ids' => $product_ids ) ) + } + + $actual = graphql( + array( + 'query' => $mutation, + 'operation_name' => 'checkout', + 'variables' => array( 'input' => $input ), + ) ); - WC()->cart->add_to_cart( $product_ids[0], 3 ); - WC()->cart->add_to_cart( $product_ids[1], 6 ); - WC()->cart->add_to_cart( + return $actual; + } + + // tests + public function testCheckoutMutation() { + wp_set_current_user( $this->simple_customer ); + WC()->customer->set_billing_company( 'Harris Teeter' ); + + $variable = $this->variation->create( $this->product->create_variable() ); + $product_ids = array( + $this->product->create_simple(), + $this->product->create_simple(), + $variable['product'], + ); + $coupon = new WC_Coupon( + $this->coupon->create( array( 'product_ids' => $product_ids ) ) + ); + + WC()->cart->add_to_cart( $product_ids[0], 3 ); + WC()->cart->add_to_cart( $product_ids[1], 6 ); + WC()->cart->add_to_cart( $product_ids[2], 2, $variable['variations'][0], array( 'attribute_pa_color' => 'red' ) ); - WC()->cart->apply_coupon( $coupon->get_code() ); - - $input = array( - 'clientMutationId' => 'someId', - 'paymentMethod' => 'bacs', - 'shippingMethod' => array( 'flat rate' ), - 'customerNote' => 'Test customer note', - 'billing' => array( - 'firstName' => 'May', - 'lastName' => 'Parker', - 'address1' => '20 Ingram St', - 'city' => 'New York City', - 'state' => 'NY', - 'postcode' => '12345', - 'country' => 'US', - 'email' => 'superfreak500@gmail.com', - 'phone' => '555-555-1234', - 'overwrite' => true - ), - 'shipping' => array( - 'firstName' => 'May', - 'lastName' => 'Parker', - 'address1' => '20 Ingram St', - 'city' => 'New York City', - 'state' => 'NY', - 'postcode' => '12345', - 'country' => 'US', - ), - 'metaData' => array( - array( - 'key' => 'test_key', - 'value' => 'test value', - ), - ) - ); - - /** + WC()->cart->apply_coupon( $coupon->get_code() ); + + $input = array( + 'clientMutationId' => 'someId', + 'paymentMethod' => 'bacs', + 'shippingMethod' => array( 'flat rate' ), + 'customerNote' => 'Test customer note', + 'billing' => array( + 'firstName' => 'May', + 'lastName' => 'Parker', + 'address1' => '20 Ingram St', + 'city' => 'New York City', + 'state' => 'NY', + 'postcode' => '12345', + 'country' => 'US', + 'email' => 'superfreak500@gmail.com', + 'phone' => '555-555-1234', + 'overwrite' => true, + ), + 'shipping' => array( + 'firstName' => 'May', + 'lastName' => 'Parker', + 'address1' => '20 Ingram St', + 'city' => 'New York City', + 'state' => 'NY', + 'postcode' => '12345', + 'country' => 'US', + ), + 'metaData' => array( + array( + 'key' => 'test_key', + 'value' => 'test value', + ), + ), + ); + + /** * Assertion One * * Test mutation and input. */ - $actual = $this->checkout( $input ); - - // use --debug flag to view. - codecept_debug( $actual ); - - $this->assertArrayHasKey('data', $actual ); - $this->assertArrayHasKey('checkout', $actual['data'] ); - $this->assertArrayHasKey('order', $actual['data']['checkout'] ); - $this->assertArrayHasKey('id', $actual['data']['checkout']['order'] ); - $order = \WC_Order_Factory::get_order( $actual['data']['checkout']['order']['databaseId'] ); - - // Get Available payment gateways. - $available_gateways = WC()->payment_gateways->get_available_payment_gateways(); - - $expected = array( - 'data' => array( - 'checkout' => array( - 'clientMutationId' => 'someId', - 'order' => array_merge( - $this->order->print_query( $order->get_id() ), - array( - 'metaData' => array( - array( - 'key' => 'is_vat_exempt', - 'value' => 'no', - ), - array( - 'key' => 'test_key', - 'value' => 'test value', - ), + $actual = $this->checkout( $input ); + + // use --debug flag to view. + codecept_debug( $actual ); + + $this->assertArrayHasKey( 'data', $actual ); + $this->assertArrayHasKey( 'checkout', $actual['data'] ); + $this->assertArrayHasKey( 'order', $actual['data']['checkout'] ); + $this->assertArrayHasKey( 'id', $actual['data']['checkout']['order'] ); + $order = \WC_Order_Factory::get_order( $actual['data']['checkout']['order']['databaseId'] ); + + // Get Available payment gateways. + $available_gateways = WC()->payment_gateways->get_available_payment_gateways(); + + $expected = array( + 'data' => array( + 'checkout' => array( + 'clientMutationId' => 'someId', + 'order' => array_merge( + $this->order->print_query( $order->get_id() ), + array( + 'metaData' => array( + array( + 'key' => 'is_vat_exempt', + 'value' => 'no', + ), + array( + 'key' => 'test_key', + 'value' => 'test value', + ), // array( - // 'key' => '_new_order_email_sent', - // 'value' => 'true' + // 'key' => '_new_order_email_sent', + // 'value' => 'true' // ) - ), - 'couponLines' => array( - 'nodes' => array_reverse( - array_map( - function( $item ) { - return array( - 'databaseId' => $item->get_id(), - 'orderId' => $item->get_order_id(), - 'code' => $item->get_code(), - 'discount' => ! empty( $item->get_discount() ) ? $item->get_discount() : null, - 'discountTax' => ! empty( $item->get_discount_tax() ) ? $item->get_discount_tax() : null, - 'coupon' => null, - ); - }, - $order->get_items( 'coupon' ) - ) - ), - ), - 'feeLines' => array( - 'nodes' => array_reverse( - array_map( - function( $item ) { - return array( - 'databaseId' => $item->get_id(), - 'orderId' => $item->get_order_id(), - 'amount' => $item->get_amount(), - 'name' => $item->get_name(), - 'taxStatus' => strtoupper( $item->get_tax_status() ), - 'total' => $item->get_total(), - 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, - 'taxClass' => ! empty( $item->get_tax_class() ) - ? WPEnumType::get_safe_name( $item->get_tax_class() ) - : 'STANDARD', - ); - }, - $order->get_items( 'fee' ) - ) - ), - ), - 'shippingLines' => array( - 'nodes' => array_reverse( - array_map( - function( $item ) { - - return array( - 'databaseId' => $item->get_id(), - 'orderId' => $item->get_order_id(), - 'methodTitle' => $item->get_method_title(), - 'total' => $item->get_total(), - 'totalTax' => !empty( $item->get_total_tax() ) - ? $item->get_total_tax() - : null, - 'taxClass' => ! empty( $item->get_tax_class() ) - ? $item->get_tax_class() === 'inherit' - ? WPEnumType::get_safe_name( 'inherit cart' ) - : WPEnumType::get_safe_name( $item->get_tax_class() ) - : 'STANDARD' - ); - }, - $order->get_items( 'shipping' ) - ) - ), - ), - 'taxLines' => array( - 'nodes' => array_reverse( - array_map( - function( $item ) { - return array( - 'rateCode' => $item->get_rate_code(), - 'label' => $item->get_label(), - 'taxTotal' => $item->get_tax_total(), - 'shippingTaxTotal' => $item->get_shipping_tax_total(), - 'isCompound' => $item->is_compound(), - 'taxRate' => array( 'databaseId' => $item->get_rate_id() ), - ); - }, - $order->get_items( 'tax' ) - ) - ), - ), - 'lineItems' => array( - 'nodes' => array_values( - array_map( - function( $item ) { - return array( - 'productId' => $item->get_product_id(), - 'variationId' => ! empty( $item->get_variation_id() ) - ? $item->get_variation_id() - : null, - 'quantity' => $item->get_quantity(), - 'taxClass' => ! empty( $item->get_tax_class() ) - ? strtoupper( $item->get_tax_class() ) - : 'STANDARD', - 'subtotal' => ! empty( $item->get_subtotal() ) ? $item->get_subtotal() : null, - 'subtotalTax' => ! empty( $item->get_subtotal_tax() ) ? $item->get_subtotal_tax() : null, - 'total' => ! empty( $item->get_total() ) ? $item->get_total() : null, - 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, - 'taxStatus' => strtoupper( $item->get_tax_status() ), - 'product' => array( 'id' => $this->product->to_relay_id( $item->get_product_id() ) ), - 'variation' => ! empty( $item->get_variation_id() ) - ? array( - 'id' => $this->variation->to_relay_id( $item->get_variation_id() ) - ) - : null, - ); - }, - $order->get_items() - ) - ), - ), - ) - ), - 'customer' => array( - 'id' => $this->customer->to_relay_id( $order->get_customer_id() ) - ), - 'result' => 'success', - 'redirect' => $available_gateways['bacs']->process_payment( $order->get_id() )['redirect'], - ), - ) - ); - - $this->assertEquals( $expected, $actual ); - } - - public function testCheckoutMutationWithNewAccount() { - $variable = $this->variation->create( $this->product->create_variable() ); - $product_ids = array( - $this->product->create_simple(), - $this->product->create_simple(), - $variable['product'], - ); - $coupon = new WC_Coupon( - $this->coupon->create( array( 'product_ids' => $product_ids ) ) - ); - WC()->cart->add_to_cart( $product_ids[0], 3 ); - WC()->cart->add_to_cart( $product_ids[1], 6 ); - WC()->cart->add_to_cart( + ), + 'couponLines' => array( + 'nodes' => array_reverse( + array_map( + function( $item ) { + return array( + 'databaseId' => $item->get_id(), + 'orderId' => $item->get_order_id(), + 'code' => $item->get_code(), + 'discount' => ! empty( $item->get_discount() ) ? $item->get_discount() : null, + 'discountTax' => ! empty( $item->get_discount_tax() ) ? $item->get_discount_tax() : null, + 'coupon' => null, + ); + }, + $order->get_items( 'coupon' ) + ) + ), + ), + 'feeLines' => array( + 'nodes' => array_reverse( + array_map( + function( $item ) { + return array( + 'databaseId' => $item->get_id(), + 'orderId' => $item->get_order_id(), + 'amount' => $item->get_amount(), + 'name' => $item->get_name(), + 'taxStatus' => strtoupper( $item->get_tax_status() ), + 'total' => $item->get_total(), + 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, + 'taxClass' => ! empty( $item->get_tax_class() ) + ? WPEnumType::get_safe_name( $item->get_tax_class() ) + : 'STANDARD', + ); + }, + $order->get_items( 'fee' ) + ) + ), + ), + 'shippingLines' => array( + 'nodes' => array_reverse( + array_map( + function( $item ) { + return array( + 'databaseId' => $item->get_id(), + 'orderId' => $item->get_order_id(), + 'methodTitle' => $item->get_method_title(), + 'total' => $item->get_total(), + 'totalTax' => ! empty( $item->get_total_tax() ) + ? $item->get_total_tax() + : null, + 'taxClass' => ! empty( $item->get_tax_class() ) + ? $item->get_tax_class() === 'inherit' + ? WPEnumType::get_safe_name( 'inherit cart' ) + : WPEnumType::get_safe_name( $item->get_tax_class() ) + : 'STANDARD', + ); + }, + $order->get_items( 'shipping' ) + ) + ), + ), + 'taxLines' => array( + 'nodes' => array_reverse( + array_map( + function( $item ) { + return array( + 'rateCode' => $item->get_rate_code(), + 'label' => $item->get_label(), + 'taxTotal' => $item->get_tax_total(), + 'shippingTaxTotal' => $item->get_shipping_tax_total(), + 'isCompound' => $item->is_compound(), + 'taxRate' => array( 'databaseId' => $item->get_rate_id() ), + ); + }, + $order->get_items( 'tax' ) + ) + ), + ), + 'lineItems' => array( + 'nodes' => array_values( + array_map( + function( $item ) { + return array( + 'productId' => $item->get_product_id(), + 'variationId' => ! empty( $item->get_variation_id() ) + ? $item->get_variation_id() + : null, + 'quantity' => $item->get_quantity(), + 'taxClass' => ! empty( $item->get_tax_class() ) + ? strtoupper( $item->get_tax_class() ) + : 'STANDARD', + 'subtotal' => ! empty( $item->get_subtotal() ) ? $item->get_subtotal() : null, + 'subtotalTax' => ! empty( $item->get_subtotal_tax() ) ? $item->get_subtotal_tax() : null, + 'total' => ! empty( $item->get_total() ) ? $item->get_total() : null, + 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, + 'taxStatus' => strtoupper( $item->get_tax_status() ), + 'product' => array( 'id' => $this->product->to_relay_id( $item->get_product_id() ) ), + 'variation' => ! empty( $item->get_variation_id() ) + ? array( + 'id' => $this->variation->to_relay_id( $item->get_variation_id() ), + ) + : null, + ); + }, + $order->get_items() + ) + ), + ), + ) + ), + 'customer' => array( + 'id' => $this->customer->to_relay_id( $order->get_customer_id() ), + ), + 'result' => 'success', + 'redirect' => $available_gateways['bacs']->process_payment( $order->get_id() )['redirect'], + ), + ), + ); + + $this->assertEquals( $expected, $actual ); + } + + public function testCheckoutMutationWithNewAccount() { + $variable = $this->variation->create( $this->product->create_variable() ); + $product_ids = array( + $this->product->create_simple(), + $this->product->create_simple(), + $variable['product'], + ); + $coupon = new WC_Coupon( + $this->coupon->create( array( 'product_ids' => $product_ids ) ) + ); + WC()->cart->add_to_cart( $product_ids[0], 3 ); + WC()->cart->add_to_cart( $product_ids[1], 6 ); + WC()->cart->add_to_cart( $product_ids[2], 2, $variable['variations'][0], array( 'attribute_pa_color' => 'red' ) ); - WC()->cart->apply_coupon( $coupon->get_code() ); - - $input = array( - 'clientMutationId' => 'someId', - 'paymentMethod' => 'bacs', - 'shippingMethod' => array( 'flat rate' ), - 'billing' => array( - 'firstName' => 'May', - 'lastName' => 'Parker', - 'company' => 'Harris Teeter', - 'address1' => '20 Ingram St', - 'city' => 'New York City', - 'state' => 'NY', - 'postcode' => '12345', - 'country' => 'US', - 'email' => 'superfreak500@gmail.com', - 'phone' => '555-555-1234', - ), - 'account' => array( - 'username' => 'test_user_1', - 'password' => 'test_pass' - ) - ); - - /** + WC()->cart->apply_coupon( $coupon->get_code() ); + + $input = array( + 'clientMutationId' => 'someId', + 'paymentMethod' => 'bacs', + 'shippingMethod' => array( 'flat rate' ), + 'billing' => array( + 'firstName' => 'May', + 'lastName' => 'Parker', + 'company' => 'Harris Teeter', + 'address1' => '20 Ingram St', + 'city' => 'New York City', + 'state' => 'NY', + 'postcode' => '12345', + 'country' => 'US', + 'email' => 'superfreak500@gmail.com', + 'phone' => '555-555-1234', + ), + 'account' => array( + 'username' => 'test_user_1', + 'password' => 'test_pass', + ), + ); + + /** * Assertion One * * Test mutation and input. */ - $actual = $this->checkout( $input ); - - // use --debug flag to view. - codecept_debug( $actual ); - - $this->assertArrayHasKey('data', $actual ); - $this->assertArrayHasKey('checkout', $actual['data'] ); - $this->assertArrayHasKey('order', $actual['data']['checkout'] ); - $this->assertArrayHasKey('id', $actual['data']['checkout']['order'] ); - $order = \WC_Order_Factory::get_order( $actual['data']['checkout']['order']['databaseId'] ); - - // Get Available payment gateways. - $available_gateways = WC()->payment_gateways->get_available_payment_gateways(); - - $expected = array( - 'data' => array( - 'checkout' => array( - 'clientMutationId' => 'someId', - 'order' => array_merge( - $this->order->print_query( $order->get_id() ), - array( - 'metaData' => array( - array( - 'key' => 'is_vat_exempt', - 'value' => 'no', - ), - ), - 'couponLines' => array( - 'nodes' => array_reverse( - array_map( - function( $item ) { - return array( - 'databaseId' => $item->get_id(), - 'orderId' => $item->get_order_id(), - 'code' => $item->get_code(), - 'discount' => ! empty( $item->get_discount() ) ? $item->get_discount() : null, - 'discountTax' => ! empty( $item->get_discount_tax() ) ? $item->get_discount_tax() : null, - 'coupon' => null, - ); - }, - $order->get_items( 'coupon' ) - ) - ), - ), - 'feeLines' => array( - 'nodes' => array_reverse( - array_map( - function( $item ) { - return array( - 'databaseId' => $item->get_id(), - 'orderId' => $item->get_order_id(), - 'amount' => $item->get_amount(), - 'name' => $item->get_name(), - 'taxStatus' => strtoupper( $item->get_tax_status() ), - 'total' => $item->get_total(), - 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, - 'taxClass' => ! empty( $item->get_tax_class() ) - ? WPEnumType::get_safe_name( $item->get_tax_class() ) - : 'STANDARD', - ); - }, - $order->get_items( 'fee' ) - ) - ), - ), - 'shippingLines' => array( - 'nodes' => array_reverse( - array_map( - function( $item ) { - - return array( - 'databaseId' => $item->get_id(), - 'orderId' => $item->get_order_id(), - 'methodTitle' => $item->get_method_title(), - 'total' => $item->get_total(), - 'totalTax' => !empty( $item->get_total_tax() ) - ? $item->get_total_tax() - : null, - 'taxClass' => ! empty( $item->get_tax_class() ) - ? $item->get_tax_class() === 'inherit' - ? WPEnumType::get_safe_name( 'inherit cart' ) - : WPEnumType::get_safe_name( $item->get_tax_class() ) - : 'STANDARD' - ); - }, - $order->get_items( 'shipping' ) - ) - ), - ), - 'taxLines' => array( - 'nodes' => array_reverse( - array_map( - function( $item ) { - return array( - 'rateCode' => $item->get_rate_code(), - 'label' => $item->get_label(), - 'taxTotal' => $item->get_tax_total(), - 'shippingTaxTotal' => $item->get_shipping_tax_total(), - 'isCompound' => $item->is_compound(), - 'taxRate' => array( 'databaseId' => $item->get_rate_id() ), - ); - }, - $order->get_items( 'tax' ) - ) - ), - ), - 'lineItems' => array( - 'nodes' => array_values( - array_map( - function( $item ) { - return array( - 'productId' => $item->get_product_id(), - 'variationId' => ! empty( $item->get_variation_id() ) - ? $item->get_variation_id() - : null, - 'quantity' => $item->get_quantity(), - 'taxClass' => ! empty( $item->get_tax_class() ) - ? strtoupper( $item->get_tax_class() ) - : 'STANDARD', - 'subtotal' => ! empty( $item->get_subtotal() ) ? $item->get_subtotal() : null, - 'subtotalTax' => ! empty( $item->get_subtotal_tax() ) ? $item->get_subtotal_tax() : null, - 'total' => ! empty( $item->get_total() ) ? $item->get_total() : null, - 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, - 'taxStatus' => strtoupper( $item->get_tax_status() ), - 'product' => array( 'id' => $this->product->to_relay_id( $item->get_product_id() ) ), - 'variation' => ! empty( $item->get_variation_id() ) - ? array( - 'id' => $this->variation->to_relay_id( $item->get_variation_id() ) - ) - : null, - ); - }, - $order->get_items() - ) - ), - ), - ) - ), - 'customer' => array( - 'id' => $this->customer->to_relay_id( $order->get_customer_id() ) - ), - 'result' => 'success', - 'redirect' => $available_gateways['bacs']->process_payment( $order->get_id() )['redirect'], - ), - ) - ); - - $this->assertEquals( $expected, $actual ); - } - - public function testCheckoutMutationWithNoAccount() { - update_option( 'woocommerce_enable_guest_checkout', 'yes' ); - $variable = $this->variation->create( $this->product->create_variable() ); - $product_ids = array( - $this->product->create_simple(), - $this->product->create_simple(), - $variable['product'], - ); - $coupon = new WC_Coupon( - $this->coupon->create( array( 'product_ids' => $product_ids ) ) - ); - WC()->cart->add_to_cart( $product_ids[0], 3 ); - WC()->cart->add_to_cart( $product_ids[1], 6 ); - WC()->cart->add_to_cart( + $actual = $this->checkout( $input ); + + // use --debug flag to view. + codecept_debug( $actual ); + + $this->assertArrayHasKey( 'data', $actual ); + $this->assertArrayHasKey( 'checkout', $actual['data'] ); + $this->assertArrayHasKey( 'order', $actual['data']['checkout'] ); + $this->assertArrayHasKey( 'id', $actual['data']['checkout']['order'] ); + $order = \WC_Order_Factory::get_order( $actual['data']['checkout']['order']['databaseId'] ); + + // Get Available payment gateways. + $available_gateways = WC()->payment_gateways->get_available_payment_gateways(); + + $expected = array( + 'data' => array( + 'checkout' => array( + 'clientMutationId' => 'someId', + 'order' => array_merge( + $this->order->print_query( $order->get_id() ), + array( + 'metaData' => array( + array( + 'key' => 'is_vat_exempt', + 'value' => 'no', + ), + ), + 'couponLines' => array( + 'nodes' => array_reverse( + array_map( + function( $item ) { + return array( + 'databaseId' => $item->get_id(), + 'orderId' => $item->get_order_id(), + 'code' => $item->get_code(), + 'discount' => ! empty( $item->get_discount() ) ? $item->get_discount() : null, + 'discountTax' => ! empty( $item->get_discount_tax() ) ? $item->get_discount_tax() : null, + 'coupon' => null, + ); + }, + $order->get_items( 'coupon' ) + ) + ), + ), + 'feeLines' => array( + 'nodes' => array_reverse( + array_map( + function( $item ) { + return array( + 'databaseId' => $item->get_id(), + 'orderId' => $item->get_order_id(), + 'amount' => $item->get_amount(), + 'name' => $item->get_name(), + 'taxStatus' => strtoupper( $item->get_tax_status() ), + 'total' => $item->get_total(), + 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, + 'taxClass' => ! empty( $item->get_tax_class() ) + ? WPEnumType::get_safe_name( $item->get_tax_class() ) + : 'STANDARD', + ); + }, + $order->get_items( 'fee' ) + ) + ), + ), + 'shippingLines' => array( + 'nodes' => array_reverse( + array_map( + function( $item ) { + return array( + 'databaseId' => $item->get_id(), + 'orderId' => $item->get_order_id(), + 'methodTitle' => $item->get_method_title(), + 'total' => $item->get_total(), + 'totalTax' => ! empty( $item->get_total_tax() ) + ? $item->get_total_tax() + : null, + 'taxClass' => ! empty( $item->get_tax_class() ) + ? $item->get_tax_class() === 'inherit' + ? WPEnumType::get_safe_name( 'inherit cart' ) + : WPEnumType::get_safe_name( $item->get_tax_class() ) + : 'STANDARD', + ); + }, + $order->get_items( 'shipping' ) + ) + ), + ), + 'taxLines' => array( + 'nodes' => array_reverse( + array_map( + function( $item ) { + return array( + 'rateCode' => $item->get_rate_code(), + 'label' => $item->get_label(), + 'taxTotal' => $item->get_tax_total(), + 'shippingTaxTotal' => $item->get_shipping_tax_total(), + 'isCompound' => $item->is_compound(), + 'taxRate' => array( 'databaseId' => $item->get_rate_id() ), + ); + }, + $order->get_items( 'tax' ) + ) + ), + ), + 'lineItems' => array( + 'nodes' => array_values( + array_map( + function( $item ) { + return array( + 'productId' => $item->get_product_id(), + 'variationId' => ! empty( $item->get_variation_id() ) + ? $item->get_variation_id() + : null, + 'quantity' => $item->get_quantity(), + 'taxClass' => ! empty( $item->get_tax_class() ) + ? strtoupper( $item->get_tax_class() ) + : 'STANDARD', + 'subtotal' => ! empty( $item->get_subtotal() ) ? $item->get_subtotal() : null, + 'subtotalTax' => ! empty( $item->get_subtotal_tax() ) ? $item->get_subtotal_tax() : null, + 'total' => ! empty( $item->get_total() ) ? $item->get_total() : null, + 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, + 'taxStatus' => strtoupper( $item->get_tax_status() ), + 'product' => array( 'id' => $this->product->to_relay_id( $item->get_product_id() ) ), + 'variation' => ! empty( $item->get_variation_id() ) + ? array( + 'id' => $this->variation->to_relay_id( $item->get_variation_id() ), + ) + : null, + ); + }, + $order->get_items() + ) + ), + ), + ) + ), + 'customer' => array( + 'id' => $this->customer->to_relay_id( $order->get_customer_id() ), + ), + 'result' => 'success', + 'redirect' => $available_gateways['bacs']->process_payment( $order->get_id() )['redirect'], + ), + ), + ); + + $this->assertEquals( $expected, $actual ); + } + + public function testCheckoutMutationWithNoAccount() { + update_option( 'woocommerce_enable_guest_checkout', 'yes' ); + $variable = $this->variation->create( $this->product->create_variable() ); + $product_ids = array( + $this->product->create_simple(), + $this->product->create_simple(), + $variable['product'], + ); + $coupon = new WC_Coupon( + $this->coupon->create( array( 'product_ids' => $product_ids ) ) + ); + WC()->cart->add_to_cart( $product_ids[0], 3 ); + WC()->cart->add_to_cart( $product_ids[1], 6 ); + WC()->cart->add_to_cart( $product_ids[2], 2, $variable['variations'][0], array( 'attribute_pa_color' => 'red' ) ); - WC()->cart->apply_coupon( $coupon->get_code() ); - - $input = array( - 'clientMutationId' => 'someId', - 'paymentMethod' => 'bacs', - 'shippingMethod' => array( 'flat rate' ), - 'billing' => array( - 'firstName' => 'May', - 'lastName' => 'Parker', - 'address1' => '20 Ingram St', - 'city' => 'New York City', - 'state' => 'NY', - 'postcode' => '12345', - 'country' => 'US', - 'email' => 'superfreak500@gmail.com', - 'phone' => '555-555-1234', - ), - 'shipping' => array( - 'firstName' => 'May', - 'lastName' => 'Parker', - 'address1' => '20 Ingram St', - 'city' => 'New York City', - 'state' => 'NY', - 'postcode' => '12345', - 'country' => 'US', - ), - ); - - /** + WC()->cart->apply_coupon( $coupon->get_code() ); + + $input = array( + 'clientMutationId' => 'someId', + 'paymentMethod' => 'bacs', + 'shippingMethod' => array( 'flat rate' ), + 'billing' => array( + 'firstName' => 'May', + 'lastName' => 'Parker', + 'address1' => '20 Ingram St', + 'city' => 'New York City', + 'state' => 'NY', + 'postcode' => '12345', + 'country' => 'US', + 'email' => 'superfreak500@gmail.com', + 'phone' => '555-555-1234', + ), + 'shipping' => array( + 'firstName' => 'May', + 'lastName' => 'Parker', + 'address1' => '20 Ingram St', + 'city' => 'New York City', + 'state' => 'NY', + 'postcode' => '12345', + 'country' => 'US', + ), + ); + + /** * Assertion One * * Test mutation and input. */ - $actual = $this->checkout( $input ); - - // use --debug flag to view. - codecept_debug( $actual ); - - $this->assertArrayHasKey('data', $actual ); - $this->assertArrayHasKey('checkout', $actual['data'] ); - $this->assertArrayHasKey('order', $actual['data']['checkout'] ); - $this->assertArrayHasKey('id', $actual['data']['checkout']['order'] ); - $order = \WC_Order_Factory::get_order( $actual['data']['checkout']['order']['databaseId'] ); - - // Get Available payment gateways. - $available_gateways = WC()->payment_gateways->get_available_payment_gateways(); - - $expected = array( - 'data' => array( - 'checkout' => array( - 'clientMutationId' => 'someId', - 'order' => array_merge( - $this->order->print_query( $order->get_id() ), - array( - 'metaData' => array( - array( - 'key' => 'is_vat_exempt', - 'value' => 'no', - ), - ), - 'couponLines' => array( - 'nodes' => array_reverse( - array_map( - function( $item ) { - return array( - 'databaseId' => $item->get_id(), - 'orderId' => $item->get_order_id(), - 'code' => $item->get_code(), - 'discount' => ! empty( $item->get_discount() ) ? $item->get_discount() : null, - 'discountTax' => ! empty( $item->get_discount_tax() ) ? $item->get_discount_tax() : null, - 'coupon' => null, - ); - }, - $order->get_items( 'coupon' ) - ) - ), - ), - 'feeLines' => array( - 'nodes' => array_reverse( - array_map( - function( $item ) { - return array( - 'databaseId' => $item->get_id(), - 'orderId' => $item->get_order_id(), - 'amount' => $item->get_amount(), - 'name' => $item->get_name(), - 'taxStatus' => strtoupper( $item->get_tax_status() ), - 'total' => $item->get_total(), - 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, - 'taxClass' => ! empty( $item->get_tax_class() ) - ? WPEnumType::get_safe_name( $item->get_tax_class() ) - : 'STANDARD', - ); - }, - $order->get_items( 'fee' ) - ) - ), - ), - 'shippingLines' => array( - 'nodes' => array_reverse( - array_map( - function( $item ) { - - return array( - 'databaseId' => $item->get_id(), - 'orderId' => $item->get_order_id(), - 'methodTitle' => $item->get_method_title(), - 'total' => $item->get_total(), - 'totalTax' => !empty( $item->get_total_tax() ) - ? $item->get_total_tax() - : null, - 'taxClass' => ! empty( $item->get_tax_class() ) - ? $item->get_tax_class() === 'inherit' - ? WPEnumType::get_safe_name( 'inherit cart' ) - : WPEnumType::get_safe_name( $item->get_tax_class() ) - : 'STANDARD' - ); - }, - $order->get_items( 'shipping' ) - ) - ), - ), - 'taxLines' => array( - 'nodes' => array_reverse( - array_map( - function( $item ) { - return array( - 'rateCode' => $item->get_rate_code(), - 'label' => $item->get_label(), - 'taxTotal' => $item->get_tax_total(), - 'shippingTaxTotal' => $item->get_shipping_tax_total(), - 'isCompound' => $item->is_compound(), - 'taxRate' => array( 'databaseId' => $item->get_rate_id() ), - ); - }, - $order->get_items( 'tax' ) - ) - ), - ), - 'lineItems' => array( - 'nodes' => array_values( - array_map( - function( $item ) { - return array( - 'productId' => $item->get_product_id(), - 'variationId' => ! empty( $item->get_variation_id() ) - ? $item->get_variation_id() - : null, - 'quantity' => $item->get_quantity(), - 'taxClass' => ! empty( $item->get_tax_class() ) - ? strtoupper( $item->get_tax_class() ) - : 'STANDARD', - 'subtotal' => ! empty( $item->get_subtotal() ) ? $item->get_subtotal() : null, - 'subtotalTax' => ! empty( $item->get_subtotal_tax() ) ? $item->get_subtotal_tax() : null, - 'total' => ! empty( $item->get_total() ) ? $item->get_total() : null, - 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, - 'taxStatus' => strtoupper( $item->get_tax_status() ), - 'product' => array( 'id' => $this->product->to_relay_id( $item->get_product_id() ) ), - 'variation' => ! empty( $item->get_variation_id() ) - ? array( - 'id' => $this->variation->to_relay_id( $item->get_variation_id() ) - ) - : null, - ); - }, - $order->get_items() - ) - ), - ), - ) - ), - 'customer' => null, - 'result' => 'success', - 'redirect' => $available_gateways['bacs']->process_payment( $order->get_id() )['redirect'], - ), - ) - ); - - $this->assertEquals( $expected, $actual ); - } - - public function testCheckoutMutationWithPrepaidOrder() { - update_option( 'woocommerce_enable_guest_checkout', 'yes' ); - $product_ids = array( - $this->product->create_simple( - array( - 'virtual' => true, - 'downloadable' => true, - ) - ), - $this->product->create_simple( - array( - 'virtual' => true, - 'downloadable' => true, - ) - ), - ); - $coupon = new WC_Coupon( - $this->coupon->create( array( 'product_ids' => $product_ids ) ) - ); - WC()->cart->add_to_cart( $product_ids[0], 3 ); - WC()->cart->add_to_cart( $product_ids[1], 6 ); - WC()->cart->apply_coupon( $coupon->get_code() ); - - $input = array( - 'clientMutationId' => 'someId', - 'paymentMethod' => 'bacs', - 'isPaid' => true, - 'transactionId' => 'transaction_id', - 'shippingMethod' => array( 'flat rate' ), - 'billing' => array( - 'firstName' => 'May', - 'lastName' => 'Parker', - 'address1' => '20 Ingram St', - 'city' => 'New York City', - 'state' => 'NY', - 'postcode' => '12345', - 'country' => 'US', - 'email' => 'superfreak500@gmail.com', - 'phone' => '555-555-1234', - ), - 'shipping' => array( - 'firstName' => 'May', - 'lastName' => 'Parker', - 'address1' => '20 Ingram St', - 'city' => 'New York City', - 'state' => 'NY', - 'postcode' => '12345', - 'country' => 'US', - ), - ); - - /** + $actual = $this->checkout( $input ); + + // use --debug flag to view. + codecept_debug( $actual ); + + $this->assertArrayHasKey( 'data', $actual ); + $this->assertArrayHasKey( 'checkout', $actual['data'] ); + $this->assertArrayHasKey( 'order', $actual['data']['checkout'] ); + $this->assertArrayHasKey( 'id', $actual['data']['checkout']['order'] ); + $order = \WC_Order_Factory::get_order( $actual['data']['checkout']['order']['databaseId'] ); + + // Get Available payment gateways. + $available_gateways = WC()->payment_gateways->get_available_payment_gateways(); + + $expected = array( + 'data' => array( + 'checkout' => array( + 'clientMutationId' => 'someId', + 'order' => array_merge( + $this->order->print_query( $order->get_id() ), + array( + 'metaData' => array( + array( + 'key' => 'is_vat_exempt', + 'value' => 'no', + ), + ), + 'couponLines' => array( + 'nodes' => array_reverse( + array_map( + function( $item ) { + return array( + 'databaseId' => $item->get_id(), + 'orderId' => $item->get_order_id(), + 'code' => $item->get_code(), + 'discount' => ! empty( $item->get_discount() ) ? $item->get_discount() : null, + 'discountTax' => ! empty( $item->get_discount_tax() ) ? $item->get_discount_tax() : null, + 'coupon' => null, + ); + }, + $order->get_items( 'coupon' ) + ) + ), + ), + 'feeLines' => array( + 'nodes' => array_reverse( + array_map( + function( $item ) { + return array( + 'databaseId' => $item->get_id(), + 'orderId' => $item->get_order_id(), + 'amount' => $item->get_amount(), + 'name' => $item->get_name(), + 'taxStatus' => strtoupper( $item->get_tax_status() ), + 'total' => $item->get_total(), + 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, + 'taxClass' => ! empty( $item->get_tax_class() ) + ? WPEnumType::get_safe_name( $item->get_tax_class() ) + : 'STANDARD', + ); + }, + $order->get_items( 'fee' ) + ) + ), + ), + 'shippingLines' => array( + 'nodes' => array_reverse( + array_map( + function( $item ) { + return array( + 'databaseId' => $item->get_id(), + 'orderId' => $item->get_order_id(), + 'methodTitle' => $item->get_method_title(), + 'total' => $item->get_total(), + 'totalTax' => ! empty( $item->get_total_tax() ) + ? $item->get_total_tax() + : null, + 'taxClass' => ! empty( $item->get_tax_class() ) + ? $item->get_tax_class() === 'inherit' + ? WPEnumType::get_safe_name( 'inherit cart' ) + : WPEnumType::get_safe_name( $item->get_tax_class() ) + : 'STANDARD', + ); + }, + $order->get_items( 'shipping' ) + ) + ), + ), + 'taxLines' => array( + 'nodes' => array_reverse( + array_map( + function( $item ) { + return array( + 'rateCode' => $item->get_rate_code(), + 'label' => $item->get_label(), + 'taxTotal' => $item->get_tax_total(), + 'shippingTaxTotal' => $item->get_shipping_tax_total(), + 'isCompound' => $item->is_compound(), + 'taxRate' => array( 'databaseId' => $item->get_rate_id() ), + ); + }, + $order->get_items( 'tax' ) + ) + ), + ), + 'lineItems' => array( + 'nodes' => array_values( + array_map( + function( $item ) { + return array( + 'productId' => $item->get_product_id(), + 'variationId' => ! empty( $item->get_variation_id() ) + ? $item->get_variation_id() + : null, + 'quantity' => $item->get_quantity(), + 'taxClass' => ! empty( $item->get_tax_class() ) + ? strtoupper( $item->get_tax_class() ) + : 'STANDARD', + 'subtotal' => ! empty( $item->get_subtotal() ) ? $item->get_subtotal() : null, + 'subtotalTax' => ! empty( $item->get_subtotal_tax() ) ? $item->get_subtotal_tax() : null, + 'total' => ! empty( $item->get_total() ) ? $item->get_total() : null, + 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, + 'taxStatus' => strtoupper( $item->get_tax_status() ), + 'product' => array( 'id' => $this->product->to_relay_id( $item->get_product_id() ) ), + 'variation' => ! empty( $item->get_variation_id() ) + ? array( + 'id' => $this->variation->to_relay_id( $item->get_variation_id() ), + ) + : null, + ); + }, + $order->get_items() + ) + ), + ), + ) + ), + 'customer' => null, + 'result' => 'success', + 'redirect' => $available_gateways['bacs']->process_payment( $order->get_id() )['redirect'], + ), + ), + ); + + $this->assertEquals( $expected, $actual ); + } + + public function testCheckoutMutationWithPrepaidOrder() { + update_option( 'woocommerce_enable_guest_checkout', 'yes' ); + $product_ids = array( + $this->product->create_simple( + array( + 'virtual' => true, + 'downloadable' => true, + ) + ), + $this->product->create_simple( + array( + 'virtual' => true, + 'downloadable' => true, + ) + ), + ); + $coupon = new WC_Coupon( + $this->coupon->create( array( 'product_ids' => $product_ids ) ) + ); + WC()->cart->add_to_cart( $product_ids[0], 3 ); + WC()->cart->add_to_cart( $product_ids[1], 6 ); + WC()->cart->apply_coupon( $coupon->get_code() ); + + $input = array( + 'clientMutationId' => 'someId', + 'paymentMethod' => 'bacs', + 'isPaid' => true, + 'transactionId' => 'transaction_id', + 'shippingMethod' => array( 'flat rate' ), + 'billing' => array( + 'firstName' => 'May', + 'lastName' => 'Parker', + 'address1' => '20 Ingram St', + 'city' => 'New York City', + 'state' => 'NY', + 'postcode' => '12345', + 'country' => 'US', + 'email' => 'superfreak500@gmail.com', + 'phone' => '555-555-1234', + ), + 'shipping' => array( + 'firstName' => 'May', + 'lastName' => 'Parker', + 'address1' => '20 Ingram St', + 'city' => 'New York City', + 'state' => 'NY', + 'postcode' => '12345', + 'country' => 'US', + ), + ); + + /** * Assertion One * * Test mutation and input. */ - $actual = $this->checkout( $input ); - - // use --debug flag to view. - codecept_debug( $actual ); - - $this->assertArrayHasKey('data', $actual ); - $this->assertArrayHasKey('checkout', $actual['data'] ); - $this->assertArrayHasKey('order', $actual['data']['checkout'] ); - $this->assertArrayHasKey('id', $actual['data']['checkout']['order'] ); - $this->assertEquals('COMPLETED', $actual['data']['checkout']['order']['status'] ); - $order = \WC_Order_Factory::get_order( $actual['data']['checkout']['order']['databaseId'] ); - - // Get Available payment gateways. - $available_gateways = WC()->payment_gateways->get_available_payment_gateways(); - - $expected = array( - 'data' => array( - 'checkout' => array( - 'clientMutationId' => 'someId', - 'order' => array_merge( - $this->order->print_query( $order->get_id() ), - array( - 'metaData' => array( - array( - 'key' => 'is_vat_exempt', - 'value' => 'no', - ), - ), - 'couponLines' => array( - 'nodes' => array_reverse( - array_map( - function( $item ) { - return array( - 'databaseId' => $item->get_id(), - 'orderId' => $item->get_order_id(), - 'code' => $item->get_code(), - 'discount' => ! empty( $item->get_discount() ) ? $item->get_discount() : null, - 'discountTax' => ! empty( $item->get_discount_tax() ) ? $item->get_discount_tax() : null, - 'coupon' => null, - ); - }, - $order->get_items( 'coupon' ) - ) - ), - ), - 'feeLines' => array( - 'nodes' => array_reverse( - array_map( - function( $item ) { - return array( - 'databaseId' => $item->get_id(), - 'orderId' => $item->get_order_id(), - 'amount' => $item->get_amount(), - 'name' => $item->get_name(), - 'taxStatus' => strtoupper( $item->get_tax_status() ), - 'total' => $item->get_total(), - 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, - 'taxClass' => ! empty( $item->get_tax_class() ) - ? WPEnumType::get_safe_name( $item->get_tax_class() ) - : 'STANDARD', - ); - }, - $order->get_items( 'fee' ) - ) - ), - ), - 'shippingLines' => array( 'nodes' => array() ), - 'taxLines' => array( - 'nodes' => array_reverse( - array_map( - function( $item ) { - return array( - 'rateCode' => $item->get_rate_code(), - 'label' => $item->get_label(), - 'taxTotal' => $item->get_tax_total(), - 'shippingTaxTotal' => $item->get_shipping_tax_total(), - 'isCompound' => $item->is_compound(), - 'taxRate' => array( 'databaseId' => $item->get_rate_id() ), - ); - }, - $order->get_items( 'tax' ) - ) - ), - ), - 'lineItems' => array( - 'nodes' => array_values( - array_map( - function( $item ) { - return array( - 'productId' => $item->get_product_id(), - 'variationId' => ! empty( $item->get_variation_id() ) - ? $item->get_variation_id() - : null, - 'quantity' => $item->get_quantity(), - 'taxClass' => ! empty( $item->get_tax_class() ) - ? strtoupper( $item->get_tax_class() ) - : 'STANDARD', - 'subtotal' => ! empty( $item->get_subtotal() ) ? $item->get_subtotal() : null, - 'subtotalTax' => ! empty( $item->get_subtotal_tax() ) ? $item->get_subtotal_tax() : null, - 'total' => ! empty( $item->get_total() ) ? $item->get_total() : null, - 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, - 'taxStatus' => strtoupper( $item->get_tax_status() ), - 'product' => array( 'id' => $this->product->to_relay_id( $item->get_product_id() ) ), - 'variation' => ! empty( $item->get_variation_id() ) - ? array( - 'id' => $this->variation->to_relay_id( $item->get_variation_id() ) - ) - : null, - ); - }, - $order->get_items() - ) - ), - ), - ) - ), - 'customer' => null, - 'result' => 'success', - 'redirect' => $available_gateways['bacs']->process_payment( $order->get_id() )['redirect'], - ), - ) - ); - - $this->assertEquals( $expected, $actual ); - } - - /** - * Returns a new Stripe Customer object - * - * @param string $email Customer email - * - * @return array - */ - private function create_stripe_customer( $email ) { - $customer = \Stripe\Customer::create( array( 'email' => $email ) ); - - // use --debug flag to view. - codecept_debug( $customer ); - return $customer; - } - - /** - * Creates a new Stripe Source object, attaches it to the provided customer, - * and returns the Source object - * - * @param array $customer Customer object - * - * @return array - */ - private function create_stripe_source( $customer ) { - $source = \Stripe\Customer::createSource( - $customer['id'], - array( 'source' => 'tok_visa') - ); - - // use --debug flag to view. - codecept_debug( $source ); - - return $source; - } - - /** - * Creates a new Payment Intent object, assigns an amount and customer, - * and returns the Payment Intent object - * - * This payment intent is meant to be processed by WooCommerce upon validation - * so do not `confirm=true` must not be passed as a parameter. - * - * @param array $customer Customer object - * - * @return array - */ - private function create_stripe_payment_intent( $amount, $customer ) { - $payment_intent = \Stripe\PaymentIntent::create( - array( - 'amount' => $amount, - 'currency' => 'gbp', - 'payment_method_types' => ['card'], - 'customer' => $customer['id'], - 'payment_method' => $customer['invoice_settings']['default_payment_method'], - ) - ); - - // use --debug flag to view. - codecept_debug( $payment_intent ); - - return $payment_intent; - } - - public function testCheckoutMutationWithStripe() { - update_option( 'woocommerce_enable_guest_checkout', 'yes' ); - // Add items to the cart. - $product_ids = array( - $this->product->create_simple(), - $this->product->create_simple(), - ); - WC()->cart->add_to_cart( $product_ids[0], 3 ); - WC()->cart->add_to_cart( $product_ids[1], 6 ); - - $amount = (int) floatval( WC()->cart->get_cart_contents_total() + WC()->cart->get_cart_contents_tax() ) * 100; + $actual = $this->checkout( $input ); + + // use --debug flag to view. + codecept_debug( $actual ); + + $this->assertArrayHasKey( 'data', $actual ); + $this->assertArrayHasKey( 'checkout', $actual['data'] ); + $this->assertArrayHasKey( 'order', $actual['data']['checkout'] ); + $this->assertArrayHasKey( 'id', $actual['data']['checkout']['order'] ); + $this->assertEquals( 'COMPLETED', $actual['data']['checkout']['order']['status'] ); + $order = \WC_Order_Factory::get_order( $actual['data']['checkout']['order']['databaseId'] ); + + // Get Available payment gateways. + $available_gateways = WC()->payment_gateways->get_available_payment_gateways(); + + $expected = array( + 'data' => array( + 'checkout' => array( + 'clientMutationId' => 'someId', + 'order' => array_merge( + $this->order->print_query( $order->get_id() ), + array( + 'metaData' => array( + array( + 'key' => 'is_vat_exempt', + 'value' => 'no', + ), + ), + 'couponLines' => array( + 'nodes' => array_reverse( + array_map( + function( $item ) { + return array( + 'databaseId' => $item->get_id(), + 'orderId' => $item->get_order_id(), + 'code' => $item->get_code(), + 'discount' => ! empty( $item->get_discount() ) ? $item->get_discount() : null, + 'discountTax' => ! empty( $item->get_discount_tax() ) ? $item->get_discount_tax() : null, + 'coupon' => null, + ); + }, + $order->get_items( 'coupon' ) + ) + ), + ), + 'feeLines' => array( + 'nodes' => array_reverse( + array_map( + function( $item ) { + return array( + 'databaseId' => $item->get_id(), + 'orderId' => $item->get_order_id(), + 'amount' => $item->get_amount(), + 'name' => $item->get_name(), + 'taxStatus' => strtoupper( $item->get_tax_status() ), + 'total' => $item->get_total(), + 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, + 'taxClass' => ! empty( $item->get_tax_class() ) + ? WPEnumType::get_safe_name( $item->get_tax_class() ) + : 'STANDARD', + ); + }, + $order->get_items( 'fee' ) + ) + ), + ), + 'shippingLines' => array( 'nodes' => array() ), + 'taxLines' => array( + 'nodes' => array_reverse( + array_map( + function( $item ) { + return array( + 'rateCode' => $item->get_rate_code(), + 'label' => $item->get_label(), + 'taxTotal' => $item->get_tax_total(), + 'shippingTaxTotal' => $item->get_shipping_tax_total(), + 'isCompound' => $item->is_compound(), + 'taxRate' => array( 'databaseId' => $item->get_rate_id() ), + ); + }, + $order->get_items( 'tax' ) + ) + ), + ), + 'lineItems' => array( + 'nodes' => array_values( + array_map( + function( $item ) { + return array( + 'productId' => $item->get_product_id(), + 'variationId' => ! empty( $item->get_variation_id() ) + ? $item->get_variation_id() + : null, + 'quantity' => $item->get_quantity(), + 'taxClass' => ! empty( $item->get_tax_class() ) + ? strtoupper( $item->get_tax_class() ) + : 'STANDARD', + 'subtotal' => ! empty( $item->get_subtotal() ) ? $item->get_subtotal() : null, + 'subtotalTax' => ! empty( $item->get_subtotal_tax() ) ? $item->get_subtotal_tax() : null, + 'total' => ! empty( $item->get_total() ) ? $item->get_total() : null, + 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, + 'taxStatus' => strtoupper( $item->get_tax_status() ), + 'product' => array( 'id' => $this->product->to_relay_id( $item->get_product_id() ) ), + 'variation' => ! empty( $item->get_variation_id() ) + ? array( + 'id' => $this->variation->to_relay_id( $item->get_variation_id() ), + ) + : null, + ); + }, + $order->get_items() + ) + ), + ), + ) + ), + 'customer' => null, + 'result' => 'success', + 'redirect' => $available_gateways['bacs']->process_payment( $order->get_id() )['redirect'], + ), + ), + ); + + $this->assertEquals( $expected, $actual ); + } + + /** + * Returns a new Stripe Customer object + * + * @param string $email Customer email + * + * @return array + */ + private function create_stripe_customer( $email ) { + $customer = \Stripe\Customer::create( array( 'email' => $email ) ); + + // use --debug flag to view. + codecept_debug( $customer ); + return $customer; + } + + /** + * Creates a new Stripe Source object, attaches it to the provided customer, + * and returns the Source object + * + * @param array $customer Customer object + * + * @return array + */ + private function create_stripe_source( $customer ) { + $source = \Stripe\Customer::createSource( + $customer['id'], + array( 'source' => 'tok_visa' ) + ); + + // use --debug flag to view. + codecept_debug( $source ); + + return $source; + } + + /** + * Creates a new Payment Intent object, assigns an amount and customer, + * and returns the Payment Intent object + * + * This payment intent is meant to be processed by WooCommerce upon validation + * so do not `confirm=true` must not be passed as a parameter. + * + * @param array $customer Customer object + * + * @return array + */ + private function create_stripe_payment_intent( $amount, $customer ) { + $payment_intent = \Stripe\PaymentIntent::create( + array( + 'amount' => $amount, + 'currency' => 'gbp', + 'payment_method_types' => array( 'card' ), + 'customer' => $customer['id'], + 'payment_method' => $customer['invoice_settings']['default_payment_method'], + ) + ); + + // use --debug flag to view. + codecept_debug( $payment_intent ); + + return $payment_intent; + } + + public function testCheckoutMutationWithStripe() { + update_option( 'woocommerce_enable_guest_checkout', 'yes' ); + // Add items to the cart. + $product_ids = array( + $this->product->create_simple(), + $this->product->create_simple(), + ); + WC()->cart->add_to_cart( $product_ids[0], 3 ); + WC()->cart->add_to_cart( $product_ids[1], 6 ); + + $amount = (int) floatval( WC()->cart->get_cart_contents_total() + WC()->cart->get_cart_contents_tax() ) * 100; try { $stripe_customer = $this->create_stripe_customer( 'superfreak500@gmail.com' ); - $stripe_source = $this->create_stripe_source( $stripe_customer ); - $payment_intent = $this->create_stripe_payment_intent( $amount, $stripe_customer ); + $stripe_source = $this->create_stripe_source( $stripe_customer ); + $payment_intent = $this->create_stripe_payment_intent( $amount, $stripe_customer ); } catch ( \Stripe\Exception\AuthenticationException $e ) { $this->markTestSkipped( $e->getMessage() ); } - $input = array( - 'clientMutationId' => 'someId', - 'paymentMethod' => 'stripe', - 'shippingMethod' => 'flat rate', - 'billing' => array( - 'firstName' => 'May', - 'lastName' => 'Parker', - 'address1' => '20 Ingram St', - 'city' => 'New York City', - 'state' => 'NY', - 'postcode' => '12345', - 'country' => 'US', - 'email' => 'superfreak500@gmail.com', - 'phone' => '555-555-1234', - ), - 'metaData' => array( - array( - 'key' => '_stripe_source_id', - 'value' => $stripe_source['id'], - ), - array( - 'key' => '_stripe_customer_id', - 'value' => $stripe_customer['id'], - ), - array( - 'key' => '_stripe_intent_id', - 'value' => $payment_intent['id'], - ), - ) - ); - - // Remove "metaData" value field and "redirect" link from the mutation output. - $modified_mutation = ' + $input = array( + 'clientMutationId' => 'someId', + 'paymentMethod' => 'stripe', + 'shippingMethod' => 'flat rate', + 'billing' => array( + 'firstName' => 'May', + 'lastName' => 'Parker', + 'address1' => '20 Ingram St', + 'city' => 'New York City', + 'state' => 'NY', + 'postcode' => '12345', + 'country' => 'US', + 'email' => 'superfreak500@gmail.com', + 'phone' => '555-555-1234', + ), + 'metaData' => array( + array( + 'key' => '_stripe_source_id', + 'value' => $stripe_source['id'], + ), + array( + 'key' => '_stripe_customer_id', + 'value' => $stripe_customer['id'], + ), + array( + 'key' => '_stripe_intent_id', + 'value' => $payment_intent['id'], + ), + ), + ); + + // Remove "metaData" value field and "redirect" link from the mutation output. + $modified_mutation = ' mutation checkout( $input: CheckoutInput! ) { checkout( input: $input ) { clientMutationId @@ -1245,78 +1235,78 @@ public function testCheckoutMutationWithStripe() { } '; - /** + /** * Assertion One * * Test mutation and input. */ - $actual = $this->checkout( $input, $modified_mutation ); - - // use --debug flag to view. - codecept_debug( $actual ); - - $this->assertArrayHasKey('data', $actual ); - $this->assertArrayHasKey('checkout', $actual['data'] ); - $this->assertArrayHasKey('order', $actual['data']['checkout'] ); - $this->assertArrayHasKey('databaseId', $actual['data']['checkout']['order'] ); - $order = \WC_Order_Factory::get_order( $actual['data']['checkout']['order']['databaseId'] ); - - // Get Available payment gateways. - $available_gateways = WC()->payment_gateways->get_available_payment_gateways(); - - $expected = array( - 'data' => array( - 'checkout' => array( - 'clientMutationId' => 'someId', - 'order' => array( - 'databaseId' => $order->get_id(), - 'metaData' => array( - array( 'key' => 'is_vat_exempt', ), - array( 'key' => '_stripe_source_id' ), - array( 'key' => '_stripe_customer_id' ), - array( 'key' => '_stripe_intent_id' ), - array( 'key' => '_stripe_charge_captured' ), - array( 'key' => '_stripe_fee' ), - array( 'key' => '_stripe_net' ), - array( 'key' => '_stripe_currency' ), - ), - 'lineItems' => array( - 'nodes' => array_values( - array_map( - function( $item ) { - return array( - 'productId' => $item->get_product_id(), - 'variationId' => ! empty( $item->get_variation_id() ) - ? $item->get_variation_id() - : null, - 'quantity' => $item->get_quantity(), - 'taxClass' => ! empty( $item->get_tax_class() ) - ? strtoupper( $item->get_tax_class() ) - : 'STANDARD', - 'subtotal' => ! empty( $item->get_subtotal() ) ? $item->get_subtotal() : null, - 'subtotalTax' => ! empty( $item->get_subtotal_tax() ) ? $item->get_subtotal_tax() : null, - 'total' => ! empty( $item->get_total() ) ? $item->get_total() : null, - 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, - 'taxStatus' => strtoupper( $item->get_tax_status() ), - 'product' => array( 'id' => $this->product->to_relay_id( $item->get_product_id() ) ), - 'variation' => ! empty( $item->get_variation_id() ) - ? array( - 'id' => $this->variation->to_relay_id( $item->get_variation_id() ) - ) - : null, - ); - }, - $order->get_items() - ) - ), - ), - ), - 'result' => 'success', - ), - ) - ); - - $this->assertEquals( $expected, $actual ); + $actual = $this->checkout( $input, $modified_mutation ); + + // use --debug flag to view. + codecept_debug( $actual ); + + $this->assertArrayHasKey( 'data', $actual ); + $this->assertArrayHasKey( 'checkout', $actual['data'] ); + $this->assertArrayHasKey( 'order', $actual['data']['checkout'] ); + $this->assertArrayHasKey( 'databaseId', $actual['data']['checkout']['order'] ); + $order = \WC_Order_Factory::get_order( $actual['data']['checkout']['order']['databaseId'] ); + + // Get Available payment gateways. + $available_gateways = WC()->payment_gateways->get_available_payment_gateways(); + + $expected = array( + 'data' => array( + 'checkout' => array( + 'clientMutationId' => 'someId', + 'order' => array( + 'databaseId' => $order->get_id(), + 'metaData' => array( + array( 'key' => 'is_vat_exempt' ), + array( 'key' => '_stripe_source_id' ), + array( 'key' => '_stripe_customer_id' ), + array( 'key' => '_stripe_intent_id' ), + array( 'key' => '_stripe_charge_captured' ), + array( 'key' => '_stripe_fee' ), + array( 'key' => '_stripe_net' ), + array( 'key' => '_stripe_currency' ), + ), + 'lineItems' => array( + 'nodes' => array_values( + array_map( + function( $item ) { + return array( + 'productId' => $item->get_product_id(), + 'variationId' => ! empty( $item->get_variation_id() ) + ? $item->get_variation_id() + : null, + 'quantity' => $item->get_quantity(), + 'taxClass' => ! empty( $item->get_tax_class() ) + ? strtoupper( $item->get_tax_class() ) + : 'STANDARD', + 'subtotal' => ! empty( $item->get_subtotal() ) ? $item->get_subtotal() : null, + 'subtotalTax' => ! empty( $item->get_subtotal_tax() ) ? $item->get_subtotal_tax() : null, + 'total' => ! empty( $item->get_total() ) ? $item->get_total() : null, + 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, + 'taxStatus' => strtoupper( $item->get_tax_status() ), + 'product' => array( 'id' => $this->product->to_relay_id( $item->get_product_id() ) ), + 'variation' => ! empty( $item->get_variation_id() ) + ? array( + 'id' => $this->variation->to_relay_id( $item->get_variation_id() ), + ) + : null, + ); + }, + $order->get_items() + ) + ), + ), + ), + 'result' => 'success', + ), + ), + ); + + $this->assertEquals( $expected, $actual ); } public function testCheckoutMutationCartItemValidation() { @@ -1332,35 +1322,35 @@ public function testCheckoutMutationCartItemValidation() { $key = WC()->cart->add_to_cart( $product_id, 3 ); WC()->cart->set_quantity( $key, 5 ); - /** + /** * Assertion One * * Ensure that checkout failed when stock is too low. */ - $input = array( - 'clientMutationId' => 'someId', - 'paymentMethod' => 'bacs', - 'shippingMethod' => array( 'flat rate' ), + $input = array( + 'clientMutationId' => 'someId', + 'paymentMethod' => 'bacs', + 'shippingMethod' => array( 'flat rate' ), 'billing' => array( - 'firstName' => 'May', - 'lastName' => 'Parker', - 'company' => 'Harris Teeter', - 'address1' => '20 Ingram St', - 'city' => 'New York City', - 'state' => 'NY', - 'postcode' => '12345', - 'country' => 'US', - 'email' => 'superfreak500@gmail.com', - 'phone' => '555-555-1234', - ), - 'account' => array( - 'username' => 'test_user_1', - 'password' => 'test_pass' - ) + 'firstName' => 'May', + 'lastName' => 'Parker', + 'company' => 'Harris Teeter', + 'address1' => '20 Ingram St', + 'city' => 'New York City', + 'state' => 'NY', + 'postcode' => '12345', + 'country' => 'US', + 'email' => 'superfreak500@gmail.com', + 'phone' => '555-555-1234', + ), + 'account' => array( + 'username' => 'test_user_1', + 'password' => 'test_pass', + ), ); - $failed = $this->checkout( $input ); + $failed = $this->checkout( $input ); - // use --debug flag to view. + // use --debug flag to view. codecept_debug( $failed ); $this->assertArrayHasKey( 'errors', $failed ); diff --git a/tests/wpunit/ConnectionPaginationTest.php b/tests/wpunit/ConnectionPaginationTest.php index 4ae62ff0b..bcff63a5f 100644 --- a/tests/wpunit/ConnectionPaginationTest.php +++ b/tests/wpunit/ConnectionPaginationTest.php @@ -4,28 +4,30 @@ class ConnectionPaginationTest extends \Tests\WPGraphQL\WooCommerce\TestCase\Woo public function toCursor( $id ) { if ( $id instanceof \WC_Product_Download ) { + // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode return base64_encode( 'arrayconnection:' . $id['id'] ); } + // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode return base64_encode( 'arrayconnection:' . $id ); } - // tests - public function testCouponsPagination() { + // tests + public function testCouponsPagination() { $coupons = array( - $this->factory->coupon->create(), $this->factory->coupon->create(), $this->factory->coupon->create(), - $this->factory->coupon->create(), $this->factory->coupon->create(), - ); + $this->factory->coupon->create(), + $this->factory->coupon->create(), + ); - usort( - $coupons, - function( $key_a, $key_b ) { + usort( + $coupons, + function( $key_a, $key_b ) { return $key_a < $key_b; } - ); + ); $query = ' query ($first: Int, $last: Int, $after: String, $before: String) { @@ -43,14 +45,14 @@ function( $key_a, $key_b ) { } '; - $this->loginAsShopManager(); + $this->loginAsShopManager(); - /** + /** * Assertion One * * Test "first" parameter. */ - $variables = array( 'first' => 2 ); + $variables = array( 'first' => 2 ); $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedField( 'coupons.pageInfo.hasPreviousPage', false ), @@ -61,14 +63,14 @@ function( $key_a, $key_b ) { $this->expectedField( 'coupons.nodes.1.databaseId', $coupons[1] ), ); - $this->assertQuerySuccessful( $response, $expected ); + $this->assertQuerySuccessful( $response, $expected ); - /** + /** * Assertion Two * * Test "after" parameter. */ - $variables = array( + $variables = array( 'first' => 3, 'after' => $this->toCursor( $coupons[1] ), ); @@ -83,7 +85,7 @@ function( $key_a, $key_b ) { $this->expectedField( 'coupons.nodes.2.databaseId', $coupons[4] ), ); - $this->assertQuerySuccessful( $response, $expected ); + $this->assertQuerySuccessful( $response, $expected ); /** * Assertion Three @@ -91,8 +93,8 @@ function( $key_a, $key_b ) { * Test "last" parameter. */ \WPGraphQL::set_is_graphql_request( true ); - $variables = array( - 'last' => 2, + $variables = array( + 'last' => 2, ); $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( @@ -104,14 +106,14 @@ function( $key_a, $key_b ) { $this->expectedField( 'coupons.nodes.1.databaseId', $coupons[4] ), ); - //$this->assertQuerySuccessful( $response, $expected ); + // $this->assertQuerySuccessful( $response, $expected ); /** * Assertion Four * * Test "before" parameter. */ - $variables = array( + $variables = array( 'last' => 2, 'before' => $this->toCursor( $coupons[3] ), ); @@ -125,24 +127,24 @@ function( $key_a, $key_b ) { $this->expectedField( 'coupons.nodes.1.databaseId', $coupons[2] ), ); - //$this->assertQuerySuccessful( $response, $expected ); - } + // $this->assertQuerySuccessful( $response, $expected ); + } - public function testProductsPagination() { - $products = array( - $this->factory->product->createSimple(), - $this->factory->product->createSimple(), - $this->factory->product->createSimple(), - $this->factory->product->createSimple(), - $this->factory->product->createSimple(), - ); + public function testProductsPagination() { + $products = array( + $this->factory->product->createSimple(), + $this->factory->product->createSimple(), + $this->factory->product->createSimple(), + $this->factory->product->createSimple(), + $this->factory->product->createSimple(), + ); - usort( - $products, - function( $key_a, $key_b ) { + usort( + $products, + function( $key_a, $key_b ) { return $key_a < $key_b; } - ); + ); $query = ' query ($first: Int, $last: Int, $after: String, $before: String) { @@ -160,12 +162,12 @@ function( $key_a, $key_b ) { } '; - /** + /** * Assertion One * * Test "first" parameter. */ - $variables = array( 'first' => 2 ); + $variables = array( 'first' => 2 ); $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedField( 'products.pageInfo.hasPreviousPage', false ), @@ -176,14 +178,14 @@ function( $key_a, $key_b ) { $this->expectedField( 'products.nodes.1.databaseId', $products[1] ), ); - $this->assertQuerySuccessful( $response, $expected ); + $this->assertQuerySuccessful( $response, $expected ); - /** + /** * Assertion Two * * Test "after" parameter. */ - $variables = array( + $variables = array( 'first' => 3, 'after' => $this->toCursor( $products[1] ), ); @@ -198,14 +200,14 @@ function( $key_a, $key_b ) { $this->expectedField( 'products.nodes.2.databaseId', $products[4] ), ); - $this->assertQuerySuccessful( $response, $expected ); + $this->assertQuerySuccessful( $response, $expected ); /** * Assertion Three * * Test "last" parameter. */ - $variables = array( 'last' => 2 ); + $variables = array( 'last' => 2 ); $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedField( 'products.pageInfo.hasPreviousPage', true ), @@ -216,14 +218,14 @@ function( $key_a, $key_b ) { $this->expectedField( 'products.nodes.1.databaseId', $products[4] ), ); - //$this->assertQuerySuccessful( $response, $expected ); + // $this->assertQuerySuccessful( $response, $expected ); /** * Assertion Four * * Test "before" parameter. */ - $variables = array( + $variables = array( 'last' => 2, 'before' => $this->toCursor( $products[3] ), ); @@ -237,10 +239,10 @@ function( $key_a, $key_b ) { $this->expectedField( 'products.nodes.1.databaseId', $products[2] ), ); - //$this->assertQuerySuccessful( $response, $expected ); - } + // $this->assertQuerySuccessful( $response, $expected ); + } - public function testOrdersPagination() { + public function testOrdersPagination() { $this->loginAsShopManager(); $query = new \WC_Order_Query(); @@ -251,20 +253,20 @@ public function testOrdersPagination() { unset( $old_orders ); unset( $query ); - $orders = array( - $this->factory->order->createNew(), + $orders = array( + $this->factory->order->createNew(), $this->factory->order->createNew(), $this->factory->order->createNew(), - $this->factory->order->createNew(), $this->factory->order->createNew(), - ); + $this->factory->order->createNew(), + ); - usort( - $orders, - function( $key_a, $key_b ) { + usort( + $orders, + function( $key_a, $key_b ) { return $key_a < $key_b; } - ); + ); $query = ' query ($first: Int, $last: Int, $after: String, $before: String) { @@ -282,12 +284,12 @@ function( $key_a, $key_b ) { } '; - /** + /** * Assertion One * * Test "first" parameter. */ - $variables = array( 'first' => 2 ); + $variables = array( 'first' => 2 ); $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedField( 'orders.pageInfo.hasPreviousPage', false ), @@ -298,14 +300,14 @@ function( $key_a, $key_b ) { $this->expectedField( 'orders.nodes.1.databaseId', $orders[1] ), ); - $this->assertQuerySuccessful( $response, $expected ); + $this->assertQuerySuccessful( $response, $expected ); - /** + /** * Assertion Two * * Test "after" parameter. */ - $variables = array( + $variables = array( 'first' => 3, 'after' => $this->toCursor( $orders[1] ), ); @@ -320,14 +322,14 @@ function( $key_a, $key_b ) { $this->expectedField( 'orders.nodes.2.databaseId', $orders[4] ), ); - $this->assertQuerySuccessful( $response, $expected ); + $this->assertQuerySuccessful( $response, $expected ); /** * Assertion Three * * Test "last" parameter. */ - $variables = array( 'last' => 2 ); + $variables = array( 'last' => 2 ); $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedField( 'orders.pageInfo.hasPreviousPage', true ), @@ -338,14 +340,14 @@ function( $key_a, $key_b ) { $this->expectedField( 'orders.nodes.1.databaseId', $orders[4] ), ); - //$this->assertQuerySuccessful( $response, $expected ); + // $this->assertQuerySuccessful( $response, $expected ); - /** + /** * Assertion Four * * Test "before" parameter. */ - $variables = array( + $variables = array( 'last' => 2, 'before' => $this->toCursor( $orders[3] ), ); @@ -359,25 +361,25 @@ function( $key_a, $key_b ) { $this->expectedField( 'orders.nodes.1.databaseId', $orders[2] ), ); - //$this->assertQuerySuccessful( $response, $expected ); - } + // $this->assertQuerySuccessful( $response, $expected ); + } - public function testRefundsPagination() { - $order = $this->factory->order->createNew(); - $refunds = array( - $this->factory->refund->createNew( $order, array( 'amount' => 0.5 ) ), + public function testRefundsPagination() { + $order = $this->factory->order->createNew(); + $refunds = array( + $this->factory->refund->createNew( $order, array( 'amount' => 0.5 ) ), + $this->factory->refund->createNew( $order, array( 'amount' => 0.5 ) ), $this->factory->refund->createNew( $order, array( 'amount' => 0.5 ) ), $this->factory->refund->createNew( $order, array( 'amount' => 0.5 ) ), - $this->factory->refund->createNew( $order, array( 'amount' => 0.5 ) ), $this->factory->refund->createNew( $order, array( 'amount' => 0.5 ) ), - ); + ); - usort( - $refunds, - function( $key_a, $key_b ) { + usort( + $refunds, + function( $key_a, $key_b ) { return $key_a < $key_b; } - ); + ); $query = ' query ($first: Int, $last: Int, $after: String, $before: String) { @@ -395,14 +397,14 @@ function( $key_a, $key_b ) { } '; - $this->loginAsShopManager(); + $this->loginAsShopManager(); - /** + /** * Assertion One * * Test "first" parameter. */ - $variables = array( 'first' => 2 ); + $variables = array( 'first' => 2 ); $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedField( 'refunds.pageInfo.hasPreviousPage', false ), @@ -413,14 +415,14 @@ function( $key_a, $key_b ) { $this->expectedField( 'refunds.nodes.1.databaseId', $refunds[1] ), ); - $this->assertQuerySuccessful( $response, $expected ); + $this->assertQuerySuccessful( $response, $expected ); - /** + /** * Assertion Two * * Test "after" parameter. */ - $variables = array( + $variables = array( 'first' => 3, 'after' => $this->toCursor( $refunds[1] ), ); @@ -435,14 +437,14 @@ function( $key_a, $key_b ) { $this->expectedField( 'refunds.nodes.2.databaseId', $refunds[4] ), ); - $this->assertQuerySuccessful( $response, $expected ); + $this->assertQuerySuccessful( $response, $expected ); /** * Assertion Three * * Test "last" parameter. */ - $variables = array( 'last' => 2 ); + $variables = array( 'last' => 2 ); $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedField( 'refunds.pageInfo.hasPreviousPage', true ), @@ -453,14 +455,14 @@ function( $key_a, $key_b ) { $this->expectedField( 'refunds.nodes.1.databaseId', $refunds[4] ), ); - //$this->assertQuerySuccessful( $response, $expected ); + // $this->assertQuerySuccessful( $response, $expected ); - /** + /** * Assertion Four * * Test "before" parameter. */ - $variables = array( + $variables = array( 'last' => 2, 'before' => $this->toCursor( $refunds[3] ), ); @@ -474,17 +476,17 @@ function( $key_a, $key_b ) { $this->expectedField( 'refunds.nodes.1.databaseId', $refunds[2] ), ); - //$this->assertQuerySuccessful( $response, $expected ); - } + // $this->assertQuerySuccessful( $response, $expected ); + } - public function testCustomersPagination() { - $some_customers = array( - $this->factory->customer->create(), - $this->factory->customer->create(), - $this->factory->customer->create(), - $this->factory->customer->create(), - $this->factory->customer->create(), - ); + public function testCustomersPagination() { + $some_customers = array( + $this->factory->customer->create(), + $this->factory->customer->create(), + $this->factory->customer->create(), + $this->factory->customer->create(), + $this->factory->customer->create(), + ); $customers = get_users( array( @@ -497,7 +499,7 @@ public function testCustomersPagination() { $customers = array_map( 'absint', $customers ); - $query = ' + $query = ' query ($first: Int, $last: Int, $after: String, $before: String) { customers(first: $first, last: $last, after: $after, before: $before) { nodes { @@ -514,14 +516,14 @@ public function testCustomersPagination() { } '; - $this->loginAsShopManager(); + $this->loginAsShopManager(); - /** + /** * Assertion One * * Test "first" parameter. */ - $variables = array( 'first' => 2 ); + $variables = array( 'first' => 2 ); $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedField( 'customers.pageInfo.hasPreviousPage', false ), @@ -532,14 +534,14 @@ public function testCustomersPagination() { $this->expectedField( 'customers.pageInfo.endCursor', $this->toCursor( $customers[1] ) ), ); - $this->assertQuerySuccessful( $response, $expected ); + $this->assertQuerySuccessful( $response, $expected ); - /** + /** * Assertion Two * * Test "after" parameter. */ - $variables = array( + $variables = array( 'first' => 3, 'after' => $this->toCursor( $customers[1] ), ); @@ -553,14 +555,14 @@ public function testCustomersPagination() { $this->expectedField( 'customers.nodes.2.databaseId', $customers[4] ), ); - $this->assertQuerySuccessful( $response, $expected ); + $this->assertQuerySuccessful( $response, $expected ); /** * Assertion Three * * Test "last" parameter. */ - $variables = array( 'last' => 2 ); + $variables = array( 'last' => 2 ); $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedField( 'customers.pageInfo.hasPreviousPage', true ), @@ -571,14 +573,14 @@ public function testCustomersPagination() { $this->expectedField( 'customers.nodes.1.databaseId', $customers[4] ), ); - //$this->assertQuerySuccessful( $response, $expected ); + // $this->assertQuerySuccessful( $response, $expected ); - /** + /** * Assertion Four * * Test "before" parameter. */ - $variables = array( + $variables = array( 'last' => 2, 'before' => $this->toCursor( $customers[3] ), ); @@ -592,11 +594,11 @@ public function testCustomersPagination() { $this->expectedField( 'customers.nodes.1.databaseId', $customers[2] ), ); - //$this->assertQuerySuccessful( $response, $expected ); - } + // $this->assertQuerySuccessful( $response, $expected ); + } - public function testDownloadableItemsPagination() { - $customer_id = $this->factory->customer->create(); + public function testDownloadableItemsPagination() { + $customer_id = $this->factory->customer->create(); $downloads = array( $this->factory->product->createDownload(), @@ -606,42 +608,42 @@ public function testDownloadableItemsPagination() { $this->factory->product->createDownload(), ); - $products = array_map( + $products = array_map( function( $download ) { return $this->factory->product->createSimple( array( 'downloadable' => true, - 'downloads' => array( $download ) + 'downloads' => array( $download ), ) ); }, $downloads ); - $order_id = $this->factory->order->createNew( - array( - 'status' => 'completed', - 'customer_id' => $customer_id, - ), - array( - 'line_items' => array_map( - function( $product_id ) { - return array( - 'product' => $product_id, - 'qty' => 1, - ); - }, - $products - ), - ) - ); + $order_id = $this->factory->order->createNew( + array( + 'status' => 'completed', + 'customer_id' => $customer_id, + ), + array( + 'line_items' => array_map( + function( $product_id ) { + return array( + 'product' => $product_id, + 'qty' => 1, + ); + }, + $products + ), + ) + ); $order = \wc_get_order( $order_id ); - // Force download permission updated. - wc_downloadable_product_permissions( $order_id, true ); + // Force download permission updated. + wc_downloadable_product_permissions( $order_id, true ); - $query = ' + $query = ' query ($first: Int, $last: Int, $after: String, $before: String) { customer { orders { @@ -666,14 +668,14 @@ function( $product_id ) { } '; - $this->loginAs( $customer_id ); + $this->loginAs( $customer_id ); - /** + /** * Assertion One * * Test "first" parameter. */ - $variables = array( 'first' => 2 ); + $variables = array( 'first' => 2 ); $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedField( 'customer.orders.nodes.0.downloadableItems.pageInfo.hasPreviousPage', false ), @@ -684,14 +686,14 @@ function( $product_id ) { $this->expectedField( 'customer.orders.nodes.0.downloadableItems.nodes.1.product.databaseId', $products[1] ), ); - $this->assertQuerySuccessful( $response, $expected ); + $this->assertQuerySuccessful( $response, $expected ); - /** + /** * Assertion Two * * Test "after" parameter. */ - $variables = array( + $variables = array( 'first' => 3, 'after' => $this->toCursor( $downloads[1] ), ); @@ -706,14 +708,14 @@ function( $product_id ) { $this->expectedField( 'customer.orders.nodes.0.downloadableItems.nodes.2.product.databaseId', $products[4] ), ); - $this->assertQuerySuccessful( $response, $expected ); + $this->assertQuerySuccessful( $response, $expected ); /** * Assertion Three * * Test "last" parameter. */ - $variables = array( 'last' => 2 ); + $variables = array( 'last' => 2 ); $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedField( 'customer.orders.nodes.0.downloadableItems.pageInfo.hasPreviousPage', true ), @@ -724,15 +726,15 @@ function( $product_id ) { $this->expectedField( 'customer.orders.nodes.0.downloadableItems.nodes.1.product.databaseId', $products[4] ), ); - $this->assertQuerySuccessful( $response, $expected ); + $this->assertQuerySuccessful( $response, $expected ); - /** + /** * Assertion Two * * Test "before" parameter. */ - $variables = array( - 'last' => 3, + $variables = array( + 'last' => 3, 'before' => $this->toCursor( $downloads[3] ), ); $response = $this->graphql( compact( 'query', 'variables' ) ); @@ -746,6 +748,6 @@ function( $product_id ) { $this->expectedField( 'customer.orders.nodes.0.downloadableItems.nodes.2.product.databaseId', $products[2] ), ); - $this->assertQuerySuccessful( $response, $expected ); - } + $this->assertQuerySuccessful( $response, $expected ); + } } diff --git a/tests/wpunit/CoreInterfaceQueriesTest.php b/tests/wpunit/CoreInterfaceQueriesTest.php index 6e6f1c280..826432dd4 100644 --- a/tests/wpunit/CoreInterfaceQueriesTest.php +++ b/tests/wpunit/CoreInterfaceQueriesTest.php @@ -1,21 +1,14 @@ products = $this->getModule('\Helper\Wpunit')->product(); - $this->variations = $this->getModule('\Helper\Wpunit')->product_variation(); - $this->orders = $this->getModule('\Helper\Wpunit')->order(); - } - - public function tearDown(): void { - // your tear down methods here - - // then - parent::tearDown(); + $this->products = $this->getModule( '\Helper\Wpunit' )->product(); + $this->variations = $this->getModule( '\Helper\Wpunit' )->product_variation(); + $this->orders = $this->getModule( '\Helper\Wpunit' )->order(); } public function graphql() { @@ -27,20 +20,20 @@ public function graphql() { return $results; } - // tests - public function testProductAsNodeWithComments() { + // tests + public function testProductAsNodeWithComments() { // Create product and review to be queried. $product_id = $this->products->create_simple(); $comment_id = $this->factory()->comment->create( - array( - 'comment_author' => 'Rude customer', - 'comment_author_email' => 'rude-guy@example.com', - 'comment_post_ID' => $product_id, - 'comment_content' => 'It came covered in poop!!!', - 'comment_approved' => 1, - 'comment_type' => 'review', - ) - ); + array( + 'comment_author' => 'Rude customer', + 'comment_author_email' => 'rude-guy@example.com', + 'comment_post_ID' => $product_id, + 'comment_content' => 'It came covered in poop!!!', + 'comment_approved' => 1, + 'comment_type' => 'review', + ) + ); update_comment_meta( $comment_id, 'rating', 1 ); // Define query and variables. @@ -83,7 +76,7 @@ public function testOrderAsNodeWithComments() { $order->add_order_note( 'testcustomernote', 1, true ); // Define query and variables. - $query = ' + $query = ' query ( $id: ID! ) { order( id: $id, idType: DATABASE_ID ) { id @@ -187,10 +180,10 @@ public function testProductAsNodeWithFeaturedImage() { $attachment_id = $this->factory()->attachment->create( array( 'post_mime_type' => 'image/gif', - 'post_author' => $this->admin + 'post_author' => $this->admin, ) ); - $product_id = $this->products->create_simple( array( 'image_id' => $attachment_id ) ); + $product_id = $this->products->create_simple( array( 'image_id' => $attachment_id ) ); // Define query and variables. $query = ' @@ -270,7 +263,7 @@ public function testProductAsContentNode() { 'databaseId' => $wp_product->ID, 'date' => (string) $wc_product->get_date_created(), 'dateGmt' => \WPGraphQL\Utils\Utils::prepare_date_response( $wp_product->post_date_gmt ), - 'enclosure' => get_post_meta( $wp_product->ID, 'enclosure', true ) ?: null, + 'enclosure' => get_post_meta( $wp_product->ID, 'enclosure', true ) ?? null, 'status' => $wp_product->post_status, 'slug' => $wp_product->post_name, 'modified' => (string) $wc_product->get_date_modified(), @@ -377,7 +370,7 @@ public function testNodeInterfacesOnProductVariation() { 'databaseId' => $wp_product->ID, 'date' => (string) $wc_product->get_date_created(), 'dateGmt' => \WPGraphQL\Utils\Utils::prepare_date_response( $wp_product->post_date_gmt ), - 'enclosure' => get_post_meta( $wp_product->ID, 'enclosure', true ) ?: null, + 'enclosure' => get_post_meta( $wp_product->ID, 'enclosure', true ) ?? null, 'status' => $wp_product->post_status, 'slug' => $wp_product->post_name, 'modified' => (string) $wc_product->get_date_modified(), @@ -401,7 +394,6 @@ public function testNodeInterfacesOnProductVariation() { } public function testQueryProductWithNodeByUri() { - } } diff --git a/tests/wpunit/CouponMutationsTest.php b/tests/wpunit/CouponMutationsTest.php index f8d850d02..758f5a3ae 100644 --- a/tests/wpunit/CouponMutationsTest.php +++ b/tests/wpunit/CouponMutationsTest.php @@ -2,9 +2,9 @@ class CouponMutationsTest extends \Tests\WPGraphQL\WooCommerce\TestCase\WooGraphQLTestCase { - // Tests - public function testCreateCoupon() { - $query = ' + // Tests + public function testCreateCoupon() { + $query = ' mutation($input: CreateCouponInput!) { createCoupon(input: $input) { coupon { @@ -35,10 +35,10 @@ public function testCreateCoupon() { $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedErrorPath( 'createCoupon' ), - $this->expectedField( 'createCoupon', self::IS_NULL ) + $this->expectedField( 'createCoupon', self::IS_NULL ), ); - $this->assertQueryError( $response, $expected ); + $this->assertQueryError( $response, $expected ); /** * Assertion Two @@ -69,13 +69,13 @@ public function testCreateCoupon() { ), ); - $this->assertQuerySuccessful( $response, $expected ); - } + $this->assertQuerySuccessful( $response, $expected ); + } - public function testUpdateCoupon() { - $coupon_id = $this->factory->coupon->create(); + public function testUpdateCoupon() { + $coupon_id = $this->factory->coupon->create(); - $query = ' + $query = ' mutation($input: UpdateCouponInput!) { updateCoupon(input: $input) { coupon { @@ -105,10 +105,10 @@ public function testUpdateCoupon() { $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedErrorPath( 'updateCoupon' ), - $this->expectedField( 'updateCoupon', self::IS_NULL ) + $this->expectedField( 'updateCoupon', self::IS_NULL ), ); - $this->assertQueryError( $response, $expected ); + $this->assertQueryError( $response, $expected ); /** * Assertion Two @@ -139,11 +139,11 @@ public function testUpdateCoupon() { ), ); - $this->assertQuerySuccessful( $response, $expected ); - } + $this->assertQuerySuccessful( $response, $expected ); + } public function testDeleteCoupon() { - $coupon_id = $this->factory->coupon->create(); + $coupon_id = $this->factory->coupon->create(); $query = ' mutation($input: DeleteCouponInput!) { @@ -171,7 +171,7 @@ public function testDeleteCoupon() { $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedErrorPath( 'deleteCoupon' ), - $this->expectedField( 'deleteCoupon', self::IS_NULL ) + $this->expectedField( 'deleteCoupon', self::IS_NULL ), ); $this->assertQueryError( $response, $expected ); @@ -203,5 +203,5 @@ public function testDeleteCoupon() { ); $this->assertQuerySuccessful( $response, $expected ); - } + } } diff --git a/tests/wpunit/CouponQueriesTest.php b/tests/wpunit/CouponQueriesTest.php index bbf160a37..27a4923ca 100644 --- a/tests/wpunit/CouponQueriesTest.php +++ b/tests/wpunit/CouponQueriesTest.php @@ -28,23 +28,23 @@ public function expectedCouponData( $coupon_id ) { $this->expectedField( 'coupon.emailRestrictions', $this->maybe( $coupon->get_email_restrictions(), self::IS_NULL ) ), ); - foreach( $coupon->get_product_ids() as $product_id ) { + foreach ( $coupon->get_product_ids() as $product_id ) { $expected[] = $this->expectedNode( 'coupon.products.nodes', array( 'databaseId' => $product_id ) ); } - foreach( $coupon->get_excluded_product_ids() as $product_id ) { + foreach ( $coupon->get_excluded_product_ids() as $product_id ) { $expected[] = $this->expectedNode( 'coupon.excludedProducts.nodes', array( 'databaseId' => $product_id ) ); } - foreach( $coupon->get_product_categories() as $category_id ) { + foreach ( $coupon->get_product_categories() as $category_id ) { $expected[] = $this->expectedNode( 'coupon.productCategories.nodes', array( 'productCategoryId' => $category_id ) ); } - foreach( $coupon->get_excluded_product_categories() as $category_id ) { + foreach ( $coupon->get_excluded_product_categories() as $category_id ) { $expected[] = $this->expectedNode( 'coupon.excludedProductCategories.nodes', array( 'productCategoryId' => $category_id ) ); } - foreach( $coupon->get_used_by() as $customer_id ) { + foreach ( $coupon->get_used_by() as $customer_id ) { $expected[] = $this->expectedNode( 'coupon.usedBy.nodes', array( 'databaseId' => $customer_id ) ); } @@ -55,11 +55,11 @@ public function expectedCouponData( $coupon_id ) { public function testCouponQuery() { $coupon_id = $this->factory->coupon->create( array( - 'code' => '10off', - 'amount' => 10, - 'discount_type' => 'percent', - 'product_ids' => array( $this->factory->product->createSimple() ), - 'excluded_product_ids' => array( $this->factory->product->createSimple() ) + 'code' => '10off', + 'amount' => 10, + 'discount_type' => 'percent', + 'product_ids' => array( $this->factory->product->createSimple() ), + 'excluded_product_ids' => array( $this->factory->product->createSimple() ), ) ); diff --git a/tests/wpunit/CustomerMutationsTest.php b/tests/wpunit/CustomerMutationsTest.php index 47f129068..7a8631124 100644 --- a/tests/wpunit/CustomerMutationsTest.php +++ b/tests/wpunit/CustomerMutationsTest.php @@ -6,7 +6,7 @@ public function setUp(): void { parent::setUp(); update_option( 'users_can_register', 1 ); - $this->helper = $this->getModule('\Helper\Wpunit')->customer(); + $this->helper = $this->getModule( '\Helper\Wpunit' )->customer(); // Register Info $this->first_name = 'Peter'; @@ -78,26 +78,29 @@ public function tearDown(): void { private function empty_shipping() { return array( 'firstName' => null, - 'lastName' => null, - 'company' => null, - 'address1' => null, - 'address2' => null, - 'city' => null, - 'state' => null, - 'postcode' => null, - 'country' => null, + 'lastName' => null, + 'company' => null, + 'address1' => null, + 'address2' => null, + 'city' => null, + 'state' => null, + 'postcode' => null, + 'country' => null, ); } private function empty_billing() { return array_merge( $this->empty_shipping(), - array( 'email' => null, 'phone' => null ) + array( + 'email' => null, + 'phone' => null, + ) ); } private function registerCustomer( $input ) { - $mutation = ' + $mutation = ' mutation register( $input: RegisterCustomerInput! ) { registerCustomer( input: $input ) { clientMutationId @@ -154,7 +157,7 @@ private function registerCustomer( $input ) { } private function updateCustomer( $input ) { - $mutation = ' + $mutation = ' mutation update( $input: UpdateCustomerInput! ) { updateCustomer( input: $input ) { clientMutationId @@ -199,7 +202,7 @@ private function updateCustomer( $input ) { $actual = graphql( array( 'query' => $mutation, - 'operation_name' =>'update', + 'operation_name' => 'update', 'variables' => $variables, ) ); @@ -247,7 +250,7 @@ public function testRegisterMutationWithoutCustomerInfo() { ), 'viewer' => array( 'userId' => $user->ID, - ) + ), ), ), ); @@ -296,7 +299,7 @@ public function testRegisterMutationWithBillingInfo() { ), 'viewer' => array( 'userId' => $user->ID, - ) + ), ), ), ); @@ -349,7 +352,7 @@ public function testRegisterMutationWithShippingSameAsBillingInfo() { ), 'viewer' => array( 'userId' => $user->ID, - ) + ), ), ), ); @@ -399,7 +402,7 @@ public function testRegisterMutationWithBillingAndShippingInfo() { ), 'viewer' => array( 'userId' => $user->ID, - ) + ), ), ), ); @@ -562,7 +565,7 @@ public function testRegisterMutationWithoutAnyInfo() { ), 'viewer' => array( 'userId' => $user->ID, - ) + ), ), ), ); @@ -576,7 +579,7 @@ public function testCustomerMutationsWithMeta() { * * Test "metaData" input field with "registerCustomer" mutation. */ - $query = ' + $query = ' mutation( $input: RegisterCustomerInput! ) { registerCustomer( input: $input ) { customer { @@ -600,7 +603,7 @@ public function testCustomerMutationsWithMeta() { 'value' => 'test_meta_value', ), ), - ) + ), ); $actual = graphql( compact( 'query', 'variables' ) ); @@ -619,8 +622,8 @@ public function testCustomerMutationsWithMeta() { array( 'key' => 'test_meta_key', 'value' => 'test_meta_value', - ) - ) + ), + ), ), ), ), @@ -633,7 +636,7 @@ public function testCustomerMutationsWithMeta() { * * Test "metaData" input field with "updateCustomer" mutation. */ - $query = ' + $query = ' mutation( $input: UpdateCustomerInput! ) { updateCustomer( input: $input ) { customer { @@ -657,7 +660,7 @@ public function testCustomerMutationsWithMeta() { 'value' => 'new_meta_value', ), ), - ) + ), ); $actual = graphql( compact( 'query', 'variables' ) ); @@ -673,8 +676,8 @@ public function testCustomerMutationsWithMeta() { array( 'key' => 'test_meta_key', 'value' => 'new_meta_value', - ) - ) + ), + ), ), ), ), @@ -687,7 +690,7 @@ public function testCustomerMutationsWithMeta() { * * Test "metaData" input field with "updateCustomer" mutation on the session user. */ - $query = ' + $query = ' mutation( $input: UpdateCustomerInput! ) { updateCustomer( input: $input ) { customer { @@ -709,7 +712,7 @@ public function testCustomerMutationsWithMeta() { 'value' => 'test_meta_value', ), ), - ) + ), ); $actual = graphql( compact( 'query', 'variables' ) ); @@ -724,8 +727,8 @@ public function testCustomerMutationsWithMeta() { array( 'key' => 'test_meta_key', 'value' => 'test_meta_value', - ) - ) + ), + ), ), ), ), diff --git a/tests/wpunit/CustomerQueriesTest.php b/tests/wpunit/CustomerQueriesTest.php index 002d0a4b9..d55a11a44 100644 --- a/tests/wpunit/CustomerQueriesTest.php +++ b/tests/wpunit/CustomerQueriesTest.php @@ -7,7 +7,7 @@ public function expectedCustomerData( $id ) { $customer = new \WC_Customer( $id ); $customer->read_meta_data( true ); - $wp_user = get_user_by( 'ID', $id ); + $wp_user = get_user_by( 'ID', $id ); if ( ! $customer->get_id() ) { throw new \Exception( 'Invalid customer ID provided.' ); @@ -148,12 +148,11 @@ public function testCustomerQueryAndArgs() { $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedErrorPath( 'customer' ), - $this->expectedField( 'customer', self::IS_NULL ) + $this->expectedField( 'customer', self::IS_NULL ), ); $this->assertQueryError( $response, $expected ); - // Clear customer cache. $this->clearLoaderCache( 'wc_customer' ); @@ -185,7 +184,7 @@ public function testCustomerQueryAndArgs() { $this->expectedErrorPath( 'customer.jwtAuthToken' ), $this->expectedField( 'customer.jwtAuthToken', self::IS_NULL ), $this->expectedErrorPath( 'customer.jwtRefreshToken' ), - $this->expectedField( 'customer.jwtRefreshToken', self::IS_NULL ) + $this->expectedField( 'customer.jwtRefreshToken', self::IS_NULL ), ), $this->expectedCustomerData( $new_customer_id ) ); @@ -233,7 +232,7 @@ public function testCustomerQueryAndArgs() { $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedErrorPath( 'customer' ), - $this->expectedField( 'customer', self::IS_NULL ) + $this->expectedField( 'customer', self::IS_NULL ), ); $this->assertQueryError( $response, $expected ); @@ -246,8 +245,8 @@ public function testCustomersQueryAndWhereArgs() { $users = array( $this->factory->customer->create( array( - 'email' => 'gotcha@example.com', - 'username' => 'megaman8080' + 'email' => 'gotcha@example.com', + 'username' => 'megaman8080', ) ), $this->factory->customer->create(), @@ -324,7 +323,7 @@ public function testCustomersQueryAndWhereArgs() { * * Tests "include" where argument. */ - $variables = array( 'include' => array( $users[2]) ); + $variables = array( 'include' => array( $users[2] ) ); $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedField( 'customers.nodes.0.databaseId', $users[2] ), @@ -369,7 +368,10 @@ public function testCustomersQueryAndWhereArgs() { * * Tests "orderby" and "order" where arguments. */ - $variables = array( 'orderby' => 'USERNAME', 'order' => 'ASC' ); + $variables = array( + 'orderby' => 'USERNAME', + 'order' => 'ASC', + ); $response = $this->graphql( compact( 'query', 'variables' ) ); $all_users = get_users( diff --git a/tests/wpunit/DownloadableItemQueriesTest.php b/tests/wpunit/DownloadableItemQueriesTest.php index 0eaff82c7..09a342470 100644 --- a/tests/wpunit/DownloadableItemQueriesTest.php +++ b/tests/wpunit/DownloadableItemQueriesTest.php @@ -1,44 +1,44 @@ factory->product->createSimple( - array( - 'downloadable' => true, - 'downloads' => array( $this->factory->product->createDownload() ) - ) - ); - $order_id = $this->factory->order->createNew( - array( - 'status' => 'completed', - 'customer_id' => $this->customer, - ), - array( - 'line_items' => array( - array( - 'product' => $downloadable_product, - 'qty' => 1, - ), - ), - ) - ); + // tests + public function testOrderToDownloadableItemsQuery() { + $downloadable_product = $this->factory->product->createSimple( + array( + 'downloadable' => true, + 'downloads' => array( $this->factory->product->createDownload() ), + ) + ); + $order_id = $this->factory->order->createNew( + array( + 'status' => 'completed', + 'customer_id' => $this->customer, + ), + array( + 'line_items' => array( + array( + 'product' => $downloadable_product, + 'qty' => 1, + ), + ), + ) + ); - // Force download permission updated. - wc_downloadable_product_permissions( $order_id, true ); + // Force download permission updated. + wc_downloadable_product_permissions( $order_id, true ); - $order = wc_get_order( $order_id ); - $downloadable_items = $order->get_downloadable_items(); + $order = wc_get_order( $order_id ); + $downloadable_items = $order->get_downloadable_items(); - $query = ' + $query = ' query { customer { orders { @@ -64,96 +64,96 @@ public function testOrderToDownloadableItemsQuery() { } '; - /** + /** * Assertion One * - * tests query results + * Tests query results */ $this->loginAsCustomer(); $response = $this->graphql( compact( 'query' ) ); - $expected = array_map( - function( $item ) { - return $this->expectedNode( - 'customer.orders.nodes', - array( - $this->expectedNode( - 'downloadableItems.nodes', - array( - $this->expectedField( 'url', $item['download_url'] ), - $this->expectedField( 'accessExpires', $item['access_expires'] ), - $this->expectedField( 'downloadId', $item['download_id'] ), - $this->expectedField( - 'downloadsRemaining', - isset( $item['downloads_remaining'] ) && 'integer' === gettype( $item['downloads_remaining'] ) - ? $item['downloads_remaining'] - : self::IS_NULL - ), - $this->expectedField( 'name', $item['download_name'] ), - $this->expectedField( 'product.databaseId', $item['product_id'] ), - $this->expectedField( 'download.downloadId', $item['download_id'] ), - ) - ), - ), - 0 - ); - }, - $downloadable_items - ); + $expected = array_map( + function( $item ) { + return $this->expectedNode( + 'customer.orders.nodes', + array( + $this->expectedNode( + 'downloadableItems.nodes', + array( + $this->expectedField( 'url', $item['download_url'] ), + $this->expectedField( 'accessExpires', $item['access_expires'] ), + $this->expectedField( 'downloadId', $item['download_id'] ), + $this->expectedField( + 'downloadsRemaining', + isset( $item['downloads_remaining'] ) && 'integer' === gettype( $item['downloads_remaining'] ) + ? $item['downloads_remaining'] + : self::IS_NULL + ), + $this->expectedField( 'name', $item['download_name'] ), + $this->expectedField( 'product.databaseId', $item['product_id'] ), + $this->expectedField( 'download.downloadId', $item['download_id'] ), + ) + ), + ), + 0 + ); + }, + $downloadable_items + ); - $this->assertQuerySuccessful( $response, $expected ); - } + $this->assertQuerySuccessful( $response, $expected ); + } - public function testOrderToDownloadableItemsQueryArgs() { - $valid_product = $this->factory->product->createSimple( - array( - 'downloadable' => true, - 'downloads' => array( $this->factory->product->createDownload() ) - ) - ); - $downloadable_product = $this->factory->product->createSimple( - array( - 'download_expiry' => 5, - 'download_limit' => 3, - 'downloadable' => true, - 'downloads' => array( $this->factory->product->createDownload() ) - ) - ); - $downloaded_product = $this->factory->product->createSimple( - array( - 'download_limit' => 0, - 'downloadable' => true, - 'downloads' => array( $this->factory->product->createDownload() ) - ) - ); + public function testOrderToDownloadableItemsQueryArgs() { + $valid_product = $this->factory->product->createSimple( + array( + 'downloadable' => true, + 'downloads' => array( $this->factory->product->createDownload() ), + ) + ); + $downloadable_product = $this->factory->product->createSimple( + array( + 'download_expiry' => 5, + 'download_limit' => 3, + 'downloadable' => true, + 'downloads' => array( $this->factory->product->createDownload() ), + ) + ); + $downloaded_product = $this->factory->product->createSimple( + array( + 'download_limit' => 0, + 'downloadable' => true, + 'downloads' => array( $this->factory->product->createDownload() ), + ) + ); - $order_id = $this->factory->order->createNew( - array( - 'status' => 'completed', - 'customer_id' => $this->customer, - ), - array( - 'line_items' => array( - array( - 'product' => $valid_product, - 'qty' => 1, - ), - array( - 'product' => $downloadable_product, - 'qty' => 1, - ), - array( - 'product' => $downloaded_product, - 'qty' => 1, - ), - ), - ) - ); + $order_id = $this->factory->order->createNew( + array( + 'status' => 'completed', + 'customer_id' => $this->customer, + ), + array( + 'line_items' => array( + array( + 'product' => $valid_product, + 'qty' => 1, + ), + array( + 'product' => $downloadable_product, + 'qty' => 1, + ), + array( + 'product' => $downloaded_product, + 'qty' => 1, + ), + ), + ) + ); - // Force download permission updated. - wc_downloadable_product_permissions( $order_id, true ); + // Force download permission updated. + wc_downloadable_product_permissions( $order_id, true ); - $query = ' + $query = ' query($active: Boolean, $hasDownloadsRemaining: Boolean) { customer { orders { @@ -171,156 +171,156 @@ public function testOrderToDownloadableItemsQueryArgs() { } '; - /** + /** * Assertion One * - * tests "active" whereArg + * Tests "active" whereArg */ $this->loginAsCustomer(); - $variables = array( 'active' => true ); + $variables = array( 'active' => true ); $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( - $this->expectedNode( - 'customer.orders.nodes', - array( - $this->expectedNode( - 'downloadableItems.nodes', - array( $this->expectedField( 'product.databaseId', $valid_product ) ) - ), - $this->expectedNode( - 'downloadableItems.nodes', - array( $this->expectedField( 'product.databaseId', $downloadable_product ) ) - ), - $this->not()->expectedNode( - 'downloadableItems.nodes', - array( $this->expectedField( 'product.databaseId', $downloaded_product ) ) - ), - ), - 0 - ), - ); + $this->expectedNode( + 'customer.orders.nodes', + array( + $this->expectedNode( + 'downloadableItems.nodes', + array( $this->expectedField( 'product.databaseId', $valid_product ) ) + ), + $this->expectedNode( + 'downloadableItems.nodes', + array( $this->expectedField( 'product.databaseId', $downloadable_product ) ) + ), + $this->not()->expectedNode( + 'downloadableItems.nodes', + array( $this->expectedField( 'product.databaseId', $downloaded_product ) ) + ), + ), + 0 + ), + ); - $this->assertQuerySuccessful( $response, $expected ); + $this->assertQuerySuccessful( $response, $expected ); - /** + /** * Assertion Two * - * tests "active" whereArg reversed + * Tests "active" whereArg reversed */ - $variables = array( 'active' => false ); + $variables = array( 'active' => false ); $response = $this->graphql( compact( 'query', 'variables' ) ); - $expected = array( - $this->expectedNode( - 'customer.orders.nodes', - array( - $this->expectedNode( - 'downloadableItems.nodes', - array( $this->expectedField( 'product.databaseId', $downloaded_product ) ) - ), - $this->not()->expectedNode( - 'downloadableItems.nodes', - array( $this->expectedField( 'product.databaseId', $valid_product ) ) - ), - $this->not()->expectedNode( - 'downloadableItems.nodes', - array( $this->expectedField( 'product.databaseId', $downloadable_product ) ) - ), - ), - 0 - ), - ); + $expected = array( + $this->expectedNode( + 'customer.orders.nodes', + array( + $this->expectedNode( + 'downloadableItems.nodes', + array( $this->expectedField( 'product.databaseId', $downloaded_product ) ) + ), + $this->not()->expectedNode( + 'downloadableItems.nodes', + array( $this->expectedField( 'product.databaseId', $valid_product ) ) + ), + $this->not()->expectedNode( + 'downloadableItems.nodes', + array( $this->expectedField( 'product.databaseId', $downloadable_product ) ) + ), + ), + 0 + ), + ); - $this->assertQuerySuccessful( $response, $expected ); + $this->assertQuerySuccessful( $response, $expected ); - /** + /** * Assertion Three * - * tests "hasDownloadsRemaining" whereArg + * Tests "hasDownloadsRemaining" whereArg */ - $variables = array( 'hasDownloadsRemaining' => true ); + $variables = array( 'hasDownloadsRemaining' => true ); $response = $this->graphql( compact( 'query', 'variables' ) ); - $expected = array( - $this->expectedNode( - 'customer.orders.nodes', - array( - $this->not()->expectedNode( - 'downloadableItems.nodes', - array( $this->expectedField( 'product.databaseId', $downloaded_product ) ) - ), - $this->expectedNode( - 'downloadableItems.nodes', - array( $this->expectedField( 'product.databaseId', $valid_product ) ) - ), - $this->expectedNode( - 'downloadableItems.nodes', - array( $this->expectedField( 'product.databaseId', $downloadable_product ) ) - ), - ), - 0 - ), - ); + $expected = array( + $this->expectedNode( + 'customer.orders.nodes', + array( + $this->not()->expectedNode( + 'downloadableItems.nodes', + array( $this->expectedField( 'product.databaseId', $downloaded_product ) ) + ), + $this->expectedNode( + 'downloadableItems.nodes', + array( $this->expectedField( 'product.databaseId', $valid_product ) ) + ), + $this->expectedNode( + 'downloadableItems.nodes', + array( $this->expectedField( 'product.databaseId', $downloadable_product ) ) + ), + ), + 0 + ), + ); - $this->assertQuerySuccessful( $response, $expected ); + $this->assertQuerySuccessful( $response, $expected ); - /** + /** * Assertion Four * - * tests "hasDownloadsRemaining" whereArg reversed + * Tests "hasDownloadsRemaining" whereArg reversed */ - $variables = array( 'hasDownloadsRemaining' => false ); - $response = $this->graphql( compact( 'query', 'variables' ) ); - $expected = array( - $this->expectedNode( - 'customer.orders.nodes', - array( - $this->expectedNode( - 'downloadableItems.nodes', - array( $this->expectedField( 'product.databaseId', $downloaded_product ) ) - ), - $this->not()->expectedNode( - 'downloadableItems.nodes', - array( $this->expectedField( 'product.databaseId', $valid_product ) ) - ), - $this->not()->expectedNode( - 'downloadableItems.nodes', - array( $this->expectedField( 'product.databaseId', $downloadable_product ) ) - ), - ), - 0 - ), - ); + $variables = array( 'hasDownloadsRemaining' => false ); + $response = $this->graphql( compact( 'query', 'variables' ) ); + $expected = array( + $this->expectedNode( + 'customer.orders.nodes', + array( + $this->expectedNode( + 'downloadableItems.nodes', + array( $this->expectedField( 'product.databaseId', $downloaded_product ) ) + ), + $this->not()->expectedNode( + 'downloadableItems.nodes', + array( $this->expectedField( 'product.databaseId', $valid_product ) ) + ), + $this->not()->expectedNode( + 'downloadableItems.nodes', + array( $this->expectedField( 'product.databaseId', $downloadable_product ) ) + ), + ), + 0 + ), + ); - $this->assertQuerySuccessful( $response, $expected ); - } + $this->assertQuerySuccessful( $response, $expected ); + } - public function testCustomerToDownloadableItemsQuery() { - $downloadable_product = $this->factory->product->createSimple( - array( - 'downloadable' => true, - 'downloads' => array( $this->factory->product->createDownload() ) - ) - ); - $order_id = $this->factory->order->createNew( - array( - 'status' => 'completed', - 'customer_id' => $this->customer, - ), - array( - 'line_items' => array( - array( - 'product' => $downloadable_product, - 'qty' => 1, - ), - ), - ) - ); + public function testCustomerToDownloadableItemsQuery() { + $downloadable_product = $this->factory->product->createSimple( + array( + 'downloadable' => true, + 'downloads' => array( $this->factory->product->createDownload() ), + ) + ); + $order_id = $this->factory->order->createNew( + array( + 'status' => 'completed', + 'customer_id' => $this->customer, + ), + array( + 'line_items' => array( + array( + 'product' => $downloadable_product, + 'qty' => 1, + ), + ), + ) + ); - // Force download permission updated. - wc_downloadable_product_permissions( $order_id, true ); + // Force download permission updated. + wc_downloadable_product_permissions( $order_id, true ); - $downloadable_items = \wc_get_customer_available_downloads( $this->customer ); + $downloadable_items = \wc_get_customer_available_downloads( $this->customer ); - $query = ' + $query = ' query { customer { downloadableItems(first: 1) { @@ -342,37 +342,37 @@ public function testCustomerToDownloadableItemsQuery() { } '; - /** + /** * Assertion One * - * tests query results + * Tests query results */ $this->loginAsCustomer(); - $response = $this->graphql( compact( 'query' ) ); - $expected = array_map( - function( $item ) { - return $this->expectedNode( - 'customer.downloadableItems.nodes', - array( - $this->expectedField( 'url', $item['download_url'] ), - $this->expectedField( 'accessExpires', $item['access_expires'] ), - $this->expectedField( 'downloadId', $item['download_id'] ), - $this->expectedField( - 'downloadsRemaining', - isset( $item['downloads_remaining'] ) && 'integer' === gettype( $item['downloads_remaining'] ) - ? $item['downloads_remaining'] - : self::IS_NULL - ), - $this->expectedField( 'name', $item['download_name'] ), - $this->expectedField( 'product.databaseId', $item['product_id'] ), - $this->expectedField( 'download.downloadId', $item['download_id'] ), - ), - 0 - ); - }, - $downloadable_items - ); + $response = $this->graphql( compact( 'query' ) ); + $expected = array_map( + function( $item ) { + return $this->expectedNode( + 'customer.downloadableItems.nodes', + array( + $this->expectedField( 'url', $item['download_url'] ), + $this->expectedField( 'accessExpires', $item['access_expires'] ), + $this->expectedField( 'downloadId', $item['download_id'] ), + $this->expectedField( + 'downloadsRemaining', + isset( $item['downloads_remaining'] ) && 'integer' === gettype( $item['downloads_remaining'] ) + ? $item['downloads_remaining'] + : self::IS_NULL + ), + $this->expectedField( 'name', $item['download_name'] ), + $this->expectedField( 'product.databaseId', $item['product_id'] ), + $this->expectedField( 'download.downloadId', $item['download_id'] ), + ), + 0 + ); + }, + $downloadable_items + ); - $this->assertQuerySuccessful( $response, $expected ); - } + $this->assertQuerySuccessful( $response, $expected ); + } } diff --git a/tests/wpunit/IntrospectionQueryTest.php b/tests/wpunit/IntrospectionQueryTest.php index 44c8acb93..503d57df5 100644 --- a/tests/wpunit/IntrospectionQueryTest.php +++ b/tests/wpunit/IntrospectionQueryTest.php @@ -2,8 +2,8 @@ class IntrospectionQueryTest extends \Codeception\TestCase\WPTestCase { - public function setUp(): void { - // before + public function setUp(): void { + // before parent::setUp(); $settings = get_option( 'graphql_general_settings' ); @@ -13,37 +13,30 @@ public function setUp(): void { $settings['public_introspection_enabled'] = 'on'; update_option( 'graphql_general_settings', $settings ); \WPGraphQL::clear_schema(); - } - - public function tearDown(): void { - // your tear down methods here - - // then - parent::tearDown(); - } - - // Validate schema. - public function testSchema() { - try { - $request = new \WPGraphQL\Request(); - $request->schema->assertValid(); - - // Assert true upon success. - $this->assertTrue( true ); - } catch (\GraphQL\Error\InvariantViolation $e) { - // use --debug flag to view. - codecept_debug( $e->getMessage() ); - - // Fail upon throwing - $this->assertTrue( false ); - } - } - - // Test introspection query. - public function testIntrospectionQuery() { - $query = \GraphQL\Type\Introspection::getIntrospectionQuery(); - $results = graphql( array( 'query' => $query ) ); - - $this->assertArrayNotHasKey('errors', $results ); - } + } + + // Validate schema. + public function testSchema() { + try { + $request = new \WPGraphQL\Request(); + $request->schema->assertValid(); + + // Assert true upon success. + $this->assertTrue( true ); + } catch ( \GraphQL\Error\InvariantViolation $e ) { + // use --debug flag to view. + codecept_debug( $e->getMessage() ); + + // Fail upon throwing + $this->assertTrue( false ); + } + } + + // Test introspection query. + public function testIntrospectionQuery() { + $query = \GraphQL\Type\Introspection::getIntrospectionQuery(); + $results = graphql( array( 'query' => $query ) ); + + $this->assertArrayNotHasKey( 'errors', $results ); + } } diff --git a/tests/wpunit/MetaDataQueriesTest.php b/tests/wpunit/MetaDataQueriesTest.php index 16067a15c..1026bf2ca 100644 --- a/tests/wpunit/MetaDataQueriesTest.php +++ b/tests/wpunit/MetaDataQueriesTest.php @@ -4,81 +4,81 @@ class MetaDataQueriesTest extends \Codeception\TestCase\WPTestCase { - public function setUp(): void { - // before - parent::setUp(); - - // Create users. - $this->shop_manager = $this->factory->user->create( array( 'role' => 'shop_manager' ) ); - $this->customer = $this->factory->user->create( array( 'role' => 'customer' ) ); - - // Assign helpers. - $this->cart = $this->getModule('\Helper\Wpunit')->cart(); - $this->coupons = $this->getModule('\Helper\Wpunit')->coupon(); - $this->customers = $this->getModule('\Helper\Wpunit')->customer(); - $this->orders = $this->getModule('\Helper\Wpunit')->order(); - $this->order_items = $this->getModule('\Helper\Wpunit')->item(); - $this->products = $this->getModule('\Helper\Wpunit')->product(); - $this->refunds = $this->getModule('\Helper\Wpunit')->refund(); - $this->variations = $this->getModule('\Helper\Wpunit')->product_variation(); - - // Create test objects. - $this->createObjects(); - } - - public function tearDown(): void { - // Clear cart. + public function setUp(): void { + // before + parent::setUp(); + + // Create users. + $this->shop_manager = $this->factory->user->create( array( 'role' => 'shop_manager' ) ); + $this->customer = $this->factory->user->create( array( 'role' => 'customer' ) ); + + // Assign helpers. + $this->cart = $this->getModule( '\Helper\Wpunit' )->cart(); + $this->coupons = $this->getModule( '\Helper\Wpunit' )->coupon(); + $this->customers = $this->getModule( '\Helper\Wpunit' )->customer(); + $this->orders = $this->getModule( '\Helper\Wpunit' )->order(); + $this->order_items = $this->getModule( '\Helper\Wpunit' )->item(); + $this->products = $this->getModule( '\Helper\Wpunit' )->product(); + $this->refunds = $this->getModule( '\Helper\Wpunit' )->refund(); + $this->variations = $this->getModule( '\Helper\Wpunit' )->product_variation(); + + // Create test objects. + $this->createObjects(); + } + + public function tearDown(): void { + // Clear cart. WC()->cart->empty_cart( true ); - // then - parent::tearDown(); - } + // then + parent::tearDown(); + } - public function set_user( $user ) { + public function set_user( $user ) { wp_set_current_user( $user ); WC()->customer = new WC_Customer( get_current_user_id(), true ); } - private function createObjects() { - $data = array( - 'meta_data' => array( - array( - 'id' => 0, - 'key' => 'meta_1', - 'value' => 'test_meta_1' - ), - array( - 'id' => 0, - 'key' => 'meta_2', - 'value' => 'test_meta_2' - ), - array( - 'id' => 0, - 'key' => 'meta_1', - 'value' => 75, - ), - ), - ); - - // Create Coupon with meta data. - $this->coupon_id = $this->coupons->create( $data ); - - // Create Customer with meta data. - $this->customer_id = $this->customers->create( $data ); - - // Create Order and Refund with meta data. - $this->order_id = $this->orders->create( array_merge( $data, array( 'customer_id' => $this->customer ) ) ); - $this->order_items->add_fee( $this->order_id, $data ); - $this->refund_id = $this->refunds->create( $this->order_id, $data ); - - // Create Products with meta data. - $this->product_id = $this->products->create_variable( $data ); - $this->variation_ids = $this->variations->create( $this->product_id, $data ); - - // Add Cart Item with extra data. - $cart_meta_data = array( - 'meta_1' => 'test_meta_1', - 'meta_2' => 'test_meta_2' + private function createObjects() { + $data = array( + 'meta_data' => array( + array( + 'id' => 0, + 'key' => 'meta_1', + 'value' => 'test_meta_1', + ), + array( + 'id' => 0, + 'key' => 'meta_2', + 'value' => 'test_meta_2', + ), + array( + 'id' => 0, + 'key' => 'meta_1', + 'value' => 75, + ), + ), + ); + + // Create Coupon with meta data. + $this->coupon_id = $this->coupons->create( $data ); + + // Create Customer with meta data. + $this->customer_id = $this->customers->create( $data ); + + // Create Order and Refund with meta data. + $this->order_id = $this->orders->create( array_merge( $data, array( 'customer_id' => $this->customer ) ) ); + $this->order_items->add_fee( $this->order_id, $data ); + $this->refund_id = $this->refunds->create( $this->order_id, $data ); + + // Create Products with meta data. + $this->product_id = $this->products->create_variable( $data ); + $this->variation_ids = $this->variations->create( $this->product_id, $data ); + + // Add Cart Item with extra data. + $cart_meta_data = array( + 'meta_1' => 'test_meta_1', + 'meta_2' => 'test_meta_2', ); // Clear cart. @@ -87,18 +87,18 @@ private function createObjects() { // Add item to cart. $this->cart_item_key = $this->cart->add( array( - 'product_id' => $this->variation_ids['product'], - 'quantity' => 2, - 'variation_id' => $this->variation_ids['variations'][0], - 'variation' => array( 'attribute_pa_color' => 'red' ), - 'cart_item_data' => $cart_meta_data + 'product_id' => $this->variation_ids['product'], + 'quantity' => 2, + 'variation_id' => $this->variation_ids['variations'][0], + 'variation' => array( 'attribute_pa_color' => 'red' ), + 'cart_item_data' => $cart_meta_data, ) )[0]; - } + } - // tests - public function testCartMetaDataQueries() { - $query = ' + // tests + public function testCartMetaDataQueries() { + $query = ' query($key: String, $keysIn: [String]) { cart { contents { @@ -114,109 +114,119 @@ public function testCartMetaDataQueries() { } '; - /** - * Assertion One - * - * query w/o filter - */ - $actual = graphql( array( 'query' => $query ) ); - $expected = array( - 'data' => array( - 'cart' => array( - 'contents' => array( - 'nodes' => array( - array( - 'key' => $this->cart_item_key, - 'extraData' => array( - array( - 'key' => 'meta_1', - 'value' => 'test_meta_1', - ), - array( - 'key' => 'meta_2', - 'value' => 'test_meta_2', - ), - ), - ) - ) - ) - ) - ), - ); - - // use --debug flag to view. - codecept_debug( $actual ); - - $this->assertEquals( $expected, $actual ); - - /** - * Assertion Two - * - * query w/ "key" filter - */ - $variables = array( 'key' => 'meta_2' ); - $actual = graphql( array( 'query' => $query, 'variables' => $variables ) ); - $expected = array( - 'data' => array( - 'cart' => array( - 'contents' => array( - 'nodes' => array( - array( - 'key' => $this->cart_item_key, - 'extraData' => array( - array( - 'key' => 'meta_2', - 'value' => 'test_meta_2', - ), - ), - ) - ) - ) - ) - ), - ); - - // use --debug flag to view. - codecept_debug( $actual ); - - $this->assertEquals( $expected, $actual ); - - /** - * Assertion Three - * - * query w/ "keysIn" filter - */ - $variables = array( 'keysIn' => array( 'meta_2' ) ); - $actual = graphql( array( 'query' => $query, 'variables' => $variables ) ); - $expected = array( - 'data' => array( - 'cart' => array( - 'contents' => array( - 'nodes' => array( - array( - 'key' => $this->cart_item_key, - 'extraData' => array( - array( - 'key' => 'meta_2', - 'value' => 'test_meta_2', - ), - ), - ) - ) - ) - ) - ), - ); - - // use --debug flag to view. - codecept_debug( $actual ); - - $this->assertEquals( $expected, $actual ); - } - - public function testCouponMetaDataQueries() { - $id = Relay::toGlobalId( 'shop_coupon', $this->coupon_id ); - $query = ' + /** + * Assertion One + * + * Query w/o filter + */ + $actual = graphql( array( 'query' => $query ) ); + $expected = array( + 'data' => array( + 'cart' => array( + 'contents' => array( + 'nodes' => array( + array( + 'key' => $this->cart_item_key, + 'extraData' => array( + array( + 'key' => 'meta_1', + 'value' => 'test_meta_1', + ), + array( + 'key' => 'meta_2', + 'value' => 'test_meta_2', + ), + ), + ), + ), + ), + ), + ), + ); + + // use --debug flag to view. + codecept_debug( $actual ); + + $this->assertEquals( $expected, $actual ); + + /** + * Assertion Two + * + * Query w/ "key" filter + */ + $variables = array( 'key' => 'meta_2' ); + $actual = graphql( + array( + 'query' => $query, + 'variables' => $variables, + ) + ); + $expected = array( + 'data' => array( + 'cart' => array( + 'contents' => array( + 'nodes' => array( + array( + 'key' => $this->cart_item_key, + 'extraData' => array( + array( + 'key' => 'meta_2', + 'value' => 'test_meta_2', + ), + ), + ), + ), + ), + ), + ), + ); + + // use --debug flag to view. + codecept_debug( $actual ); + + $this->assertEquals( $expected, $actual ); + + /** + * Assertion Three + * + * Query w/ "keysIn" filter + */ + $variables = array( 'keysIn' => array( 'meta_2' ) ); + $actual = graphql( + array( + 'query' => $query, + 'variables' => $variables, + ) + ); + $expected = array( + 'data' => array( + 'cart' => array( + 'contents' => array( + 'nodes' => array( + array( + 'key' => $this->cart_item_key, + 'extraData' => array( + array( + 'key' => 'meta_2', + 'value' => 'test_meta_2', + ), + ), + ), + ), + ), + ), + ), + ); + + // use --debug flag to view. + codecept_debug( $actual ); + + $this->assertEquals( $expected, $actual ); + } + + public function testCouponMetaDataQueries() { + $id = Relay::toGlobalId( 'shop_coupon', $this->coupon_id ); + $query = ' query ($id: ID!, $key: String, $keysIn: [String], $multiple: Boolean) { coupon(id: $id) { id @@ -228,191 +238,233 @@ public function testCouponMetaDataQueries() { } '; - /** - * Assertion One - * - * query w/o filters - */ - wp_set_current_user( $this->shop_manager ); - $variables = array( 'id' => $id ); - $actual = graphql( - array( - 'query' => $query, - 'variables' => $variables, - ) - ); - $expected = array( - 'data' => array( - 'coupon' => array( - 'id' => $id, - 'metaData' => array( - array( - 'key' => 'meta_1', - 'value' => 'test_meta_1', - ), - array( - 'key' => 'meta_2', - 'value' => 'test_meta_2', - ), - ) - ), - ), - ); - - // use --debug flag to view. - codecept_debug( $actual ); - - $this->assertEquals( $expected, $actual ); - - /** - * Assertion Two - * - * query w/ "key" filter - */ - $variables = array( 'id' => $id, 'key' => 'meta_2' ); - $actual = graphql( array( 'query' => $query, 'variables' => $variables ) ); - $expected = array( - 'data' => array( - 'coupon' => array( - 'id' => $id, - 'metaData' => array( - array( - 'key' => 'meta_2', - 'value' => 'test_meta_2', - ), - ) - ), - ), - ); - - // use --debug flag to view. - codecept_debug( $actual ); - - $this->assertEquals( $expected, $actual ); - - /** - * Assertion Three - * - * query w/ "keysIn" filter - */ - $variables = array( 'id' => $id, 'keysIn' => array( 'meta_2' ) ); - $actual = graphql( array( 'query' => $query, 'variables' => $variables ) ); - $expected = array( - 'data' => array( - 'coupon' => array( - 'id' => $id, - 'metaData' => array( - array( - 'key' => 'meta_2', - 'value' => 'test_meta_2', - ), - ) - ), - ), - ); - - // use --debug flag to view. - codecept_debug( $actual ); - - $this->assertEquals( $expected, $actual ); - - /** - * Assertion Four - * - * query w/ "key" filter and "multiple" set to true to get non-unique results. - */ - $variables = array( 'id' => $id, 'key' => 'meta_1', 'multiple' => true ); - $actual = graphql( array( 'query' => $query, 'variables' => $variables ) ); - $expected = array( - 'data' => array( - 'coupon' => array( - 'id' => $id, - 'metaData' => array( - array( - 'key' => 'meta_1', - 'value' => 'test_meta_1', - ), - array( - 'key' => 'meta_1', - 'value' => '75', - ), - ) - ), - ), - ); - - // use --debug flag to view. - codecept_debug( $actual ); - - $this->assertEquals( $expected, $actual ); - - /** - * Assertion Five - * - * query w/ "keysIn" filter and "multiple" set to true to get non-unique results. - */ - $variables = array( 'id' => $id, 'keysIn' => array( 'meta_1' ), 'multiple' => true ); - $actual = graphql( array( 'query' => $query, 'variables' => $variables ) ); - $expected = array( - 'data' => array( - 'coupon' => array( - 'id' => $id, - 'metaData' => array( - array( - 'key' => 'meta_1', - 'value' => 'test_meta_1', - ), - array( - 'key' => 'meta_1', - 'value' => '75', - ), - ) - ), - ), - ); - - // use --debug flag to view. - codecept_debug( $actual ); - - $this->assertEquals( $expected, $actual ); - - /** - * Assertion Six - * - * query w/o filters and "multiple" set to true to get non-unique results. - */ - $variables = array( 'id' => $id, 'multiple' => true ); - $actual = graphql( array( 'query' => $query, 'variables' => $variables ) ); - $expected = array( - 'data' => array( - 'coupon' => array( - 'id' => $id, - 'metaData' => array( - array( - 'key' => 'meta_1', - 'value' => 'test_meta_1', - ), - array( - 'key' => 'meta_2', - 'value' => 'test_meta_2', - ), - array( - 'key' => 'meta_1', - 'value' => '75', - ), - ) - ), - ), - ); - - // use --debug flag to view. - codecept_debug( $actual ); - - $this->assertEquals( $expected, $actual ); - } - - public function testCustomerMetaDataQueries() { - $query = ' + /** + * Assertion One + * + * Query w/o filters + */ + wp_set_current_user( $this->shop_manager ); + $variables = array( 'id' => $id ); + $actual = graphql( + array( + 'query' => $query, + 'variables' => $variables, + ) + ); + $expected = array( + 'data' => array( + 'coupon' => array( + 'id' => $id, + 'metaData' => array( + array( + 'key' => 'meta_1', + 'value' => 'test_meta_1', + ), + array( + 'key' => 'meta_2', + 'value' => 'test_meta_2', + ), + ), + ), + ), + ); + + // use --debug flag to view. + codecept_debug( $actual ); + + $this->assertEquals( $expected, $actual ); + + /** + * Assertion Two + * + * Query w/ "key" filter + */ + $variables = array( + 'id' => $id, + 'key' => 'meta_2', + ); + $actual = graphql( + array( + 'query' => $query, + 'variables' => $variables, + ) + ); + $expected = array( + 'data' => array( + 'coupon' => array( + 'id' => $id, + 'metaData' => array( + array( + 'key' => 'meta_2', + 'value' => 'test_meta_2', + ), + ), + ), + ), + ); + + // use --debug flag to view. + codecept_debug( $actual ); + + $this->assertEquals( $expected, $actual ); + + /** + * Assertion Three + * + * Query w/ "keysIn" filter + */ + $variables = array( + 'id' => $id, + 'keysIn' => array( 'meta_2' ), + ); + $actual = graphql( + array( + 'query' => $query, + 'variables' => $variables, + ) + ); + $expected = array( + 'data' => array( + 'coupon' => array( + 'id' => $id, + 'metaData' => array( + array( + 'key' => 'meta_2', + 'value' => 'test_meta_2', + ), + ), + ), + ), + ); + + // use --debug flag to view. + codecept_debug( $actual ); + + $this->assertEquals( $expected, $actual ); + + /** + * Assertion Four + * + * Query w/ "key" filter and "multiple" set to true to get non-unique results. + */ + $variables = array( + 'id' => $id, + 'key' => 'meta_1', + 'multiple' => true, + ); + $actual = graphql( + array( + 'query' => $query, + 'variables' => $variables, + ) + ); + $expected = array( + 'data' => array( + 'coupon' => array( + 'id' => $id, + 'metaData' => array( + array( + 'key' => 'meta_1', + 'value' => 'test_meta_1', + ), + array( + 'key' => 'meta_1', + 'value' => '75', + ), + ), + ), + ), + ); + + // use --debug flag to view. + codecept_debug( $actual ); + + $this->assertEquals( $expected, $actual ); + + /** + * Assertion Five + * + * Query w/ "keysIn" filter and "multiple" set to true to get non-unique results. + */ + $variables = array( + 'id' => $id, + 'keysIn' => array( 'meta_1' ), + 'multiple' => true, + ); + $actual = graphql( + array( + 'query' => $query, + 'variables' => $variables, + ) + ); + $expected = array( + 'data' => array( + 'coupon' => array( + 'id' => $id, + 'metaData' => array( + array( + 'key' => 'meta_1', + 'value' => 'test_meta_1', + ), + array( + 'key' => 'meta_1', + 'value' => '75', + ), + ), + ), + ), + ); + + // use --debug flag to view. + codecept_debug( $actual ); + + $this->assertEquals( $expected, $actual ); + + /** + * Assertion Six + * + * Query w/o filters and "multiple" set to true to get non-unique results. + */ + $variables = array( + 'id' => $id, + 'multiple' => true, + ); + $actual = graphql( + array( + 'query' => $query, + 'variables' => $variables, + ) + ); + $expected = array( + 'data' => array( + 'coupon' => array( + 'id' => $id, + 'metaData' => array( + array( + 'key' => 'meta_1', + 'value' => 'test_meta_1', + ), + array( + 'key' => 'meta_2', + 'value' => 'test_meta_2', + ), + array( + 'key' => 'meta_1', + 'value' => '75', + ), + ), + ), + ), + ); + + // use --debug flag to view. + codecept_debug( $actual ); + + $this->assertEquals( $expected, $actual ); + } + + public function testCustomerMetaDataQueries() { + $query = ' query { customer { id @@ -424,38 +476,38 @@ public function testCustomerMetaDataQueries() { } '; - /** - * Assertion One - */ - $this->set_user( $this->customer_id ); - $actual = graphql( array( 'query' => $query ) ); - $expected = array( - 'data' => array( - 'customer' => array( - 'id' => Relay::toGlobalId( 'customer', $this->customer_id ), - 'metaData' => array( - array( - 'key' => 'meta_1', - 'value' => 'test_meta_1', - ), - array( - 'key' => 'meta_2', - 'value' => 'test_meta_2', - ), - ) - ), - ), - ); - - // use --debug flag to view. - codecept_debug( $actual ); - - $this->assertEquals( $expected, $actual ); - } - - public function testOrderMetaDataQueries() { - $id = Relay::toGlobalId( 'shop_order', $this->order_id ); - $query = ' + /** + * Assertion One + */ + $this->set_user( $this->customer_id ); + $actual = graphql( array( 'query' => $query ) ); + $expected = array( + 'data' => array( + 'customer' => array( + 'id' => Relay::toGlobalId( 'customer', $this->customer_id ), + 'metaData' => array( + array( + 'key' => 'meta_1', + 'value' => 'test_meta_1', + ), + array( + 'key' => 'meta_2', + 'value' => 'test_meta_2', + ), + ), + ), + ), + ); + + // use --debug flag to view. + codecept_debug( $actual ); + + $this->assertEquals( $expected, $actual ); + } + + public function testOrderMetaDataQueries() { + $id = Relay::toGlobalId( 'shop_order', $this->order_id ); + $query = ' query ($id: ID!) { order(id: $id) { id @@ -475,62 +527,62 @@ public function testOrderMetaDataQueries() { } '; - // Must be an "shop_manager" or "admin" to query orders not owned by the user. - wp_set_current_user( $this->shop_manager ); - - /** - * Assertion One - */ - $variables = array( 'id' => $id ); - $actual = graphql( - array( - 'query' => $query, - 'variables' => $variables, - ) - ); - $expected = array( - 'data' => array( - 'order' => array( - 'id' => $id, - 'metaData' => array( - array( - 'key' => 'meta_1', - 'value' => 'test_meta_1', - ), - array( - 'key' => 'meta_2', - 'value' => 'test_meta_2', - ), - ), - 'feeLines' => array( - 'nodes' => array( - array( - 'metaData' => array( - array( - 'key' => 'meta_1', - 'value' => 'test_meta_1', - ), - array( - 'key' => 'meta_2', - 'value' => 'test_meta_2', - ), - ), - ), - ), - ), - ), - ), - ); - - // use --debug flag to view. - codecept_debug( $actual ); - - $this->assertEquals( $expected, $actual ); - } - - public function testProductMetaDataQueries() { - $id = Relay::toGlobalId( 'product', $this->product_id ); - $query = ' + // Must be an "shop_manager" or "admin" to query orders not owned by the user. + wp_set_current_user( $this->shop_manager ); + + /** + * Assertion One + */ + $variables = array( 'id' => $id ); + $actual = graphql( + array( + 'query' => $query, + 'variables' => $variables, + ) + ); + $expected = array( + 'data' => array( + 'order' => array( + 'id' => $id, + 'metaData' => array( + array( + 'key' => 'meta_1', + 'value' => 'test_meta_1', + ), + array( + 'key' => 'meta_2', + 'value' => 'test_meta_2', + ), + ), + 'feeLines' => array( + 'nodes' => array( + array( + 'metaData' => array( + array( + 'key' => 'meta_1', + 'value' => 'test_meta_1', + ), + array( + 'key' => 'meta_2', + 'value' => 'test_meta_2', + ), + ), + ), + ), + ), + ), + ), + ); + + // use --debug flag to view. + codecept_debug( $actual ); + + $this->assertEquals( $expected, $actual ); + } + + public function testProductMetaDataQueries() { + $id = Relay::toGlobalId( 'product', $this->product_id ); + $query = ' query ($id: ID!) { product(id: $id) { ... on VariableProduct { @@ -544,43 +596,43 @@ public function testProductMetaDataQueries() { } '; - /** - * Assertion One - */ - $variables = array( 'id' => $id ); - $actual = graphql( - array( - 'query' => $query, - 'variables' => $variables, - ) - ); - $expected = array( - 'data' => array( - 'product' => array( - 'id' => $id, - 'metaData' => array( - array( - 'key' => 'meta_1', - 'value' => 'test_meta_1', - ), - array( - 'key' => 'meta_2', - 'value' => 'test_meta_2', - ), - ) - ), - ), - ); - - // use --debug flag to view. - codecept_debug( $actual ); - - $this->assertEquals( $expected, $actual ); - } - - public function testProductVariationMetaDataQueries() { - $id = Relay::toGlobalId( 'product_variation', $this->variation_ids['variations'][0] ); - $query = ' + /** + * Assertion One + */ + $variables = array( 'id' => $id ); + $actual = graphql( + array( + 'query' => $query, + 'variables' => $variables, + ) + ); + $expected = array( + 'data' => array( + 'product' => array( + 'id' => $id, + 'metaData' => array( + array( + 'key' => 'meta_1', + 'value' => 'test_meta_1', + ), + array( + 'key' => 'meta_2', + 'value' => 'test_meta_2', + ), + ), + ), + ), + ); + + // use --debug flag to view. + codecept_debug( $actual ); + + $this->assertEquals( $expected, $actual ); + } + + public function testProductVariationMetaDataQueries() { + $id = Relay::toGlobalId( 'product_variation', $this->variation_ids['variations'][0] ); + $query = ' query ($id: ID!) { productVariation(id: $id) { id @@ -592,42 +644,42 @@ public function testProductVariationMetaDataQueries() { } '; - /** - * Assertion One - */ - $variables = array( 'id' => $id ); - $actual = graphql( - array( - 'query' => $query, - 'variables' => $variables, - ) - ); - $expected = array( - 'data' => array( - 'productVariation' => array( - 'id' => $id, - 'metaData' => array( - array( - 'key' => 'meta_1', - 'value' => 'test_meta_1', - ), - array( - 'key' => 'meta_2', - 'value' => 'test_meta_2', - ), - ) - ), - ), - ); - - // use --debug flag to view. - codecept_debug( $actual ); - - $this->assertEquals( $expected, $actual ); - } - - public function testRefundMetaDataQueries() { - $id = Relay::toGlobalId( 'shop_order_refund', $this->refund_id ); + /** + * Assertion One + */ + $variables = array( 'id' => $id ); + $actual = graphql( + array( + 'query' => $query, + 'variables' => $variables, + ) + ); + $expected = array( + 'data' => array( + 'productVariation' => array( + 'id' => $id, + 'metaData' => array( + array( + 'key' => 'meta_1', + 'value' => 'test_meta_1', + ), + array( + 'key' => 'meta_2', + 'value' => 'test_meta_2', + ), + ), + ), + ), + ); + + // use --debug flag to view. + codecept_debug( $actual ); + + $this->assertEquals( $expected, $actual ); + } + + public function testRefundMetaDataQueries() { + $id = Relay::toGlobalId( 'shop_order_refund', $this->refund_id ); $query = ' query refundQuery( $id: ID! ) { refund( id: $id ) { @@ -640,38 +692,38 @@ public function testRefundMetaDataQueries() { } '; - /** - * Assertion One - */ - wp_set_current_user( $this->customer ); - $variables = array( 'id' => $id ); - $actual = graphql( - array( - 'query' => $query, - 'variables' => $variables, - ) - ); - $expected = array( - 'data' => array( - 'refund' => array( - 'id' => $id, - 'metaData' => array( - array( - 'key' => 'meta_1', - 'value' => 'test_meta_1', - ), - array( - 'key' => 'meta_2', - 'value' => 'test_meta_2', - ), - ), - ), - ), - ); - - // use --debug flag to view. - codecept_debug( $actual ); - - $this->assertEquals( $expected, $actual ); - } + /** + * Assertion One + */ + wp_set_current_user( $this->customer ); + $variables = array( 'id' => $id ); + $actual = graphql( + array( + 'query' => $query, + 'variables' => $variables, + ) + ); + $expected = array( + 'data' => array( + 'refund' => array( + 'id' => $id, + 'metaData' => array( + array( + 'key' => 'meta_1', + 'value' => 'test_meta_1', + ), + array( + 'key' => 'meta_2', + 'value' => 'test_meta_2', + ), + ), + ), + ), + ); + + // use --debug flag to view. + codecept_debug( $actual ); + + $this->assertEquals( $expected, $actual ); + } } diff --git a/tests/wpunit/OrderItemQueriesTest.php b/tests/wpunit/OrderItemQueriesTest.php index 6428b007c..713ef653c 100644 --- a/tests/wpunit/OrderItemQueriesTest.php +++ b/tests/wpunit/OrderItemQueriesTest.php @@ -5,15 +5,15 @@ class OrderItemQueriesTest extends \Tests\WPGraphQL\WooCommerce\TestCase\WooGraphQLTestCase { - // tests - public function testCouponLinesQuery() { - $order_id = $this->factory->order->createNew(); - $this->factory->order->add_coupon_line( $order_id ); - $order = new WC_Order( $order_id ); - $coupon_lines = $order->get_items( 'coupon' ); - $id = $this->toRelayId( 'shop_order', $order_id ); + // tests + public function testCouponLinesQuery() { + $order_id = $this->factory->order->createNew(); + $this->factory->order->add_coupon_line( $order_id ); + $order = new WC_Order( $order_id ); + $coupon_lines = $order->get_items( 'coupon' ); + $id = $this->toRelayId( 'shop_order', $order_id ); - $query = ' + $query = ' query ($id: ID!) { order(id: $id) { couponLines { @@ -32,42 +32,42 @@ public function testCouponLinesQuery() { } '; - /** + /** * Assertion One * - * tests query and results + * Tests query and results */ - $this->loginAsShopManager(); - $variables = array( 'id' => $id ); - $response = $this->graphql( compact( 'query', 'variables') ); + $this->loginAsShopManager(); + $variables = array( 'id' => $id ); + $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array_map( - function( $item ) { - return $this->expectedNode( - 'order.couponLines.nodes', - array( - $this->expectedField( 'databaseId', $item->get_id() ), - $this->expectedField( 'orderId', $item->get_order_id() ), - $this->expectedField( 'code', $item->get_code() ), - $this->expectedField( 'discount', $this->maybe( $item->get_discount(), self::IS_NULL ) ), - $this->expectedField( 'discountTax', $this->maybe( $item->get_discount_tax(), self::IS_NULL ) ), - $this->expectedField( 'coupon.id', $this->toRelayId( 'shop_coupon', \wc_get_coupon_id_by_code( $item->get_code() ) ) ), - ) - ); - }, - $coupon_lines - ); + function( $item ) { + return $this->expectedNode( + 'order.couponLines.nodes', + array( + $this->expectedField( 'databaseId', $item->get_id() ), + $this->expectedField( 'orderId', $item->get_order_id() ), + $this->expectedField( 'code', $item->get_code() ), + $this->expectedField( 'discount', $this->maybe( $item->get_discount(), self::IS_NULL ) ), + $this->expectedField( 'discountTax', $this->maybe( $item->get_discount_tax(), self::IS_NULL ) ), + $this->expectedField( 'coupon.id', $this->toRelayId( 'shop_coupon', \wc_get_coupon_id_by_code( $item->get_code() ) ) ), + ) + ); + }, + $coupon_lines + ); - $this->assertQuerySuccessful( $response, $expected ); - } + $this->assertQuerySuccessful( $response, $expected ); + } - public function testFeeLinesQuery() { - $order_id = $this->factory->order->createNew(); - $this->factory->order->add_fee( $order_id ); - $order = new WC_Order( $order_id ); - $fee_lines = $order->get_items( 'fee' ); - $id = $this->toRelayId( 'shop_order', $order_id ); + public function testFeeLinesQuery() { + $order_id = $this->factory->order->createNew(); + $this->factory->order->add_fee( $order_id ); + $order = new WC_Order( $order_id ); + $fee_lines = $order->get_items( 'fee' ); + $id = $this->toRelayId( 'shop_order', $order_id ); - $query = ' + $query = ' query ($id: ID!) { order(id: $id) { feeLines { @@ -86,48 +86,48 @@ public function testFeeLinesQuery() { } '; - /** + /** * Assertion One * - * tests query and results + * Tests query and results */ - $this->loginAsShopManager(); - $variables = array( 'id' => $id ); + $this->loginAsShopManager(); + $variables = array( 'id' => $id ); $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array_map( - function( $item ) { - return $this->expectedNode( - 'order.feeLines.nodes', - array( - $this->expectedField( 'databaseId', $item->get_id() ), - $this->expectedField( 'orderId', $item->get_order_id() ), - $this->expectedField( 'amount', $item->get_amount() ), - $this->expectedField( 'name', $item->get_name() ), - $this->expectedField( 'taxStatus', strtoupper( $item->get_tax_status() ) ), - $this->expectedField( 'total', $item->get_total() ), - $this->expectedField( 'totalTax', $this->maybe( $item->get_total_tax(), self::IS_NULL ) ), - $this->expectedField( - 'taxClass', - ! empty( $item->get_tax_class() ) - ? WPEnumType::get_safe_name( $item->get_tax_class() ) - : 'STANDARD' - ), - ) - ); - }, - $fee_lines - ); + function( $item ) { + return $this->expectedNode( + 'order.feeLines.nodes', + array( + $this->expectedField( 'databaseId', $item->get_id() ), + $this->expectedField( 'orderId', $item->get_order_id() ), + $this->expectedField( 'amount', $item->get_amount() ), + $this->expectedField( 'name', $item->get_name() ), + $this->expectedField( 'taxStatus', strtoupper( $item->get_tax_status() ) ), + $this->expectedField( 'total', $item->get_total() ), + $this->expectedField( 'totalTax', $this->maybe( $item->get_total_tax(), self::IS_NULL ) ), + $this->expectedField( + 'taxClass', + ! empty( $item->get_tax_class() ) + ? WPEnumType::get_safe_name( $item->get_tax_class() ) + : 'STANDARD' + ), + ) + ); + }, + $fee_lines + ); - $this->assertQuerySuccessful( $response, $expected ); - } + $this->assertQuerySuccessful( $response, $expected ); + } - public function testShippingLinesQuery() { - $order_id = $this->factory->order->createNew(); - $order = new WC_Order( $order_id ); - $shipping_lines = $order->get_items( 'shipping' ); - $id = $this->toRelayId( 'shop_order', $order_id ); + public function testShippingLinesQuery() { + $order_id = $this->factory->order->createNew(); + $order = new WC_Order( $order_id ); + $shipping_lines = $order->get_items( 'shipping' ); + $id = $this->toRelayId( 'shop_order', $order_id ); - $query = ' + $query = ' query ($id: ID!) { order(id: $id) { shippingLines { @@ -144,49 +144,49 @@ public function testShippingLinesQuery() { } '; - /** + /** * Assertion One * - * tests query and results + * Tests query and results */ - $this->loginAsShopManager(); - $variables = array( 'id' => $id ); + $this->loginAsShopManager(); + $variables = array( 'id' => $id ); $response = $this->graphql( compact( 'query', 'variables' ) ); - $expected = array_map( - function( $item ) { - return $this->expectedNode( - 'order.shippingLines.nodes', - array( - $this->expectedField( 'databaseId', $item->get_id() ), - $this->expectedField( 'orderId', $item->get_order_id() ), - $this->expectedField( 'methodTitle', $item->get_method_title() ), - $this->expectedField( 'total', $item->get_total() ), - $this->expectedField( 'totalTax', $this->maybe( $item->get_total_tax(), self::IS_NULL ) ), - $this->expectedField( - 'taxClass', - ! empty( $item->get_tax_class() ) - ? $item->get_tax_class() === 'inherit' - ? WPEnumType::get_safe_name( 'inherit cart' ) - : WPEnumType::get_safe_name( $item->get_tax_class() ) - : 'STANDARD' - ), - ) - ); - }, - $shipping_lines - ); + $expected = array_map( + function( $item ) { + return $this->expectedNode( + 'order.shippingLines.nodes', + array( + $this->expectedField( 'databaseId', $item->get_id() ), + $this->expectedField( 'orderId', $item->get_order_id() ), + $this->expectedField( 'methodTitle', $item->get_method_title() ), + $this->expectedField( 'total', $item->get_total() ), + $this->expectedField( 'totalTax', $this->maybe( $item->get_total_tax(), self::IS_NULL ) ), + $this->expectedField( + 'taxClass', + ! empty( $item->get_tax_class() ) + ? $item->get_tax_class() === 'inherit' + ? WPEnumType::get_safe_name( 'inherit cart' ) + : WPEnumType::get_safe_name( $item->get_tax_class() ) + : 'STANDARD' + ), + ) + ); + }, + $shipping_lines + ); - $this->assertQuerySuccessful( $response, $expected ); - } + $this->assertQuerySuccessful( $response, $expected ); + } - public function testTaxLinesQuery() { - $order_id = $this->factory->order->createNew(); - $this->factory->order->add_tax( $order_id ); - $order = new WC_Order( $order_id ); - $tax_lines = $order->get_items( 'tax' ); - $id = $this->toRelayId( 'shop_order', $order_id ); + public function testTaxLinesQuery() { + $order_id = $this->factory->order->createNew(); + $this->factory->order->add_tax( $order_id ); + $order = new WC_Order( $order_id ); + $tax_lines = $order->get_items( 'tax' ); + $id = $this->toRelayId( 'shop_order', $order_id ); - $query = ' + $query = ' query ($id: ID!) { order(id: $id) { taxLines { @@ -205,41 +205,41 @@ public function testTaxLinesQuery() { } '; - /** + /** * Assertion One * - * tests query and results + * Tests query and results */ - $this->loginAsShopManager(); - $variables = array( 'id' => $id ); + $this->loginAsShopManager(); + $variables = array( 'id' => $id ); $response = $this->graphql( compact( 'query', 'variables' ) ); - $expected = array_map( - function( $item ) { - return $this->expectedNode( - 'order.taxLines.nodes', - array( - $this->expectedField( 'rateCode', $item->get_rate_code() ), - $this->expectedField( 'label', $item->get_label() ), - $this->expectedField( 'taxTotal', $item->get_tax_total() ), - $this->expectedField( 'shippingTaxTotal', $item->get_shipping_tax_total() ), - $this->expectedField( 'isCompound', $item->is_compound() ), - $this->expectedField( 'taxRate.databaseId', $item->get_rate_id() ), - ) - ); - }, - $tax_lines - ); + $expected = array_map( + function( $item ) { + return $this->expectedNode( + 'order.taxLines.nodes', + array( + $this->expectedField( 'rateCode', $item->get_rate_code() ), + $this->expectedField( 'label', $item->get_label() ), + $this->expectedField( 'taxTotal', $item->get_tax_total() ), + $this->expectedField( 'shippingTaxTotal', $item->get_shipping_tax_total() ), + $this->expectedField( 'isCompound', $item->is_compound() ), + $this->expectedField( 'taxRate.databaseId', $item->get_rate_id() ), + ) + ); + }, + $tax_lines + ); - $this->assertQuerySuccessful( $response, $expected ); - } + $this->assertQuerySuccessful( $response, $expected ); + } - public function testLineItemsQuery() { - $order_id = $this->factory->order->createNew(); - $order = new WC_Order( $order_id ); - $line_items = $order->get_items(); - $id = $this->toRelayId( 'shop_order', $order_id ); + public function testLineItemsQuery() { + $order_id = $this->factory->order->createNew(); + $order = new WC_Order( $order_id ); + $line_items = $order->get_items(); + $id = $this->toRelayId( 'shop_order', $order_id ); - $query = ' + $query = ' query ($id: ID!) { order(id: $id) { lineItems { @@ -273,47 +273,47 @@ public function testLineItemsQuery() { } '; - /** + /** * Assertion One * - * tests query and results + * Tests query and results */ - $this->loginAsShopManager(); - $variables = array( 'id' => $id ); + $this->loginAsShopManager(); + $variables = array( 'id' => $id ); $response = $this->graphql( compact( 'query', 'variables' ) ); - $expected = array_map( - function( $item ) { - return $this->expectedNode( - 'order.lineItems.nodes', - array( - $this->expectedField( 'productId', $item->get_product_id() ), - $this->expectedField( 'variationId', $this->maybe( $item->get_variation_id(), self::IS_NULL ) ), - $this->expectedField( 'quantity', $item->get_quantity() ), - $this->expectedField( - 'taxClass', - ! empty( $item->get_tax_class() ) - ? strtoupper( $item->get_tax_class() ) - : 'STANDARD' - ), - $this->expectedField( 'subtotal', $this->maybe( $item->get_subtotal(), self::IS_NULL ) ), - $this->expectedField( 'subtotalTax', $this->maybe( $item->get_subtotal_tax(), self::IS_NULL ) ), - $this->expectedField( 'total', $this->maybe( $item->get_total(), self::IS_NULL ) ), - $this->expectedField( 'totalTax', $this->maybe( $item->get_total_tax(), self::IS_NULL ) ), - $this->expectedField( 'itemDownloads', null ), - $this->expectedField( 'taxStatus', strtoupper( $item->get_tax_status() ) ), - $this->expectedField( 'product.id', $this->toRelayId( 'product', $item->get_product_id() ) ), - $this->expectedField( - 'variation.id', - ! empty( $item->get_variation_id() ) - ? $this->toRelayId( 'product_variation', $item->get_variation_id() ) - : null - ), - ) - ); - }, - $line_items - ); + $expected = array_map( + function( $item ) { + return $this->expectedNode( + 'order.lineItems.nodes', + array( + $this->expectedField( 'productId', $item->get_product_id() ), + $this->expectedField( 'variationId', $this->maybe( $item->get_variation_id(), self::IS_NULL ) ), + $this->expectedField( 'quantity', $item->get_quantity() ), + $this->expectedField( + 'taxClass', + ! empty( $item->get_tax_class() ) + ? strtoupper( $item->get_tax_class() ) + : 'STANDARD' + ), + $this->expectedField( 'subtotal', $this->maybe( $item->get_subtotal(), self::IS_NULL ) ), + $this->expectedField( 'subtotalTax', $this->maybe( $item->get_subtotal_tax(), self::IS_NULL ) ), + $this->expectedField( 'total', $this->maybe( $item->get_total(), self::IS_NULL ) ), + $this->expectedField( 'totalTax', $this->maybe( $item->get_total_tax(), self::IS_NULL ) ), + $this->expectedField( 'itemDownloads', null ), + $this->expectedField( 'taxStatus', strtoupper( $item->get_tax_status() ) ), + $this->expectedField( 'product.id', $this->toRelayId( 'product', $item->get_product_id() ) ), + $this->expectedField( + 'variation.id', + ! empty( $item->get_variation_id() ) + ? $this->toRelayId( 'product_variation', $item->get_variation_id() ) + : null + ), + ) + ); + }, + $line_items + ); - $this->assertQuerySuccessful( $response, $expected ); - } + $this->assertQuerySuccessful( $response, $expected ); + } } diff --git a/tests/wpunit/OrderMutationsTest.php b/tests/wpunit/OrderMutationsTest.php index 16d47e5f1..b65839f88 100644 --- a/tests/wpunit/OrderMutationsTest.php +++ b/tests/wpunit/OrderMutationsTest.php @@ -4,53 +4,46 @@ class OrderMutationsTest extends \Codeception\TestCase\WPTestCase { - public function setUp(): void { - // before - parent::setUp(); - - // Create users. - $this->shop_manager = $this->factory->user->create( array( 'role' => 'shop_manager' ) ); - $this->customer = $this->factory->user->create( array( 'role' => 'customer' ) ); - - // Get helper instances - $this->order = $this->getModule('\Helper\Wpunit')->order(); - $this->coupon = $this->getModule('\Helper\Wpunit')->coupon(); - $this->product = $this->getModule('\Helper\Wpunit')->product(); - $this->variation = $this->getModule('\Helper\Wpunit')->product_variation(); - $this->cart = $this->getModule('\Helper\Wpunit')->cart(); - $this->tax = $this->getModule('\Helper\Wpunit')->tax_rate(); - - // Turn on tax calculations. Important! - update_option( 'woocommerce_prices_include_tax', 'no' ); + public function setUp(): void { + // before + parent::setUp(); + + // Create users. + $this->shop_manager = $this->factory->user->create( array( 'role' => 'shop_manager' ) ); + $this->customer = $this->factory->user->create( array( 'role' => 'customer' ) ); + + // Get helper instances + $this->order = $this->getModule( '\Helper\Wpunit' )->order(); + $this->coupon = $this->getModule( '\Helper\Wpunit' )->coupon(); + $this->product = $this->getModule( '\Helper\Wpunit' )->product(); + $this->variation = $this->getModule( '\Helper\Wpunit' )->product_variation(); + $this->cart = $this->getModule( '\Helper\Wpunit' )->cart(); + $this->tax = $this->getModule( '\Helper\Wpunit' )->tax_rate(); + + // Turn on tax calculations. Important! + update_option( 'woocommerce_prices_include_tax', 'no' ); update_option( 'woocommerce_calc_taxes', 'yes' ); update_option( 'woocommerce_tax_round_at_subtotal', 'no' ); - // Create a tax rate. - $this->tax->create( - array( - 'country' => '', - 'state' => '', - 'rate' => 20.000, - 'name' => 'VAT', - 'priority' => '1', - 'compound' => '0', - 'shipping' => '1', - 'class' => '' - ) - ); - // Create sample order to be used as a parent order. - $this->order_id = $this->order->create(); - } - - public function tearDown(): void { - // your tear down methods here - - // then - parent::tearDown(); - } - - private function orderMutation( $input, $operation_name = 'createOrder', $input_type = 'CreateOrderInput' ) { - $mutation = " + // Create a tax rate. + $this->tax->create( + array( + 'country' => '', + 'state' => '', + 'rate' => 20.000, + 'name' => 'VAT', + 'priority' => '1', + 'compound' => '0', + 'shipping' => '1', + 'class' => '', + ) + ); + // Create sample order to be used as a parent order. + $this->order_id = $this->order->create(); + } + + private function orderMutation( $input, $operation_name = 'createOrder', $input_type = 'CreateOrderInput' ) { + $mutation = " mutation {$operation_name}( \$input: {$input_type}! ) { {$operation_name}( input: \$input ) { clientMutationId @@ -211,887 +204,885 @@ private function orderMutation( $input, $operation_name = 'createOrder', $input_ } "; - $actual = graphql( - array( - 'query' => $mutation, - 'operation_name' => $operation_name, - 'variables' => array( 'input' => $input ), - ) - ); - - return $actual; - } - - // tests - public function testCreateOrderMutation() { - $variable = $this->variation->create( $this->product->create_variable() ); - $product_ids = array( - $this->product->create_simple(), - $this->product->create_simple(), - $variable['product'], - ); - $coupon = new WC_Coupon( - $this->coupon->create( array( 'product_ids' => $product_ids ) ) - ); - - $input = array( - 'clientMutationId' => 'someId', + $actual = graphql( + array( + 'query' => $mutation, + 'operation_name' => $operation_name, + 'variables' => array( 'input' => $input ), + ) + ); + + return $actual; + } + + // tests + public function testCreateOrderMutation() { + $variable = $this->variation->create( $this->product->create_variable() ); + $product_ids = array( + $this->product->create_simple(), + $this->product->create_simple(), + $variable['product'], + ); + $coupon = new WC_Coupon( + $this->coupon->create( array( 'product_ids' => $product_ids ) ) + ); + + $input = array( + 'clientMutationId' => 'someId', 'customerId' => $this->customer, 'customerNote' => 'Customer test note', 'coupons' => array( - $coupon->get_code(), - ), + $coupon->get_code(), + ), 'paymentMethod' => 'bacs', - 'paymentMethodTitle' => 'Direct Bank Transfer', + 'paymentMethodTitle' => 'Direct Bank Transfer', 'billing' => array( - 'firstName' => 'May', - 'lastName' => 'Parker', - 'address1' => '20 Ingram St', - 'city' => 'New York City', - 'state' => 'NY', - 'postcode' => '12345', - 'country' => 'US', - 'email' => 'superfreak500@gmail.com', - 'phone' => '555-555-1234', - ), + 'firstName' => 'May', + 'lastName' => 'Parker', + 'address1' => '20 Ingram St', + 'city' => 'New York City', + 'state' => 'NY', + 'postcode' => '12345', + 'country' => 'US', + 'email' => 'superfreak500@gmail.com', + 'phone' => '555-555-1234', + ), 'shipping' => array( - 'firstName' => 'May', - 'lastName' => 'Parker', - 'address1' => '20 Ingram St', - 'city' => 'New York City', - 'state' => 'NY', - 'postcode' => '12345', - 'country' => 'US', - ), + 'firstName' => 'May', + 'lastName' => 'Parker', + 'address1' => '20 Ingram St', + 'city' => 'New York City', + 'state' => 'NY', + 'postcode' => '12345', + 'country' => 'US', + ), 'lineItems' => array( - array( - 'productId' => $product_ids[0], - 'quantity' => 5, - 'metaData' => array( - array( - 'key' => 'test_product_key', - 'value' => 'test product value', - ), - ), - ), - array( - 'productId' => $product_ids[1], - 'quantity' => 2, - ), - array( - 'productId' => $product_ids[2], - 'quantity' => 6, - 'variationId' => $variable['variations'][0] - ), - ), - 'shippingLines' => array( - array( - 'methodId' => 'flat_rate_shipping', - 'methodTitle' => 'Flat Rate shipping', - 'total' => '10', - ), - ), + array( + 'productId' => $product_ids[0], + 'quantity' => 5, + 'metaData' => array( + array( + 'key' => 'test_product_key', + 'value' => 'test product value', + ), + ), + ), + array( + 'productId' => $product_ids[1], + 'quantity' => 2, + ), + array( + 'productId' => $product_ids[2], + 'quantity' => 6, + 'variationId' => $variable['variations'][0], + ), + ), + 'shippingLines' => array( + array( + 'methodId' => 'flat_rate_shipping', + 'methodTitle' => 'Flat Rate shipping', + 'total' => '10', + ), + ), 'feeLines' => array( - array( - 'name' => 'Some Fee', - 'taxStatus' => 'TAXABLE', - 'total' => '100', - 'taxClass' => 'STANDARD', - ), - ), + array( + 'name' => 'Some Fee', + 'taxStatus' => 'TAXABLE', + 'total' => '100', + 'taxClass' => 'STANDARD', + ), + ), 'metaData' => array( - array( - 'key' => 'test_key', - 'value' => 'test value', - ), - ), + array( + 'key' => 'test_key', + 'value' => 'test value', + ), + ), 'isPaid' => true, - ); + ); - /** + /** * Assertion One * * User without necessary capabilities cannot create order an order. */ wp_set_current_user( $this->customer ); - $actual = $this->orderMutation( $input ); + $actual = $this->orderMutation( $input ); - // use --debug flag to view. - codecept_debug( $actual ); + // use --debug flag to view. + codecept_debug( $actual ); - $this->assertArrayHasKey('errors', $actual ); + $this->assertArrayHasKey( 'errors', $actual ); - /** + /** * Assertion Two * * Test mutation and input. */ wp_set_current_user( $this->shop_manager ); - $actual = $this->orderMutation( $input ); - - // use --debug flag to view. - codecept_debug( $actual ); - - $this->assertArrayHasKey('data', $actual ); - $this->assertArrayHasKey('createOrder', $actual['data'] ); - $this->assertArrayHasKey('order', $actual['data']['createOrder'] ); - $this->assertArrayHasKey('id', $actual['data']['createOrder']['order'] ); - $order = \WC_Order_Factory::get_order( $actual['data']['createOrder']['order']['databaseId'] ); - - $expected = array( - 'data' => array( - 'createOrder' => array( - 'clientMutationId' => 'someId', - 'order' => array_merge( - $this->order->print_query( $order->get_id() ), - array( - 'couponLines' => array( - 'nodes' => array_reverse( - array_map( - function( $item ) { - return array( - 'databaseId' => $item->get_id(), - 'orderId' => $item->get_order_id(), - 'code' => $item->get_code(), - 'discount' => ! empty( $item->get_discount() ) ? $item->get_discount() : null, - 'discountTax' => ! empty( $item->get_discount_tax() ) ? $item->get_discount_tax() : null, - 'coupon' => array( - 'id' => $this->coupon->to_relay_id( \wc_get_coupon_id_by_code( $item->get_code() ) ), - ), - ); - }, - $order->get_items( 'coupon' ) - ) - ), - ), - 'feeLines' => array( - 'nodes' => array_reverse( - array_map( - function( $item ) { - return array( - 'databaseId' => $item->get_id(), - 'orderId' => $item->get_order_id(), - 'amount' => $item->get_amount(), - 'name' => $item->get_name(), - 'taxStatus' => strtoupper( $item->get_tax_status() ), - 'total' => $item->get_total(), - 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, - 'taxClass' => ! empty( $item->get_tax_class() ) - ? WPEnumType::get_safe_name( $item->get_tax_class() ) - : 'STANDARD', - ); - }, - $order->get_items( 'fee' ) - ) - ), - ), - 'shippingLines' => array( - 'nodes' => array_reverse( - array_map( - function( $item ) { - - return array( - 'databaseId' => $item->get_id(), - 'orderId' => $item->get_order_id(), - 'methodTitle' => $item->get_method_title(), - 'total' => $item->get_total(), - 'totalTax' => !empty( $item->get_total_tax() ) - ? $item->get_total_tax() - : null, - 'taxClass' => ! empty( $item->get_tax_class() ) - ? $item->get_tax_class() === 'inherit' - ? WPEnumType::get_safe_name( 'inherit cart' ) - : WPEnumType::get_safe_name( $item->get_tax_class() ) - : 'STANDARD' - ); - }, - $order->get_items( 'shipping' ) - ) - ), - ), - 'taxLines' => array( - 'nodes' => array_reverse( - array_map( - function( $item ) { - return array( - 'rateCode' => $item->get_rate_code(), - 'label' => $item->get_label(), - 'taxTotal' => $item->get_tax_total(), - 'shippingTaxTotal' => $item->get_shipping_tax_total(), - 'isCompound' => $item->is_compound(), - 'taxRate' => array( 'databaseId' => $item->get_rate_id() ), - ); - }, - $order->get_items( 'tax' ) - ) - ), - ), - 'lineItems' => array( - 'nodes' => array_values( - array_map( - function( $item ) { - return array( - 'productId' => $item->get_product_id(), - 'variationId' => ! empty( $item->get_variation_id() ) - ? $item->get_variation_id() - : null, - 'quantity' => $item->get_quantity(), - 'taxClass' => ! empty( $item->get_tax_class() ) - ? strtoupper( $item->get_tax_class() ) - : 'STANDARD', - 'subtotal' => ! empty( $item->get_subtotal() ) ? $item->get_subtotal() : null, - 'subtotalTax' => ! empty( $item->get_subtotal_tax() ) ? $item->get_subtotal_tax() : null, - 'total' => ! empty( $item->get_total() ) ? $item->get_total() : null, - 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, - 'taxStatus' => strtoupper( $item->get_tax_status() ), - 'product' => array( 'id' => $this->product->to_relay_id( $item->get_product_id() ) ), - 'variation' => ! empty( $item->get_variation_id() ) - ? array( - 'id' => $this->variation->to_relay_id( $item->get_variation_id() ) - ) - : null, - ); - }, - $order->get_items() - ) - ), - ), - ) - ) - ), - ) - ); - - $this->assertEquals( $expected, $actual ); - } - - public function testUpdateOrderMutation() { - // Create products and coupons to be used in order creation. - $variable = $this->variation->create( $this->product->create_variable() ); - $product_ids = array( - $this->product->create_simple(), - $this->product->create_simple(), - $variable['product'], - ); - $coupon = new WC_Coupon( - $this->coupon->create( array( 'product_ids' => $product_ids ) ) - ); - - // Create initial order input. - $initial_input = array( - 'clientMutationId' => 'someId', + $actual = $this->orderMutation( $input ); + + // use --debug flag to view. + codecept_debug( $actual ); + + $this->assertArrayHasKey( 'data', $actual ); + $this->assertArrayHasKey( 'createOrder', $actual['data'] ); + $this->assertArrayHasKey( 'order', $actual['data']['createOrder'] ); + $this->assertArrayHasKey( 'id', $actual['data']['createOrder']['order'] ); + $order = \WC_Order_Factory::get_order( $actual['data']['createOrder']['order']['databaseId'] ); + + $expected = array( + 'data' => array( + 'createOrder' => array( + 'clientMutationId' => 'someId', + 'order' => array_merge( + $this->order->print_query( $order->get_id() ), + array( + 'couponLines' => array( + 'nodes' => array_reverse( + array_map( + function( $item ) { + return array( + 'databaseId' => $item->get_id(), + 'orderId' => $item->get_order_id(), + 'code' => $item->get_code(), + 'discount' => ! empty( $item->get_discount() ) ? $item->get_discount() : null, + 'discountTax' => ! empty( $item->get_discount_tax() ) ? $item->get_discount_tax() : null, + 'coupon' => array( + 'id' => $this->coupon->to_relay_id( \wc_get_coupon_id_by_code( $item->get_code() ) ), + ), + ); + }, + $order->get_items( 'coupon' ) + ) + ), + ), + 'feeLines' => array( + 'nodes' => array_reverse( + array_map( + function( $item ) { + return array( + 'databaseId' => $item->get_id(), + 'orderId' => $item->get_order_id(), + 'amount' => $item->get_amount(), + 'name' => $item->get_name(), + 'taxStatus' => strtoupper( $item->get_tax_status() ), + 'total' => $item->get_total(), + 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, + 'taxClass' => ! empty( $item->get_tax_class() ) + ? WPEnumType::get_safe_name( $item->get_tax_class() ) + : 'STANDARD', + ); + }, + $order->get_items( 'fee' ) + ) + ), + ), + 'shippingLines' => array( + 'nodes' => array_reverse( + array_map( + function( $item ) { + return array( + 'databaseId' => $item->get_id(), + 'orderId' => $item->get_order_id(), + 'methodTitle' => $item->get_method_title(), + 'total' => $item->get_total(), + 'totalTax' => ! empty( $item->get_total_tax() ) + ? $item->get_total_tax() + : null, + 'taxClass' => ! empty( $item->get_tax_class() ) + ? $item->get_tax_class() === 'inherit' + ? WPEnumType::get_safe_name( 'inherit cart' ) + : WPEnumType::get_safe_name( $item->get_tax_class() ) + : 'STANDARD', + ); + }, + $order->get_items( 'shipping' ) + ) + ), + ), + 'taxLines' => array( + 'nodes' => array_reverse( + array_map( + function( $item ) { + return array( + 'rateCode' => $item->get_rate_code(), + 'label' => $item->get_label(), + 'taxTotal' => $item->get_tax_total(), + 'shippingTaxTotal' => $item->get_shipping_tax_total(), + 'isCompound' => $item->is_compound(), + 'taxRate' => array( 'databaseId' => $item->get_rate_id() ), + ); + }, + $order->get_items( 'tax' ) + ) + ), + ), + 'lineItems' => array( + 'nodes' => array_values( + array_map( + function( $item ) { + return array( + 'productId' => $item->get_product_id(), + 'variationId' => ! empty( $item->get_variation_id() ) + ? $item->get_variation_id() + : null, + 'quantity' => $item->get_quantity(), + 'taxClass' => ! empty( $item->get_tax_class() ) + ? strtoupper( $item->get_tax_class() ) + : 'STANDARD', + 'subtotal' => ! empty( $item->get_subtotal() ) ? $item->get_subtotal() : null, + 'subtotalTax' => ! empty( $item->get_subtotal_tax() ) ? $item->get_subtotal_tax() : null, + 'total' => ! empty( $item->get_total() ) ? $item->get_total() : null, + 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, + 'taxStatus' => strtoupper( $item->get_tax_status() ), + 'product' => array( 'id' => $this->product->to_relay_id( $item->get_product_id() ) ), + 'variation' => ! empty( $item->get_variation_id() ) + ? array( + 'id' => $this->variation->to_relay_id( $item->get_variation_id() ), + ) + : null, + ); + }, + $order->get_items() + ) + ), + ), + ) + ), + ), + ), + ); + + $this->assertEquals( $expected, $actual ); + } + + public function testUpdateOrderMutation() { + // Create products and coupons to be used in order creation. + $variable = $this->variation->create( $this->product->create_variable() ); + $product_ids = array( + $this->product->create_simple(), + $this->product->create_simple(), + $variable['product'], + ); + $coupon = new WC_Coupon( + $this->coupon->create( array( 'product_ids' => $product_ids ) ) + ); + + // Create initial order input. + $initial_input = array( + 'clientMutationId' => 'someId', 'customerId' => $this->customer, 'customerNote' => 'Customer test note', 'coupons' => array( - $coupon->get_code(), - ), + $coupon->get_code(), + ), 'paymentMethod' => 'bacs', - 'paymentMethodTitle' => 'Direct Bank Transfer', + 'paymentMethodTitle' => 'Direct Bank Transfer', 'billing' => array( - 'firstName' => 'May', - 'lastName' => 'Parker', - 'address1' => '20 Ingram St', - 'city' => 'New York City', - 'state' => 'NY', - 'postcode' => '12345', - 'country' => 'US', - 'email' => 'superfreak500@gmail.com', - 'phone' => '555-555-1234', - ), + 'firstName' => 'May', + 'lastName' => 'Parker', + 'address1' => '20 Ingram St', + 'city' => 'New York City', + 'state' => 'NY', + 'postcode' => '12345', + 'country' => 'US', + 'email' => 'superfreak500@gmail.com', + 'phone' => '555-555-1234', + ), 'shipping' => array( - 'firstName' => 'May', - 'lastName' => 'Parker', - 'address1' => '20 Ingram St', - 'city' => 'New York City', - 'state' => 'NY', - 'postcode' => '12345', - 'country' => 'US', - ), + 'firstName' => 'May', + 'lastName' => 'Parker', + 'address1' => '20 Ingram St', + 'city' => 'New York City', + 'state' => 'NY', + 'postcode' => '12345', + 'country' => 'US', + ), 'lineItems' => array( - array( - 'productId' => $product_ids[0], - 'quantity' => 5, - 'metaData' => array( - array( - 'key' => 'test_product_key', - 'value' => 'test product value', - ), - ), - ), - array( - 'productId' => $product_ids[1], - 'quantity' => 2, - ), - array( - 'productId' => $product_ids[2], - 'quantity' => 6, - 'variationId' => $variable['variations'][0] - ), - ), - 'shippingLines' => array( - array( - 'methodId' => 'flat_rate_shipping', - 'methodTitle' => 'Flat Rate shipping', - 'total' => '10', - ), - ), + array( + 'productId' => $product_ids[0], + 'quantity' => 5, + 'metaData' => array( + array( + 'key' => 'test_product_key', + 'value' => 'test product value', + ), + ), + ), + array( + 'productId' => $product_ids[1], + 'quantity' => 2, + ), + array( + 'productId' => $product_ids[2], + 'quantity' => 6, + 'variationId' => $variable['variations'][0], + ), + ), + 'shippingLines' => array( + array( + 'methodId' => 'flat_rate_shipping', + 'methodTitle' => 'Flat Rate shipping', + 'total' => '10', + ), + ), 'feeLines' => array( - array( - 'name' => 'Some Fee', - 'taxStatus' => 'TAXABLE', - 'total' => '100', - 'taxClass' => 'STANDARD', - ), - ), + array( + 'name' => 'Some Fee', + 'taxStatus' => 'TAXABLE', + 'total' => '100', + 'taxClass' => 'STANDARD', + ), + ), 'metaData' => array( - array( - 'key' => 'test_key', - 'value' => 'test value', - ), - ), + array( + 'key' => 'test_key', + 'value' => 'test value', + ), + ), 'isPaid' => false, - ); + ); - // Create order to update. + // Create order to update. wp_set_current_user( $this->shop_manager ); - $initial_response = $this->orderMutation( $initial_input ); - - // use --debug flag to view. - codecept_debug( $initial_response ); - - // Retrieve order and items - $order = \WC_Order_Factory::get_order( $initial_response['data']['createOrder']['order']['databaseId'] ); - $line_items = $order->get_items(); - $shipping_lines = $order->get_items( 'shipping' ); - $fee_lines = $order->get_items( 'fee' ); - - // Create update order input. - $updated_input = array( - 'id' => $this->order->to_relay_id( $order->get_id() ), - 'clientMutationId' => 'someId', - 'customerNote' => 'Customer test note', - 'coupons' => array( - $coupon->get_code(), - ), - 'billing' => array( - 'firstName' => 'Ben', - ), - 'shipping' => array( - 'firstName' => 'Ben', - ), - 'lineItems' => array( - array( - - 'id' => array_keys( $line_items )[0], - 'quantity' => 6, - 'metaData' => array( - array( - 'key' => 'test_product_key', - 'value' => 'updated test product value', - ), - ), - ), - array( - 'id' => array_keys( $line_items )[1], - 'quantity' => 1, - ), - array( - 'id' => array_keys( $line_items )[2], - 'quantity' => 10, - ), - ), - 'shippingLines' => array( - array( - 'id' => array_keys( $shipping_lines )[0], - 'methodId' => 'reduced_rate_shipping', - 'methodTitle' => 'reduced Rate shipping', - 'total' => '7', - ), - ), - 'feeLines' => array( - array( - 'id' => array_keys( $fee_lines )[0], - 'name' => 'Some Updated Fee', - 'taxStatus' => 'TAXABLE', - 'total' => '125', - 'taxClass' => 'STANDARD', - ), - ), - 'metaData' => array( - array( - 'key' => 'test_key', - 'value' => 'new test value', - ), - ), - 'isPaid' => true, - ); - - /** + $initial_response = $this->orderMutation( $initial_input ); + + // use --debug flag to view. + codecept_debug( $initial_response ); + + // Retrieve order and items + $order = \WC_Order_Factory::get_order( $initial_response['data']['createOrder']['order']['databaseId'] ); + $line_items = $order->get_items(); + $shipping_lines = $order->get_items( 'shipping' ); + $fee_lines = $order->get_items( 'fee' ); + + // Create update order input. + $updated_input = array( + 'id' => $this->order->to_relay_id( $order->get_id() ), + 'clientMutationId' => 'someId', + 'customerNote' => 'Customer test note', + 'coupons' => array( + $coupon->get_code(), + ), + 'billing' => array( + 'firstName' => 'Ben', + ), + 'shipping' => array( + 'firstName' => 'Ben', + ), + 'lineItems' => array( + array( + + 'id' => array_keys( $line_items )[0], + 'quantity' => 6, + 'metaData' => array( + array( + 'key' => 'test_product_key', + 'value' => 'updated test product value', + ), + ), + ), + array( + 'id' => array_keys( $line_items )[1], + 'quantity' => 1, + ), + array( + 'id' => array_keys( $line_items )[2], + 'quantity' => 10, + ), + ), + 'shippingLines' => array( + array( + 'id' => array_keys( $shipping_lines )[0], + 'methodId' => 'reduced_rate_shipping', + 'methodTitle' => 'reduced Rate shipping', + 'total' => '7', + ), + ), + 'feeLines' => array( + array( + 'id' => array_keys( $fee_lines )[0], + 'name' => 'Some Updated Fee', + 'taxStatus' => 'TAXABLE', + 'total' => '125', + 'taxClass' => 'STANDARD', + ), + ), + 'metaData' => array( + array( + 'key' => 'test_key', + 'value' => 'new test value', + ), + ), + 'isPaid' => true, + ); + + /** * Assertion One * * User without necessary capabilities cannot update order an order. */ - wp_set_current_user( $this->customer ); - $actual = $this->orderMutation( - $updated_input, - 'updateOrder', - 'UpdateOrderInput' - ); + wp_set_current_user( $this->customer ); + $actual = $this->orderMutation( + $updated_input, + 'updateOrder', + 'UpdateOrderInput' + ); - // use --debug flag to view. - codecept_debug( $actual ); + // use --debug flag to view. + codecept_debug( $actual ); - $this->assertArrayHasKey('errors', $actual ); + $this->assertArrayHasKey( 'errors', $actual ); - /** + /** * Assertion Two * * Test mutation and input. */ wp_set_current_user( $this->shop_manager ); - $actual = $this->orderMutation( - $updated_input, - 'updateOrder', - 'UpdateOrderInput' - ); - - // use --debug flag to view. - codecept_debug( $actual ); - - // Apply new changes to order instances. - $order = \WC_Order_Factory::get_order( $order->get_id() ); - - $expected = array( - 'data' => array( - 'updateOrder' => array( - 'clientMutationId' => 'someId', - 'order' => array_merge( - $this->order->print_query( $order->get_id() ), - array( - 'couponLines' => array( - 'nodes' => array_reverse( - array_map( - function( $item ) { - return array( - 'databaseId' => $item->get_id(), - 'orderId' => $item->get_order_id(), - 'code' => $item->get_code(), - 'discount' => ! empty( $item->get_discount() ) ? $item->get_discount() : null, - 'discountTax' => ! empty( $item->get_discount_tax() ) ? $item->get_discount_tax() : null, - 'coupon' => array( - 'id' => $this->coupon->to_relay_id( \wc_get_coupon_id_by_code( $item->get_code() ) ), - ), - ); - }, - $order->get_items( 'coupon' ) - ) - ), - ), - 'feeLines' => array( - 'nodes' => array_reverse( - array_map( - function( $item ) { - return array( - 'databaseId'=> $item->get_id(), - 'orderId' => $item->get_order_id(), - 'amount' => ! empty( $item->get_amount() ) ? $item->get_amount() : null, - 'name' => $item->get_name(), - 'taxStatus' => strtoupper( $item->get_tax_status() ), - 'total' => $item->get_total(), - 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, - 'taxClass' => ! empty( $item->get_tax_class() ) - ? WPEnumType::get_safe_name( $item->get_tax_class() ) - : 'STANDARD', - ); - }, - $order->get_items( 'fee' ) - ) - ), - ), - 'shippingLines' => array( - 'nodes' => array_reverse( - array_map( - function( $item ) { - - return array( - 'databaseId' => $item->get_id(), - 'orderId' => $item->get_order_id(), - 'methodTitle' => $item->get_method_title(), - 'total' => $item->get_total(), - 'totalTax' => !empty( $item->get_total_tax() ) - ? $item->get_total_tax() - : null, - 'taxClass' => ! empty( $item->get_tax_class() ) - ? $item->get_tax_class() === 'inherit' - ? WPEnumType::get_safe_name( 'inherit cart' ) - : WPEnumType::get_safe_name( $item->get_tax_class() ) - : 'STANDARD' - ); - }, - $order->get_items( 'shipping' ) - ) - ), - ), - 'taxLines' => array( - 'nodes' => array_reverse( - array_map( - function( $item ) { - return array( - 'rateCode' => $item->get_rate_code(), - 'label' => $item->get_label(), - 'taxTotal' => $item->get_tax_total(), - 'shippingTaxTotal' => $item->get_shipping_tax_total(), - 'isCompound' => $item->is_compound(), - 'taxRate' => array( 'databaseId' => $item->get_rate_id() ), - ); - }, - $order->get_items( 'tax' ) - ) - ), - ), - 'lineItems' => array( - 'nodes' => array_values( - array_map( - function( $item ) { - return array( - 'productId' => $item->get_product_id(), - 'variationId' => ! empty( $item->get_variation_id() ) - ? $item->get_variation_id() - : null, - 'quantity' => $item->get_quantity(), - 'taxClass' => ! empty( $item->get_tax_class() ) - ? strtoupper( $item->get_tax_class() ) - : 'STANDARD', - 'subtotal' => ! empty( $item->get_subtotal() ) ? $item->get_subtotal() : null, - 'subtotalTax' => ! empty( $item->get_subtotal_tax() ) ? $item->get_subtotal_tax() : null, - 'total' => ! empty( $item->get_total() ) ? $item->get_total() : null, - 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, - 'taxStatus' => strtoupper( $item->get_tax_status() ), - 'product' => array( 'id' => $this->product->to_relay_id( $item->get_product_id() ) ), - 'variation' => ! empty( $item->get_variation_id() ) - ? array( - 'id' => $this->variation->to_relay_id( $item->get_variation_id() ) - ) - : null, - ); - }, - $order->get_items() - ) - ), - ), - ) - ) - ), - ) - ); - - $this->assertEquals( $expected, $actual ); - $this->assertNotEquals( $initial_response, $actual ); - } - - public function testDeleteOrderMutation() { - // Create products and coupons to be used in order creation. - $variable = $this->variation->create( $this->product->create_variable() ); - $product_ids = array( - $this->product->create_simple(), - $this->product->create_simple(), - $variable['product'], - ); - $coupon = new WC_Coupon( - $this->coupon->create( array( 'product_ids' => $product_ids ) ) - ); - - // Create initial order input. - $initial_input = array( - 'clientMutationId' => 'someId', + $actual = $this->orderMutation( + $updated_input, + 'updateOrder', + 'UpdateOrderInput' + ); + + // use --debug flag to view. + codecept_debug( $actual ); + + // Apply new changes to order instances. + $order = \WC_Order_Factory::get_order( $order->get_id() ); + + $expected = array( + 'data' => array( + 'updateOrder' => array( + 'clientMutationId' => 'someId', + 'order' => array_merge( + $this->order->print_query( $order->get_id() ), + array( + 'couponLines' => array( + 'nodes' => array_reverse( + array_map( + function( $item ) { + return array( + 'databaseId' => $item->get_id(), + 'orderId' => $item->get_order_id(), + 'code' => $item->get_code(), + 'discount' => ! empty( $item->get_discount() ) ? $item->get_discount() : null, + 'discountTax' => ! empty( $item->get_discount_tax() ) ? $item->get_discount_tax() : null, + 'coupon' => array( + 'id' => $this->coupon->to_relay_id( \wc_get_coupon_id_by_code( $item->get_code() ) ), + ), + ); + }, + $order->get_items( 'coupon' ) + ) + ), + ), + 'feeLines' => array( + 'nodes' => array_reverse( + array_map( + function( $item ) { + return array( + 'databaseId' => $item->get_id(), + 'orderId' => $item->get_order_id(), + 'amount' => ! empty( $item->get_amount() ) ? $item->get_amount() : null, + 'name' => $item->get_name(), + 'taxStatus' => strtoupper( $item->get_tax_status() ), + 'total' => $item->get_total(), + 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, + 'taxClass' => ! empty( $item->get_tax_class() ) + ? WPEnumType::get_safe_name( $item->get_tax_class() ) + : 'STANDARD', + ); + }, + $order->get_items( 'fee' ) + ) + ), + ), + 'shippingLines' => array( + 'nodes' => array_reverse( + array_map( + function( $item ) { + return array( + 'databaseId' => $item->get_id(), + 'orderId' => $item->get_order_id(), + 'methodTitle' => $item->get_method_title(), + 'total' => $item->get_total(), + 'totalTax' => ! empty( $item->get_total_tax() ) + ? $item->get_total_tax() + : null, + 'taxClass' => ! empty( $item->get_tax_class() ) + ? $item->get_tax_class() === 'inherit' + ? WPEnumType::get_safe_name( 'inherit cart' ) + : WPEnumType::get_safe_name( $item->get_tax_class() ) + : 'STANDARD', + ); + }, + $order->get_items( 'shipping' ) + ) + ), + ), + 'taxLines' => array( + 'nodes' => array_reverse( + array_map( + function( $item ) { + return array( + 'rateCode' => $item->get_rate_code(), + 'label' => $item->get_label(), + 'taxTotal' => $item->get_tax_total(), + 'shippingTaxTotal' => $item->get_shipping_tax_total(), + 'isCompound' => $item->is_compound(), + 'taxRate' => array( 'databaseId' => $item->get_rate_id() ), + ); + }, + $order->get_items( 'tax' ) + ) + ), + ), + 'lineItems' => array( + 'nodes' => array_values( + array_map( + function( $item ) { + return array( + 'productId' => $item->get_product_id(), + 'variationId' => ! empty( $item->get_variation_id() ) + ? $item->get_variation_id() + : null, + 'quantity' => $item->get_quantity(), + 'taxClass' => ! empty( $item->get_tax_class() ) + ? strtoupper( $item->get_tax_class() ) + : 'STANDARD', + 'subtotal' => ! empty( $item->get_subtotal() ) ? $item->get_subtotal() : null, + 'subtotalTax' => ! empty( $item->get_subtotal_tax() ) ? $item->get_subtotal_tax() : null, + 'total' => ! empty( $item->get_total() ) ? $item->get_total() : null, + 'totalTax' => ! empty( $item->get_total_tax() ) ? $item->get_total_tax() : null, + 'taxStatus' => strtoupper( $item->get_tax_status() ), + 'product' => array( 'id' => $this->product->to_relay_id( $item->get_product_id() ) ), + 'variation' => ! empty( $item->get_variation_id() ) + ? array( + 'id' => $this->variation->to_relay_id( $item->get_variation_id() ), + ) + : null, + ); + }, + $order->get_items() + ) + ), + ), + ) + ), + ), + ), + ); + + $this->assertEquals( $expected, $actual ); + $this->assertNotEquals( $initial_response, $actual ); + } + + public function testDeleteOrderMutation() { + // Create products and coupons to be used in order creation. + $variable = $this->variation->create( $this->product->create_variable() ); + $product_ids = array( + $this->product->create_simple(), + $this->product->create_simple(), + $variable['product'], + ); + $coupon = new WC_Coupon( + $this->coupon->create( array( 'product_ids' => $product_ids ) ) + ); + + // Create initial order input. + $initial_input = array( + 'clientMutationId' => 'someId', 'customerId' => $this->customer, 'customerNote' => 'Customer test note', 'coupons' => array( - $coupon->get_code(), - ), + $coupon->get_code(), + ), 'paymentMethod' => 'bacs', - 'paymentMethodTitle' => 'Direct Bank Transfer', + 'paymentMethodTitle' => 'Direct Bank Transfer', 'billing' => array( - 'firstName' => 'May', - 'lastName' => 'Parker', - 'address1' => '20 Ingram St', - 'city' => 'New York City', - 'state' => 'NY', - 'postcode' => '12345', - 'country' => 'US', - 'email' => 'superfreak500@gmail.com', - 'phone' => '555-555-1234', - ), + 'firstName' => 'May', + 'lastName' => 'Parker', + 'address1' => '20 Ingram St', + 'city' => 'New York City', + 'state' => 'NY', + 'postcode' => '12345', + 'country' => 'US', + 'email' => 'superfreak500@gmail.com', + 'phone' => '555-555-1234', + ), 'shipping' => array( - 'firstName' => 'May', - 'lastName' => 'Parker', - 'address1' => '20 Ingram St', - 'city' => 'New York City', - 'state' => 'NY', - 'postcode' => '12345', - 'country' => 'US', - ), + 'firstName' => 'May', + 'lastName' => 'Parker', + 'address1' => '20 Ingram St', + 'city' => 'New York City', + 'state' => 'NY', + 'postcode' => '12345', + 'country' => 'US', + ), 'lineItems' => array( - array( - 'productId' => $product_ids[0], - 'quantity' => 5, - 'metaData' => array( - array( - 'key' => 'test_product_key', - 'value' => 'test product value', - ), - ), - ), - array( - 'productId' => $product_ids[1], - 'quantity' => 2, - ), - array( - 'productId' => $product_ids[2], - 'quantity' => 6, - 'variationId' => $variable['variations'][0] - ), - ), - 'shippingLines' => array( - array( - 'methodId' => 'flat_rate_shipping', - 'methodTitle' => 'Flat Rate shipping', - 'total' => '10', - ), - ), + array( + 'productId' => $product_ids[0], + 'quantity' => 5, + 'metaData' => array( + array( + 'key' => 'test_product_key', + 'value' => 'test product value', + ), + ), + ), + array( + 'productId' => $product_ids[1], + 'quantity' => 2, + ), + array( + 'productId' => $product_ids[2], + 'quantity' => 6, + 'variationId' => $variable['variations'][0], + ), + ), + 'shippingLines' => array( + array( + 'methodId' => 'flat_rate_shipping', + 'methodTitle' => 'Flat Rate shipping', + 'total' => '10', + ), + ), 'feeLines' => array( - array( - 'name' => 'Some Fee', - 'taxStatus' => 'TAXABLE', - 'total' => '100', - 'taxClass' => 'STANDARD', - ), - ), + array( + 'name' => 'Some Fee', + 'taxStatus' => 'TAXABLE', + 'total' => '100', + 'taxClass' => 'STANDARD', + ), + ), 'metaData' => array( - array( - 'key' => 'test_key', - 'value' => 'test value', - ), - ), + array( + 'key' => 'test_key', + 'value' => 'test value', + ), + ), 'isPaid' => false, - ); + ); - // Create order to delete. + // Create order to delete. wp_set_current_user( $this->shop_manager ); - $initial_response = $this->orderMutation( $initial_input ); - - // use --debug flag to view. - codecept_debug( $initial_response ); - - // Clear loader cache. - $this->getModule('\Helper\Wpunit')->clear_loader_cache( 'wc_post' ); - - // Retrieve order and items - $order_id = $initial_response['data']['createOrder']['order']['databaseId']; - $order = \WC_Order_Factory::get_order( $order_id ); - $line_items = $order->get_items(); - $shipping_lines = $order->get_items( 'shipping' ); - $fee_lines = $order->get_items( 'fee' ); - $coupon_lines = $order->get_items( 'coupon' ); - $tax_lines = $order->get_items( 'tax' ); - - // Create DeleteOrderInput. - $deleted_input = array( - 'clientMutationId' => 'someId', - 'id' => $this->order->to_relay_id( $order->get_id() ), - 'forceDelete' => true, - ); - - /** + $initial_response = $this->orderMutation( $initial_input ); + + // use --debug flag to view. + codecept_debug( $initial_response ); + + // Clear loader cache. + $this->getModule( '\Helper\Wpunit' )->clear_loader_cache( 'wc_post' ); + + // Retrieve order and items + $order_id = $initial_response['data']['createOrder']['order']['databaseId']; + $order = \WC_Order_Factory::get_order( $order_id ); + $line_items = $order->get_items(); + $shipping_lines = $order->get_items( 'shipping' ); + $fee_lines = $order->get_items( 'fee' ); + $coupon_lines = $order->get_items( 'coupon' ); + $tax_lines = $order->get_items( 'tax' ); + + // Create DeleteOrderInput. + $deleted_input = array( + 'clientMutationId' => 'someId', + 'id' => $this->order->to_relay_id( $order->get_id() ), + 'forceDelete' => true, + ); + + /** * Assertion One * * User without necessary capabilities cannot delete order an order. */ - wp_set_current_user( $this->customer ); - $actual = $this->orderMutation( - $deleted_input, - 'deleteOrder', - 'DeleteOrderInput' - ); + wp_set_current_user( $this->customer ); + $actual = $this->orderMutation( + $deleted_input, + 'deleteOrder', + 'DeleteOrderInput' + ); - // use --debug flag to view. - codecept_debug( $actual ); + // use --debug flag to view. + codecept_debug( $actual ); - $this->assertArrayHasKey('errors', $actual ); + $this->assertArrayHasKey( 'errors', $actual ); - /** + /** * Assertion Two * * Test mutation and input. */ wp_set_current_user( $this->shop_manager ); - $actual = $this->orderMutation( - $deleted_input, - 'deleteOrder', - 'DeleteOrderInput' - ); - - // use --debug flag to view. - codecept_debug( $actual ); - - $this->assertArrayHasKey( 'data', $actual ); - $this->assertArrayHasKey( 'deleteOrder', $actual['data'] ); - $this->assertEquals( $initial_response['data']['createOrder'], $actual['data']['deleteOrder'] ); - $this->assertFalse( \WC_Order_Factory::get_order( $order->get_id() ) ); - } - - public function testDeleteOrderItemsMutation() { - // Create products and coupons to be used in order creation. - $variable = $this->variation->create( $this->product->create_variable() ); - $product_ids = array( - $this->product->create_simple(), - $this->product->create_simple(), - $variable['product'], - ); - $coupon = new WC_Coupon( - $this->coupon->create( array( 'product_ids' => $product_ids ) ) - ); - - // Create initial order input. - $initial_input = array( - 'clientMutationId' => 'someId', + $actual = $this->orderMutation( + $deleted_input, + 'deleteOrder', + 'DeleteOrderInput' + ); + + // use --debug flag to view. + codecept_debug( $actual ); + + $this->assertArrayHasKey( 'data', $actual ); + $this->assertArrayHasKey( 'deleteOrder', $actual['data'] ); + $this->assertEquals( $initial_response['data']['createOrder'], $actual['data']['deleteOrder'] ); + $this->assertFalse( \WC_Order_Factory::get_order( $order->get_id() ) ); + } + + public function testDeleteOrderItemsMutation() { + // Create products and coupons to be used in order creation. + $variable = $this->variation->create( $this->product->create_variable() ); + $product_ids = array( + $this->product->create_simple(), + $this->product->create_simple(), + $variable['product'], + ); + $coupon = new WC_Coupon( + $this->coupon->create( array( 'product_ids' => $product_ids ) ) + ); + + // Create initial order input. + $initial_input = array( + 'clientMutationId' => 'someId', 'customerId' => $this->customer, 'customerNote' => 'Customer test note', 'coupons' => array( - $coupon->get_code(), - ), + $coupon->get_code(), + ), 'paymentMethod' => 'bacs', - 'paymentMethodTitle' => 'Direct Bank Transfer', + 'paymentMethodTitle' => 'Direct Bank Transfer', 'billing' => array( - 'firstName' => 'May', - 'lastName' => 'Parker', - 'address1' => '20 Ingram St', - 'city' => 'New York City', - 'state' => 'NY', - 'postcode' => '12345', - 'country' => 'US', - 'email' => 'superfreak500@gmail.com', - 'phone' => '555-555-1234', - ), + 'firstName' => 'May', + 'lastName' => 'Parker', + 'address1' => '20 Ingram St', + 'city' => 'New York City', + 'state' => 'NY', + 'postcode' => '12345', + 'country' => 'US', + 'email' => 'superfreak500@gmail.com', + 'phone' => '555-555-1234', + ), 'shipping' => array( - 'firstName' => 'May', - 'lastName' => 'Parker', - 'address1' => '20 Ingram St', - 'city' => 'New York City', - 'state' => 'NY', - 'postcode' => '12345', - 'country' => 'US', - ), + 'firstName' => 'May', + 'lastName' => 'Parker', + 'address1' => '20 Ingram St', + 'city' => 'New York City', + 'state' => 'NY', + 'postcode' => '12345', + 'country' => 'US', + ), 'lineItems' => array( - array( - 'productId' => $product_ids[0], - 'quantity' => 5, - 'metaData' => array( - array( - 'key' => 'test_product_key', - 'value' => 'test product value', - ), - ), - ), - array( - 'productId' => $product_ids[1], - 'quantity' => 2, - ), - array( - 'productId' => $product_ids[2], - 'quantity' => 6, - 'variationId' => $variable['variations'][0] - ), - ), - 'shippingLines' => array( - array( - 'methodId' => 'flat_rate_shipping', - 'methodTitle' => 'Flat Rate shipping', - 'total' => '10', - ), - ), + array( + 'productId' => $product_ids[0], + 'quantity' => 5, + 'metaData' => array( + array( + 'key' => 'test_product_key', + 'value' => 'test product value', + ), + ), + ), + array( + 'productId' => $product_ids[1], + 'quantity' => 2, + ), + array( + 'productId' => $product_ids[2], + 'quantity' => 6, + 'variationId' => $variable['variations'][0], + ), + ), + 'shippingLines' => array( + array( + 'methodId' => 'flat_rate_shipping', + 'methodTitle' => 'Flat Rate shipping', + 'total' => '10', + ), + ), 'feeLines' => array( - array( - 'name' => 'Some Fee', - 'taxStatus' => 'TAXABLE', - 'total' => '100', - 'taxClass' => 'STANDARD', - ), - ), + array( + 'name' => 'Some Fee', + 'taxStatus' => 'TAXABLE', + 'total' => '100', + 'taxClass' => 'STANDARD', + ), + ), 'metaData' => array( - array( - 'key' => 'test_key', - 'value' => 'test value', - ), - ), + array( + 'key' => 'test_key', + 'value' => 'test value', + ), + ), 'isPaid' => false, - ); + ); - // Create order to delete. + // Create order to delete. wp_set_current_user( $this->shop_manager ); - $initial_response = $this->orderMutation( $initial_input ); - - // use --debug flag to view. - codecept_debug( $initial_response ); - - // Clear loader cache. - $this->getModule('\Helper\Wpunit')->clear_loader_cache( 'wc_post' ); - - // Retrieve order and items - $order_id = $initial_response['data']['createOrder']['order']['databaseId']; - $order = \WC_Order_Factory::get_order( $order_id ); - $line_items = $order->get_items(); - $shipping_lines = $order->get_items( 'shipping' ); - $fee_lines = $order->get_items( 'fee' ); - $coupon_lines = $order->get_items( 'coupon' ); - $tax_lines = $order->get_items( 'tax' ); - - // Create DeleteOrderInput. - $deleted_items_input = array( - 'clientMutationId' => 'someId', - 'orderId' => $order->get_id(), - 'itemIds' => array( - current( $line_items )->get_id(), - current( $coupon_lines )->get_id(), - ), - ); - - /** + $initial_response = $this->orderMutation( $initial_input ); + + // use --debug flag to view. + codecept_debug( $initial_response ); + + // Clear loader cache. + $this->getModule( '\Helper\Wpunit' )->clear_loader_cache( 'wc_post' ); + + // Retrieve order and items + $order_id = $initial_response['data']['createOrder']['order']['databaseId']; + $order = \WC_Order_Factory::get_order( $order_id ); + $line_items = $order->get_items(); + $shipping_lines = $order->get_items( 'shipping' ); + $fee_lines = $order->get_items( 'fee' ); + $coupon_lines = $order->get_items( 'coupon' ); + $tax_lines = $order->get_items( 'tax' ); + + // Create DeleteOrderInput. + $deleted_items_input = array( + 'clientMutationId' => 'someId', + 'orderId' => $order->get_id(), + 'itemIds' => array( + current( $line_items )->get_id(), + current( $coupon_lines )->get_id(), + ), + ); + + /** * Assertion One * * User without necessary capabilities cannot delete order an order. */ - wp_set_current_user( $this->customer ); - $actual = $this->orderMutation( - $deleted_items_input, - 'deleteOrderItems', - 'DeleteOrderItemsInput' - ); + wp_set_current_user( $this->customer ); + $actual = $this->orderMutation( + $deleted_items_input, + 'deleteOrderItems', + 'DeleteOrderItemsInput' + ); - // use --debug flag to view. - codecept_debug( $actual ); + // use --debug flag to view. + codecept_debug( $actual ); - $this->assertArrayHasKey('errors', $actual ); + $this->assertArrayHasKey( 'errors', $actual ); - /** + /** * Assertion Two * * Test mutation and input. */ wp_set_current_user( $this->shop_manager ); - $actual = $this->orderMutation( - $deleted_items_input, - 'deleteOrderItems', - 'DeleteOrderItemsInput' - ); - - // use --debug flag to view. - codecept_debug( $actual ); - - $this->assertArrayHasKey( 'data', $actual ); - $this->assertArrayHasKey( 'deleteOrderItems', $actual['data'] ); - $this->assertEquals( $initial_response['data']['createOrder'], $actual['data']['deleteOrderItems'] ); - $this->assertFalse( \WC_Order_Factory::get_order_item( current( $line_items ) ) ); - $this->assertFalse( \WC_Order_Factory::get_order_item( current( $coupon_lines ) ) ); - } + $actual = $this->orderMutation( + $deleted_items_input, + 'deleteOrderItems', + 'DeleteOrderItemsInput' + ); + + // use --debug flag to view. + codecept_debug( $actual ); + + $this->assertArrayHasKey( 'data', $actual ); + $this->assertArrayHasKey( 'deleteOrderItems', $actual['data'] ); + $this->assertEquals( $initial_response['data']['createOrder'], $actual['data']['deleteOrderItems'] ); + $this->assertFalse( \WC_Order_Factory::get_order_item( current( $line_items ) ) ); + $this->assertFalse( \WC_Order_Factory::get_order_item( current( $coupon_lines ) ) ); + } } diff --git a/tests/wpunit/OrderQueriesTest.php b/tests/wpunit/OrderQueriesTest.php index b529a79ec..c1e99cd8e 100644 --- a/tests/wpunit/OrderQueriesTest.php +++ b/tests/wpunit/OrderQueriesTest.php @@ -18,7 +18,7 @@ public function expectedOrderData( $order_id ) { $this->expectedField( 'date', $order->get_date_created()->__toString() ), $this->expectedField( 'modified', $order->get_date_modified()->__toString() ), $this->expectedField( 'status', WPEnumType::get_safe_name( $order->get_status() ) ), - $this->expectedField( 'discountTotal', \wc_graphql_price( $order->get_discount_total(), array( 'currency' => $order->get_currency() ) ) ), + $this->expectedField( 'discountTotal', \wc_graphql_price( $order->get_discount_total(), array( 'currency' => $order->get_currency() ) ) ), $this->expectedField( 'discountTax', \wc_graphql_price( $order->get_discount_tax(), array( 'currency' => $order->get_currency() ) ) ), $this->expectedField( 'shippingTotal', \wc_graphql_price( $order->get_shipping_total(), array( 'currency' => $order->get_currency() ) ) ), $this->expectedField( 'shippingTax', \wc_graphql_price( $order->get_shipping_tax(), array( 'currency' => $order->get_currency() ) ) ), @@ -54,7 +54,7 @@ public function expectedOrderData( $order_id ) { $this->expectedField( 'address2', $this->maybe( $order->get_billing_address_2() ) ), $this->expectedField( 'city', $this->maybe( $order->get_billing_city() ) ), $this->expectedField( 'state', $this->maybe( $order->get_billing_state() ) ), - $this->expectedField( 'postcode', $this->maybe( $order->get_billing_postcode() ) ), + $this->expectedField( 'postcode', $this->maybe( $order->get_billing_postcode() ) ), $this->expectedField( 'country', $this->maybe( $order->get_billing_country() ) ), $this->expectedField( 'email', $this->maybe( $order->get_billing_email() ) ), $this->expectedField( 'phone', $this->maybe( $order->get_billing_phone() ) ), @@ -70,7 +70,7 @@ public function expectedOrderData( $order_id ) { $this->expectedField( 'address2', $this->maybe( $order->get_shipping_address_2() ) ), $this->expectedField( 'city', $this->maybe( $order->get_shipping_city() ) ), $this->expectedField( 'state', $this->maybe( $order->get_shipping_state() ) ), - $this->expectedField( 'postcode', $this->maybe( $order->get_shipping_postcode() ) ), + $this->expectedField( 'postcode', $this->maybe( $order->get_shipping_postcode() ) ), $this->expectedField( 'country', $this->maybe( $order->get_shipping_country() ) ), ) ), @@ -191,7 +191,7 @@ public function testOrderQuery() { /** * Assertion One * - * tests query as customer, should return "null" because the customer isn't authorized. + * Tests query as customer, should return "null" because the customer isn't authorized. */ $this->loginAsCustomer(); $variables = array( 'id' => $id ); @@ -203,11 +203,11 @@ public function testOrderQuery() { /** * Assertion Two * - * tests query as shop manager + * Tests query as shop manager */ $this->loginAsShopManager(); - $response = $this->graphql( compact( 'query', 'variables' ) ); - $expected = $this->expectedOrderData( $order_id ); + $response = $this->graphql( compact( 'query', 'variables' ) ); + $expected = $this->expectedOrderData( $order_id ); $this->assertQuerySuccessful( $response, $expected ); } @@ -230,7 +230,7 @@ public function testOrderQueryAndIds() { /** * Assertion One * - * tests "ID" ID type. + * Tests "ID" ID type. */ $variables = array( 'id' => $id, @@ -244,7 +244,7 @@ public function testOrderQueryAndIds() { /** * Assertion Two * - * tests "DATABASE_ID" ID type. + * Tests "DATABASE_ID" ID type. */ $variables = array( 'id' => $order_id, @@ -257,7 +257,7 @@ public function testOrderQueryAndIds() { /** * Assertion Three * - * tests "ORDER_NUMBER" ID type + * Tests "ORDER_NUMBER" ID type */ $variables = array( 'id' => $this->factory->order->get_order_key( $order_id ), @@ -295,11 +295,11 @@ public function testOrdersQueryAndWhereArgs() { ), $this->factory->order->createNew( array( - 'status' => 'completed', + 'status' => 'completed', 'customer_id' => $customer, ), array( - 'line_items' => array( + 'line_items' => array( array( 'product' => $product, 'qty' => 2, @@ -328,7 +328,7 @@ public function testOrdersQueryAndWhereArgs() { /** * Assertion One * - * tests query with no without required capabilities + * Tests query with no without required capabilities */ $this->loginAsCustomer(); $response = $this->graphql( compact( 'query' ) ); @@ -340,7 +340,7 @@ public function testOrdersQueryAndWhereArgs() { /** * Assertion Two * - * tests query with required capabilities + * Tests query with required capabilities */ $this->loginAsShopManager(); $response = $this->graphql( compact( 'query' ) ); @@ -356,11 +356,11 @@ public function testOrdersQueryAndWhereArgs() { /** * Assertion Three * - * tests "statuses" where argument + * Tests "statuses" where argument */ $variables = array( 'statuses' => array( 'COMPLETED' ) ); - $response = $this->graphql( compact( 'query', 'variables' ) ); - $expected = array( + $response = $this->graphql( compact( 'query', 'variables' ) ); + $expected = array( $this->expectedNode( 'orders.nodes', array( 'id' => $this->toRelayId( 'shop_order', $orders[1] ) ) ), ); @@ -370,10 +370,10 @@ public function testOrdersQueryAndWhereArgs() { /** * Assertion Four * - * tests "customerId" where argument + * Tests "customerId" where argument */ $variables = array( 'customerId' => $customer ); - $response = $this->graphql( compact( 'query', 'variables' ) ); + $response = $this->graphql( compact( 'query', 'variables' ) ); $this->assertQuerySuccessful( $response, $expected ); $this->clearLoaderCache( 'wc_post' ); @@ -381,10 +381,10 @@ public function testOrdersQueryAndWhereArgs() { /** * Assertion Five * - * tests "customerIn" where argument + * Tests "customerIn" where argument */ $variables = array( 'customersIn' => array( $customer ) ); - $response = $this->graphql( compact( 'query', 'variables' ) ); + $response = $this->graphql( compact( 'query', 'variables' ) ); $this->assertQuerySuccessful( $response, $expected ); $this->clearLoaderCache( 'wc_post' ); @@ -392,10 +392,10 @@ public function testOrdersQueryAndWhereArgs() { /** * Assertion Six * - * tests "productId" where argument + * Tests "productId" where argument */ $variables = array( 'productId' => $product ); - $response = $this->graphql( compact( 'query', 'variables' ) ); + $response = $this->graphql( compact( 'query', 'variables' ) ); $this->assertQuerySuccessful( $response, $expected ); $this->clearLoaderCache( 'wc_post' ); @@ -403,7 +403,7 @@ public function testOrdersQueryAndWhereArgs() { /** * Assertion Seven * - * tests `orders` query as existing customer, should return customer's + * Tests `orders` query as existing customer, should return customer's * orders only */ $this->loginAs( $customer ); diff --git a/tests/wpunit/PaymentGatewayQueriesTest.php b/tests/wpunit/PaymentGatewayQueriesTest.php index bed4610d9..f80762800 100644 --- a/tests/wpunit/PaymentGatewayQueriesTest.php +++ b/tests/wpunit/PaymentGatewayQueriesTest.php @@ -1,6 +1,6 @@ 'no', - 'title' => 'Credit Card (Stripe)', - 'description' => 'Pay with your credit card via Stripe', - 'webhook' => '', - 'testmode' => 'yes', - 'test_publishable_key' => defined( 'STRIPE_API_PUBLISHABLE_KEY' ) - ? STRIPE_API_PUBLISHABLE_KEY - : getenv( 'STRIPE_API_PUBLISHABLE_KEY' ), - 'test_secret_key' => defined( 'STRIPE_API_SECRET_KEY' ) - ? STRIPE_API_SECRET_KEY - : getenv( 'STRIPE_API_SECRET_KEY' ), - 'test_webhook_secret' => '', - 'publishable_key' => '', - 'secret_key' => '', - 'webhook_secret' => '', - 'inline_cc_form' => 'no', - 'statement_descriptor' => '', - 'capture' => 'yes', - 'payment_request' => 'yes', - 'payment_request_button_type' => 'buy', - 'payment_request_button_theme' => 'dark', - 'payment_request_button_height' => '44', - 'saved_cards' => 'yes', - 'logging' => 'no', - ) + 'woocommerce_stripe_settings', + array( + 'enabled' => 'no', + 'title' => 'Credit Card (Stripe)', + 'description' => 'Pay with your credit card via Stripe', + 'webhook' => '', + 'testmode' => 'yes', + 'test_publishable_key' => defined( 'STRIPE_API_PUBLISHABLE_KEY' ) + ? STRIPE_API_PUBLISHABLE_KEY + : getenv( 'STRIPE_API_PUBLISHABLE_KEY' ), + 'test_secret_key' => defined( 'STRIPE_API_SECRET_KEY' ) + ? STRIPE_API_SECRET_KEY + : getenv( 'STRIPE_API_SECRET_KEY' ), + 'test_webhook_secret' => '', + 'publishable_key' => '', + 'secret_key' => '', + 'webhook_secret' => '', + 'inline_cc_form' => 'no', + 'statement_descriptor' => '', + 'capture' => 'yes', + 'payment_request' => 'yes', + 'payment_request_button_type' => 'buy', + 'payment_request_button_theme' => 'dark', + 'payment_request_button_height' => '44', + 'saved_cards' => 'yes', + 'logging' => 'no', + ) ); // Reload gateways. @@ -80,7 +80,7 @@ public function testPaymentGatewaysQueryAndWhereArgs() { /** * Assertion One * - * tests query. + * Tests query. */ $response = $this->graphql( compact( 'query' ) ); $expected = array( @@ -91,7 +91,7 @@ public function testPaymentGatewaysQueryAndWhereArgs() { $this->expectedField( 'title', 'Direct bank transfer' ), $this->expectedField( 'icon', self::IS_NULL ), ) - ) + ), ); $this->assertQuerySuccessful( $response, $expected ); @@ -99,13 +99,13 @@ public function testPaymentGatewaysQueryAndWhereArgs() { /** * Assertion Two * - * tests query and "all" where argument response, expects errors due lack of capabilities. + * Tests query and "all" where argument response, expects errors due lack of capabilities. */ $variables = array( 'all' => true ); $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedErrorPath( 'paymentGateways' ), - $this->expectedField( 'paymentGateways', self::IS_NULL ) + $this->expectedField( 'paymentGateways', self::IS_NULL ), ); $this->assertQueryError( $response, $expected ); @@ -113,7 +113,7 @@ public function testPaymentGatewaysQueryAndWhereArgs() { /** * Assertion Three * - * tests query and "all" where argument response with proper capabilities. + * Tests query and "all" where argument response with proper capabilities. */ $this->loginAsShopManager(); $variables = array( 'all' => true ); diff --git a/tests/wpunit/ProductAttributeQueriesTest.php b/tests/wpunit/ProductAttributeQueriesTest.php index 57fae1632..15924ac64 100644 --- a/tests/wpunit/ProductAttributeQueriesTest.php +++ b/tests/wpunit/ProductAttributeQueriesTest.php @@ -1,33 +1,29 @@ shop_manager = $this->factory->user->create( array( 'role' => 'shop_manager' ) ); - $this->customer = $this->factory->user->create( array( 'role' => 'customer' ) ); - $this->helper = $this->getModule('\Helper\Wpunit')->product(); - $this->variation_helper = $this->getModule('\Helper\Wpunit')->product_variation(); - $this->product_id = $this->helper->create_variable(); - $this->variation_ids = $this->variation_helper->create( $this->product_id )['variations']; - - \WPGraphQL::clear_schema(); - } - - public function tearDown(): void { - parent::tearDown(); - } - - // tests - public function testProductAttributeQuery() { - $query = ' + private $shop_manager; + private $customer; + private $helper; + private $variation_helper; + private $product_id; + private $variation_ids; + + public function setUp(): void { + parent::setUp(); + + $this->shop_manager = $this->factory->user->create( array( 'role' => 'shop_manager' ) ); + $this->customer = $this->factory->user->create( array( 'role' => 'customer' ) ); + $this->helper = $this->getModule( '\Helper\Wpunit' )->product(); + $this->variation_helper = $this->getModule( '\Helper\Wpunit' )->product_variation(); + $this->product_id = $this->helper->create_variable(); + $this->variation_ids = $this->variation_helper->create( $this->product_id )['variations']; + + \WPGraphQL::clear_schema(); + } + + // tests + public function testProductAttributeQuery() { + $query = ' query attributeQuery( $id: ID! ) { product( id: $id ) { ... on VariableProduct { @@ -49,33 +45,33 @@ public function testProductAttributeQuery() { } '; - $variables = array( 'id' => $this->helper->to_relay_id( $this->product_id ) ); - $actual = graphql( - array( - 'query' => $query, - 'operation_name' => 'attributeQuery', - 'variables' => $variables, - ) - ); - $expected = array( - 'data' => array( - 'product' => array( - 'id' => $this->helper->to_relay_id( $this->product_id ), - 'attributes' => $this->helper->print_attributes( $this->product_id ), - ), - ), - ); - - // use --debug flag to view. + $variables = array( 'id' => $this->helper->to_relay_id( $this->product_id ) ); + $actual = graphql( + array( + 'query' => $query, + 'operation_name' => 'attributeQuery', + 'variables' => $variables, + ) + ); + $expected = array( + 'data' => array( + 'product' => array( + 'id' => $this->helper->to_relay_id( $this->product_id ), + 'attributes' => $this->helper->print_attributes( $this->product_id ), + ), + ), + ); + + // use --debug flag to view. codecept_debug( $actual ); $this->assertEquals( $expected, $actual ); - } + } - public function testProductAttributeToProductConnectionQuery() { - $query = ' + public function testProductAttributeToProductConnectionQuery() { + $query = ' query attributeConnectionQuery( $color: [String!] ) { - paColors( where: { name: $color } ) { + allPaColor( where: { name: $color } ) { nodes { products { nodes { @@ -89,42 +85,42 @@ public function testProductAttributeToProductConnectionQuery() { } '; - $variables = array( 'color' => 'red' ); - $actual = graphql( - array( - 'query' => $query, - 'operation_name' =>'attributeConnectionQuery', - 'variables' => $variables, - ) - ); - $expected = array( - 'data' => array( - 'paColors' => array ( - 'nodes' => array( - array( - 'products' => array( - 'nodes' => array( - array( - 'id' => $this->helper->to_relay_id( $this->product_id ) - ) - ) - ) - ) - ) - ), - ), - ); - - // use --debug flag to view. + $variables = array( 'color' => 'red' ); + $actual = graphql( + array( + 'query' => $query, + 'operation_name' => 'attributeConnectionQuery', + 'variables' => $variables, + ) + ); + $expected = array( + 'data' => array( + 'allPaColor' => array( + 'nodes' => array( + array( + 'products' => array( + 'nodes' => array( + array( + 'id' => $this->helper->to_relay_id( $this->product_id ), + ), + ), + ), + ), + ), + ), + ), + ); + + // use --debug flag to view. codecept_debug( $actual ); $this->assertEquals( $expected, $actual ); - } + } - public function testProductAttributeToVariationConnectionQuery() { - $query = ' + public function testProductAttributeToVariationConnectionQuery() { + $query = ' query attributeConnectionQuery( $size: [String!] ) { - paSizes( where: { name: $size } ) { + allPaSize( where: { name: $size } ) { nodes { variations { nodes { @@ -136,45 +132,45 @@ public function testProductAttributeToVariationConnectionQuery() { } '; - $variables = array( 'size' => 'small' ); - $actual = graphql( - array( - 'query' => $query, - 'operation_name' => 'attributeConnectionQuery', - 'variables' => $variables, - ) - ); - $expected = array( - 'data' => array( - 'paSizes' => array ( - 'nodes' => array( - array( - 'variations' => array( - 'nodes' => $this->variation_helper->print_nodes( - $this->variation_ids, - array( - 'filter' => function( $id ) { - $variation = new \WC_Product_Variation( $id ); - $small_attribute = array_filter( - $variation->get_attributes(), - function( $attribute ) { - return 'small' === $attribute; - } - ); - return ! empty( $small_attribute ); - }, - ) - ), - ), - ), - ), - ), - ), - ); - - // use --debug flag to view. + $variables = array( 'size' => 'small' ); + $actual = graphql( + array( + 'query' => $query, + 'operation_name' => 'attributeConnectionQuery', + 'variables' => $variables, + ) + ); + $expected = array( + 'data' => array( + 'allPaSize' => array( + 'nodes' => array( + array( + 'variations' => array( + 'nodes' => $this->variation_helper->print_nodes( + $this->variation_ids, + array( + 'filter' => function( $id ) { + $variation = new \WC_Product_Variation( $id ); + $small_attribute = array_filter( + $variation->get_attributes(), + function( $attribute ) { + return 'small' === $attribute; + } + ); + return ! empty( $small_attribute ); + }, + ) + ), + ), + ), + ), + ), + ), + ); + + // use --debug flag to view. codecept_debug( $actual ); $this->assertEquals( $expected, $actual ); - } + } } diff --git a/tests/wpunit/ProductQueriesTest.php b/tests/wpunit/ProductQueriesTest.php index 482571647..ac0a5c0b3 100644 --- a/tests/wpunit/ProductQueriesTest.php +++ b/tests/wpunit/ProductQueriesTest.php @@ -5,7 +5,7 @@ public function getExpectedProductData( $product_id ) { $product = \wc_get_product( $product_id ); $is_shop_manager = false; $user = wp_get_current_user(); - if ( $user && in_array( 'shop_manager', (array) $user->roles ) ) { + if ( $user && in_array( 'shop_manager', (array) $user->roles, true ) ) { $is_shop_manager = true; } @@ -130,7 +130,7 @@ public function getExpectedProductData( $product_id ) { 'product.downloadExpiry', $this->maybe( $product->get_download_expiry(), self::IS_NULL ) ), - $this->expectedField( 'product.averageRating', (float) $product->get_average_rating() ), + $this->expectedField( 'product.averageRating', (float) $product->get_average_rating() ), $this->expectedField( 'product.reviewCount', (int) $product->get_review_count() ), $this->expectedField( 'product.backordersAllowed', @@ -168,8 +168,8 @@ public function getExpectedProductData( $product_id ) { } public function getExpectedProductDownloadData( $product_id ) { - $product = wc_get_product( $product_id ); - $downloads = (array) $product->get_downloads(); + $product = wc_get_product( $product_id ); + $downloads = (array) $product->get_downloads(); if ( empty( $downloads ) ) { return null; } @@ -249,20 +249,19 @@ public function testSimpleProductQuery() { } '; - /** * Assertion One * * Test querying product. */ $variables = array( 'id' => $this->toRelayId( 'product', $product_id ) ); - $response = $this->graphql( compact( 'query', 'variables' ) ); - $expected = $this->getExpectedProductData( $product_id ); + $response = $this->graphql( compact( 'query', 'variables' ) ); + $expected = $this->getExpectedProductData( $product_id ); $this->assertQuerySuccessful( $response, $expected ); // Clear cache - $this->getModule('\Helper\Wpunit')->clear_loader_cache( 'wc_post' ); + $this->getModule( '\Helper\Wpunit' )->clear_loader_cache( 'wc_post' ); /** * Assertion Two @@ -274,8 +273,8 @@ public function testSimpleProductQuery() { 'id' => $this->toRelayId( 'product', $product_id ), 'format' => 'RAW', ); - $response = $this->graphql( compact( 'query', 'variables' ) ); - $expected = array( + $response = $this->graphql( compact( 'query', 'variables' ) ); + $expected = array( $this->expectedField( 'product.description', $product->get_description() ), $this->expectedField( 'product.shortDescription', $product->get_short_description() ), $this->expectedField( 'product.totalSales', $product->get_total_sales() ), @@ -293,7 +292,7 @@ public function testProductTaxonomies() { $attachment_id = $this->factory->attachment->create( array( 'post_mime_type' => 'image/gif', - 'post_author' => $this->admin, + 'post_author' => $this->admin, ) ); $product_id = $this->factory->product->createSimple( @@ -344,7 +343,7 @@ public function testProductTaxonomies() { */ $variables = array( 'id' => $product_id, - 'idType' => 'DATABASE_ID' + 'idType' => 'DATABASE_ID', ); $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( @@ -383,8 +382,8 @@ public function testProductQueryAndIds() { '; // Define expected data for coming assertions. - $expected = array( - $this->expectedField( 'product.id', $this->toRelayId( 'product', $product_id ) ) + $expected = array( + $this->expectedField( 'product.id', $this->toRelayId( 'product', $product_id ) ), ); /** @@ -439,19 +438,19 @@ public function testProductQueryAndIds() { public function testProductsQueryAndWhereArgs() { $category_3 = $this->factory->product->createProductCategory( 'category-three' ); $category_4 = $this->factory->product->createProductCategory( 'category-four' ); - $product_ids = array ( + $product_ids = array( $this->factory->product->createSimple( array( 'slug' => 'test-product-1', 'price' => 6000, - 'regular_price' => 6000 + 'regular_price' => 6000, ) ), $this->factory->product->createSimple( array( 'price' => 2, 'regular_price' => 2, - 'category_ids' => array( $category_3, $category_4 ) + 'category_ids' => array( $category_3, $category_4 ), ) ), $this->factory->product->createSimple( @@ -658,10 +657,17 @@ function( $node, $index ) use ( $product_ids ) { * Tests query with "orderby" where argument, and expect products to * be return in descending order by "price". */ - $variables = array( 'orderby' => array( array( 'field' => 'PRICE', 'order' => 'DESC' ) ) ); + $variables = array( + 'orderby' => array( + array( + 'field' => 'PRICE', + 'order' => 'DESC', + ), + ), + ); $response = $this->graphql( compact( 'query', 'variables' ) ); - $expected = array( + $expected = array( $this->expectedNode( 'products.nodes', array( 'id' => $this->toRelayId( 'product', $product_ids[0] ) ), @@ -733,7 +739,7 @@ function( $node, $index ) use ( $product_ids, $category_3 ) { $all_expected_product_nodes, function( $node, $index ) use ( $product_ids, $category_4 ) { $product = \wc_get_product( $product_ids[ $index ] ); - return ! in_array( $category_4, $product->get_category_ids() ); + return ! in_array( $category_4, $product->get_category_ids(), true ); }, ARRAY_FILTER_USE_BOTH ); @@ -752,7 +758,6 @@ function( $node, $index ) use ( $product_ids, $category_4 ) { $this->assertQuerySuccessful( $response, $expected ); - /** * Assertion Fifteen * @@ -775,7 +780,7 @@ function( $node, $index ) use ( $product_ids, $category_4 ) { /** * Assertion Sixteen * - * tests "taxonomyFilter" where argument + * Tests "taxonomyFilter" where argument */ $variables = array( 'taxonomyFilter' => array( @@ -788,9 +793,9 @@ function( $node, $index ) use ( $product_ids, $category_4 ) { array( 'taxonomy' => 'PRODUCTCATEGORY', 'terms' => array( 'category-four' ), - 'operator' => 'NOT_IN' + 'operator' => 'NOT_IN', ), - ) + ), ), ); $response = $this->graphql( compact( 'query', 'variables' ) ); @@ -798,8 +803,8 @@ function( $node, $index ) use ( $product_ids, $category_4 ) { $all_expected_product_nodes, function( $node, $index ) use ( $product_ids, $category_4, $category_3 ) { $product = \wc_get_product( $product_ids[ $index ] ); - return ! in_array( $category_4, $product->get_category_ids() ) - && in_array( $category_3, $product->get_category_ids() ); + return ! in_array( $category_4, $product->get_category_ids(), true ) + && in_array( $category_3, $product->get_category_ids(), true ); }, ARRAY_FILTER_USE_BOTH ); @@ -809,46 +814,46 @@ function( $node, $index ) use ( $product_ids, $category_4, $category_3 ) { /** * Assertion 17-18 * - * tests "include" where argument + * Tests "include" where argument */ $variables = array( - 'include' => array( $product_ids[0] ) + 'include' => array( $product_ids[0] ), ); $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedNode( 'products.nodes', array( 'id' => $this->toRelayId( 'product', $product_ids[0] ) ) - ) + ), ); $this->assertQuerySuccessful( $response, $expected ); $variables = array( - 'include' => array( 1000 ) + 'include' => array( 1000 ), ); $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedField( 'products.nodes', - [] - ) + array() + ), ); $this->assertQuerySuccessful( $response, $expected ); /** * Assertion 19-20 * - * tests "exclude" where argument + * Tests "exclude" where argument */ $variables = array( - 'exclude' => array( $product_ids[0] ) + 'exclude' => array( $product_ids[0] ), ); $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->not()->expectedNode( 'products.nodes', array( 'id' => $this->toRelayId( 'product', $product_ids[0] ) ) - ) + ), ); $this->assertQuerySuccessful( $response, $expected ); @@ -857,8 +862,8 @@ function( $node, $index ) use ( $product_ids, $category_4, $category_3 ) { $expected = array( $this->expectedField( 'products.nodes', - [] - ) + array() + ), ); $this->assertQuerySuccessful( $response, $expected ); } @@ -868,8 +873,8 @@ public function testProductToTermConnection() { $test_tag = $this->factory->product->createProductTag( 'test-product-tag-1' ); $product_id = $this->factory->product->createSimple( array( - 'tag_ids' => array( $test_tag ), - 'category_ids' => array( $test_category ), + 'tag_ids' => array( $test_tag ), + 'category_ids' => array( $test_category ), ) ); $relay_id = $this->toRelayId( 'product', $product_id ); @@ -914,13 +919,13 @@ public function testProductToTermConnection() { } public function testTermToProductConnection() { - $test_tag = $this->factory->product->createProductTag( 'test-product-tag-2' ); + $test_tag = $this->factory->product->createProductTag( 'test-product-tag-2' ); $image_id = $this->factory->post->create( array( - 'post_author' => $this->shop_manager, - 'post_status' => 'publish', - 'post_title' => 'Product Image', - 'post_type' => 'attachment', + 'post_author' => $this->shop_manager, + 'post_status' => 'publish', + 'post_title' => 'Product Image', + 'post_type' => 'attachment', ) ); $test_category = $this->factory->product->createProductCategory( 'test-product-category-2' ); @@ -928,8 +933,8 @@ public function testTermToProductConnection() { $product_id = $this->factory->product->createSimple( array( - 'tag_ids' => array( $test_tag ), - 'category_ids' => array( $test_category ), + 'tag_ids' => array( $test_tag ), + 'category_ids' => array( $test_category ), ) ); @@ -973,7 +978,7 @@ public function testTermToProductConnection() { 'name' => 'test-product-tag-2', 'products' => array( 'nodes' => array( - array ( 'id' => $this->toRelayId( 'product', $product_id ) ), + array( 'id' => $this->toRelayId( 'product', $product_id ) ), ), ), ), @@ -986,7 +991,7 @@ public function testTermToProductConnection() { 'image' => array( 'id' => $this->toRelayId( 'post', $image_id ) ), 'products' => array( 'nodes' => array( - array ( 'id' => $this->toRelayId( 'product', $product_id ) ), + array( 'id' => $this->toRelayId( 'product', $product_id ) ), ), ), ), @@ -1000,10 +1005,10 @@ public function testTermToProductConnection() { public function testProductToMediaItemConnections() { $image_id = $this->factory->post->create( array( - 'post_author' => $this->shop_manager, - 'post_status' => 'publish', - 'post_title' => 'Product Image', - 'post_type' => 'attachment', + 'post_author' => $this->shop_manager, + 'post_status' => 'publish', + 'post_title' => 'Product Image', + 'post_type' => 'attachment', ) ); $product_id = $this->factory->product->createSimple( @@ -1014,7 +1019,7 @@ public function testProductToMediaItemConnections() { ); $product_relay_id = $this->toRelayId( 'product', $product_id ); - $image_relay_id = $this->toRelayId( 'post', $image_id ); + $image_relay_id = $this->toRelayId( 'post', $image_id ); $query = ' query ( $id: ID! ) { @@ -1035,7 +1040,7 @@ public function testProductToMediaItemConnections() { '; $variables = array( 'id' => $product_relay_id ); - $response = graphql( compact( 'query', 'variables' ) ); + $response = graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedField( 'product.id', $product_relay_id ), $this->expectedField( 'product.image.id', $image_relay_id ), @@ -1048,12 +1053,12 @@ public function testProductToMediaItemConnections() { public function testProductDownloads() { $product_id = $this->factory->product->createSimple( array( - 'downloadable' => true, - 'downloads' => array( $this->factory->product->createDownload() ), + 'downloadable' => true, + 'downloads' => array( $this->factory->product->createDownload() ), ) ); - $relay_id = $this->toRelayId( 'product', $product_id ); + $relay_id = $this->toRelayId( 'product', $product_id ); $query = ' query ( $id: ID! ) { @@ -1094,7 +1099,7 @@ public function testExternalProductQuery() { ); $relay_id = $this->toRelayId( 'product', $product_id ); - $query = ' + $query = ' query ( $id: ID! ) { product(id: $id) { ... on ExternalProduct { @@ -1121,7 +1126,7 @@ public function testGroupProductConnections() { $product_id = $this->factory->product->createGrouped( array( 'name' => 'Test Group', - 'children' => array() + 'children' => array(), ) ); $grouped_product_ids = array( @@ -1160,11 +1165,12 @@ public function testGroupProductConnections() { $this->expectedField( 'product.addToCartText', 'View products' ), $this->expectedField( 'product.addToCartDescription', - sprintf( __( 'View products in the “%s” group', 'woocommerce' ), 'Test Group' ) + /* translators: %s: Group name */ + sprintf( __( 'View products in the “%s” group', 'wp-graphql-woocommerce' ), 'Test Group' ) ), ); - foreach( $product->get_children() as $grouped_product_id ) { + foreach ( $product->get_children() as $grouped_product_id ) { $expected[] = $this->expectedNode( 'product.products.nodes', array( 'id' => $this->toRelayId( 'product', $grouped_product_id ) ) @@ -1225,19 +1231,19 @@ public function testRelatedProductConnections() { $variables = array( 'id' => $this->toRelayId( 'product', $products['product'] ) ); $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array(); - foreach( $products['related'] + $products['cross_sell'] + $products['upsell'] as $product_id ) { + foreach ( $products['related'] + $products['cross_sell'] + $products['upsell'] as $product_id ) { $expected[] = $this->expectedNode( 'product.related.nodes', array( 'id' => $this->toRelayId( 'product', $product_id ) ) ); } - foreach( $products['cross_sell'] as $product_id ) { + foreach ( $products['cross_sell'] as $product_id ) { $expected[] = $this->expectedNode( 'product.crossSell.nodes', array( 'id' => $this->toRelayId( 'product', $product_id ) ) ); } - foreach( $products['upsell'] as $product_id ) { + foreach ( $products['upsell'] as $product_id ) { $expected[] = $this->expectedNode( 'product.upsell.nodes', array( 'id' => $this->toRelayId( 'product', $product_id ) ) @@ -1283,7 +1289,7 @@ public function testProductToReviewConnections() { $this->expectedField( 'product.reviews.averageRating', floatval( $product->get_average_rating() ) ), ); - foreach( $reviews as $review_id ) { + foreach ( $reviews as $review_id ) { $expected[] = $this->expectedEdge( 'product.reviews.edges', array( @@ -1320,14 +1326,14 @@ public function testProductGalleryImagesConnection() { '; $variables = array( 'id' => $this->toRelayId( 'product', $product_id ) ); - $response = $this->graphql( compact( 'query', 'variables' ) ); + $response = $this->graphql( compact( 'query', 'variables' ) ); $this->assertQuerySuccessful( $response, array( $this->expectedNode( 'product.galleryImages.nodes', array( 'id' => $this->toRelayId( 'post', $image_id ) ) - ) + ), ) ); } diff --git a/tests/wpunit/ProductReviewMutationsTest.php b/tests/wpunit/ProductReviewMutationsTest.php index 5907fbd2c..2cdfd9c8b 100644 --- a/tests/wpunit/ProductReviewMutationsTest.php +++ b/tests/wpunit/ProductReviewMutationsTest.php @@ -4,26 +4,19 @@ class ProductReviewMutationsTest extends \Codeception\TestCase\WPTestCase { - public function setUp(): void { - // before - parent::setUp(); - - // your set up methods here - $this->shop_manager = $this->factory->user->create( array( 'role' => 'shop_manager' ) ); - $this->customer = $this->factory->user->create( array( 'role' => 'customer' ) ); - $this->products = $this->getModule('\Helper\Wpunit')->product(); - } - - public function tearDown(): void { - // your tear down methods here - - // then - parent::tearDown(); - } - - private function run_mutation( $mutation_name, $input = null ) { - $input_type = ucfirst( $mutation_name ) . 'Input!'; - $mutation = " + public function setUp(): void { + // before + parent::setUp(); + + // your set up methods here + $this->shop_manager = $this->factory->user->create( array( 'role' => 'shop_manager' ) ); + $this->customer = $this->factory->user->create( array( 'role' => 'customer' ) ); + $this->products = $this->getModule( '\Helper\Wpunit' )->product(); + } + + private function run_mutation( $mutation_name, $input = null ) { + $input_type = ucfirst( $mutation_name ) . 'Input!'; + $mutation = " mutation ( \$input: {$input_type} ) { {$mutation_name}( input: \$input ) { clientMutationId @@ -35,150 +28,150 @@ private function run_mutation( $mutation_name, $input = null ) { } "; - $results = graphql( - array( - 'query' => $mutation, - 'variables' => array( 'input' => $input ), - ) - ); - - // Use --debug flag to view - codecept_debug( $results ); - - return $results; - } - - // tests - public function testCreateNewReviewMutation() { - wp_set_current_user( $this->shop_manager ); - $input = array( - 'clientMutationId' => 'some_id', - 'rating' => 1, - 'commentOn' => $this->products->create_simple(), + $results = graphql( + array( + 'query' => $mutation, + 'variables' => array( 'input' => $input ), + ) + ); + + // Use --debug flag to view + codecept_debug( $results ); + + return $results; + } + + // tests + public function testCreateNewReviewMutation() { + wp_set_current_user( $this->shop_manager ); + $input = array( + 'clientMutationId' => 'some_id', + 'rating' => 1, + 'commentOn' => $this->products->create_simple(), 'content' => 'It came covered in poop!!!', 'author' => 'Rude customer', 'authorEmail' => 'rude-guy@example.com', - ); - - $actual = $this->run_mutation( 'writeReview', $input ); - $expected = array( - 'data' => array( - 'writeReview' => array( - 'clientMutationId' => 'some_id', - 'rating' => 1.0, - 'review' => array( - 'content' => 'It came covered in poop!!!', - ), - ), - ), - ); - $this->assertEquals( $expected, $actual ); - } - - public function testUpdateReviewMutation() { - wp_set_current_user( $this->shop_manager ); - $comment_id = $this->factory()->comment->create( - array( - 'comment_author' => 'Rude customer', - 'comment_author_email' => 'rude-guy@example.com', - 'comment_post_ID' => $this->products->create_simple(), - 'comment_content' => 'It came covered in poop!!!', - 'comment_approved' => 1, - 'comment_type' => 'review', - ) - ); - update_comment_meta( $comment_id, 'rating', 1 ); - - $input = array( - 'clientMutationId' => 'some_id', - 'rating' => 5, - 'id' => Relay::toGlobalId( 'comment', $comment_id ), - 'content' => 'Turns out it was Nutella. My bad =P', - ); - - $actual = $this->run_mutation( 'updateReview', $input ); - $expected = array( - 'data' => array( - 'updateReview' => array( - 'clientMutationId' => 'some_id', - 'rating' => 5.0, - 'review' => array( - 'content' => 'Turns out it was Nutella. My bad =P', - ), - ), - ), - ); - $this->assertEquals( $expected, $actual ); - } - - public function testDeleteReviewMutation() { - wp_set_current_user( $this->shop_manager ); - $comment_id = $this->factory()->comment->create( - array( - 'comment_author' => 'Rude customer', - 'comment_author_email' => 'rude-guy@example.com', - 'comment_post_ID' => $this->products->create_simple(), - 'comment_content' => 'It came covered in poop!!!', - 'comment_approved' => 1, - 'comment_type' => 'review', - ) - ); - update_comment_meta( $comment_id, 'rating', 1 ); - - $input = array( - 'clientMutationId' => 'some_id', - 'id' => Relay::toGlobalID( 'comment', $comment_id ), - ); - - $actual = $this->run_mutation( 'deleteReview', $input ); - $expected = array( - 'data' => array( - 'deleteReview' => array( - 'clientMutationId' => 'some_id', - 'rating' => 1.0, - 'review' => array( - 'content' => 'It came covered in poop!!!', - ), - ), - ), - ); - $this->assertEquals( $expected, $actual ); - } - - public function testRestoreReviewMutation() { - wp_set_current_user( $this->shop_manager ); - $comment_id = $this->factory()->comment->create( - array( - 'comment_author' => 'Rude customer', - 'comment_author_email' => 'rude-guy@example.com', - 'comment_post_ID' => $this->products->create_simple(), - 'comment_content' => 'It came covered in poop!!!', - 'comment_approved' => 1, - 'comment_type' => 'review', - ) - ); - update_comment_meta( $comment_id, 'rating', 1 ); - - // Trash comment - wp_delete_comment( $comment_id ); - - $input = array( - 'clientMutationId' => 'some_id', - 'id' => Relay::toGlobalID( 'comment', $comment_id ), - ); - - $actual = $this->run_mutation( 'restoreReview', $input ); - $expected = array( - 'data' => array( - 'restoreReview' => array( - 'clientMutationId' => 'some_id', - 'rating' => 1.0, - 'review' => array( - 'content' => 'It came covered in poop!!!', - ), - ), - ), - ); - $this->assertEquals( $expected, $actual ); - } + ); + + $actual = $this->run_mutation( 'writeReview', $input ); + $expected = array( + 'data' => array( + 'writeReview' => array( + 'clientMutationId' => 'some_id', + 'rating' => 1.0, + 'review' => array( + 'content' => 'It came covered in poop!!!', + ), + ), + ), + ); + $this->assertEquals( $expected, $actual ); + } + + public function testUpdateReviewMutation() { + wp_set_current_user( $this->shop_manager ); + $comment_id = $this->factory()->comment->create( + array( + 'comment_author' => 'Rude customer', + 'comment_author_email' => 'rude-guy@example.com', + 'comment_post_ID' => $this->products->create_simple(), + 'comment_content' => 'It came covered in poop!!!', + 'comment_approved' => 1, + 'comment_type' => 'review', + ) + ); + update_comment_meta( $comment_id, 'rating', 1 ); + + $input = array( + 'clientMutationId' => 'some_id', + 'rating' => 5, + 'id' => Relay::toGlobalId( 'comment', $comment_id ), + 'content' => 'Turns out it was Nutella. My bad =P', + ); + + $actual = $this->run_mutation( 'updateReview', $input ); + $expected = array( + 'data' => array( + 'updateReview' => array( + 'clientMutationId' => 'some_id', + 'rating' => 5.0, + 'review' => array( + 'content' => 'Turns out it was Nutella. My bad =P', + ), + ), + ), + ); + $this->assertEquals( $expected, $actual ); + } + + public function testDeleteReviewMutation() { + wp_set_current_user( $this->shop_manager ); + $comment_id = $this->factory()->comment->create( + array( + 'comment_author' => 'Rude customer', + 'comment_author_email' => 'rude-guy@example.com', + 'comment_post_ID' => $this->products->create_simple(), + 'comment_content' => 'It came covered in poop!!!', + 'comment_approved' => 1, + 'comment_type' => 'review', + ) + ); + update_comment_meta( $comment_id, 'rating', 1 ); + + $input = array( + 'clientMutationId' => 'some_id', + 'id' => Relay::toGlobalID( 'comment', $comment_id ), + ); + + $actual = $this->run_mutation( 'deleteReview', $input ); + $expected = array( + 'data' => array( + 'deleteReview' => array( + 'clientMutationId' => 'some_id', + 'rating' => 1.0, + 'review' => array( + 'content' => 'It came covered in poop!!!', + ), + ), + ), + ); + $this->assertEquals( $expected, $actual ); + } + + public function testRestoreReviewMutation() { + wp_set_current_user( $this->shop_manager ); + $comment_id = $this->factory()->comment->create( + array( + 'comment_author' => 'Rude customer', + 'comment_author_email' => 'rude-guy@example.com', + 'comment_post_ID' => $this->products->create_simple(), + 'comment_content' => 'It came covered in poop!!!', + 'comment_approved' => 1, + 'comment_type' => 'review', + ) + ); + update_comment_meta( $comment_id, 'rating', 1 ); + + // Trash comment + wp_delete_comment( $comment_id ); + + $input = array( + 'clientMutationId' => 'some_id', + 'id' => Relay::toGlobalID( 'comment', $comment_id ), + ); + + $actual = $this->run_mutation( 'restoreReview', $input ); + $expected = array( + 'data' => array( + 'restoreReview' => array( + 'clientMutationId' => 'some_id', + 'rating' => 1.0, + 'review' => array( + 'content' => 'It came covered in poop!!!', + ), + ), + ), + ); + $this->assertEquals( $expected, $actual ); + } } diff --git a/tests/wpunit/ProductVariationQueriesTest.php b/tests/wpunit/ProductVariationQueriesTest.php index ddbdb2f8a..33897c79b 100644 --- a/tests/wpunit/ProductVariationQueriesTest.php +++ b/tests/wpunit/ProductVariationQueriesTest.php @@ -4,33 +4,26 @@ class ProductVariationQueriesTest extends \Codeception\TestCase\WPTestCase { private $shop_manager; - private $customer; - private $products; + private $customer; + private $products; - public function setUp(): void { - parent::setUp(); + public function setUp(): void { + parent::setUp(); - $this->shop_manager = $this->factory->user->create( array( 'role' => 'shop_manager' ) ); - $this->customer = $this->factory->user->create( array( 'role' => 'customer' ) ); - $this->product_helper = $this->getModule('\Helper\Wpunit')->product(); - $this->helper = $this->getModule('\Helper\Wpunit')->product_variation(); + $this->shop_manager = $this->factory->user->create( array( 'role' => 'shop_manager' ) ); + $this->customer = $this->factory->user->create( array( 'role' => 'customer' ) ); + $this->product_helper = $this->getModule( '\Helper\Wpunit' )->product(); + $this->helper = $this->getModule( '\Helper\Wpunit' )->product_variation(); $this->products = $this->helper->create( $this->product_helper->create_variable() ); \WPGraphQL::clear_schema(); - } - - public function tearDown(): void { - // your tear down methods here - - // then - parent::tearDown(); - } + } - // tests - public function testVariationQuery() { - $variation_id = $this->products['variations'][0]; - $id = $this->helper->to_relay_id( $variation_id ); - $query = ' + // tests + public function testVariationQuery() { + $variation_id = $this->products['variations'][0]; + $id = $this->helper->to_relay_id( $variation_id ); + $query = ' query ($id: ID, $idType: ProductVariationIdTypeEnum) { productVariation(id: $id, idType: $idType) { id @@ -76,60 +69,60 @@ public function testVariationQuery() { } '; - /** + /** * Assertion One * - * test "ID" ID type. + * Tests "ID" ID type. */ $variables = array( - 'id' => $id, - 'idType' => 'ID', - ); + 'id' => $id, + 'idType' => 'ID', + ); $actual = graphql( - array( - 'query' => $query, - 'variables' => $variables, - ) - ); + array( + 'query' => $query, + 'variables' => $variables, + ) + ); $expected = array( 'data' => array( 'productVariation' => $this->helper->print_query( $variation_id ) ) ); // use --debug flag to view. codecept_debug( $actual ); - $this->assertEquals( $expected, $actual ); + $this->assertEquals( $expected, $actual ); - $this->getModule('\Helper\Wpunit')->clear_loader_cache( 'wc_post' ); + $this->getModule( '\Helper\Wpunit' )->clear_loader_cache( 'wc_post' ); /** * Assertion Two * - * test "DATABASE_ID" ID type. + * Tests "DATABASE_ID" ID type. */ $variables = array( - 'id' => $variation_id, - 'idType' => 'DATABASE_ID', + 'id' => $variation_id, + 'idType' => 'DATABASE_ID', - ); - $actual = graphql( - array( - 'query' => $query, - 'variables' => $variables, - ) - ); - $expected = array( 'data' => array( 'productVariation' => $this->helper->print_query( $variation_id ) ) ); + ); + $actual = graphql( + array( + 'query' => $query, + 'variables' => $variables, + ) + ); + $expected = array( 'data' => array( 'productVariation' => $this->helper->print_query( $variation_id ) ) ); // use --debug flag to view. codecept_debug( $actual ); $this->assertEquals( $expected, $actual ); - } + } - public function testVariationsQueryAndWhereArgs() { + public function testVariationsQueryAndWhereArgs() { $id = $this->product_helper->to_relay_id( $this->products['product'] ); $product = wc_get_product( $this->products['product'] ); - $variations = $this->products['variations']; + $variations = $this->products['variations']; - $query = ' + $query = ' query ( $id: ID!, $minPrice: Float, @@ -157,14 +150,19 @@ public function testVariationsQueryAndWhereArgs() { } '; - /** + /** * Assertion One * * Test query with no arguments */ - wp_set_current_user( $this->shop_manager ); - $variables = array( 'id' => $id ); - $actual = graphql( array( 'query' => $query, 'variables' => $variables ) ); + wp_set_current_user( $this->shop_manager ); + $variables = array( 'id' => $id ); + $actual = graphql( + array( + 'query' => $query, + 'variables' => $variables, + ) + ); // use --debug flag to view. codecept_debug( $actual ); @@ -173,7 +171,7 @@ public function testVariationsQueryAndWhereArgs() { $product_data = $actual['data']['product']; // Assert variations. - foreach( $variations as $vid ) { + foreach ( $variations as $vid ) { $this->assertTrue( in_array( array( 'id' => $this->helper->to_relay_id( $vid ) ), @@ -185,28 +183,34 @@ public function testVariationsQueryAndWhereArgs() { } // Assert prices. - $prices = $this->product_helper->field( $this->products['product'], 'variation_prices', array( true ) ); - $this->assertTrue( - $product_data['price'] === \wc_graphql_price( current( $prices['price'] ) ) - . ' - ' - . \wc_graphql_price( end( $prices['price'] ) ) - ); + $prices = $this->product_helper->field( $this->products['product'], 'variation_prices', array( true ) ); + $expected_price = \wc_graphql_price( current( $prices['price'] ) ) + . ' - ' + . \wc_graphql_price( end( $prices['price'] ) ); + $this->assertTrue( $expected_price === $product_data['price'] ); - $this->assertTrue( - $product_data['regularPrice'] === \wc_graphql_price( current( $prices['regular_price'] ) ) + $expected_price = \wc_graphql_price( current( $prices['regular_price'] ) ) . ' - ' - . \wc_graphql_price( end( $prices['regular_price'] ) ) - ); + . \wc_graphql_price( end( $prices['regular_price'] ) ); + $this->assertTrue( $expected_price === $product_data['regularPrice'] ); - $this->assertTrue( $product_data['salePrice'] === null ); + $this->assertTrue( null === $product_data['salePrice'] ); - /** + /** * Assertion Two * * Test "minPrice" where argument */ - $variables = array( 'id' => $id, 'minPrice' => 15 ); - $actual = graphql( array( 'query' => $query, 'variables' => $variables ) ); + $variables = array( + 'id' => $id, + 'minPrice' => 15, + ); + $actual = graphql( + array( + 'query' => $query, + 'variables' => $variables, + ) + ); // use --debug flag to view. codecept_debug( $actual ); @@ -220,7 +224,7 @@ public function testVariationsQueryAndWhereArgs() { return 15.00 <= floatval( $variation->get_price() ); }; - foreach( array_filter( $variations, $filter ) as $vid ) { + foreach ( array_filter( $variations, $filter ) as $vid ) { $this->assertTrue( in_array( array( 'id' => $this->helper->to_relay_id( $vid ) ), @@ -230,9 +234,9 @@ public function testVariationsQueryAndWhereArgs() { $this->helper->to_relay_id( $vid ) . ' not a variation of ' . $product->get_name() ); } - } + } - public function testProductVariationToMediaItemConnections() { + public function testProductVariationToMediaItemConnections() { $id = $this->helper->to_relay_id( $this->products['variations'][1] ); $query = ' query ($id: ID!) { @@ -246,29 +250,34 @@ public function testProductVariationToMediaItemConnections() { '; $variables = array( 'id' => $id ); - $actual = graphql( array( 'query' => $query, 'variables' => $variables ) ); + $actual = graphql( + array( + 'query' => $query, + 'variables' => $variables, + ) + ); $expected = array( 'data' => array( 'productVariation' => array( - 'id' => $id, - 'image' => array( - 'id' => Relay::toGlobalId( - 'post', - $this->helper->field( $this->products['variations'][1], 'image_id' ) - ), + 'id' => $id, + 'image' => array( + 'id' => Relay::toGlobalId( + 'post', + $this->helper->field( $this->products['variations'][1], 'image_id' ) + ), ), ), ), ); // use --debug flag to view. - codecept_debug( $actual ); + codecept_debug( $actual ); $this->assertEquals( $expected, $actual ); } public function testProductVariationDownloads() { - $id = $this->helper->to_relay_id( $this->products['variations'][0] ); + $id = $this->helper->to_relay_id( $this->products['variations'][0] ); $query = ' query ($id: ID!) { @@ -289,12 +298,17 @@ public function testProductVariationDownloads() { '; $variables = array( 'id' => $id ); - $actual = graphql( array( 'query' => $query, 'variables' => $variables ) ); + $actual = graphql( + array( + 'query' => $query, + 'variables' => $variables, + ) + ); $expected = array( 'data' => array( 'productVariation' => array( - 'id' => $id, - 'downloads' => $this->helper->print_downloads( $this->products['variations'][0] ), + 'id' => $id, + 'downloads' => $this->helper->print_downloads( $this->products['variations'][0] ), ), ), ); diff --git a/tests/wpunit/RefundQueriesTest.php b/tests/wpunit/RefundQueriesTest.php index 7a6287395..89f81b7b3 100644 --- a/tests/wpunit/RefundQueriesTest.php +++ b/tests/wpunit/RefundQueriesTest.php @@ -69,8 +69,8 @@ public function testRefundQuery() { * Test query and results for users with required caps */ $this->loginAsShopManager(); - $response = $this->graphql( compact( 'query', 'variables' ) ); - $expected = $this->expectedRefundData( $refund_id ); + $response = $this->graphql( compact( 'query', 'variables' ) ); + $expected = $this->expectedRefundData( $refund_id ); $this->assertQuerySuccessful( $response, $expected ); } @@ -99,7 +99,7 @@ public function testRefundQueryAndIds() { 'id' => $relay_id, 'idType' => 'ID', ); - $response = $this->graphql( compact( 'query', 'variables' ) ); + $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedField( 'refund.id', $relay_id ) ); $this->assertQuerySuccessful( $response, $expected ); @@ -123,7 +123,7 @@ public function testRefundQueryAndIds() { public function testRefundsQueryAndWhereArgs() { $order_id = $this->factory->order->createNew(); - $refunds = array( + $refunds = array( $this->factory->refund->createNew( $order_id ), $this->factory->refund->createNew( $this->factory->order->createNew() ), $this->factory->refund->createNew( $this->factory->order->createNew(), array( 'status' => 'pending' ) ), @@ -183,7 +183,7 @@ public function testRefundsQueryAndWhereArgs() { * Note: This argument is functionally useless Refunds' "post_status" is always set to "completed". */ $variables = array( 'statuses' => array( 'completed' ) ); - $response = $this->graphql( compact( 'query', 'variables' ) ); + $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedNode( 'refunds.nodes', array( 'databaseId' => $refunds[0] ) ), @@ -201,7 +201,7 @@ public function testRefundsQueryAndWhereArgs() { * Test "orderIn" where argument */ $variables = array( 'orderIn' => array( $order_id ) ); - $response = $this->graphql( compact( 'query', 'variables' ) ); + $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedNode( 'refunds.nodes', array( 'databaseId' => $refunds[0] ) ), @@ -214,11 +214,17 @@ public function testOrderToRefundsConnection() { $order_id = $this->factory->order->createNew(); $refunds = array( $this->factory->refund->createNew( $order_id, array( 'amount' => 0.5 ) ), - $this->factory->refund->createNew( $order_id, array( 'status' => 'pending', 'amount' => 0.5 ) ), + $this->factory->refund->createNew( + $order_id, + array( + 'status' => 'pending', + 'amount' => 0.5, + ) + ), $this->factory->refund->createNew( $this->factory->order->createNew() ), ); - $query = ' + $query = ' query ( $id: ID! ) { order(id: $id) { refunds { @@ -232,7 +238,7 @@ public function testOrderToRefundsConnection() { $this->loginAsShopManager(); $variables = array( 'id' => $this->toRelayId( 'shop_order', $order_id ) ); - $response = $this->graphql( compact( 'query', 'variables' ) ); + $response = $this->graphql( compact( 'query', 'variables' ) ); $expected = array( $this->expectedNode( 'order.refunds.nodes', array( 'databaseId' => $refunds[0] ) ), @@ -247,10 +253,16 @@ public function testCustomerToRefundsConnection() { $refunds = array( $this->factory->refund->createNew( $this->factory->order->createNew() ), $this->factory->refund->createNew( $order_id, array( 'amount' => 0.5 ) ), - $this->factory->refund->createNew( $order_id, array( 'status' => 'pending', 'amount' => 0.5 ) ), + $this->factory->refund->createNew( + $order_id, + array( + 'status' => 'pending', + 'amount' => 0.5, + ) + ), ); - $query = ' + $query = ' query { customer { refunds { diff --git a/tests/wpunit/ShippingMethodQueriesTest.php b/tests/wpunit/ShippingMethodQueriesTest.php index f1e71bee8..4055ac708 100644 --- a/tests/wpunit/ShippingMethodQueriesTest.php +++ b/tests/wpunit/ShippingMethodQueriesTest.php @@ -13,16 +13,10 @@ public function setUp(): void { $this->shop_manager = $this->factory->user->create( array( 'role' => 'shop_manager' ) ); $this->customer = $this->factory->user->create( array( 'role' => 'customer' ) ); - $this->helper = $this->getModule('\Helper\Wpunit')->shipping_method(); + $this->helper = $this->getModule( '\Helper\Wpunit' )->shipping_method(); $this->method = 'flat_rate'; } - public function tearDown(): void { - // your tear down methods here - // then - parent::tearDown(); - } - // tests public function testShippingMethodQueryAndArgs() { $id = Relay::toGlobalId( 'shipping_method', $this->method ); @@ -41,19 +35,19 @@ public function testShippingMethodQueryAndArgs() { /** * Assertion One * - * test "ID" ID type. + * Test "ID" ID type. */ $variables = array( 'id' => $id, 'idType' => 'ID', ); - $actual = graphql( + $actual = graphql( array( 'query' => $query, 'variables' => $variables, - ) + ) ); - $expected = array( 'data' => array( 'shippingMethod' => $this->helper->print_query( $this->method ) ) ); + $expected = array( 'data' => array( 'shippingMethod' => $this->helper->print_query( $this->method ) ) ); // use --debug flag to view. codecept_debug( $actual ); @@ -63,30 +57,29 @@ public function testShippingMethodQueryAndArgs() { /** * Assertion Two * - * test "DATABASE_ID" ID type. + * Test "DATABASE_ID" ID type. */ $variables = array( 'id' => $this->method, 'idType' => 'DATABASE_ID', ); - $actual = graphql( + $actual = graphql( array( 'query' => $query, 'variables' => $variables, - ) + ) ); - $expected = array( 'data' => array( 'shippingMethod' => $this->helper->print_query( $this->method ) ) ); + $expected = array( 'data' => array( 'shippingMethod' => $this->helper->print_query( $this->method ) ) ); // use --debug flag to view. codecept_debug( $actual ); $this->assertEquals( $expected, $actual ); - } public function testShippingMethodsQuery() { $wc_shipping = WC_Shipping::instance(); - $methods = array_values( + $methods = array_values( array_map( function( $method ) { return array( 'id' => Relay::toGlobalId( 'shipping_method', $method->id ) ); @@ -108,9 +101,9 @@ function( $method ) { /** * Assertion One * - * tests query + * Tests query */ - $actual = do_graphql_request( $query, 'shippingMethodQuery' ); + $actual = do_graphql_request( $query, 'shippingMethodQuery' ); $expected = array( 'data' => array( 'shippingMethods' => array( 'nodes' => $methods ) ) ); // use --debug flag to view. diff --git a/tests/wpunit/TaxRateQueriesTest.php b/tests/wpunit/TaxRateQueriesTest.php index cc660f5a6..194aaf468 100644 --- a/tests/wpunit/TaxRateQueriesTest.php +++ b/tests/wpunit/TaxRateQueriesTest.php @@ -13,16 +13,10 @@ public function setUp(): void { $this->shop_manager = $this->factory->user->create( array( 'role' => 'shop_manager' ) ); $this->customer = $this->factory->user->create( array( 'role' => 'customer' ) ); - $this->helper = $this->getModule('\Helper\Wpunit')->tax_rate(); + $this->helper = $this->getModule( '\Helper\Wpunit' )->tax_rate(); $this->rate = $this->helper->create(); } - public function tearDown(): void { - // your tear down methods here - // then - parent::tearDown(); - } - // tests public function testTaxQuery() { $id = Relay::toGlobalId( 'tax_rate', $this->rate ); @@ -50,11 +44,11 @@ class /** * Assertion One * - * tests query, "id" query arg, and results + * Tests query, "id" query arg, and results */ $variables = array( 'id' => $id ); - $actual = do_graphql_request( $query, 'taxRateQuery', $variables ); - $expected = array( 'data' => array( 'taxRate' => $this->helper->print_query( $this->rate ) ) ); + $actual = do_graphql_request( $query, 'taxRateQuery', $variables ); + $expected = array( 'data' => array( 'taxRate' => $this->helper->print_query( $this->rate ) ) ); // use --debug flag to view. codecept_debug( $actual ); @@ -64,14 +58,14 @@ class /** * Assertion Two * - * tests query, "rateId" query arg, and results + * Tests query, "rateId" query arg, and results */ $variables = array( 'id' => $this->rate, 'idType' => 'DATABASE_ID', ); - $actual = do_graphql_request( $query, 'taxRateQuery', $variables ); - $expected = array( 'data' => array( 'taxRate' => $this->helper->print_query( $this->rate ) ) ); + $actual = do_graphql_request( $query, 'taxRateQuery', $variables ); + $expected = array( 'data' => array( 'taxRate' => $this->helper->print_query( $this->rate ) ) ); // use --debug flag to view. codecept_debug( $actual ); @@ -125,7 +119,7 @@ public function testTaxesQuery() { /** * Assertion One * - * tests query + * Tests query */ $actual = graphql( array( 'query' => $query ) ); $expected = array( @@ -136,9 +130,9 @@ function( $id ) { return array( 'id' => Relay::toGlobalId( 'tax_rate', $id ) ); }, $rates - ) - ) - ) + ), + ), + ), ); // use --debug flag to view. @@ -149,7 +143,7 @@ function( $id ) { /** * Assertion Two * - * tests "class" where arg + * Tests "class" where arg */ $variables = array( 'class' => 'REDUCED_RATE' ); $actual = graphql( @@ -174,9 +168,9 @@ function( $id ) { } ) ) - ) - ) - ) + ), + ), + ), ); // use --debug flag to view. @@ -187,7 +181,7 @@ function( $id ) { /** * Assertion Three * - * tests "postCode" where arg + * Tests "postCode" where arg */ $variables = array( 'postCode' => '23451' ); $actual = graphql( @@ -204,9 +198,9 @@ function( $id ) { return array( 'id' => Relay::toGlobalId( 'tax_rate', $id ) ); }, array( $rates[2] ) - ) - ) - ) + ), + ), + ), ); // use --debug flag to view. @@ -217,7 +211,7 @@ function( $id ) { /** * Assertion Four * - * tests "postCodeIn" where arg + * Tests "postCodeIn" where arg */ $variables = array( 'postCodeIn' => array( '123456', '23451' ) ); $actual = graphql( @@ -233,10 +227,10 @@ function( $id ) { function( $id ) { return array( 'id' => Relay::toGlobalId( 'tax_rate', $id ) ); }, - array( $rates[1],$rates[2] ) - ) - ) - ) + array( $rates[1], $rates[2] ) + ), + ), + ), ); // use --debug flag to view. diff --git a/tests/wpunit/VariationAttributeQueriesTest.php b/tests/wpunit/VariationAttributeQueriesTest.php index eafa02d7e..e3d8b2c31 100644 --- a/tests/wpunit/VariationAttributeQueriesTest.php +++ b/tests/wpunit/VariationAttributeQueriesTest.php @@ -1,36 +1,29 @@ shop_manager = $this->factory->user->create( array( 'role' => 'shop_manager' ) ); - $this->customer = $this->factory->user->create( array( 'role' => 'customer' ) ); - $this->product = $this->getModule('\Helper\Wpunit')->product(); - $this->variation = $this->getModule('\Helper\Wpunit')->product_variation(); - $ids = $this->variation->create( $this->product->create_variable() ); - $this->product_id = $ids['product']; - $this->variation_id = $ids['variations'][0]; + $this->shop_manager = $this->factory->user->create( array( 'role' => 'shop_manager' ) ); + $this->customer = $this->factory->user->create( array( 'role' => 'customer' ) ); + $this->product = $this->getModule( '\Helper\Wpunit' )->product(); + $this->variation = $this->getModule( '\Helper\Wpunit' )->product_variation(); + $ids = $this->variation->create( $this->product->create_variable() ); + $this->product_id = $ids['product']; + $this->variation_id = $ids['variations'][0]; - \WPGraphQL::clear_schema(); - } + \WPGraphQL::clear_schema(); + } - public function tearDown(): void { - // your tear down methods here - - // then - parent::tearDown(); - } - - // tests - public function testProductVariationToVariationAttributeQuery() { - $query = ' + // tests + public function testProductVariationToVariationAttributeQuery() { + $query = ' query fromVariationQuery( $id: ID! ) { productVariation( id: $id ) { id @@ -46,30 +39,35 @@ public function testProductVariationToVariationAttributeQuery() { } '; - /** + /** * Assertion One * - * test query and results + * Test query and results */ $variables = array( 'id' => $this->variation->to_relay_id( $this->variation_id ) ); - $actual = graphql( array( 'query' => $query, 'variables' => $variables ) ); + $actual = graphql( + array( + 'query' => $query, + 'variables' => $variables, + ) + ); $expected = array( - 'data' => array( - 'productVariation' => array( - 'id' => $this->variation->to_relay_id( $this->variation_id ), - 'attributes' => $this->variation->print_attributes( $this->variation_id ), - ), - ), - ); + 'data' => array( + 'productVariation' => array( + 'id' => $this->variation->to_relay_id( $this->variation_id ), + 'attributes' => $this->variation->print_attributes( $this->variation_id ), + ), + ), + ); // use --debug flag to view. codecept_debug( $actual ); $this->assertEquals( $expected, $actual ); - } + } - public function testProductToVariationAttributeQuery() { - $query = ' + public function testProductToVariationAttributeQuery() { + $query = ' query ( $id: ID! ) { product( id: $id ) { ... on VariableProduct { @@ -87,26 +85,31 @@ public function testProductToVariationAttributeQuery() { } '; - /** + /** * Assertion One * - * test query and results + * Test query and results */ $variables = array( 'id' => $this->product->to_relay_id( $this->product_id ) ); - $actual = graphql( array( 'query' => $query, 'variables' => $variables ) ); - $expected = array( - 'data' => array( - 'product' => array( - 'id' => $this->product->to_relay_id( $this->product_id ), - 'defaultAttributes' => $this->variation->print_attributes( $this->product_id, 'PRODUCT' ), - ), - ), - ); + $actual = graphql( + array( + 'query' => $query, + 'variables' => $variables, + ) + ); + $expected = array( + 'data' => array( + 'product' => array( + 'id' => $this->product->to_relay_id( $this->product_id ), + 'defaultAttributes' => $this->variation->print_attributes( $this->product_id, 'PRODUCT' ), + ), + ), + ); // use --debug flag to view. codecept_debug( $actual ); $this->assertEquals( $expected, $actual ); - } + } }