WooCommerce - Version 6.3.0

Version Description

2022-03-08 =

See changelog for all versions.

Download this release

Release Info

Developer royho
Plugin Icon 128x128 WooCommerce
Version 6.3.0
Comparing to
See all releases

Code changes from version 6.3.0-rc.2 to 6.3.0

Files changed (180) hide show
  1. i18n/languages/woocommerce.pot +7 -7
  2. includes/class-wc-checkout.php +12 -3
  3. includes/class-wc-session-handler.php +73 -1
  4. packages/woocommerce-blocks/bin/build-plugin-zip.sh +0 -146
  5. packages/woocommerce-blocks/bin/changelog/common/get-entry.js +0 -88
  6. packages/woocommerce-blocks/bin/changelog/common/index.js +0 -4
  7. packages/woocommerce-blocks/bin/changelog/common/make.js +0 -34
  8. packages/woocommerce-blocks/bin/changelog/config.js +0 -46
  9. packages/woocommerce-blocks/bin/changelog/github/index.js +0 -7
  10. packages/woocommerce-blocks/bin/changelog/github/make-change-log.js +0 -70
  11. packages/woocommerce-blocks/bin/changelog/github/requests.js +0 -93
  12. packages/woocommerce-blocks/bin/changelog/index.js +0 -19
  13. packages/woocommerce-blocks/bin/changelog/zenhub/index.js +0 -7
  14. packages/woocommerce-blocks/bin/changelog/zenhub/make-change-log.js +0 -88
  15. packages/woocommerce-blocks/bin/changelog/zenhub/requests.js +0 -100
  16. packages/woocommerce-blocks/bin/copy-plugin-files.sh +0 -34
  17. packages/woocommerce-blocks/bin/development-check.sh +0 -83
  18. packages/woocommerce-blocks/bin/docker/wp-cli/entrypoint.sh +0 -72
  19. packages/woocommerce-blocks/bin/docker/wp-cli/wait-for-it.sh +0 -208
  20. packages/woocommerce-blocks/bin/eslint-plugin-woocommerce/index.js +0 -3
  21. packages/woocommerce-blocks/bin/eslint-plugin-woocommerce/rules/__tests__/feature-flag.js +0 -188
  22. packages/woocommerce-blocks/bin/eslint-plugin-woocommerce/rules/feature-flag.js +0 -255
  23. packages/woocommerce-blocks/bin/eslint-plugin-woocommerce/rules/index.js +0 -1
  24. packages/woocommerce-blocks/bin/fallback-module-directory-webpack-plugin.js +0 -128
  25. packages/woocommerce-blocks/bin/fix-package-lock.sh +0 -76
  26. packages/woocommerce-blocks/bin/github-deploy.sh +0 -190
  27. packages/woocommerce-blocks/bin/hook-docs/actions/index.js +0 -66
  28. packages/woocommerce-blocks/bin/hook-docs/data/actions.json +0 -730
  29. packages/woocommerce-blocks/bin/hook-docs/data/filters.json +0 -951
  30. packages/woocommerce-blocks/bin/hook-docs/filters/index.js +0 -66
  31. packages/woocommerce-blocks/bin/hook-docs/format-hook-doc/example.js +0 -27
  32. packages/woocommerce-blocks/bin/hook-docs/format-hook-doc/exceptions.js +0 -16
  33. packages/woocommerce-blocks/bin/hook-docs/format-hook-doc/files.js +0 -11
  34. packages/woocommerce-blocks/bin/hook-docs/format-hook-doc/index.js +0 -8
  35. packages/woocommerce-blocks/bin/hook-docs/format-hook-doc/params.js +0 -24
  36. packages/woocommerce-blocks/bin/hook-docs/format-hook-doc/related.js +0 -15
  37. packages/woocommerce-blocks/bin/hook-docs/format-hook-doc/returns.js +0 -16
  38. packages/woocommerce-blocks/bin/hook-docs/index.js +0 -39
  39. packages/woocommerce-blocks/bin/hook-docs/utilities/content-with-heading.js +0 -7
  40. packages/woocommerce-blocks/bin/hook-docs/utilities/create-docs.js +0 -25
  41. packages/woocommerce-blocks/bin/hook-docs/utilities/generate-hook-name.js +0 -16
  42. packages/woocommerce-blocks/bin/hook-docs/utilities/generate-introduction.js +0 -71
  43. packages/woocommerce-blocks/bin/hook-docs/utilities/generate-toc.js +0 -38
  44. packages/woocommerce-blocks/bin/hook-docs/utilities/index.js +0 -17
  45. packages/woocommerce-blocks/bin/hook-docs/utilities/json2md.js +0 -12
  46. packages/woocommerce-blocks/bin/hook-docs/utilities/section-with-heading.js +0 -5
  47. packages/woocommerce-blocks/bin/remove-files-webpack-plugin.js +0 -28
  48. packages/woocommerce-blocks/bin/version-changes.sh +0 -22
  49. packages/woocommerce-blocks/bin/webpack-configs.js +0 -765
  50. packages/woocommerce-blocks/bin/webpack-entries.js +0 -156
  51. packages/woocommerce-blocks/bin/webpack-helpers.js +0 -147
  52. packages/woocommerce-blocks/bin/wordpress-deploy.sh +0 -176
  53. packages/woocommerce-blocks/bin/wp-env-config.sh +0 -22
  54. packages/woocommerce-blocks/bin/wp-env-phpunit-pre-config.sh +0 -6
  55. packages/woocommerce-blocks/bin/wp-env-pre-config.sh +0 -3
  56. packages/woocommerce-blocks/docker-compose.yml +0 -82
  57. packages/woocommerce-blocks/docs/blocks/checkout.jpg +0 -0
  58. packages/woocommerce-blocks/docs/blocks/reserve-stock.jpg +0 -0
  59. packages/woocommerce-blocks/postcss.config.js +0 -6
  60. packages/woocommerce-blocks/storybook/__mocks__/woocommerce-base-hooks.js +0 -33
  61. packages/woocommerce-blocks/storybook/__mocks__/woocommerce-block-settings.js +0 -1
  62. packages/woocommerce-blocks/storybook/custom-controls/currency.ts +0 -43
  63. packages/woocommerce-blocks/storybook/custom-controls/index.ts +0 -3
  64. packages/woocommerce-blocks/storybook/main.js +0 -17
  65. packages/woocommerce-blocks/storybook/preview.js +0 -23
  66. packages/woocommerce-blocks/storybook/style.scss +0 -32
  67. packages/woocommerce-blocks/tests/bootstrap.php +0 -52
  68. packages/woocommerce-blocks/tests/e2e/config/custom-matchers/__fixtures__/best-selling-products.fixture.json +0 -1
  69. packages/woocommerce-blocks/tests/e2e/config/custom-matchers/__fixtures__/featured-category.fixture.json +0 -1
  70. packages/woocommerce-blocks/tests/e2e/config/custom-matchers/__fixtures__/hand-picked-products.fixture.json +0 -1
  71. packages/woocommerce-blocks/tests/e2e/config/custom-matchers/__fixtures__/newest-products.fixture.json +0 -1
  72. packages/woocommerce-blocks/tests/e2e/config/custom-matchers/__fixtures__/product-categories-list.fixture.json +0 -1
  73. packages/woocommerce-blocks/tests/e2e/config/custom-matchers/__fixtures__/top-rated-products.fixture.json +0 -1
  74. packages/woocommerce-blocks/tests/e2e/config/custom-matchers/index.js +0 -6
  75. packages/woocommerce-blocks/tests/e2e/config/custom-matchers/to-render-block.js +0 -58
  76. packages/woocommerce-blocks/tests/e2e/config/custom-matchers/to-toggle-element.js +0 -47
  77. packages/woocommerce-blocks/tests/e2e/config/custom-matchers/to-toggle-required-attr-of.js +0 -49
  78. packages/woocommerce-blocks/tests/e2e/config/default.json +0 -63
  79. packages/woocommerce-blocks/tests/e2e/config/environment.js +0 -16
  80. packages/woocommerce-blocks/tests/e2e/config/jest.config.js +0 -38
  81. packages/woocommerce-blocks/tests/e2e/config/jest.setup.js +0 -151
  82. packages/woocommerce-blocks/tests/e2e/config/setup.js +0 -75
  83. packages/woocommerce-blocks/tests/e2e/config/teardown.js +0 -37
  84. packages/woocommerce-blocks/tests/e2e/config/test.json +0 -1
  85. packages/woocommerce-blocks/tests/e2e/fixtures/fixture-data.js +0 -374
  86. packages/woocommerce-blocks/tests/e2e/fixtures/fixture-loaders.js +0 -426
  87. packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/active-product-filters.fixture.json +0 -1
  88. packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/all-products.fixture.json +0 -1
  89. packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/all-reviews.fixture.json +0 -1
  90. packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/cart.fixture.json +0 -1
  91. packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/checkout.fixture.json +0 -1
  92. packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/featured-product.fixture.json +0 -1
  93. packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/filter-products-by-attribute.fixture.json +0 -1
  94. packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/filter-products-by-price.fixture.json +0 -1
  95. packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/filter-products-by-stock.fixture.json +0 -1
  96. packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/mini-cart.fixture.json +0 -1
  97. packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/product-category.fixture.json +0 -1
  98. packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/product-on-sale.fixture.json +0 -1
  99. packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/product-search.fixture.json +0 -4
  100. packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/product-tag.fixture.json +0 -1
  101. packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/products-by-attribute.fixture.json +0 -1
  102. packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/reviews-by-category.fixture.json +0 -1
  103. packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/reviews-by-product.fixture.json +0 -1
  104. packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/single-product.fixture.json +0 -1
  105. packages/woocommerce-blocks/tests/e2e/specs/backend/__snapshots__/product-search.test.js.snap +0 -3
  106. packages/woocommerce-blocks/tests/e2e/specs/backend/active-filters.test.js +0 -81
  107. packages/woocommerce-blocks/tests/e2e/specs/backend/all-products.test.js +0 -53
  108. packages/woocommerce-blocks/tests/e2e/specs/backend/all-reviews.test.js +0 -35
  109. packages/woocommerce-blocks/tests/e2e/specs/backend/attribute-filter.test.js +0 -167
  110. packages/woocommerce-blocks/tests/e2e/specs/backend/cart.test.js +0 -172
  111. packages/woocommerce-blocks/tests/e2e/specs/backend/checkout.test.js +0 -196
  112. packages/woocommerce-blocks/tests/e2e/specs/backend/featured-category.test.js +0 -30
  113. packages/woocommerce-blocks/tests/e2e/specs/backend/featured-product.test.js +0 -30
  114. packages/woocommerce-blocks/tests/e2e/specs/backend/filter-products-by-stock.test.js +0 -60
  115. packages/woocommerce-blocks/tests/e2e/specs/backend/handpicked-products.test.js +0 -30
  116. packages/woocommerce-blocks/tests/e2e/specs/backend/mini-cart.test.js +0 -71
  117. packages/woocommerce-blocks/tests/e2e/specs/backend/price-filter.test.js +0 -112
  118. packages/woocommerce-blocks/tests/e2e/specs/backend/product-best-sellers.test.js +0 -30
  119. packages/woocommerce-blocks/tests/e2e/specs/backend/product-categories.test.js +0 -30
  120. packages/woocommerce-blocks/tests/e2e/specs/backend/product-category.test.js +0 -30
  121. packages/woocommerce-blocks/tests/e2e/specs/backend/product-new.test.js +0 -30
  122. packages/woocommerce-blocks/tests/e2e/specs/backend/product-on-sale.test.js +0 -30
  123. packages/woocommerce-blocks/tests/e2e/specs/backend/product-search.test.js +0 -63
  124. packages/woocommerce-blocks/tests/e2e/specs/backend/product-tag.test.js +0 -30
  125. packages/woocommerce-blocks/tests/e2e/specs/backend/product-top-rated.test.js +0 -30
  126. packages/woocommerce-blocks/tests/e2e/specs/backend/products-by-attribute.test.js +0 -30
  127. packages/woocommerce-blocks/tests/e2e/specs/backend/reviews-by-category.test.js +0 -48
  128. packages/woocommerce-blocks/tests/e2e/specs/backend/reviews-by-product.test.js +0 -62
  129. packages/woocommerce-blocks/tests/e2e/specs/backend/single-product.test.js +0 -32
  130. packages/woocommerce-blocks/tests/e2e/specs/frontend/checkout.test.js +0 -163
  131. packages/woocommerce-blocks/tests/e2e/utils.js +0 -82
  132. packages/woocommerce-blocks/tests/js/jest.config.json +0 -55
  133. packages/woocommerce-blocks/tests/js/jestPreprocess.js +0 -6
  134. packages/woocommerce-blocks/tests/js/setup-after-env.js +0 -4
  135. packages/woocommerce-blocks/tests/js/setup-fetch.js +0 -2
  136. packages/woocommerce-blocks/tests/js/setup-globals.js +0 -104
  137. packages/woocommerce-blocks/tests/php/Assets/AssetDataRegistry.php +0 -98
  138. packages/woocommerce-blocks/tests/php/Bootstrap/MainFile.php +0 -48
  139. packages/woocommerce-blocks/tests/php/Domain/Package.php +0 -46
  140. packages/woocommerce-blocks/tests/php/Domain/Services/CreateAccount.php +0 -240
  141. packages/woocommerce-blocks/tests/php/Domain/Services/DeleteDraftOrders.php +0 -200
  142. packages/woocommerce-blocks/tests/php/Domain/Services/TestExtendRestApi.php +0 -110
  143. packages/woocommerce-blocks/tests/php/Helpers/FixtureData.php +0 -297
  144. packages/woocommerce-blocks/tests/php/Helpers/TestValidateSchema.php +0 -128
  145. packages/woocommerce-blocks/tests/php/Helpers/ValidateSchema.php +0 -113
  146. packages/woocommerce-blocks/tests/php/Registry/Container.php +0 -78
  147. packages/woocommerce-blocks/tests/php/StoreApi/Formatters/TestCurrencyFormatter.php +0 -39
  148. packages/woocommerce-blocks/tests/php/StoreApi/Formatters/TestFormatters.php +0 -48
  149. packages/woocommerce-blocks/tests/php/StoreApi/Formatters/TestHtmlFormatter.php +0 -32
  150. packages/woocommerce-blocks/tests/php/StoreApi/Formatters/TestMoneyFormatter.php +0 -49
  151. packages/woocommerce-blocks/tests/php/StoreApi/Routes/Batch.php +0 -154
  152. packages/woocommerce-blocks/tests/php/StoreApi/Routes/Cart.php +0 -446
  153. packages/woocommerce-blocks/tests/php/StoreApi/Routes/CartCoupons.php +0 -183
  154. packages/woocommerce-blocks/tests/php/StoreApi/Routes/CartExtensions.php +0 -39
  155. packages/woocommerce-blocks/tests/php/StoreApi/Routes/CartItems.php +0 -271
  156. packages/woocommerce-blocks/tests/php/StoreApi/Routes/Checkout.php +0 -225
  157. packages/woocommerce-blocks/tests/php/StoreApi/Routes/ControllerTestCase.php +0 -49
  158. packages/woocommerce-blocks/tests/php/StoreApi/Routes/ProductAttributeTerms.php +0 -99
  159. packages/woocommerce-blocks/tests/php/StoreApi/Routes/ProductAttributes.php +0 -107
  160. packages/woocommerce-blocks/tests/php/StoreApi/Routes/ProductCollectionData.php +0 -185
  161. packages/woocommerce-blocks/tests/php/StoreApi/Routes/Products.php +0 -198
  162. packages/woocommerce-blocks/tests/php/StoreApi/Utilities/CartController.php +0 -82
  163. packages/woocommerce-blocks/tests/php/StoreApi/Utilities/NoticeHandler.php +0 -20
  164. packages/woocommerce-blocks/tests/php/StoreApi/Utilities/OrderController.php +0 -31
  165. packages/woocommerce-blocks/tests/php/StoreApi/Utilities/ProductQueryFilters.php +0 -55
  166. packages/woocommerce-blocks/tests/php/mocks/AssetDataRegistry.php +0 -30
  167. packages/woocommerce-blocks/tests/php/mocks/MockTestDependency.php +0 -11
  168. packages/woocommerce-blocks/tests/utils/find-by-text.ts +0 -61
  169. packages/woocommerce-blocks/tests/utils/find-label-with-text.js +0 -15
  170. packages/woocommerce-blocks/tests/utils/get-block-page-permalink.js +0 -50
  171. packages/woocommerce-blocks/tests/utils/get-normal-page-permalink.js +0 -14
  172. packages/woocommerce-blocks/tests/utils/index.js +0 -8
  173. packages/woocommerce-blocks/tests/utils/save-or-publish.js +0 -22
  174. packages/woocommerce-blocks/tests/utils/scroll-to.ts +0 -13
  175. packages/woocommerce-blocks/tests/utils/select-block-by-name.js +0 -22
  176. packages/woocommerce-blocks/tests/utils/shopper.js +0 -49
  177. packages/woocommerce-blocks/tests/utils/visit-block-page.js +0 -123
  178. readme.txt +4 -4
  179. vendor/composer/installed.php +2 -2
  180. woocommerce.php +2 -2
i18n/languages/woocommerce.pot CHANGED
@@ -2,14 +2,14 @@
2
  # This file is distributed under the same license as the WooCommerce plugin.
3
  msgid ""
4
  msgstr ""
5
- "Project-Id-Version: WooCommerce 6.3.0-rc.2\n"
6
  "Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/woocommerce\n"
7
  "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
8
  "Language-Team: LANGUAGE <LL@li.org>\n"
9
  "MIME-Version: 1.0\n"
10
  "Content-Type: text/plain; charset=UTF-8\n"
11
  "Content-Transfer-Encoding: 8bit\n"
12
- "POT-Creation-Date: 2022-02-28T16:47:57+00:00\n"
13
  "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
14
  "X-Generator: WP-CLI 2.6.0\n"
15
  "X-Domain: woocommerce\n"
@@ -19283,16 +19283,16 @@ msgstr ""
19283
  msgid "Invalid payment method."
19284
  msgstr ""
19285
 
19286
- #: includes/class-wc-checkout.php:1141
19287
- msgid "We were unable to process your order, please try again."
 
19288
  msgstr ""
19289
 
19290
- #. translators: %s: shop cart url
19291
  #: includes/class-wc-checkout.php:1151
19292
- msgid "Sorry, your session has expired. <a href=\"%s\" class=\"wc-backward\">Return to shop</a>"
19293
  msgstr ""
19294
 
19295
- #: includes/class-wc-checkout.php:1182
19296
  msgid "Unable to create order."
19297
  msgstr ""
19298
 
2
  # This file is distributed under the same license as the WooCommerce plugin.
3
  msgid ""
4
  msgstr ""
5
+ "Project-Id-Version: WooCommerce 6.3.0\n"
6
  "Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/woocommerce\n"
7
  "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
8
  "Language-Team: LANGUAGE <LL@li.org>\n"
9
  "MIME-Version: 1.0\n"
10
  "Content-Type: text/plain; charset=UTF-8\n"
11
  "Content-Transfer-Encoding: 8bit\n"
12
+ "POT-Creation-Date: 2022-03-04T16:56:22+00:00\n"
13
  "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
14
  "X-Generator: WP-CLI 2.6.0\n"
15
  "X-Domain: woocommerce\n"
19283
  msgid "Invalid payment method."
19284
  msgstr ""
19285
 
19286
+ #. translators: %s: shop cart url
19287
+ #: includes/class-wc-checkout.php:1140
19288
+ msgid "Sorry, your session has expired. <a href=\"%s\" class=\"wc-backward\">Return to shop</a>"
19289
  msgstr ""
19290
 
 
19291
  #: includes/class-wc-checkout.php:1151
19292
+ msgid "We were unable to process your order, please try again."
19293
  msgstr ""
19294
 
19295
+ #: includes/class-wc-checkout.php:1191
19296
  msgid "Unable to create order."
19297
  msgstr ""
19298
 
includes/class-wc-checkout.php CHANGED
@@ -1134,9 +1134,19 @@ class WC_Checkout {
1134
  */
1135
  public function process_checkout() {
1136
  try {
1137
- $nonce_value = wc_get_var( $_REQUEST['woocommerce-process-checkout-nonce'], wc_get_var( $_REQUEST['_wpnonce'], '' ) ); // phpcs:ignore
 
 
 
 
 
1138
 
1139
  if ( empty( $nonce_value ) || ! wp_verify_nonce( $nonce_value, 'woocommerce-process_checkout' ) ) {
 
 
 
 
 
1140
  WC()->session->set( 'refresh_totals', true );
1141
  throw new Exception( __( 'We were unable to process your order, please try again.', 'woocommerce' ) );
1142
  }
@@ -1147,8 +1157,7 @@ class WC_Checkout {
1147
  do_action( 'woocommerce_before_checkout_process' );
1148
 
1149
  if ( WC()->cart->is_empty() ) {
1150
- /* translators: %s: shop cart url */
1151
- throw new Exception( sprintf( __( 'Sorry, your session has expired. <a href="%s" class="wc-backward">Return to shop</a>', 'woocommerce' ), esc_url( wc_get_page_permalink( 'shop' ) ) ) );
1152
  }
1153
 
1154
  do_action( 'woocommerce_checkout_process' );
1134
  */
1135
  public function process_checkout() {
1136
  try {
1137
+ $nonce_value = wc_get_var( $_REQUEST['woocommerce-process-checkout-nonce'], wc_get_var( $_REQUEST['_wpnonce'], '' ) ); // phpcs:ignore
1138
+ $expiry_message = sprintf(
1139
+ /* translators: %s: shop cart url */
1140
+ __( 'Sorry, your session has expired. <a href="%s" class="wc-backward">Return to shop</a>', 'woocommerce' ),
1141
+ esc_url( wc_get_page_permalink( 'shop' ) )
1142
+ );
1143
 
1144
  if ( empty( $nonce_value ) || ! wp_verify_nonce( $nonce_value, 'woocommerce-process_checkout' ) ) {
1145
+ // If the cart is empty, the nonce check failed because of session expiry.
1146
+ if ( WC()->cart->is_empty() ) {
1147
+ throw new Exception( $expiry_message );
1148
+ }
1149
+
1150
  WC()->session->set( 'refresh_totals', true );
1151
  throw new Exception( __( 'We were unable to process your order, please try again.', 'woocommerce' ) );
1152
  }
1157
  do_action( 'woocommerce_before_checkout_process' );
1158
 
1159
  if ( WC()->cart->is_empty() ) {
1160
+ throw new Exception( $expiry_message );
 
1161
  }
1162
 
1163
  do_action( 'woocommerce_checkout_process' );
includes/class-wc-session-handler.php CHANGED
@@ -88,12 +88,18 @@ class WC_Session_Handler extends WC_Session {
88
  $cookie = $this->get_session_cookie();
89
 
90
  if ( $cookie ) {
 
91
  $this->_customer_id = $cookie[0];
92
  $this->_session_expiration = $cookie[1];
93
  $this->_session_expiring = $cookie[2];
94
  $this->_has_cookie = true;
95
  $this->_data = $this->get_session_data();
96
 
 
 
 
 
 
97
  // If the user logs in, update session.
98
  if ( is_user_logged_in() && strval( get_current_user_id() ) !== $this->_customer_id ) {
99
  $guest_session_id = $this->_customer_id;
@@ -115,6 +121,30 @@ class WC_Session_Handler extends WC_Session {
115
  }
116
  }
117
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  /**
119
  * Sets the session cookie on-demand (usually after adding an item to the cart).
120
  *
@@ -181,12 +211,54 @@ class WC_Session_Handler extends WC_Session {
181
  if ( empty( $customer_id ) ) {
182
  require_once ABSPATH . 'wp-includes/class-phpass.php';
183
  $hasher = new PasswordHash( 8, false );
184
- $customer_id = md5( $hasher->get_random_bytes( 32 ) );
185
  }
186
 
187
  return $customer_id;
188
  }
189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  /**
191
  * Get session unique ID for requests if session is initialized or user ID if logged in.
192
  * Introduced to help with unit tests.
88
  $cookie = $this->get_session_cookie();
89
 
90
  if ( $cookie ) {
91
+ // Customer ID will be an MD5 hash id this is a guest session.
92
  $this->_customer_id = $cookie[0];
93
  $this->_session_expiration = $cookie[1];
94
  $this->_session_expiring = $cookie[2];
95
  $this->_has_cookie = true;
96
  $this->_data = $this->get_session_data();
97
 
98
+ if ( ! $this->is_session_cookie_valid() ) {
99
+ $this->destroy_session();
100
+ $this->set_session_expiration();
101
+ }
102
+
103
  // If the user logs in, update session.
104
  if ( is_user_logged_in() && strval( get_current_user_id() ) !== $this->_customer_id ) {
105
  $guest_session_id = $this->_customer_id;
121
  }
122
  }
123
 
124
+ /**
125
+ * Checks if session cookie is expired, or belongs to a logged out user.
126
+ *
127
+ * @return bool Whether session cookie is valid.
128
+ */
129
+ private function is_session_cookie_valid() {
130
+ // If session is expired, session cookie is invalid.
131
+ if ( time() > $this->_session_expiration ) {
132
+ return false;
133
+ }
134
+
135
+ // If user has logged out, session cookie is invalid.
136
+ if ( ! is_user_logged_in() && ! $this->is_customer_guest( $this->_customer_id ) ) {
137
+ return false;
138
+ }
139
+
140
+ // Session from a different user is not valid. (Although from a guest user will be valid)
141
+ if ( is_user_logged_in() && ! $this->is_customer_guest( $this->_customer_id ) && strval( get_current_user_id() ) !== $this->_customer_id ) {
142
+ return false;
143
+ }
144
+
145
+ return true;
146
+ }
147
+
148
  /**
149
  * Sets the session cookie on-demand (usually after adding an item to the cart).
150
  *
211
  if ( empty( $customer_id ) ) {
212
  require_once ABSPATH . 'wp-includes/class-phpass.php';
213
  $hasher = new PasswordHash( 8, false );
214
+ $customer_id = 't_' . substr( md5( $hasher->get_random_bytes( 32 ) ), 2 );
215
  }
216
 
217
  return $customer_id;
218
  }
219
 
220
+ /**
221
+ * Checks if this is an auto-generated customer ID.
222
+ *
223
+ * @param string|int $customer_id Customer ID to check.
224
+ *
225
+ * @return bool Whether customer ID is randomly generated.
226
+ */
227
+ private function is_customer_guest( $customer_id ) {
228
+ $customer_id = strval( $customer_id );
229
+
230
+ if ( empty( $customer_id ) ) {
231
+ return true;
232
+ }
233
+
234
+ if ( 't_' === substr( $customer_id, 0, 2 ) ) {
235
+ return true;
236
+ }
237
+
238
+ /**
239
+ * Legacy checks. This is to handle sessions that were created from a previous release.
240
+ * Maybe we can get rid of them after a few releases.
241
+ */
242
+
243
+ // Almost all random $customer_ids will have some letters in it, while all actual ids will be integers.
244
+ if ( strval( (int) $customer_id ) !== $customer_id ) {
245
+ return true;
246
+ }
247
+
248
+ // Performance hack to potentially save a DB query, when same user as $customer_id is logged in.
249
+ if ( is_user_logged_in() && strval( get_current_user_id() ) === $customer_id ) {
250
+ return false;
251
+ } else {
252
+ $customer = new WC_Customer( $customer_id );
253
+
254
+ if ( 0 === $customer->get_id() ) {
255
+ return true;
256
+ }
257
+ }
258
+
259
+ return false;
260
+ }
261
+
262
  /**
263
  * Get session unique ID for requests if session is initialized or user ID if logged in.
264
  * Introduced to help with unit tests.
packages/woocommerce-blocks/bin/build-plugin-zip.sh DELETED
@@ -1,146 +0,0 @@
1
- #!/bin/bash
2
-
3
- # Exit if any command fails.
4
- set -e
5
-
6
- TYPE='PRODUCTION'
7
-
8
- print_usage() {
9
- echo "build-plugin-zip - attempt to build a plugin"
10
- echo "By default this will build a clean production build and zip archive"
11
- echo "of the built plugin assets"
12
- echo " "
13
- echo "build-plugin-zip [arguments]"
14
- echo " "
15
- echo "options:"
16
- echo "-h show brief help"
17
- echo "-d build plugin in development mode"
18
- echo "-z build zip only, skipping build commands (so it uses files"
19
- echo " existing on disk already)"
20
- echo " "
21
- }
22
-
23
- # get args
24
- while getopts 'hdz' flag; do
25
- case "${flag}" in
26
- h) print_usage ;;
27
- d) TYPE='DEV' ;;
28
- z) TYPE='ZIP_ONLY' ;;
29
- *)
30
- print_usage
31
- exit 1
32
- ;;
33
- esac
34
- done
35
-
36
- # Tool for grabbing version from package.json
37
- get_version() {
38
- grep '\"version\"' package.json \
39
- | cut -d ':' -f 2 \
40
- | sed 's/"//g' \
41
- | sed 's/,//g' \
42
- | sed 's/ //g'
43
- }
44
-
45
- # Set version
46
- VERSION=$(get_version)
47
-
48
- # Store paths
49
- SOURCE_PATH=$(pwd)
50
-
51
- # Change to the expected directory.
52
- cd "$(dirname "$0")"
53
- cd ..
54
-
55
- # Enable nicer messaging for build status.
56
- BLUE_BOLD='\033[1;34m';
57
- GREEN_BOLD='\033[1;32m';
58
- RED_BOLD='\033[1;31m';
59
- YELLOW_BOLD='\033[1;33m';
60
- COLOR_RESET='\033[0m';
61
- error () {
62
- echo -e "\n${RED_BOLD}$1${COLOR_RESET}\n"
63
- }
64
- status () {
65
- echo -e "\n${BLUE_BOLD}$1${COLOR_RESET}\n"
66
- }
67
- success () {
68
- echo -e "\n${GREEN_BOLD}$1${COLOR_RESET}\n"
69
- }
70
- warning () {
71
- echo -e "\n${YELLOW_BOLD}$1${COLOR_RESET}\n"
72
- }
73
-
74
- status "💃 Time to build a WooCommerce Blocks ZIP 🕺"
75
-
76
- if [ -z "$NO_CHECKS" ]; then
77
- # Make sure there are no changes in the working tree. Release builds should be
78
- # traceable to a particular commit and reliably reproducible. (This is not
79
- # totally true at the moment because we download nightly vendor scripts).
80
- changed=
81
- if ! git diff --exit-code > /dev/null; then
82
- changed="file(s) modified"
83
- elif ! git diff --cached --exit-code > /dev/null; then
84
- changed="file(s) staged"
85
- fi
86
- if [ ! -z "$changed" ]; then
87
- git status
88
- error "ERROR: Cannot build plugin zip with dirty working tree. ☝️
89
- Commit your changes and try again."
90
- exit 1
91
- fi
92
- fi
93
-
94
- # Add version to composer.json
95
- perl -i -pe "s/\"type\":*.+/\"type\":\"wordpress-plugin\",\n\t\"version\": \"${VERSION}\",/" composer.json
96
-
97
- # Run the build.
98
- npm list webpack
99
- if [ $TYPE = 'DEV' ]; then
100
- status "Installing dependencies... 👷‍♀️"
101
- status "==========================="
102
- composer install
103
- PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true npm install
104
- status "==========================="
105
- status "Generating development build... 👷‍♀️"
106
- status "==========================="
107
- npm list webpack
108
- npm run dev
109
- status "==========================="
110
- elif [ $TYPE = 'ZIP_ONLY' ]; then
111
- composer dump-autoload
112
- status "Skipping build commands - using current built assets on disk for built archive...👷‍♀️"
113
- status "==========================="
114
- else
115
- status "Installing dependencies... 📦"
116
- composer install --no-dev
117
- PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true npm install
118
- status "==========================="
119
- status "Generating production build... 👷‍♀️"
120
- status "==========================="
121
- npm list webpack
122
- npm run build
123
- status "==========================="
124
- fi
125
-
126
- # Generate the plugin zip file.
127
- status "Creating archive... 🎁"
128
- mkdir zip-file
129
- mkdir zip-file/build
130
- sh "$SOURCE_PATH/bin/copy-plugin-files.sh" "$SOURCE_PATH" "$SOURCE_PATH/zip-file"
131
- cd "$(pwd)/zip-file"
132
- if [ $TYPE = 'DEV' ]; then
133
- touch blocks.ini
134
- printf 'woocommerce_blocks_phase = 3\nwoocommerce_blocks_env = development' > blocks.ini
135
- fi
136
- zip -r ../woocommerce-gutenberg-products-block.zip ./
137
- cd ..
138
- rm -r zip-file
139
-
140
- # cleanup composer.json
141
- git checkout -- composer.json
142
-
143
- # regenerate classmap for development use
144
- composer dump-autoload
145
-
146
- success "Done. You've built WooCommerce Blocks! 🎉"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/changelog/common/get-entry.js DELETED
@@ -1,88 +0,0 @@
1
- 'use strict';
2
-
3
- const requestPromise = require( 'request-promise' );
4
- const { graphql } = require( '@octokit/graphql' );
5
- const { pkg, REPO } = require( '../config' );
6
-
7
- /* eslint no-console: 0 */
8
-
9
- const headers = {
10
- authorization: `token ${ pkg.changelog.ghApiToken }`,
11
- 'user-agent': 'changelog-tool',
12
- };
13
-
14
- const authedGraphql = graphql.defaults( { headers } );
15
-
16
- const getPullRequestType = ( labels ) => {
17
- const typeLabel = labels.find( ( label ) =>
18
- label.name.includes( pkg.changelog.labelPrefix )
19
- );
20
- if ( ! typeLabel ) {
21
- return pkg.changelog.defaultPrefix;
22
- }
23
- return typeLabel.name.replace( `${ pkg.changelog.labelPrefix } `, '' );
24
- };
25
-
26
- const devNoteSuffix = ( labels ) => {
27
- const noteLabel = labels.find( ( label ) =>
28
- label.name.includes( pkg.changelog.devNoteLabel )
29
- );
30
- return noteLabel ? ' [DN]' : '';
31
- };
32
-
33
- const isCollaborator = async ( username ) => {
34
- return requestPromise( {
35
- url: `https://api.github.com/orgs/${
36
- REPO.split( '/' )[ 0 ]
37
- }/members/${ username }`,
38
- headers,
39
- resolveWithFullResponse: true,
40
- } )
41
- .then( ( response ) => {
42
- return response.statusCode === 204;
43
- } )
44
- .catch( ( err ) => {
45
- if ( err.statusCode !== 404 ) {
46
- console.log( '🤯' );
47
- console.log( err.message );
48
- }
49
- } );
50
- };
51
-
52
- const getEntry = async ( pullRequest ) => {
53
- if (
54
- pullRequest.labels.nodes.some(
55
- ( label ) => label.name === pkg.changelog.skipLabel
56
- )
57
- ) {
58
- return;
59
- }
60
-
61
- const collaborator = await isCollaborator( pullRequest.author.login );
62
- const type = getPullRequestType( pullRequest.labels.nodes );
63
- const authorTag = collaborator ? '' : `👏 @${ pullRequest.author.login }`;
64
- const devNote = devNoteSuffix( pullRequest.labels.nodes );
65
- let title;
66
- if ( /### Changelog\r\n\r\n> /.test( pullRequest.body ) ) {
67
- const bodyParts = pullRequest.body.split( '### Changelog\r\n\r\n> ' );
68
- const note = bodyParts[ bodyParts.length - 1 ];
69
- title = note
70
- // Remove comment prompt
71
- .replace( /<!---(.*)--->/gm, '' )
72
- // Remove new lines and whitespace
73
- .trim();
74
- if ( ! title.length ) {
75
- title = `${ type }: ${ pullRequest.title }`;
76
- } else {
77
- title = `${ type }: ${ title }`;
78
- }
79
- } else {
80
- title = `${ type }: ${ pullRequest.title }`;
81
- }
82
- return `- ${ title } [#${ pullRequest.number }](${ pullRequest.url })${ devNote } ${ authorTag }`;
83
- };
84
-
85
- module.exports = {
86
- authedGraphql,
87
- getEntry,
88
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/changelog/common/index.js DELETED
@@ -1,4 +0,0 @@
1
- const { authedGraphql } = require( './get-entry' );
2
- const { make } = require( './make' );
3
-
4
- module.exports = { authedGraphql, make };
 
 
 
 
packages/woocommerce-blocks/bin/changelog/common/make.js DELETED
@@ -1,34 +0,0 @@
1
- 'use strict';
2
-
3
- const chalk = require( 'chalk' );
4
- const { getEntry } = require( './get-entry' );
5
-
6
- /* eslint no-console: 0*/
7
-
8
- const make = async ( pullRequestFetcher, version ) => {
9
- const pullRequests = await pullRequestFetcher( version );
10
- let entries = await Promise.all(
11
- pullRequests.map( async ( pr ) => await getEntry( pr ) )
12
- );
13
- if ( ! entries || ! entries.length ) {
14
- console.log(
15
- chalk.yellow( "This version doesn't have any associated PR." )
16
- );
17
- return;
18
- }
19
-
20
- entries = entries.filter( Boolean );
21
-
22
- if ( ! entries || ! entries.length ) {
23
- console.log(
24
- chalk.yellow(
25
- 'None of the PRs of this version are eligible for the changelog.'
26
- )
27
- );
28
- return;
29
- }
30
- entries.sort();
31
- console.log( entries.join( '\n' ) );
32
- };
33
-
34
- module.exports = { make };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/changelog/config.js DELETED
@@ -1,46 +0,0 @@
1
- 'use strict';
2
-
3
- const pkg = require( '../../package.json' );
4
- const Config = require( 'merge-config' );
5
-
6
- const config = new Config();
7
-
8
- const changelogSrcTypes = {
9
- MILESTONE: 'MILESTONE',
10
- ZENHUB: 'ZENHUB_RELEASE',
11
- };
12
-
13
- const DEFAULTS = {
14
- labelPrefix: 'type:',
15
- skipLabel: 'no-changelog',
16
- defaultPrefix: 'dev',
17
- changelogSrcType: changelogSrcTypes.MILESTONE,
18
- devNoteLabel: 'dev-note',
19
- repo: '',
20
- ghApiToken: '',
21
- zhApiToken: '',
22
- };
23
-
24
- pkg.changelog = pkg.changelog || DEFAULTS;
25
-
26
- config.merge( { ...DEFAULTS, ...pkg.changelog } );
27
- config.env( [ 'GH_API_TOKEN', 'ZH_API_TOKEN' ] );
28
- config.argv( Object.keys( DEFAULTS ) );
29
-
30
- const REPO = config.get( 'repo' );
31
-
32
- if ( ! REPO ) {
33
- throw new Error(
34
- "The 'repo' configuration value is not set. This script requires the\n" +
35
- 'repository namespace used as the source for the changelog entries.'
36
- );
37
- }
38
-
39
- module.exports = {
40
- pkg: {
41
- ...pkg,
42
- changelog: config.get(),
43
- },
44
- REPO,
45
- changelogSrcTypes,
46
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/changelog/github/index.js DELETED
@@ -1,7 +0,0 @@
1
- 'use-strict';
2
-
3
- const { makeChangeLog } = require( './make-change-log' );
4
-
5
- module.exports = {
6
- makeChangeLog,
7
- };
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/changelog/github/make-change-log.js DELETED
@@ -1,70 +0,0 @@
1
- 'use strict';
2
- const chalk = require( 'chalk' );
3
- const promptly = require( 'promptly' );
4
- const { REPO, pkg } = require( '../config' );
5
- const { make } = require( '../common' );
6
- const { fetchAllPullRequests } = require( './requests' );
7
-
8
- /* eslint no-console: 0 */
9
- let ready = false;
10
-
11
- const makeChangeLog = async () => {
12
- if ( ! pkg.changelog.ghApiToken ) {
13
- console.log(
14
- chalk.yellow(
15
- 'This program requires an api token. You can create one here: '
16
- ) + 'https://github.com/settings/tokens'
17
- );
18
- console.log( '' );
19
- console.log(
20
- chalk.yellow(
21
- 'Token scope will require read permissions on public_repo, admin:org, and user.'
22
- )
23
- );
24
- console.log( '' );
25
- console.log(
26
- chalk.yellow(
27
- 'Export the token as variable called GH_API_TOKEN from your bash profile.'
28
- )
29
- );
30
- console.log( '' );
31
-
32
- ready = await promptly.confirm( 'Are you ready to continue? ' );
33
- } else {
34
- console.log( chalk.green( 'Detected GH_API_TOKEN is set.' ) );
35
- ready = true;
36
- }
37
-
38
- if ( ready ) {
39
- console.log( '' );
40
- console.log(
41
- chalk.yellow(
42
- 'In order to generate the changelog, you will have to provide a version number to retrieve the PRs from.'
43
- )
44
- );
45
- console.log( '' );
46
- console.log(
47
- chalk.yellow( 'Write it as it appears in the milestones page: ' ) +
48
- `https://github.com/${ REPO }/milestones`
49
- );
50
- console.log( '' );
51
- const version = await promptly.prompt( 'Version number: ' );
52
- console.log( '' );
53
- console.log(
54
- chalk.green(
55
- 'Here is the generated changelog. Be sure to remove entries ' +
56
- `not intended for a ${ pkg.title } release.`
57
- )
58
- );
59
- console.log( '' );
60
- make( fetchAllPullRequests, version );
61
- } else {
62
- console.log( '' );
63
- console.log( chalk.yellow( 'Ok, see you soon.' ) );
64
- console.log( '' );
65
- }
66
- };
67
-
68
- module.exports = {
69
- makeChangeLog,
70
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/changelog/github/requests.js DELETED
@@ -1,93 +0,0 @@
1
- 'use strict';
2
-
3
- const { REPO } = require( '../config' );
4
- const { authedGraphql } = require( '../common' );
5
-
6
- /* eslint no-console: 0 */
7
-
8
- const getMilestoneNumber = async ( version ) => {
9
- const [ owner, repo ] = REPO.split( '/' );
10
- const query = `
11
- {
12
- repository(owner: "${ owner }", name: "${ repo }") {
13
- milestones(last: 50) {
14
- nodes {
15
- title
16
- number
17
- }
18
- }
19
- }
20
- }
21
- `;
22
- const data = await authedGraphql( query );
23
- const matchingNode = data.repository.milestones.nodes.find(
24
- ( node ) => node.title === version
25
- );
26
- if ( ! matchingNode ) {
27
- throw new Error(
28
- `Unable to find a milestone matching the given version ${ version }`
29
- );
30
- }
31
- return matchingNode.number;
32
- };
33
-
34
- const getQuery = ( milestoneNumber, before ) => {
35
- const [ owner, repo ] = REPO.split( '/' );
36
- const paging = before ? `, before: "${ before }"` : '';
37
- return `
38
- {
39
- repository(owner: "${ owner }", name: "${ repo }") {
40
- milestone(number: ${ milestoneNumber }) {
41
- pullRequests(last: 100, states: [MERGED]${ paging }) {
42
- totalCount
43
- pageInfo {
44
- hasPreviousPage
45
- startCursor
46
- }
47
- nodes {
48
- number
49
- title
50
- url
51
- author {
52
- login
53
- }
54
- body
55
- labels(last: 10) {
56
- nodes {
57
- name
58
- }
59
- }
60
- }
61
- }
62
- }
63
- }
64
- }
65
- `;
66
- };
67
-
68
- const fetchAllPullRequests = async ( version ) =>
69
- await ( async () => {
70
- const milestoneNumber = await getMilestoneNumber( version );
71
- const fetchResults = async ( before ) => {
72
- const query = getQuery( milestoneNumber, before );
73
- const results = await authedGraphql( query );
74
- if (
75
- results.repository.milestone.pullRequests.pageInfo
76
- .hasPreviousPage === false
77
- ) {
78
- return results.repository.milestone.pullRequests.nodes;
79
- }
80
-
81
- const nextResults = await fetchResults(
82
- results.repository.milestone.pullRequests.pageInfo.startCursor
83
- );
84
- return results.repository.milestone.pullRequests.nodes.concat(
85
- nextResults
86
- );
87
- };
88
- return await fetchResults();
89
- } )();
90
-
91
- module.exports = {
92
- fetchAllPullRequests,
93
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/changelog/index.js DELETED
@@ -1,19 +0,0 @@
1
- #!/usr/bin/env node
2
- 'use strict';
3
- /* eslint no-console: 0 */
4
- const chalk = require( 'chalk' );
5
-
6
- try {
7
- const { makeChangeLog: githubMake } = require( './github' );
8
- const { makeChangeLog: zenhubMake } = require( './zenhub' );
9
- const { pkg, changelogSrcTypes } = require( './config' );
10
-
11
- const makeChangeLog =
12
- pkg.changelog.changelogSrcType === changelogSrcTypes.ZENHUB
13
- ? zenhubMake
14
- : githubMake;
15
-
16
- makeChangeLog();
17
- } catch ( error ) {
18
- console.log( chalk.red( error.message ) );
19
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/changelog/zenhub/index.js DELETED
@@ -1,7 +0,0 @@
1
- 'use-strict';
2
-
3
- const { makeChangeLog } = require( './make-change-log' );
4
-
5
- module.exports = {
6
- makeChangeLog,
7
- };
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/changelog/zenhub/make-change-log.js DELETED
@@ -1,88 +0,0 @@
1
- 'use strict';
2
- const chalk = require( 'chalk' );
3
- const promptly = require( 'promptly' );
4
- const { pkg } = require( '../config' );
5
- const { make } = require( '../common' );
6
- const { fetchAllPullRequests } = require( './requests' );
7
-
8
- /* eslint no-console: 0 */
9
- let ready = false;
10
-
11
- const makeChangeLog = async () => {
12
- if ( ! pkg.changelog.zhApiToken || ! pkg.changelog.ghApiToken ) {
13
- const zenhubSet = pkg.changelog.zhApiToken
14
- ? chalk.green( 'set' )
15
- : chalk.red( 'not set' );
16
- const githubSet = pkg.changelog.ghApiToken
17
- ? chalk.green( 'set' )
18
- : chalk.red( 'not set' );
19
- console.log( `${ chalk.yellow( 'Zenhub Token:' ) } ${ zenhubSet }` );
20
- console.log( `${ chalk.yellow( 'Github Token:' ) } ${ githubSet }` );
21
- console.log( '' );
22
- console.log(
23
- chalk.yellow(
24
- 'This program requires an api token from Github and Zenhub.'
25
- )
26
- );
27
- console.log(
28
- chalk.yellow(
29
- 'You can create and get a Github token here: https://github.com/settings/tokens'
30
- )
31
- );
32
- console.log(
33
- chalk.yellow(
34
- 'You can create and get a Zenhub token here: https://app.zenhub.com/dashboard/tokens'
35
- )
36
- );
37
- console.log( '' );
38
- console.log(
39
- chalk.yellow(
40
- 'Token scope for Github will require read permissions on public_repo, admin:org, and user.'
41
- )
42
- );
43
- console.log( '' );
44
- console.log(
45
- chalk.yellow(
46
- 'Export the github token as variable called GH_API_TOKEN and the Zenhub token as a variable called ZH_API_TOKEN from your bash profile.'
47
- )
48
- );
49
- console.log( '' );
50
-
51
- ready = await promptly.confirm( 'Are you ready to continue? ' );
52
- } else {
53
- console.log(
54
- chalk.green(
55
- 'Detected that ZH_API_TOKEN and GH_API_TOKEN values are set.'
56
- )
57
- );
58
- ready = true;
59
- }
60
-
61
- if ( ready ) {
62
- console.log( '' );
63
- console.log(
64
- chalk.yellow(
65
- 'In order to generate the changelog, you will have to provide the Zenhub release ID to retrieve the PRs from. You can get that from `release` param value in the url of the release report page.'
66
- )
67
- );
68
- console.log( '' );
69
- const releaseId = await promptly.prompt( 'Release Id: ' );
70
- console.log( '' );
71
- console.log(
72
- chalk.green(
73
- 'Here is the generated changelog. Be sure to remove entries ' +
74
- `not intended for a ${ pkg.title } release. All entries with the ${ pkg.changelog.skipLabel } label have been skipped`
75
- )
76
- );
77
- console.log( '' );
78
- make( fetchAllPullRequests, releaseId );
79
- } else {
80
- console.log( '' );
81
- console.log( chalk.yellow( 'Ok, see you soon.' ) );
82
- console.log( '' );
83
- }
84
- };
85
-
86
- module.exports = {
87
- makeChangeLog,
88
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/changelog/zenhub/requests.js DELETED
@@ -1,100 +0,0 @@
1
- 'use strict';
2
-
3
- /* eslint no-console: 0 */
4
-
5
- const ZenHub = require( 'zenhub-api' );
6
- const { REPO, pkg } = require( '../config' );
7
- const { authedGraphql } = require( '../common' );
8
- const { pull } = require( 'lodash' );
9
-
10
- const api = new ZenHub( pkg.changelog.zhApiToken );
11
-
12
- const getQuery = ( before ) => {
13
- const [ owner, repo ] = REPO.split( '/' );
14
- const paging = before ? `, before: "${ before }"` : '';
15
- const query = `
16
- {
17
- repository(owner: "${ owner }", name: "${ repo }") {
18
- pullRequests(last: 100, states: [MERGED]${ paging }) {
19
- totalCount
20
- pageInfo {
21
- startCursor
22
- }
23
- nodes {
24
- number
25
- title
26
- url
27
- author {
28
- login
29
- }
30
- body
31
- labels(last: 10) {
32
- nodes {
33
- name
34
- }
35
- }
36
- }
37
- }
38
- }
39
- }
40
- `;
41
- return query;
42
- };
43
-
44
- const fetchAllIssuesForRelease = async ( releaseId ) => {
45
- const releaseIssues = await api.getReleaseReportIssues( {
46
- release_id: releaseId,
47
- } );
48
- return releaseIssues.map( ( releaseIssue ) => releaseIssue.issue_number );
49
- };
50
-
51
- const extractPullRequestsMatchingReleaseIssue = (
52
- releaseIds,
53
- pullRequests
54
- ) => {
55
- return pullRequests.filter( ( pullRequest ) => {
56
- const hasPullRequest = releaseIds.includes( pullRequest.number );
57
- if ( hasPullRequest ) {
58
- pull( releaseIds, pullRequest.number );
59
- return true;
60
- }
61
- return false;
62
- } );
63
- };
64
-
65
- const fetchAllPullRequests = async ( releaseId ) => {
66
- // first get all release issue ids
67
- const releaseIds = await fetchAllIssuesForRelease( releaseId );
68
- let maxPages = Math.ceil( releaseIds.length / 100 ) + 2;
69
- const fetchResults = async ( before ) => {
70
- const query = getQuery( before );
71
- const results = await authedGraphql( query );
72
- const pullRequests = extractPullRequestsMatchingReleaseIssue(
73
- releaseIds,
74
- results.repository.pullRequests.nodes
75
- );
76
- if ( maxPages === 0 ) {
77
- return pullRequests;
78
- }
79
- maxPages--;
80
- const nextResults = await fetchResults(
81
- results.repository.pullRequests.pageInfo.startCursor
82
- );
83
- return pullRequests.concat(
84
- extractPullRequestsMatchingReleaseIssue( releaseIds, nextResults )
85
- );
86
- };
87
- let results = [];
88
- try {
89
- results = await fetchResults();
90
- } catch ( e ) {
91
- console.log( e.request );
92
- console.log( e.message );
93
- console.log( e.data );
94
- }
95
- return results;
96
- };
97
-
98
- module.exports = {
99
- fetchAllPullRequests,
100
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/copy-plugin-files.sh DELETED
@@ -1,34 +0,0 @@
1
- cd "$1" || exit
2
- rsync ./ "$2"/ --recursive --delete --delete-excluded \
3
- --exclude=assets/ \
4
- --exclude=".*/" \
5
- --exclude="*.md" \
6
- --exclude=".*" \
7
- --exclude="composer.*" \
8
- --exclude="*.lock" \
9
- --exclude=bin/ \
10
- --exclude=node_modules/ \
11
- --exclude=tests/ \
12
- --exclude=docs/ \
13
- --exclude=phpcs.xml \
14
- --exclude=phpunit.xml.dist \
15
- --exclude=CODEOWNERS \
16
- --exclude=renovate.json \
17
- --exclude="*.config.js" \
18
- --exclude="*-config.js" \
19
- --exclude="*.config.json" \
20
- --exclude=package.json \
21
- --exclude=package-lock.json \
22
- --exclude=none \
23
- --exclude=blocks.ini \
24
- --exclude=docker-compose.yml \
25
- --exclude=tsconfig.json \
26
- --exclude=tsconfig.base.json \
27
- --exclude=woocommerce-gutenberg-products-block.zip \
28
- --exclude="zip-file/" \
29
- --exclude=global.d.ts \
30
- --exclude=packages/ \
31
- --exclude=patches/ \
32
- --exclude=reports/ \
33
- --exclude=storybook/
34
- echo -e "\nDone copying files!\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/development-check.sh DELETED
@@ -1,83 +0,0 @@
1
- #!/bin/bash
2
-
3
- # Output colorized strings
4
- #
5
- # Color codes:
6
- # 0 - black
7
- # 1 - red
8
- # 2 - green
9
- # 3 - yellow
10
- # 4 - blue
11
- # 5 - magenta
12
- # 6 - cian
13
- # 7 - white
14
- output() {
15
- echo "$(tput setaf "$1")$2$(tput sgr0)"
16
- }
17
-
18
- pass() {
19
- output 2 "$1"
20
- }
21
-
22
- fail() {
23
- output 1 "$1"
24
- }
25
-
26
- warn() {
27
- output 3 "$1"
28
- }
29
-
30
- function command_exists_as_alias {
31
- alias $1 2>/dev/null >/dev/null
32
- }
33
-
34
- function which {
35
- type "$1" >>/dev/null 2>&1
36
- }
37
-
38
- function command_is_available {
39
- which $1 || command_exists_as_alias $1 || type $1 >/dev/null 2>/dev/null
40
- }
41
-
42
- function node_modules_are_available {
43
- [ -d node_modules ]
44
- }
45
-
46
- function vendor_dir_is_available {
47
- [ -d vendor ]
48
- }
49
-
50
- function assert {
51
- $1 $2 && pass "- $3 is available ✔"
52
- $1 $2 || fail "- $3 is missing ✗ $4"
53
- }
54
-
55
- echo
56
- output 6 "BLOCKS DEVELOPMENT ENVIRONMENT CHECKS"
57
- output 6 "====================================="
58
- echo
59
- echo "Checking under $PWD"
60
- echo
61
- output 6 "(*・‿・)ノ⌒*:・゚✧"
62
-
63
- echo
64
- echo "Tools for building assets"
65
- echo "========================="
66
- echo
67
- assert command_is_available node "Node.js" "Node and NPM allow us to install required dependencies. You can install it from here: https://nodejs.org/en/download/"
68
- assert command_is_available composer "Composer" "Composer allows us to install PHP dependencies. You can install it from https://getcomposer.org, or if you are running Brew you can install it by running $ brew install composer"
69
-
70
- echo
71
- echo "Dependencies"
72
- echo "============"
73
- echo
74
- assert node_modules_are_available "" "node_modules dir" "You need to have node installed and run: $ npm install"
75
- assert vendor_dir_is_available "" "vendor dir" "You need to have composer installed and run: $ composer install"
76
-
77
- echo
78
- echo "Contributing and other helpers"
79
- echo "=============================="
80
- echo
81
- assert command_is_available git "git" "Git is required to push and pull from the GitHub repository. If you're running Brew, you can install it by running $ brew install git"
82
- assert command_is_available hub "Hub" "Hub provides some useful git commands used by the deployment scripts. If you're running Brew, you can install it by running $ brew install hub"
83
- echo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/docker/wp-cli/entrypoint.sh DELETED
@@ -1,72 +0,0 @@
1
- #!/bin/bash
2
- set -eu
3
-
4
- declare -p WORDPRESS_HOST
5
- wait-for-it ${WORDPRESS_HOST} -t 120
6
-
7
- ## if file exists then exit early because initialization already happened.
8
- if [ -f /var/www/html/.initialized ]
9
- then
10
- echo "The environment has already been initialized."
11
- exit 0
12
- fi
13
-
14
- chown xfs:xfs /var/www/html/wp-content
15
- chown xfs:xfs /var/www/html/wp-content/plugins
16
-
17
- ## switch user
18
- if [ $UID -eq 0 ]; then
19
- user=xfs
20
- dir=/var/www/html
21
- cd "$dir"
22
- exec su -s /bin/bash "$user" "$0" -- "$@"
23
- # nothing will be executed beyond that line,
24
- # because exec replaces running process with the new one
25
- fi
26
-
27
- declare -p WORDPRESS_PORT
28
- [[ "${WORDPRESS_PORT}" == 80 ]] && \
29
- URL="http://localhost" || \
30
- URL="http://localhost:${WORDPRESS_PORT}"
31
-
32
- if $(wp core is-installed);
33
- then
34
- echo "Wordpress is already installed..."
35
- else
36
- declare -p WORDPRESS_TITLE >/dev/null
37
- declare -p WORDPRESS_LOGIN >/dev/null
38
- declare -p WORDPRESS_PASSWORD >/dev/null
39
- declare -p WORDPRESS_EMAIL >/dev/null
40
- echo "Installing wordpress..."
41
- wp core install \
42
- --url=${URL} \
43
- --title="$WORDPRESS_TITLE" \
44
- --admin_user=${WORDPRESS_LOGIN} \
45
- --admin_password=${WORDPRESS_PASSWORD} \
46
- --admin_email=${WORDPRESS_EMAIL} \
47
- --skip-email
48
- fi
49
- # WC Rest API needs pretty links to work
50
- wp rewrite structure "/%postname%/" --hard
51
- # we cannot create API keys for the API, so we using basic auth, this plugin allows that.
52
- wp plugin install https://github.com/WP-API/Basic-Auth/archive/master.zip --activate
53
- wp plugin install woocommerce --activate
54
- wp plugin activate woocommerce-gutenberg-products-block
55
- wp theme install storefront --activate
56
- declare -p GUTENBERG_LATEST
57
- if [ "${GUTENBERG_LATEST-}" == 'true' ]; then
58
- wp plugin install gutenberg --activate
59
- fi
60
-
61
- wp user create customer customer@woocommercecoree2etestsuite.com --user_pass=password --role=customer --path=/var/www/html
62
- wp post create --post_type=page --post_status=publish --post_title='Ready' --post_content='E2E-tests.'
63
-
64
- declare -r CURRENT_DOMAIN=$(wp option get siteurl)
65
-
66
- if ! [[ ${CURRENT_DOMAIN} == ${URL} ]]; then
67
- echo "Replacing ${CURRENT_DOMAIN} with ${URL} in database..."
68
- wp search-replace ${CURRENT_DOMAIN} ${URL}
69
- fi
70
-
71
- echo "Visit $(wp option get siteurl)"
72
- touch /var/www/html/.initialized
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/docker/wp-cli/wait-for-it.sh DELETED
@@ -1,208 +0,0 @@
1
- #!/usr/bin/env bash
2
- #source https://github.com/vishnubob/wait-for-it/pull/81
3
- #The MIT License (MIT)
4
- #
5
- #Original work Copyright (c) 2016 Giles Hall: wait-for-it.sh
6
- #Modified work Copyright (c) 2019 iturgeon: wait-for-it.sh
7
- #
8
- #Permission is hereby granted, free of charge, to any person obtaining a copy of
9
- #this software and associated documentation files (the "Software"), to deal in
10
- #the Software without restriction, including without limitation the rights to
11
- #use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
12
- #of the Software, and to permit persons to whom the Software is furnished to do
13
- #so, subject to the following conditions:
14
- #
15
- #The above copyright notice and this permission notice shall be included in all
16
- #copies or substantial portions of the Software.
17
- #
18
- #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
- #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
- #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
- #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
- #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
- #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
- #SOFTWARE.
25
-
26
- # Use this script to test if a given TCP host/port are available
27
-
28
- WAITFORIT_cmdname=${0##*/}
29
-
30
- echoerr() { if [[ $WAITFORIT_QUIET -ne 1 ]]; then echo "$@" 1>&2; fi }
31
-
32
- usage()
33
- {
34
- cat << USAGE >&2
35
- Usage:
36
- $WAITFORIT_cmdname host:port [-s] [-t timeout] [-- command args]
37
- -h HOST | --host=HOST Host or IP under test
38
- -p PORT | --port=PORT TCP port under test
39
- Alternatively, you specify the host and port as host:port
40
- -s | --strict Only execute subcommand if the test succeeds
41
- -q | --quiet Don't output any status messages
42
- -t TIMEOUT | --timeout=TIMEOUT
43
- Timeout in seconds, zero for no timeout
44
- -- COMMAND ARGS Execute command with args after the test finishes
45
- USAGE
46
- exit 1
47
- }
48
-
49
- wait_for()
50
- {
51
- if [[ $WAITFORIT_TIMEOUT -gt 0 ]]; then
52
- echoerr "$WAITFORIT_cmdname: waiting $WAITFORIT_TIMEOUT seconds for $WAITFORIT_HOST:$WAITFORIT_PORT"
53
- else
54
- echoerr "$WAITFORIT_cmdname: waiting for $WAITFORIT_HOST:$WAITFORIT_PORT without a timeout"
55
- fi
56
- WAITFORIT_start_ts=$(date +%s)
57
- while :
58
- do
59
- if [[ $WAITFORIT_ISBUSY -eq 1 ]]; then
60
- nc -z $WAITFORIT_HOST $WAITFORIT_PORT
61
- WAITFORIT_result=$?
62
- else
63
- (echo > /dev/tcp/$WAITFORIT_HOST/$WAITFORIT_PORT) >/dev/null 2>&1
64
- WAITFORIT_result=$?
65
- fi
66
- if [[ $WAITFORIT_result -eq 0 ]]; then
67
- WAITFORIT_end_ts=$(date +%s)
68
- echoerr "$WAITFORIT_cmdname: $WAITFORIT_HOST:$WAITFORIT_PORT is available after $((WAITFORIT_end_ts - WAITFORIT_start_ts)) seconds"
69
- break
70
- fi
71
- sleep 1
72
- done
73
- return $WAITFORIT_result
74
- }
75
-
76
- wait_for_wrapper()
77
- {
78
- # In order to support SIGINT during timeout: http://unix.stackexchange.com/a/57692
79
- if [[ $WAITFORIT_QUIET -eq 1 ]]; then
80
- timeout $WAITFORIT_BUSYTIMEFLAG $WAITFORIT_TIMEOUT $0 --quiet --child --host=$WAITFORIT_HOST --port=$WAITFORIT_PORT --timeout=$WAITFORIT_TIMEOUT &
81
- else
82
- timeout $WAITFORIT_BUSYTIMEFLAG $WAITFORIT_TIMEOUT $0 --child --host=$WAITFORIT_HOST --port=$WAITFORIT_PORT --timeout=$WAITFORIT_TIMEOUT &
83
- fi
84
- WAITFORIT_PID=$!
85
- trap "kill -INT -$WAITFORIT_PID" INT
86
- wait $WAITFORIT_PID
87
- WAITFORIT_RESULT=$?
88
- if [[ $WAITFORIT_RESULT -ne 0 ]]; then
89
- echoerr "$WAITFORIT_cmdname: timeout occurred after waiting $WAITFORIT_TIMEOUT seconds for $WAITFORIT_HOST:$WAITFORIT_PORT"
90
- fi
91
- return $WAITFORIT_RESULT
92
- }
93
-
94
- # process arguments
95
- while [[ $# -gt 0 ]]
96
- do
97
- case "$1" in
98
- *:* )
99
- WAITFORIT_hostport=(${1//:/ })
100
- WAITFORIT_HOST=${WAITFORIT_hostport[0]}
101
- WAITFORIT_PORT=${WAITFORIT_hostport[1]}
102
- shift 1
103
- ;;
104
- --child)
105
- WAITFORIT_CHILD=1
106
- shift 1
107
- ;;
108
- -q | --quiet)
109
- WAITFORIT_QUIET=1
110
- shift 1
111
- ;;
112
- -s | --strict)
113
- WAITFORIT_STRICT=1
114
- shift 1
115
- ;;
116
- -h)
117
- WAITFORIT_HOST="$2"
118
- if [[ $WAITFORIT_HOST == "" ]]; then break; fi
119
- shift 2
120
- ;;
121
- --host=*)
122
- WAITFORIT_HOST="${1#*=}"
123
- shift 1
124
- ;;
125
- -p)
126
- WAITFORIT_PORT="$2"
127
- if [[ $WAITFORIT_PORT == "" ]]; then break; fi
128
- shift 2
129
- ;;
130
- --port=*)
131
- WAITFORIT_PORT="${1#*=}"
132
- shift 1
133
- ;;
134
- -t)
135
- WAITFORIT_TIMEOUT="$2"
136
- if [[ $WAITFORIT_TIMEOUT == "" ]]; then break; fi
137
- shift 2
138
- ;;
139
- --timeout=*)
140
- WAITFORIT_TIMEOUT="${1#*=}"
141
- shift 1
142
- ;;
143
- --)
144
- shift
145
- WAITFORIT_CLI=("$@")
146
- break
147
- ;;
148
- --help)
149
- usage
150
- ;;
151
- *)
152
- echoerr "Unknown argument: $1"
153
- usage
154
- ;;
155
- esac
156
- done
157
-
158
- if [[ "$WAITFORIT_HOST" == "" || "$WAITFORIT_PORT" == "" ]]; then
159
- echoerr "Error: you need to provide a host and port to test."
160
- usage
161
- fi
162
-
163
- WAITFORIT_TIMEOUT=${WAITFORIT_TIMEOUT:-15}
164
- WAITFORIT_STRICT=${WAITFORIT_STRICT:-0}
165
- WAITFORIT_CHILD=${WAITFORIT_CHILD:-0}
166
- WAITFORIT_QUIET=${WAITFORIT_QUIET:-0}
167
- WAITFORIT_ISBUSY=0
168
- WAITFORIT_BUSYTIMEFLAG=""
169
- WAITFORIT_TIMEOUT_PATH=$(type -p timeout)
170
- WAITFORIT_TIMEOUT_PATH=$(realpath $WAITFORIT_TIMEOUT_PATH 2>/dev/null || readlink -f $WAITFORIT_TIMEOUT_PATH)
171
-
172
- # check to see if we're using busybox?
173
- if [[ $WAITFORIT_TIMEOUT_PATH =~ "busybox" ]]; then
174
- WAITFORIT_ISBUSY=1
175
- fi
176
-
177
- # see if timeout.c args have been updated in busybox v1.30.0 or newer
178
- # note: this requires the use of bash on Alpine
179
- if [[ $WAITFORIT_ISBUSY && $(busybox | head -1) =~ ^.*v([[:digit:]]+)\.([[:digit:]]+)\..+$ ]]; then
180
- if [[ ${BASH_REMATCH[1]} -le 1 && ${BASH_REMATCH[2]} -lt 30 ]]; then
181
- # using pre 1.30.0 version with `-t SEC` arg
182
- WAITFORIT_BUSYTIMEFLAG="-t"
183
- fi
184
- fi
185
-
186
- if [[ $WAITFORIT_CHILD -gt 0 ]]; then
187
- wait_for
188
- WAITFORIT_RESULT=$?
189
- exit $WAITFORIT_RESULT
190
- else
191
- if [[ $WAITFORIT_TIMEOUT -gt 0 ]]; then
192
- wait_for_wrapper
193
- WAITFORIT_RESULT=$?
194
- else
195
- wait_for
196
- WAITFORIT_RESULT=$?
197
- fi
198
- fi
199
-
200
- if [[ $WAITFORIT_CLI != "" ]]; then
201
- if [[ $WAITFORIT_RESULT -ne 0 && $WAITFORIT_STRICT -eq 1 ]]; then
202
- echoerr "$WAITFORIT_cmdname: strict mode, refusing to execute subprocess"
203
- exit $WAITFORIT_RESULT
204
- fi
205
- exec "${WAITFORIT_CLI[@]}"
206
- else
207
- exit $WAITFORIT_RESULT
208
- fi
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/eslint-plugin-woocommerce/index.js DELETED
@@ -1,3 +0,0 @@
1
- module.exports = {
2
- rules: require( './rules' ),
3
- };
 
 
 
packages/woocommerce-blocks/bin/eslint-plugin-woocommerce/rules/__tests__/feature-flag.js DELETED
@@ -1,188 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import { RuleTester } from 'eslint';
5
-
6
- /**
7
- * Internal dependencies
8
- */
9
- import rule from '../feature-flag';
10
-
11
- const ruleTester = new RuleTester( {
12
- parserOptions: {
13
- sourceType: 'module',
14
- ecmaVersion: 6,
15
- },
16
- } );
17
-
18
- ruleTester.run( 'feature-flag', rule, {
19
- valid: [
20
- {
21
- code: `
22
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE === 'experimental' ) {
23
- registerBlockType( 'woocommerce/checkout', settings );
24
- }`,
25
- },
26
- ],
27
- invalid: [
28
- {
29
- code: `
30
- if ( WOOCOMMERCE_BLOCKS_PHASE === 'experimental' ) {
31
- registerBlockType( 'woocommerce/checkout', settings );
32
- }`,
33
- errors: [
34
- {
35
- messageId: 'accessedViaEnv',
36
- },
37
- ],
38
- output: `
39
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE === 'experimental' ) {
40
- registerBlockType( 'woocommerce/checkout', settings );
41
- }`,
42
- },
43
- {
44
- code: `
45
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE !== 'experimental' ) {
46
- registerBlockType( 'woocommerce/checkout', settings );
47
- }`,
48
- errors: [
49
- {
50
- messageId: 'equalOperator',
51
- },
52
- ],
53
- output: `
54
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE === 'experimental' ) {
55
- registerBlockType( 'woocommerce/checkout', settings );
56
- }`,
57
- },
58
- {
59
- code: `
60
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE == 'experimental' ) {
61
- registerBlockType( 'woocommerce/checkout', settings );
62
- }`,
63
- errors: [
64
- {
65
- messageId: 'equalOperator',
66
- },
67
- ],
68
- output: `
69
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE === 'experimental' ) {
70
- registerBlockType( 'woocommerce/checkout', settings );
71
- }`,
72
- },
73
- {
74
- code: `
75
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE > 'experimental' ) {
76
- registerBlockType( 'woocommerce/checkout', settings );
77
- }`,
78
- errors: [
79
- {
80
- messageId: 'equalOperator',
81
- },
82
- ],
83
- output: `
84
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE === 'experimental' ) {
85
- registerBlockType( 'woocommerce/checkout', settings );
86
- }`,
87
- },
88
- {
89
- code: `
90
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE < 'experimental' ) {
91
- registerBlockType( 'woocommerce/checkout', settings );
92
- }`,
93
- errors: [
94
- {
95
- messageId: 'equalOperator',
96
- },
97
- ],
98
- output: `
99
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE === 'experimental' ) {
100
- registerBlockType( 'woocommerce/checkout', settings );
101
- }`,
102
- },
103
- {
104
- code: `
105
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE >= 'experimental' ) {
106
- registerBlockType( 'woocommerce/checkout', settings );
107
- }`,
108
- errors: [
109
- {
110
- messageId: 'equalOperator',
111
- },
112
- ],
113
- output: `
114
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE === 'experimental' ) {
115
- registerBlockType( 'woocommerce/checkout', settings );
116
- }`,
117
- },
118
- {
119
- code: `
120
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE <= 'experimental' ) {
121
- registerBlockType( 'woocommerce/checkout', settings );
122
- }`,
123
- errors: [
124
- {
125
- messageId: 'equalOperator',
126
- },
127
- ],
128
- output: `
129
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE === 'experimental' ) {
130
- registerBlockType( 'woocommerce/checkout', settings );
131
- }`,
132
- },
133
- {
134
- code: `
135
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE == 'experimental' ) {
136
- registerBlockType( 'woocommerce/checkout', settings );
137
- }`,
138
- errors: [
139
- {
140
- messageId: 'equalOperator',
141
- },
142
- ],
143
- output: `
144
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE === 'experimental' ) {
145
- registerBlockType( 'woocommerce/checkout', settings );
146
- }`,
147
- },
148
- {
149
- code: `
150
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE > 'experimental' ) {
151
- registerBlockType( 'woocommerce/checkout', settings );
152
- }`,
153
- errors: [
154
- {
155
- messageId: 'equalOperator',
156
- },
157
- ],
158
- output: `
159
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE === 'experimental' ) {
160
- registerBlockType( 'woocommerce/checkout', settings );
161
- }`,
162
- },
163
- {
164
- code: `
165
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE === 'core' ) {
166
- registerBlockType( 'woocommerce/checkout', settings );
167
- }`,
168
- errors: [
169
- {
170
- messageId: 'whiteListedFlag',
171
- },
172
- ],
173
- output: `
174
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE === 'experimental' ) {
175
- registerBlockType( 'woocommerce/checkout', settings );
176
- }`,
177
- },
178
- {
179
- code: `
180
- const featureFlag = process.env.WOOCOMMERCE_BLOCKS_PHASE === 'experimental'`,
181
- errors: [
182
- {
183
- messageId: 'noTernary',
184
- },
185
- ],
186
- },
187
- ],
188
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/eslint-plugin-woocommerce/rules/feature-flag.js DELETED
@@ -1,255 +0,0 @@
1
- /**
2
- * Traverse up through the chain of parent AST nodes returning the first parent
3
- * the predicate returns a truthy value for.
4
- *
5
- * @param {Object} sourceNode The AST node to search from.
6
- * @param {Function} predicate A predicate invoked for each parent.
7
- *
8
- * @return {?Object } The first encountered parent node where the predicate
9
- * returns a truthy value.
10
- */
11
- function findParent( sourceNode, predicate ) {
12
- if ( ! sourceNode.parent ) {
13
- return;
14
- }
15
-
16
- if ( predicate( sourceNode.parent ) ) {
17
- return sourceNode.parent;
18
- }
19
-
20
- return findParent( sourceNode.parent, predicate );
21
- }
22
-
23
- /**
24
- * Tests whether the WOOCOMMERCE_BLOCKS_PHASE variable is accessed via
25
- * `process.env.WOOCOMMERCE_BLOCKS_PHASE`.
26
- *
27
- * @example
28
- * ```js
29
- * // good
30
- * if ( process.env.WOOCOMMERCE_BLOCKS_PHASE > 1 ) {
31
- *
32
- * // bad
33
- * if ( WOOCOMMERCE_BLOCKS_PHASE > 1 ) {
34
- * ```
35
- *
36
- * @param {Object} node The WOOCOMMERCE_BLOCKS_PHASE identifier node.
37
- * @param {Object} context The eslint context object.
38
- * @todo update this rule to match the new flags.
39
- */
40
- function testIsAccessedViaProcessEnv( node, context ) {
41
- let parent = node.parent;
42
-
43
- if (
44
- parent &&
45
- parent.type === 'MemberExpression' &&
46
- context.getSource( parent ) === 'process.env.WOOCOMMERCE_BLOCKS_PHASE'
47
- ) {
48
- return;
49
- }
50
- if ( parent && parent.type === 'BinaryExpression' ) {
51
- if ( parent.left.type === 'Identifier' ) {
52
- parent = parent.left;
53
- } else {
54
- parent = parent.right;
55
- }
56
- }
57
- context.report( {
58
- node,
59
- messageId: 'accessedViaEnv',
60
- fix( fixer ) {
61
- return fixer.replaceText(
62
- parent,
63
- 'process.env.WOOCOMMERCE_BLOCKS_PHASE'
64
- );
65
- },
66
- } );
67
- }
68
-
69
- /**
70
- * Tests whether the WOOCOMMERCE_BLOCKS_PHASE strict binary comparison
71
- * is strict equal only
72
- *
73
- * @example
74
- * ```js
75
- * // good
76
- * if ( process.env.WOOCOMMERCE_BLOCKS_PHASE === 'experimental' ) {
77
- * if ( process.env.WOOCOMMERCE_BLOCKS_PHASE === 'stable' ) {
78
- *
79
- * // bad
80
- * if ( process.env.WOOCOMMERCE_BLOCKS_PHASE !== 'experimental' ) {
81
- * if ( process.env.WOOCOMMERCE_BLOCKS_PHASE !== 'stable' ) {
82
- * ```
83
- *
84
- * @param {Object} node The WOOCOMMERCE_BLOCKS_PHASE identifier node.
85
- * @param {Object} context The eslint context object.
86
- */
87
- function testBinaryExpressionOperatorIsEqual( node, context ) {
88
- const sourceCode = context.getSourceCode();
89
- node = node.parent.parent;
90
- if ( node.type === 'BinaryExpression' ) {
91
- const operatorToken = sourceCode.getFirstTokenBetween(
92
- node.left,
93
- node.right,
94
- ( token ) => token.value === node.operator
95
- );
96
-
97
- if ( operatorToken.value === '===' ) {
98
- return;
99
- }
100
- context.report( {
101
- node,
102
- loc: operatorToken.loc,
103
- messageId: 'equalOperator',
104
- fix( fixer ) {
105
- return fixer.replaceText( operatorToken, '===' );
106
- },
107
- } );
108
- }
109
- }
110
-
111
- /**
112
- * Tests whether the WOOCOMMERCE_BLOCKS_PHASE variable is used in a strict binary
113
- * equality expression in a comparison with a enum of string flags, triggering a
114
- * violation if not.
115
- *
116
- * @example
117
- * ```js
118
- * // good
119
- * if ( process.env.WOOCOMMERCE_BLOCKS_PHASE === 'experimental' ) {
120
- * if ( process.env.WOOCOMMERCE_BLOCKS_PHASE === 'stable' ) {
121
- *
122
- * // bad
123
- * if ( process.env.WOOCOMMERCE_BLOCKS_PHASE == 'experimental' ) {
124
- * if ( process.env.WOOCOMMERCE_BLOCKS_PHASE === 'core' ) {
125
- * ```
126
- *
127
- * @param {Object} node The WOOCOMMERCE_BLOCKS_PHASE identifier node.
128
- * @param {Object} context The eslint context object.
129
- */
130
- function testIsUsedInStrictBinaryExpression( node, context ) {
131
- const parent = findParent(
132
- node,
133
- ( candidate ) => candidate.type === 'BinaryExpression'
134
- );
135
- const flags = [ 'experimental', 'stable' ];
136
- let providedFlag;
137
- if ( parent ) {
138
- const comparisonNode =
139
- node.parent.type === 'MemberExpression' ? node.parent : node;
140
- const hasCorrectOperands =
141
- ( parent.left === comparisonNode &&
142
- flags.includes( parent.right.value ) ) ||
143
- ( parent.right === comparisonNode &&
144
- flags.includes( parent.left.value ) );
145
- if (
146
- parent.left === comparisonNode &&
147
- typeof parent.right.value === 'string'
148
- ) {
149
- providedFlag = parent.right;
150
- } else {
151
- providedFlag = parent.left;
152
- }
153
- if ( hasCorrectOperands ) {
154
- return;
155
- }
156
- }
157
-
158
- if ( providedFlag && providedFlag.loc ) {
159
- context.report( {
160
- node,
161
- loc: providedFlag.loc,
162
- messageId: 'whiteListedFlag',
163
- data: {
164
- flags: flags.join( ', ' ),
165
- },
166
- fix( fixer ) {
167
- return fixer.replaceText( providedFlag, "'experimental'" );
168
- },
169
- } );
170
- }
171
- }
172
-
173
- /**
174
- * Tests whether the WOOCOMMERCE_BLOCKS_PHASE variable is used as the condition for an
175
- * if statement, triggering a violation if not.
176
- *
177
- * @example
178
- * ```js
179
- * // good
180
- * if ( process.env.WOOCOMMERCE_BLOCKS_PHASE === 'experimental' ) {
181
- *
182
- * // bad
183
- * const isFeatureActive = process.env.WOOCOMMERCE_BLOCKS_PHASE === 'experimental';
184
- * ```
185
- *
186
- * @param {Object} node The WOOCOMMERCE_BLOCKS_PHASE identifier node.
187
- * @param {Object} context The eslint context object.
188
- */
189
- function testIsUsedInIfOrTernary( node, context ) {
190
- const conditionalParent = findParent( node, ( candidate ) =>
191
- [ 'IfStatement', 'ConditionalExpression' ].includes( candidate.type )
192
- );
193
- const binaryParent = findParent(
194
- node,
195
- ( candidate ) => candidate.type === 'BinaryExpression'
196
- );
197
-
198
- if (
199
- conditionalParent &&
200
- binaryParent &&
201
- conditionalParent.test &&
202
- conditionalParent.test.range[ 0 ] === binaryParent.range[ 0 ] &&
203
- conditionalParent.test.range[ 1 ] === binaryParent.range[ 1 ]
204
- ) {
205
- return;
206
- }
207
-
208
- context.report( {
209
- node,
210
- messageId: 'noTernary',
211
- } );
212
- }
213
-
214
- module.exports = {
215
- meta: {
216
- type: 'problem',
217
- schema: [],
218
- fixable: 'code',
219
- messages: {
220
- accessedViaEnv:
221
- 'The `WOOCOMMERCE_BLOCKS_PHASE` constant should be accessed using `process.env.WOOCOMMERCE_BLOCKS_PHASE`.',
222
- whiteListedFlag:
223
- 'The `WOOCOMMERCE_BLOCKS_PHASE` constant should only be used in a strict equality comparison with a predefined flag of: {{ flags }}.',
224
- equalOperator:
225
- 'The `WOOCOMMERCE_BLOCKS_PHASE` comparison should only be a strict equal `===`, if you need `!==` try switching the flag ',
226
- noTernary:
227
- 'The `WOOCOMMERCE_BLOCKS_PHASE` constant should only be used as part of the condition in an if statement or ternary expression.',
228
- },
229
- },
230
- create( context ) {
231
- return {
232
- Identifier( node ) {
233
- // Bypass any identifiers with a node name different to `WOOCOMMERCE_BLOCKS_PHASE`.
234
- if ( node.name !== 'WOOCOMMERCE_BLOCKS_PHASE' ) {
235
- return;
236
- }
237
-
238
- testIsAccessedViaProcessEnv( node, context );
239
- testIsUsedInStrictBinaryExpression( node, context );
240
- testBinaryExpressionOperatorIsEqual( node, context );
241
- testIsUsedInIfOrTernary( node, context );
242
- },
243
- Literal( node ) {
244
- // Bypass any identifiers with a node value different to `WOOCOMMERCE_BLOCKS_PHASE`.
245
- if ( node.value !== 'WOOCOMMERCE_BLOCKS_PHASE' ) {
246
- return;
247
- }
248
-
249
- if ( node.parent && node.parent.type === 'MemberExpression' ) {
250
- testIsAccessedViaProcessEnv( node, context );
251
- }
252
- },
253
- };
254
- },
255
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/eslint-plugin-woocommerce/rules/index.js DELETED
@@ -1 +0,0 @@
1
- module.exports = require( 'requireindex' )( __dirname );
 
packages/woocommerce-blocks/bin/fallback-module-directory-webpack-plugin.js DELETED
@@ -1,128 +0,0 @@
1
- /*eslint-env node*/
2
-
3
- /**
4
- * External dependencies
5
- */
6
- const fs = require( 'fs' );
7
- const path = require( 'path' );
8
-
9
- // Note, this has some inspiration from the AliasPlugin and its implementation
10
- // @see https://github.com/webpack/enhanced-resolve/blob/v4.1.0/lib/AliasPlugin.js
11
-
12
- module.exports = class FallbackModuleDirectoryWebpackPlugin {
13
- constructor( search, replacement, alias ) {
14
- this.search = search;
15
- this.replacement = replacement;
16
- this.alias = this.parseAlias( alias );
17
- this.hooks = [
18
- [ 'described-resolve', 'resolve' ],
19
- [ 'file', 'resolve' ],
20
- ];
21
- this.applyFallback = this.applyFallback.bind( this );
22
- this.doApply = this.doApply.bind( this );
23
- }
24
-
25
- parseAlias( alias ) {
26
- if ( typeof alias === 'object' && ! Array.isArray( alias ) ) {
27
- alias = Object.keys( alias ).map( ( key ) => {
28
- let onlyModule = false;
29
- let obj = alias[ key ];
30
- if ( /\$$/.test( key ) ) {
31
- onlyModule = true;
32
- key = key.substr( 0, key.length - 1 );
33
- }
34
- if ( typeof obj === 'string' ) {
35
- obj = {
36
- alias: obj,
37
- };
38
- }
39
- obj = Object.assign(
40
- {
41
- name: key,
42
- onlyModule,
43
- },
44
- obj
45
- );
46
- return obj;
47
- } );
48
- }
49
- return alias;
50
- }
51
-
52
- getPathWithExtension( pathString ) {
53
- if ( ! Boolean( path.extname( pathString ) ) ) {
54
- return pathString + '.js';
55
- }
56
- return pathString;
57
- }
58
-
59
- applyFallback( pathString ) {
60
- if (
61
- pathString.includes( this.search ) &&
62
- ! fs.existsSync( pathString ) &&
63
- ! fs.existsSync( this.getPathWithExtension( pathString ) )
64
- ) {
65
- return pathString.replace( this.search, this.replacement );
66
- }
67
- return pathString;
68
- }
69
-
70
- doApply( resolver, source, target, alias ) {
71
- resolver
72
- .getHook( source )
73
- .tapAsync(
74
- 'FallbackModuleDirectoryWebpackPlugin',
75
- ( request, resolveContext, callback ) => {
76
- const innerRequest = request.request || request.path;
77
-
78
- if ( ! innerRequest ) return callback();
79
-
80
- for ( const item of alias ) {
81
- if (
82
- innerRequest === item.name ||
83
- ( ! item.onlyModule &&
84
- innerRequest.startsWith( item.name + '/' ) )
85
- ) {
86
- if (
87
- innerRequest !== item.alias &&
88
- ! innerRequest.startsWith( item.alias + '/' )
89
- ) {
90
- const newRequestStr = this.applyFallback(
91
- item.alias +
92
- innerRequest.substr( item.name.length )
93
- );
94
- const obj = {
95
- ...request,
96
- request: newRequestStr,
97
- };
98
- return resolver.doResolve(
99
- target,
100
- obj,
101
- `aliased with mapping '${ item.name }' to '${ newRequestStr }'`,
102
- resolveContext,
103
- ( err, result ) => {
104
- if ( err ) return callback( err );
105
-
106
- // Don't allow other aliasing or raw request
107
- if ( result === undefined ) {
108
- return callback( null, null );
109
- }
110
- callback( null, result );
111
- }
112
- );
113
- }
114
- }
115
- }
116
- return callback();
117
- }
118
- );
119
- }
120
-
121
- apply( resolver ) {
122
- const alias = this.alias;
123
- this.hooks.forEach( ( [ source, target ] ) => {
124
- target = resolver.ensureHook( target );
125
- this.doApply( resolver, source, target, alias );
126
- } );
127
- }
128
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/fix-package-lock.sh DELETED
@@ -1,76 +0,0 @@
1
- #!/bin/bash
2
-
3
- # Enable nicer messaging for build status.
4
- BLUE_BOLD='\033[1;34m';
5
- RED_BOLD='\033[1;31m';
6
- COLOR_RESET='\033[0m';
7
- GREEN_BOLD='\033[1;32m';
8
- RED_BOLD='\033[1;31m';
9
- YELLOW_BOLD='\033[1;33m';
10
- error () {
11
- echo -e "${RED_BOLD}$1${COLOR_RESET}\n";
12
- exit 0;
13
- }
14
- status () {
15
- echo -e "${BLUE_BOLD}$1${COLOR_RESET}\n"
16
- }
17
- success () {
18
- echo -e "${GREEN_BOLD}$1${COLOR_RESET}\n"
19
- }
20
- warning () {
21
- echo -e "${YELLOW_BOLD}$1${COLOR_RESET}\n"
22
- }
23
-
24
- [[ -z "$1" ]] && {
25
- error "You must specify a branch to fix, for example: npm run fix-package-lock your/branch";
26
- }
27
-
28
- echo -e "${YELLOW_BOLD} ___ ___ ___
29
- | | | |
30
- |___|___|___|
31
- | | | |
32
- |___|___|___|
33
- | | | |
34
- |___|___|___|
35
-
36
- FIX PACKAGE LOCK
37
- ================
38
- This script will attempt to rebase a Renovate PR and update the package.lock file.
39
- Usage: npm run fix-package-lock branch/name
40
- ${COLOR_RESET}"
41
-
42
- echo -e "${RED_BOLD}BEFORE PROCEEDING\n=================
43
- You should check the PR on GitHub to see if it already has conflicts with trunk.
44
- If it does, use the checkbox in the PR to force Renovate to rebase it for you.
45
- Once the PR has been rebased, you can run this script, and then do a squash merge on GitHub.${COLOR_RESET}"
46
-
47
- printf "Ready to proceed? [y/N]: "
48
- read -r PROCEED
49
- echo
50
-
51
- if [ "$(echo "${PROCEED:-n}" | tr "[:upper:]" "[:lower:]")" != "y" ]; then
52
- exit
53
- fi
54
-
55
- git fetch
56
-
57
- if ! git checkout $1
58
- then
59
- error "Unable to checkout branch";
60
- else
61
- success "Checked out branch"
62
- fi
63
-
64
- status "Removing package-lock.json...";
65
- rm package-lock.json
66
-
67
- status "Installing dependencies...";
68
- npm cache verify
69
- npm install
70
-
71
- status "Comitting updated package-lock.json...";
72
- git add package-lock.json
73
- git commit -m 'update package-lock.json'
74
- git push --force-with-lease
75
-
76
- success "Done. Package Lock has been updated. 🎉"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/github-deploy.sh DELETED
@@ -1,190 +0,0 @@
1
- #!/bin/sh
2
-
3
- RELEASER_PATH="$(pwd)"
4
- IS_PRE_RELEASE=false
5
-
6
- # Functions
7
- # Check if string contains substring
8
- is_substring() {
9
- case "$2" in
10
- *$1*)
11
- return 0
12
- ;;
13
- *)
14
- return 1
15
- ;;
16
- esac
17
- }
18
-
19
- # Output colorized strings
20
- #
21
- # Color codes:
22
- # 0 - black
23
- # 1 - red
24
- # 2 - green
25
- # 3 - yellow
26
- # 4 - blue
27
- # 5 - magenta
28
- # 6 - cian
29
- # 7 - white
30
- output() {
31
- echo "$(tput setaf "$1")$2$(tput sgr0)"
32
- }
33
-
34
- if ! [ -x "$(command -v hub)" ]; then
35
- echo 'Error: hub is not installed. Install from https://github.com/github/hub' >&2
36
- exit 1
37
- fi
38
-
39
- # Release script
40
- echo
41
- output 5 "BLOCKS->GitHub RELEASE SCRIPT"
42
- output 5 "============================="
43
- echo
44
- printf "This script will build files and create a tag on GitHub based on your local branch."
45
- echo
46
- echo
47
- printf "The /build/ directory will also be pushed to the tagged release."
48
- echo
49
- echo
50
- echo "Before proceeding:"
51
- echo " • Ensure you have checked out the branch you wish to release"
52
- echo " • Ensure you have committed/pushed all local changes"
53
- echo " • Did you remember to update changelogs, the readme and plugin files?"
54
- echo " • Are there any changes needed to the readme file?"
55
- echo " • If you are running this script directly instead of via '$ npm run deploy', ensure you have built assets and installed composer in --no-dev mode."
56
- echo
57
- output 3 "Do you want to continue? [y/N]: "
58
- read -r PROCEED
59
- echo
60
-
61
- if [ "$(echo "${PROCEED:-n}" | tr "[:upper:]" "[:lower:]")" != "y" ]; then
62
- output 1 "Release cancelled!"
63
- exit 1
64
- fi
65
- echo
66
- output 3 "Please enter the version number to tag, for example, 1.0.0:"
67
- read -r VERSION
68
- echo
69
-
70
- CURRENTBRANCH="$(git rev-parse --abbrev-ref HEAD)"
71
-
72
- # Check if is a pre-release.
73
- if is_substring "-" "${VERSION}"; then
74
- IS_PRE_RELEASE=true
75
- output 2 "Detected pre-release version!"
76
- fi
77
-
78
-
79
- echo
80
- output 3 "Will this release get published to WordPress.org? Note: If the version on WordPress.org is greater than ${VERSION}, then you should answer 'N' here. [y/N]:"
81
- read -r DO_WP_DEPLOY
82
- echo
83
-
84
- if [ ! -d "build" ]; then
85
- output 3 "Build directory not found. Aborting."
86
- exit 1
87
- fi
88
-
89
- # Safety check, if a patch release is detected ask for verification.
90
- VERSION_PIECES=${VERSION//[^.]}
91
-
92
- # explode version parts
93
- split_version() {
94
- echo ${VERSION} \
95
- | sed 's/\./ /g'
96
- }
97
-
98
- SPLIT_VERSION=($(split_version))
99
-
100
- # IF VERSION_PIECES is less than 2 then its invalid so let's update it and notify
101
- if [[ "${#VERSION_PIECES}" -lt "2" ]]; then
102
- if [[ ${#VERSION_PIECES} -eq "0" ]]; then
103
- VERSION=${VERSION}.0.0
104
- else
105
- VERSION=${VERSION}.0
106
- fi
107
- fi
108
-
109
- if [[ "${#VERSION_PIECES}" -ge "2" && "${SPLIT_VERSION[2]}" -ne "0" && "$(echo "${DO_WP_DEPLOY:-n}" | tr "[:upper:]" "[:lower:]")" = "y" ]]; then
110
- output 1 "The version you entered (${VERSION}) looks like a patch version. Since this version will be deployed to WordPress.org, it will become the latest available version. Are you sure you want that (no will abort)?: [y/N]"
111
- read -r ABORT
112
- echo
113
- if [ "$(echo "${ABORT:-n}" | tr "[:upper:]" "[:lower:]")" != "y" ]; then
114
- output 1 "Release cancelled!"
115
- exit 1
116
- fi
117
- else
118
- echo "$(output 4 "The version is set as ") $(output 3 "${VERSION}") $(output 4 " and the next step will be to bump all the version strings in relevant files.")"
119
- printf "Ready to proceed? [y/N]: "
120
- read -r PROCEED
121
- echo
122
- fi
123
-
124
- if [ "$(echo "${PROCEED:-n}" | tr "[:upper:]" "[:lower:]")" != "y" ]; then
125
- output 1 "Release cancelled!"
126
- exit 1
127
- fi
128
-
129
- # Version changes
130
- output 2 "Updating version numbers in files and regenerating php autoload classmap (note pre-releases will not have the readme.txt stable tag updated)..."
131
- source "$RELEASER_PATH/bin/version-changes.sh"
132
-
133
- composer dump-autoload
134
-
135
- # remove composer.json version bump after autoload regen (we don't commit it)
136
- git checkout -- composer.json
137
-
138
- output 2 "Committing version change..."
139
- echo
140
-
141
- git commit -am "Bumping version strings to new version." --no-verify
142
- git push origin $CURRENTBRANCH
143
-
144
- # Tag existing version for reference
145
- output 2 "Creating tag for current non-built branch on GitHub..."
146
- echo
147
- DEVTAG="v${VERSION}-dev"
148
- git tag $DEVTAG
149
- git push origin $DEVTAG
150
-
151
- output 2 "Prepping release for GitHub..."
152
- echo
153
-
154
- # Create a release branch.
155
- BRANCH="build/${VERSION}"
156
- git checkout -b $BRANCH
157
-
158
- # Force add build directory and commit.
159
- git add build/. --force
160
- git add .
161
- git commit -m "Adding /build directory to release" --no-verify
162
-
163
- # Force add vendor directory and commit.
164
- git add vendor/. --force
165
- git add .
166
- git commit -m "Adding /vendor directory to release" --no-verify
167
-
168
- # Push branch upstream
169
- git push origin $BRANCH
170
-
171
- # Create the new release.
172
- if [ "$(echo "${DO_WP_DEPLOY:-n}" | tr "[:upper:]" "[:lower:]")" = "y" ]; then
173
- if [ $IS_PRE_RELEASE = true ]; then
174
- hub release create -m $VERSION -m "Release of version $VERSION. See readme.txt for details." -t $BRANCH --prerelease "v${VERSION}"
175
- else
176
- hub release create -m $VERSION -m "Release of version $VERSION. See readme.txt for details." -t $BRANCH "v${VERSION}"
177
- fi
178
- else
179
- git tag "v${VERSION}"
180
- git push origin "v${VERSION}"
181
- fi
182
-
183
- git checkout $CURRENTBRANCH
184
- git branch -D $BRANCH
185
- git push origin --delete $BRANCH
186
-
187
- # regenerate classmap for development
188
- composer dump-autoload
189
-
190
- output 2 "GitHub release complete."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/hook-docs/actions/index.js DELETED
@@ -1,66 +0,0 @@
1
- 'use strict';
2
- /* eslint no-console: 0 */
3
-
4
- /**
5
- * External dependencies
6
- */
7
- const chalk = require( 'chalk' );
8
-
9
- /**
10
- * Internal dependencies
11
- */
12
- const {
13
- params,
14
- exceptions,
15
- returns,
16
- example,
17
- related,
18
- files,
19
- } = require( '../format-hook-doc' );
20
- const {
21
- createDocs,
22
- generateHookName,
23
- generateIntroduction,
24
- sectionWithHeading,
25
- contentWithHeading,
26
- generateToc,
27
- } = require( '../utilities' );
28
-
29
- const generate = ( hooks ) => {
30
- console.log( chalk.blue( 'Generating Action Docs...' ) );
31
-
32
- const jsonDocs = [
33
- { html: '<!-- DO NOT UPDATE THIS DOC DIRECTLY -->' },
34
- {
35
- html:
36
- '<!-- Use `npm run build:docs` to automatically build hook documentation -->',
37
- },
38
- { h1: 'Actions' },
39
- { h2: 'Table of Contents' },
40
- ...generateToc( hooks ),
41
- { hr: '' },
42
- ...hooks.map( ( hook ) => {
43
- const hookDocs = hook.doc || [];
44
-
45
- return [
46
- ...generateHookName( hook ),
47
- ...generateIntroduction( hook ),
48
- ...contentWithHeading(
49
- hook.doc.long_description_html,
50
- 'Description'
51
- ),
52
- ...sectionWithHeading( params( hookDocs ), 'Parameters' ),
53
- ...sectionWithHeading( exceptions( hookDocs ), 'Exceptions' ),
54
- ...sectionWithHeading( returns( hookDocs ), 'Returns' ),
55
- ...sectionWithHeading( example( hookDocs ), 'Example' ),
56
- ...sectionWithHeading( related( hookDocs ), 'See' ),
57
- ...sectionWithHeading( files( hook.file ), 'Source' ),
58
- { hr: '' },
59
- ].filter( Boolean );
60
- } ),
61
- ];
62
- createDocs( 'docs/extensibility/actions.md', jsonDocs );
63
- console.log( chalk.green( 'Done!' ) );
64
- };
65
-
66
- module.exports = { generate };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/hook-docs/data/actions.json DELETED
@@ -1,730 +0,0 @@
1
- {
2
- "$schema": "https://raw.githubusercontent.com/johnbillion/wp-hooks-generator/0.7.0/schema.json",
3
- "hooks": [
4
- {
5
- "name": "woocommerce_add_to_cart",
6
- "file": "StoreApi/Utilities/CartController.php",
7
- "type": "action",
8
- "doc": {
9
- "description": "Fires when an item is added to the cart.",
10
- "long_description": "This hook fires when an item is added to the cart. This is triggered from the Store API in this context, but WooCommerce core add to cart events trigger the same hook.",
11
- "tags": [
12
- {
13
- "name": "param",
14
- "content": "ID of the item in the cart.",
15
- "types": [
16
- "string"
17
- ],
18
- "variable": "$cart_id"
19
- },
20
- {
21
- "name": "param",
22
- "content": "ID of the product added to the cart.",
23
- "types": [
24
- "integer"
25
- ],
26
- "variable": "$product_id"
27
- },
28
- {
29
- "name": "param",
30
- "content": "Quantity of the item added to the cart.",
31
- "types": [
32
- "integer"
33
- ],
34
- "variable": "$request_quantity"
35
- },
36
- {
37
- "name": "param",
38
- "content": "Variation ID of the product added to the cart.",
39
- "types": [
40
- "integer"
41
- ],
42
- "variable": "$variation_id"
43
- },
44
- {
45
- "name": "param",
46
- "content": "Array of variation data.",
47
- "types": [
48
- "array"
49
- ],
50
- "variable": "$variation"
51
- },
52
- {
53
- "name": "param",
54
- "content": "Array of other cart item data.",
55
- "types": [
56
- "array"
57
- ],
58
- "variable": "$cart_item_data"
59
- }
60
- ],
61
- "long_description_html": "<p>This hook fires when an item is added to the cart. This is triggered from the Store API in this context, but WooCommerce core add to cart events trigger the same hook.</p>"
62
- },
63
- "args": 6
64
- },
65
- {
66
- "name": "woocommerce_after_main_content",
67
- "file": "BlockTypes/LegacyTemplate.php",
68
- "type": "action",
69
- "doc": {
70
- "description": "Hook: woocommerce_after_main_content",
71
- "long_description": "Called after rendering the main content for a product.",
72
- "tags": [
73
- {
74
- "name": "see",
75
- "content": "Outputs closing DIV for the content (priority 10)",
76
- "refers": "woocommerce_output_content_wrapper_end()"
77
- }
78
- ],
79
- "long_description_html": "<p>Called after rendering the main content for a product.</p>"
80
- },
81
- "args": 0
82
- },
83
- {
84
- "name": "woocommerce_after_main_content",
85
- "file": "BlockTypes/LegacyTemplate.php",
86
- "type": "action",
87
- "doc": {
88
- "description": "Hook: woocommerce_after_main_content",
89
- "long_description": "Called after rendering the main content for a product.",
90
- "tags": [
91
- {
92
- "name": "see",
93
- "content": "Outputs closing DIV for the content (priority 10)",
94
- "refers": "woocommerce_output_content_wrapper_end()"
95
- }
96
- ],
97
- "long_description_html": "<p>Called after rendering the main content for a product.</p>"
98
- },
99
- "args": 0
100
- },
101
- {
102
- "name": "woocommerce_after_shop_loop",
103
- "file": "BlockTypes/LegacyTemplate.php",
104
- "type": "action",
105
- "doc": {
106
- "description": "Hook: woocommerce_after_shop_loop.",
107
- "long_description": "",
108
- "tags": [
109
- {
110
- "name": "see",
111
- "content": "Renders pagination (priority 10)",
112
- "refers": "woocommerce_pagination()"
113
- }
114
- ],
115
- "long_description_html": ""
116
- },
117
- "args": 0
118
- },
119
- {
120
- "name": "woocommerce_applied_coupon",
121
- "file": "StoreApi/Utilities/CartController.php",
122
- "type": "action",
123
- "doc": {
124
- "description": "Fires after a coupon has been applied to the cart.",
125
- "long_description": "",
126
- "tags": [
127
- {
128
- "name": "param",
129
- "content": "The coupon code that was applied.",
130
- "types": [
131
- "string"
132
- ],
133
- "variable": "$coupon_code"
134
- }
135
- ],
136
- "long_description_html": ""
137
- },
138
- "args": 1
139
- },
140
- {
141
- "name": "woocommerce_archive_description",
142
- "file": "BlockTypes/LegacyTemplate.php",
143
- "type": "action",
144
- "doc": {
145
- "description": "Hook: woocommerce_archive_description.",
146
- "long_description": "",
147
- "tags": [
148
- {
149
- "name": "see",
150
- "content": "Renders the taxonomy archive description (priority 10)",
151
- "refers": "woocommerce_taxonomy_archive_description()"
152
- },
153
- {
154
- "name": "see",
155
- "content": "Renders the product archive description (priority 10)",
156
- "refers": "woocommerce_product_archive_description()"
157
- }
158
- ],
159
- "long_description_html": ""
160
- },
161
- "args": 0
162
- },
163
- {
164
- "name": "woocommerce_before_main_content",
165
- "file": "BlockTypes/LegacyTemplate.php",
166
- "type": "action",
167
- "doc": {
168
- "description": "Hook: woocommerce_before_main_content",
169
- "long_description": "Called before rendering the main content for a product.",
170
- "tags": [
171
- {
172
- "name": "see",
173
- "content": "Outputs opening DIV for the content (priority 10)",
174
- "refers": "woocommerce_output_content_wrapper()"
175
- },
176
- {
177
- "name": "see",
178
- "content": "Outputs breadcrumb trail to the current product (priority 20)",
179
- "refers": "woocommerce_breadcrumb()"
180
- },
181
- {
182
- "name": "see",
183
- "content": "Outputs schema markup (priority 30)",
184
- "refers": "WC_Structured_Data::generate_website_data()"
185
- }
186
- ],
187
- "long_description_html": "<p>Called before rendering the main content for a product.</p>"
188
- },
189
- "args": 0
190
- },
191
- {
192
- "name": "woocommerce_before_main_content",
193
- "file": "BlockTypes/LegacyTemplate.php",
194
- "type": "action",
195
- "doc": {
196
- "description": "Hook: woocommerce_before_main_content",
197
- "long_description": "Called before rendering the main content for a product.",
198
- "tags": [
199
- {
200
- "name": "see",
201
- "content": "Outputs opening DIV for the content (priority 10)",
202
- "refers": "woocommerce_output_content_wrapper()"
203
- },
204
- {
205
- "name": "see",
206
- "content": "Outputs breadcrumb trail to the current product (priority 20)",
207
- "refers": "woocommerce_breadcrumb()"
208
- },
209
- {
210
- "name": "see",
211
- "content": "Outputs schema markup (priority 30)",
212
- "refers": "WC_Structured_Data::generate_website_data()"
213
- }
214
- ],
215
- "long_description_html": "<p>Called before rendering the main content for a product.</p>"
216
- },
217
- "args": 0
218
- },
219
- {
220
- "name": "woocommerce_before_shop_loop",
221
- "file": "BlockTypes/LegacyTemplate.php",
222
- "type": "action",
223
- "doc": {
224
- "description": "Hook: woocommerce_before_shop_loop.",
225
- "long_description": "",
226
- "tags": [
227
- {
228
- "name": "see",
229
- "content": "Render error notices (priority 10)",
230
- "refers": "woocommerce_output_all_notices()"
231
- },
232
- {
233
- "name": "see",
234
- "content": "Show number of results found (priority 20)",
235
- "refers": "woocommerce_result_count()"
236
- },
237
- {
238
- "name": "see",
239
- "content": "Show form to control sort order (priority 30)",
240
- "refers": "woocommerce_catalog_ordering()"
241
- }
242
- ],
243
- "long_description_html": ""
244
- },
245
- "args": 0
246
- },
247
- {
248
- "name": "woocommerce_blocks_cart_enqueue_data",
249
- "file": "BlockTypes/MiniCart.php",
250
- "type": "action",
251
- "doc": {
252
- "description": "Fires after cart block data is registered.",
253
- "long_description": "",
254
- "tags": [],
255
- "long_description_html": ""
256
- },
257
- "args": 0
258
- },
259
- {
260
- "name": "woocommerce_blocks_cart_enqueue_data",
261
- "file": "BlockTypes/Cart.php",
262
- "type": "action",
263
- "doc": {
264
- "description": "Fires after cart block data is registered.",
265
- "long_description": "",
266
- "tags": [],
267
- "long_description_html": ""
268
- },
269
- "args": 0
270
- },
271
- {
272
- "name": "woocommerce_blocks_cart_update_customer_from_request",
273
- "file": "StoreApi/Routes/CartUpdateCustomer.php",
274
- "type": "action",
275
- "doc": {
276
- "description": "Fires when the Checkout Block/Store API updates a customer from the API request data.",
277
- "long_description": "",
278
- "tags": [
279
- {
280
- "name": "param",
281
- "content": "Customer object.",
282
- "types": [
283
- "\\WC_Customer"
284
- ],
285
- "variable": "$customer"
286
- },
287
- {
288
- "name": "param",
289
- "content": "Full details about the request.",
290
- "types": [
291
- "\\WP_REST_Request"
292
- ],
293
- "variable": "$request"
294
- }
295
- ],
296
- "long_description_html": ""
297
- },
298
- "args": 2
299
- },
300
- {
301
- "name": "woocommerce_blocks_cart_update_order_from_request",
302
- "file": "StoreApi/Routes/AbstractCartRoute.php",
303
- "type": "action",
304
- "doc": {
305
- "description": "Fires when the order is synced with cart data from a cart route.",
306
- "long_description": "",
307
- "tags": [
308
- {
309
- "name": "param",
310
- "content": "Order object.",
311
- "types": [
312
- "\\WC_Order"
313
- ],
314
- "variable": "$draft_order"
315
- },
316
- {
317
- "name": "param",
318
- "content": "Customer object.",
319
- "types": [
320
- "\\WC_Customer"
321
- ],
322
- "variable": "$customer"
323
- },
324
- {
325
- "name": "param",
326
- "content": "Full details about the request.",
327
- "types": [
328
- "\\WP_REST_Request"
329
- ],
330
- "variable": "$request"
331
- }
332
- ],
333
- "long_description_html": ""
334
- },
335
- "args": 2
336
- },
337
- {
338
- "name": "woocommerce_blocks_checkout_enqueue_data",
339
- "file": "BlockTypes/Checkout.php",
340
- "type": "action",
341
- "doc": {
342
- "description": "Fires after checkout block data is registered.",
343
- "long_description": "",
344
- "tags": [],
345
- "long_description_html": ""
346
- },
347
- "args": 0
348
- },
349
- {
350
- "name": "woocommerce_blocks_checkout_order_processed",
351
- "file": "StoreApi/Routes/Checkout.php",
352
- "type": "action",
353
- "doc": {
354
- "description": "Fires before an order is processed by the Checkout Block/Store API.",
355
- "long_description": "This hook informs extensions that $order has completed processing and is ready for payment.\n This is similar to existing core hook woocommerce_checkout_order_processed. We're using a new action: - To keep the interface focused (only pass $order, not passing request data). - This also explicitly indicates these orders are from checkout block/StoreAPI.",
356
- "tags": [
357
- {
358
- "name": "see",
359
- "content": "",
360
- "refers": "https://github.com/woocommerce/woocommerce-gutenberg-products-block/pull/3238"
361
- },
362
- {
363
- "name": "example",
364
- "content": "docs/examples/checkout-order-processed.md"
365
- },
366
- {
367
- "name": "param",
368
- "content": "Order object.",
369
- "types": [
370
- "\\WC_Order"
371
- ],
372
- "variable": "$order"
373
- }
374
- ],
375
- "long_description_html": "<p>This hook informs extensions that $order has completed processing and is ready for payment.</p> <p>This is similar to existing core hook woocommerce_checkout_order_processed. We're using a new action:</p> <ul> <li>To keep the interface focused (only pass $order, not passing request data).</li> <li>This also explicitly indicates these orders are from checkout block/StoreAPI.</li> </ul>"
376
- },
377
- "args": 1
378
- },
379
- {
380
- "name": "woocommerce_blocks_checkout_update_order_from_request",
381
- "file": "StoreApi/Routes/Checkout.php",
382
- "type": "action",
383
- "doc": {
384
- "description": "Fires when the Checkout Block/Store API updates an order's from the API request data.",
385
- "long_description": "This hook gives extensions the chance to update orders based on the data in the request. This can be used in conjunction with the ExtendRestAPI class to post custom data and then process it.",
386
- "tags": [
387
- {
388
- "name": "param",
389
- "content": "Order object.",
390
- "types": [
391
- "\\WC_Order"
392
- ],
393
- "variable": "$order"
394
- },
395
- {
396
- "name": "param",
397
- "content": "Full details about the request.",
398
- "types": [
399
- "\\WP_REST_Request"
400
- ],
401
- "variable": "$request"
402
- }
403
- ],
404
- "long_description_html": "<p>This hook gives extensions the chance to update orders based on the data in the request. This can be used in conjunction with the ExtendRestAPI class to post custom data and then process it.</p>"
405
- },
406
- "args": 2
407
- },
408
- {
409
- "name": "woocommerce_blocks_checkout_update_order_meta",
410
- "file": "StoreApi/Routes/Checkout.php",
411
- "type": "action",
412
- "doc": {
413
- "description": "Fires when the Checkout Block/Store API updates an order's meta data.",
414
- "long_description": "This hook gives extensions the chance to add or update meta data on the $order.\n This is similar to existing core hook woocommerce_checkout_update_order_meta. We're using a new action: - To keep the interface focused (only pass $order, not passing request data). - This also explicitly indicates these orders are from checkout block/StoreAPI.",
415
- "tags": [
416
- {
417
- "name": "see",
418
- "content": "",
419
- "refers": "https://github.com/woocommerce/woocommerce-gutenberg-products-block/pull/3686"
420
- },
421
- {
422
- "name": "param",
423
- "content": "Order object.",
424
- "types": [
425
- "\\WC_Order"
426
- ],
427
- "variable": "$order"
428
- }
429
- ],
430
- "long_description_html": "<p>This hook gives extensions the chance to add or update meta data on the $order.</p> <p>This is similar to existing core hook woocommerce_checkout_update_order_meta. We're using a new action:</p> <ul> <li>To keep the interface focused (only pass $order, not passing request data).</li> <li>This also explicitly indicates these orders are from checkout block/StoreAPI.</li> </ul>"
431
- },
432
- "args": 1
433
- },
434
- {
435
- "name": "woocommerce_blocks_enqueue_cart_block_scripts_after",
436
- "file": "BlockTypes/Cart.php",
437
- "type": "action",
438
- "doc": {
439
- "description": "Fires after cart block scripts are enqueued.",
440
- "long_description": "",
441
- "tags": [],
442
- "long_description_html": ""
443
- },
444
- "args": 0
445
- },
446
- {
447
- "name": "woocommerce_blocks_enqueue_cart_block_scripts_before",
448
- "file": "BlockTypes/Cart.php",
449
- "type": "action",
450
- "doc": {
451
- "description": "Fires before cart block scripts are enqueued.",
452
- "long_description": "",
453
- "tags": [],
454
- "long_description_html": ""
455
- },
456
- "args": 0
457
- },
458
- {
459
- "name": "woocommerce_blocks_enqueue_checkout_block_scripts_after",
460
- "file": "BlockTypes/Checkout.php",
461
- "type": "action",
462
- "doc": {
463
- "description": "Fires after checkout block scripts are enqueued.",
464
- "long_description": "",
465
- "tags": [],
466
- "long_description_html": ""
467
- },
468
- "args": 0
469
- },
470
- {
471
- "name": "woocommerce_blocks_enqueue_checkout_block_scripts_before",
472
- "file": "BlockTypes/Checkout.php",
473
- "type": "action",
474
- "doc": {
475
- "description": "Fires before checkout block scripts are enqueued.",
476
- "long_description": "",
477
- "tags": [],
478
- "long_description_html": ""
479
- },
480
- "args": 0
481
- },
482
- {
483
- "name": "woocommerce_blocks_loaded",
484
- "file": "Domain/Bootstrap.php",
485
- "type": "action",
486
- "doc": {
487
- "description": "Fires after WooCommerce Blocks plugin has loaded.",
488
- "long_description": "This hook is intended to be used as a safe event hook for when the plugin has been loaded, and all dependency requirements have been met.",
489
- "tags": [],
490
- "long_description_html": "<p>This hook is intended to be used as a safe event hook for when the plugin has been loaded, and all dependency requirements have been met.</p>"
491
- },
492
- "args": 0
493
- },
494
- {
495
- "name": "woocommerce_blocks_{$this->registry_identifier}_registration",
496
- "file": "Integrations/IntegrationRegistry.php",
497
- "type": "action",
498
- "doc": {
499
- "description": "Fires when the IntegrationRegistry is initialized.",
500
- "long_description": "Runs before integrations are initialized allowing new integration to be registered for use. This should be used as the primary hook for integrations to include their scripts, styles, and other code extending the blocks.",
501
- "tags": [
502
- {
503
- "name": "param",
504
- "content": "Instance of the IntegrationRegistry class which exposes the IntegrationRegistry::register() method.",
505
- "types": [
506
- "\\Automattic\\WooCommerce\\Blocks\\Integrations\\IntegrationRegistry"
507
- ],
508
- "variable": "$this"
509
- }
510
- ],
511
- "long_description_html": "<p>Runs before integrations are initialized allowing new integration to be registered for use. This should be used as the primary hook for integrations to include their scripts, styles, and other code extending the blocks.</p>"
512
- },
513
- "args": 1
514
- },
515
- {
516
- "name": "woocommerce_check_cart_items",
517
- "file": "StoreApi/Utilities/CartController.php",
518
- "type": "action",
519
- "doc": {
520
- "description": "Fires when cart items are being validated.",
521
- "long_description": "Allow 3rd parties to validate cart items. This is a legacy hook from Woo core. This filter will be deprecated because it encourages usage of wc_add_notice. For the API we need to capture notices and convert to exceptions instead.",
522
- "tags": [],
523
- "long_description_html": "<p>Allow 3rd parties to validate cart items. This is a legacy hook from Woo core. This filter will be deprecated because it encourages usage of wc_add_notice. For the API we need to capture notices and convert to exceptions instead.</p>"
524
- },
525
- "args": 0
526
- },
527
- {
528
- "name": "woocommerce_created_customer",
529
- "file": "Domain/Services/CreateAccount.php",
530
- "type": "action",
531
- "doc": {
532
- "description": "Fires after a customer account has been registered.",
533
- "long_description": "This hook fires after customer accounts are created and passes the customer data.",
534
- "tags": [
535
- {
536
- "name": "param",
537
- "content": "New customer (user) ID.",
538
- "types": [
539
- "integer"
540
- ],
541
- "variable": "$customer_id"
542
- },
543
- {
544
- "name": "param",
545
- "content": "Array of customer (user) data.",
546
- "types": [
547
- "array"
548
- ],
549
- "variable": "$new_customer_data"
550
- },
551
- {
552
- "name": "param",
553
- "content": "The generated password for the account.",
554
- "types": [
555
- "string"
556
- ],
557
- "variable": "$password_generated"
558
- }
559
- ],
560
- "long_description_html": "<p>This hook fires after customer accounts are created and passes the customer data.</p>"
561
- },
562
- "args": 3
563
- },
564
- {
565
- "name": "woocommerce_no_products_found",
566
- "file": "BlockTypes/LegacyTemplate.php",
567
- "type": "action",
568
- "doc": {
569
- "description": "Hook: woocommerce_no_products_found.",
570
- "long_description": "",
571
- "tags": [
572
- {
573
- "name": "see",
574
- "content": "Default no products found content (priority 10)",
575
- "refers": "wc_no_products_found()"
576
- }
577
- ],
578
- "long_description_html": ""
579
- },
580
- "args": 0
581
- },
582
- {
583
- "name": "woocommerce_register_post",
584
- "file": "Domain/Services/CreateAccount.php",
585
- "type": "action",
586
- "doc": {
587
- "description": "Fires before a customer account is registered.",
588
- "long_description": "This hook fires before customer accounts are created and passes the form data (username, email) and an array of errors.\n This could be used to add extra validation logic and append errors to the array.",
589
- "tags": [
590
- {
591
- "name": "param",
592
- "content": "Customer username.",
593
- "types": [
594
- "string"
595
- ],
596
- "variable": "$username"
597
- },
598
- {
599
- "name": "param",
600
- "content": "Customer email address.",
601
- "types": [
602
- "string"
603
- ],
604
- "variable": "$user_email"
605
- },
606
- {
607
- "name": "param",
608
- "content": "Error object.",
609
- "types": [
610
- "\\WP_Error"
611
- ],
612
- "variable": "$errors"
613
- }
614
- ],
615
- "long_description_html": "<p>This hook fires before customer accounts are created and passes the form data (username, email) and an array of errors.</p> <p>This could be used to add extra validation logic and append errors to the array.</p>"
616
- },
617
- "args": 3
618
- },
619
- {
620
- "name": "woocommerce_rest_checkout_process_payment_with_context",
621
- "file": "StoreApi/Routes/Checkout.php",
622
- "type": "action_reference",
623
- "doc": {
624
- "description": "Process payment with context.",
625
- "long_description": "",
626
- "tags": [
627
- {
628
- "name": "hook",
629
- "content": "woocommerce_rest_checkout_process_payment_with_context"
630
- },
631
- {
632
- "name": "throws",
633
- "content": "If there is an error taking payment, an \\Exception object can be thrown with an error message.",
634
- "types": [
635
- "\\Exception"
636
- ]
637
- },
638
- {
639
- "name": "param",
640
- "content": "Holds context for the payment, including order ID and payment method.",
641
- "types": [
642
- "\\Automattic\\WooCommerce\\Blocks\\Payments\\PaymentContext"
643
- ],
644
- "variable": "$context"
645
- },
646
- {
647
- "name": "param",
648
- "content": "Result object for the transaction.",
649
- "types": [
650
- "\\Automattic\\WooCommerce\\Blocks\\Payments\\PaymentResult"
651
- ],
652
- "variable": "$payment_result"
653
- }
654
- ],
655
- "long_description_html": ""
656
- },
657
- "args": 1
658
- },
659
- {
660
- "name": "woocommerce_shop_loop",
661
- "file": "BlockTypes/LegacyTemplate.php",
662
- "type": "action",
663
- "doc": {
664
- "description": "Hook: woocommerce_shop_loop.",
665
- "long_description": "",
666
- "tags": [],
667
- "long_description_html": ""
668
- },
669
- "args": 0
670
- },
671
- {
672
- "name": "wooocommerce_store_api_validate_add_to_cart",
673
- "file": "StoreApi/Utilities/CartController.php",
674
- "type": "action",
675
- "doc": {
676
- "description": "Fires during validation when adding an item to the cart via the Store API.",
677
- "long_description": "Fire action to validate add to cart. Functions hooking into this should throw an \\Exception to prevent add to cart from happening.",
678
- "tags": [
679
- {
680
- "name": "param",
681
- "content": "Product object being added to the cart.",
682
- "types": [
683
- "\\WC_Product"
684
- ],
685
- "variable": "$product"
686
- },
687
- {
688
- "name": "param",
689
- "content": "Add to cart request params including id, quantity, and variation attributes.",
690
- "types": [
691
- "array"
692
- ],
693
- "variable": "$request"
694
- }
695
- ],
696
- "long_description_html": "<p>Fire action to validate add to cart. Functions hooking into this should throw an \\Exception to prevent add to cart from happening.</p>"
697
- },
698
- "args": 2
699
- },
700
- {
701
- "name": "wooocommerce_store_api_validate_cart_item",
702
- "file": "StoreApi/Utilities/CartController.php",
703
- "type": "action",
704
- "doc": {
705
- "description": "Fire action to validate add to cart. Functions hooking into this should throw an \\Exception to prevent add to cart from occurring.",
706
- "long_description": "",
707
- "tags": [
708
- {
709
- "name": "param",
710
- "content": "Product object being added to the cart.",
711
- "types": [
712
- "\\WC_Product"
713
- ],
714
- "variable": "$product"
715
- },
716
- {
717
- "name": "param",
718
- "content": "Cart item array.",
719
- "types": [
720
- "array"
721
- ],
722
- "variable": "$cart_item"
723
- }
724
- ],
725
- "long_description_html": ""
726
- },
727
- "args": 2
728
- }
729
- ]
730
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/hook-docs/data/filters.json DELETED
@@ -1,951 +0,0 @@
1
- {
2
- "$schema": "https://raw.githubusercontent.com/johnbillion/wp-hooks-generator/0.7.0/schema.json",
3
- "hooks": [
4
- {
5
- "name": "__experimental_woocommerce_blocks_add_data_attributes_to_block",
6
- "file": "BlockTypesController.php",
7
- "type": "filter",
8
- "doc": {
9
- "description": "Filters the list of allowed Block Names",
10
- "long_description": "This hook defines which block names should have block name and attribute data- attributes appended on render.",
11
- "tags": [
12
- {
13
- "name": "param",
14
- "content": "List of namespaces.",
15
- "types": [
16
- "array"
17
- ],
18
- "variable": "$allowed_namespaces"
19
- }
20
- ],
21
- "long_description_html": "<p>This hook defines which block names should have block name and attribute data- attributes appended on render.</p>"
22
- },
23
- "args": 1
24
- },
25
- {
26
- "name": "__experimental_woocommerce_blocks_add_data_attributes_to_namespace",
27
- "file": "BlockTypesController.php",
28
- "type": "filter",
29
- "doc": {
30
- "description": "Filters the list of allowed block namespaces.",
31
- "long_description": "This hook defines which block namespaces should have block name and attribute `data-` attributes appended on render.",
32
- "tags": [
33
- {
34
- "name": "param",
35
- "content": "List of namespaces.",
36
- "types": [
37
- "array"
38
- ],
39
- "variable": "$allowed_namespaces"
40
- }
41
- ],
42
- "long_description_html": "<p>This hook defines which block namespaces should have block name and attribute <code>data-</code> attributes appended on render.</p>"
43
- },
44
- "args": 1
45
- },
46
- {
47
- "name": "__experimental_woocommerce_blocks_payment_gateway_features_list",
48
- "file": "Payments/Integrations/PayPal.php",
49
- "type": "filter",
50
- "doc": {
51
- "description": "Filter to control what features are available for each payment gateway.",
52
- "long_description": "",
53
- "tags": [
54
- {
55
- "name": "example",
56
- "content": "docs/examples/payment-gateways-features-list.md"
57
- },
58
- {
59
- "name": "param",
60
- "content": "List of supported features.",
61
- "types": [
62
- "array"
63
- ],
64
- "variable": "$features"
65
- },
66
- {
67
- "name": "param",
68
- "content": "Gateway name.",
69
- "types": [
70
- "string"
71
- ],
72
- "variable": "$name"
73
- },
74
- {
75
- "name": "return",
76
- "content": "Updated list of supported features.",
77
- "types": [
78
- "array"
79
- ]
80
- }
81
- ],
82
- "long_description_html": ""
83
- },
84
- "args": 2
85
- },
86
- {
87
- "name": "woocommerce_add_cart_item",
88
- "file": "StoreApi/Utilities/CartController.php",
89
- "type": "filter",
90
- "doc": {
91
- "description": "Filters the item being added to the cart.",
92
- "long_description": "",
93
- "tags": [
94
- {
95
- "name": "param",
96
- "content": "Array of cart item data being added to the cart.",
97
- "types": [
98
- "array"
99
- ],
100
- "variable": "$cart_item_data"
101
- },
102
- {
103
- "name": "param",
104
- "content": "Id of the item in the cart.",
105
- "types": [
106
- "string"
107
- ],
108
- "variable": "$cart_id"
109
- },
110
- {
111
- "name": "return",
112
- "content": "Updated cart item data.",
113
- "types": [
114
- "array"
115
- ]
116
- }
117
- ],
118
- "long_description_html": ""
119
- },
120
- "args": 2
121
- },
122
- {
123
- "name": "woocommerce_add_cart_item_data",
124
- "file": "StoreApi/Utilities/CartController.php",
125
- "type": "filter",
126
- "doc": {
127
- "description": "Filter cart item data for add to cart requests.",
128
- "long_description": "",
129
- "tags": [
130
- {
131
- "name": "param",
132
- "content": "Array of other cart item data.",
133
- "types": [
134
- "array"
135
- ],
136
- "variable": "$cart_item_data"
137
- },
138
- {
139
- "name": "param",
140
- "content": "ID of the product added to the cart.",
141
- "types": [
142
- "integer"
143
- ],
144
- "variable": "$product_id"
145
- },
146
- {
147
- "name": "param",
148
- "content": "Variation ID of the product added to the cart.",
149
- "types": [
150
- "integer"
151
- ],
152
- "variable": "$variation_id"
153
- },
154
- {
155
- "name": "param",
156
- "content": "Quantity of the item added to the cart.",
157
- "types": [
158
- "integer"
159
- ],
160
- "variable": "$quantity"
161
- },
162
- {
163
- "name": "return",
164
- "content": "",
165
- "types": [
166
- "array"
167
- ]
168
- }
169
- ],
170
- "long_description_html": ""
171
- },
172
- "args": 4
173
- },
174
- {
175
- "name": "woocommerce_add_to_cart_sold_individually_quantity",
176
- "file": "StoreApi/Utilities/CartController.php",
177
- "type": "filter",
178
- "doc": {
179
- "description": "Filter sold individually quantity for add to cart requests.",
180
- "long_description": "",
181
- "tags": [
182
- {
183
- "name": "param",
184
- "content": "Defaults to 1.",
185
- "types": [
186
- "integer"
187
- ],
188
- "variable": "$sold_individually_quantity"
189
- },
190
- {
191
- "name": "param",
192
- "content": "Quantity of the item added to the cart.",
193
- "types": [
194
- "integer"
195
- ],
196
- "variable": "$quantity"
197
- },
198
- {
199
- "name": "param",
200
- "content": "ID of the product added to the cart.",
201
- "types": [
202
- "integer"
203
- ],
204
- "variable": "$product_id"
205
- },
206
- {
207
- "name": "param",
208
- "content": "Variation ID of the product added to the cart.",
209
- "types": [
210
- "integer"
211
- ],
212
- "variable": "$variation_id"
213
- },
214
- {
215
- "name": "param",
216
- "content": "Array of other cart item data.",
217
- "types": [
218
- "array"
219
- ],
220
- "variable": "$cart_item_data"
221
- },
222
- {
223
- "name": "return",
224
- "content": "",
225
- "types": [
226
- "integer"
227
- ]
228
- }
229
- ],
230
- "long_description_html": ""
231
- },
232
- "args": 5
233
- },
234
- {
235
- "name": "woocommerce_add_to_cart_validation",
236
- "file": "StoreApi/Utilities/CartController.php",
237
- "type": "filter",
238
- "doc": {
239
- "description": "Filters if an item being added to the cart passed validation checks.",
240
- "long_description": "Allow 3rd parties to validate if an item can be added to the cart. This is a legacy hook from Woo core. This filter will be deprecated because it encourages usage of wc_add_notice. For the API we need to capture notices and convert to exceptions instead.",
241
- "tags": [
242
- {
243
- "name": "deprecated",
244
- "content": ""
245
- },
246
- {
247
- "name": "param",
248
- "content": "True if the item passed validation.",
249
- "types": [
250
- "boolean"
251
- ],
252
- "variable": "$passed_validation"
253
- },
254
- {
255
- "name": "param",
256
- "content": "Product ID being validated.",
257
- "types": [
258
- "integer"
259
- ],
260
- "variable": "$product_id"
261
- },
262
- {
263
- "name": "param",
264
- "content": "Quantity added to the cart.",
265
- "types": [
266
- "integer"
267
- ],
268
- "variable": "$quantity"
269
- },
270
- {
271
- "name": "param",
272
- "content": "Variation ID being added to the cart.",
273
- "types": [
274
- "integer"
275
- ],
276
- "variable": "$variation_id"
277
- },
278
- {
279
- "name": "param",
280
- "content": "Variation data.",
281
- "types": [
282
- "array"
283
- ],
284
- "variable": "$variation"
285
- },
286
- {
287
- "name": "return",
288
- "content": "",
289
- "types": [
290
- "boolean"
291
- ]
292
- }
293
- ],
294
- "long_description_html": "<p>Allow 3rd parties to validate if an item can be added to the cart. This is a legacy hook from Woo core. This filter will be deprecated because it encourages usage of wc_add_notice. For the API we need to capture notices and convert to exceptions instead.</p>"
295
- },
296
- "args": 5
297
- },
298
- {
299
- "name": "woocommerce_adjust_non_base_location_prices",
300
- "file": "StoreApi/Utilities/ProductQuery.php",
301
- "type": "filter",
302
- "doc": {
303
- "description": "Filters if taxes should be removed from locations outside the store base location.",
304
- "long_description": "The woocommerce_adjust_non_base_location_prices filter can stop base taxes being taken off when dealing with out of base locations. e.g. If a product costs 10 including tax, all users will pay 10 regardless of location and taxes.",
305
- "tags": [
306
- {
307
- "name": "param",
308
- "content": "True by default.",
309
- "types": [
310
- "boolean"
311
- ],
312
- "variable": "$adjust_non_base_location_prices"
313
- },
314
- {
315
- "name": "return",
316
- "content": "",
317
- "types": [
318
- "boolean"
319
- ]
320
- }
321
- ],
322
- "long_description_html": "<p>The woocommerce_adjust_non_base_location_prices filter can stop base taxes being taken off when dealing with out of base locations. e.g. If a product costs 10 including tax, all users will pay 10 regardless of location and taxes.</p>"
323
- },
324
- "args": 1
325
- },
326
- {
327
- "name": "woocommerce_apply_individual_use_coupon",
328
- "file": "StoreApi/Utilities/CartController.php",
329
- "type": "filter",
330
- "doc": {
331
- "description": "Filter coupons to remove when applying an individual use coupon.",
332
- "long_description": "",
333
- "tags": [
334
- {
335
- "name": "param",
336
- "content": "Array of coupons to remove from the cart.",
337
- "types": [
338
- "array"
339
- ],
340
- "variable": "$coupons"
341
- },
342
- {
343
- "name": "param",
344
- "content": "Coupon object applied to the cart.",
345
- "types": [
346
- "\\WC_Coupon"
347
- ],
348
- "variable": "$coupon"
349
- },
350
- {
351
- "name": "param",
352
- "content": "Array of applied coupons already applied to the cart.",
353
- "types": [
354
- "array"
355
- ],
356
- "variable": "$applied_coupons"
357
- },
358
- {
359
- "name": "return",
360
- "content": "",
361
- "types": [
362
- "array"
363
- ]
364
- }
365
- ],
366
- "long_description_html": ""
367
- },
368
- "args": 3
369
- },
370
- {
371
- "name": "woocommerce_apply_with_individual_use_coupon",
372
- "file": "StoreApi/Utilities/CartController.php",
373
- "type": "filter",
374
- "doc": {
375
- "description": "Filters if a coupon can be applied alongside other individual use coupons.",
376
- "long_description": "",
377
- "tags": [
378
- {
379
- "name": "param",
380
- "content": "Defaults to false.",
381
- "types": [
382
- "boolean"
383
- ],
384
- "variable": "$apply_with_individual_use_coupon"
385
- },
386
- {
387
- "name": "param",
388
- "content": "Coupon object applied to the cart.",
389
- "types": [
390
- "\\WC_Coupon"
391
- ],
392
- "variable": "$coupon"
393
- },
394
- {
395
- "name": "param",
396
- "content": "Individual use coupon already applied to the cart.",
397
- "types": [
398
- "\\WC_Coupon"
399
- ],
400
- "variable": "$individual_use_coupon"
401
- },
402
- {
403
- "name": "param",
404
- "content": "Array of applied coupons already applied to the cart.",
405
- "types": [
406
- "array"
407
- ],
408
- "variable": "$applied_coupons"
409
- },
410
- {
411
- "name": "return",
412
- "content": "",
413
- "types": [
414
- "boolean"
415
- ]
416
- }
417
- ],
418
- "long_description_html": ""
419
- },
420
- "args": 4
421
- },
422
- {
423
- "name": "woocommerce_blocks_product_grid_is_cacheable",
424
- "file": "BlockTypes/AbstractProductGrid.php",
425
- "type": "filter",
426
- "doc": {
427
- "description": "Filters whether or not the product grid is cacheable.",
428
- "long_description": "",
429
- "tags": [
430
- {
431
- "name": "param",
432
- "content": "The list of script dependencies.",
433
- "types": [
434
- "boolean"
435
- ],
436
- "variable": "$is_cacheable"
437
- },
438
- {
439
- "name": "param",
440
- "content": "Query args for the products query passed to BlocksWpQuery.",
441
- "types": [
442
- "array"
443
- ],
444
- "variable": "$query_args"
445
- },
446
- {
447
- "name": "return",
448
- "content": "True to enable cache, false to disable cache.",
449
- "types": [
450
- "array"
451
- ]
452
- }
453
- ],
454
- "long_description_html": ""
455
- },
456
- "args": 2
457
- },
458
- {
459
- "name": "woocommerce_blocks_product_grid_item_html",
460
- "file": "BlockTypes/AbstractProductGrid.php",
461
- "type": "filter",
462
- "doc": {
463
- "description": "Filters the HTML for products in the grid.",
464
- "long_description": "",
465
- "tags": [
466
- {
467
- "name": "param",
468
- "content": "Product grid item HTML.",
469
- "types": [
470
- "string"
471
- ],
472
- "variable": "$html"
473
- },
474
- {
475
- "name": "param",
476
- "content": "Product data passed to the template.",
477
- "types": [
478
- "array"
479
- ],
480
- "variable": "$data"
481
- },
482
- {
483
- "name": "param",
484
- "content": "Product object.",
485
- "types": [
486
- "\\WC_Product"
487
- ],
488
- "variable": "$product"
489
- },
490
- {
491
- "name": "return",
492
- "content": "Updated product grid item HTML.",
493
- "types": [
494
- "string"
495
- ]
496
- }
497
- ],
498
- "long_description_html": ""
499
- },
500
- "args": 3
501
- },
502
- {
503
- "name": "woocommerce_blocks_register_script_dependencies",
504
- "file": "Assets/Api.php",
505
- "type": "filter",
506
- "doc": {
507
- "description": "Filters the list of script dependencies.",
508
- "long_description": "",
509
- "tags": [
510
- {
511
- "name": "param",
512
- "content": "The list of script dependencies.",
513
- "types": [
514
- "array"
515
- ],
516
- "variable": "$dependencies"
517
- },
518
- {
519
- "name": "param",
520
- "content": "The script's handle.",
521
- "types": [
522
- "string"
523
- ],
524
- "variable": "$handle"
525
- },
526
- {
527
- "name": "return",
528
- "content": "",
529
- "types": [
530
- "array"
531
- ]
532
- }
533
- ],
534
- "long_description_html": ""
535
- },
536
- "args": 2
537
- },
538
- {
539
- "name": "woocommerce_cart_contents_changed",
540
- "file": "StoreApi/Utilities/CartController.php",
541
- "type": "filter",
542
- "doc": {
543
- "description": "Filters the entire cart contents when the cart changes.",
544
- "long_description": "",
545
- "tags": [
546
- {
547
- "name": "param",
548
- "content": "Array of all cart items.",
549
- "types": [
550
- "array"
551
- ],
552
- "variable": "$cart_contents"
553
- },
554
- {
555
- "name": "return",
556
- "content": "Updated array of all cart items.",
557
- "types": [
558
- "array"
559
- ]
560
- }
561
- ],
562
- "long_description_html": ""
563
- },
564
- "args": 1
565
- },
566
- {
567
- "name": "woocommerce_ga_disable_tracking",
568
- "file": "Domain/Services/GoogleAnalytics.php",
569
- "type": "filter",
570
- "doc": {
571
- "description": "Filter to disable Google Analytics tracking.",
572
- "long_description": "",
573
- "tags": [
574
- {
575
- "name": "param",
576
- "content": "If true, tracking will be disabled.",
577
- "types": [
578
- "boolean"
579
- ],
580
- "variable": "$disable_tracking"
581
- }
582
- ],
583
- "long_description_html": ""
584
- },
585
- "args": 1
586
- },
587
- {
588
- "name": "woocommerce_get_item_data",
589
- "file": "StoreApi/Schemas/CartItemSchema.php",
590
- "type": "filter",
591
- "doc": {
592
- "description": "Filters cart item data.",
593
- "long_description": "Filters the variation option name for custom option slugs.",
594
- "tags": [
595
- {
596
- "name": "param",
597
- "content": "Cart item data. Empty by default.",
598
- "types": [
599
- "array"
600
- ],
601
- "variable": "$item_data"
602
- },
603
- {
604
- "name": "param",
605
- "content": "Cart item array.",
606
- "types": [
607
- "array"
608
- ],
609
- "variable": "$cart_item"
610
- },
611
- {
612
- "name": "return",
613
- "content": "",
614
- "types": [
615
- "array"
616
- ]
617
- }
618
- ],
619
- "long_description_html": "<p>Filters the variation option name for custom option slugs.</p>"
620
- },
621
- "args": 2
622
- },
623
- {
624
- "name": "woocommerce_new_customer_data",
625
- "file": "Domain/Services/CreateAccount.php",
626
- "type": "filter",
627
- "doc": {
628
- "description": "Filters customer data before a customer account is registered.",
629
- "long_description": "This hook filters customer data. It allows user data to be changed, for example, username, password, email, first name, last name, and role.",
630
- "tags": [
631
- {
632
- "name": "param",
633
- "content": "An array of customer (user) data.",
634
- "types": [
635
- "array"
636
- ],
637
- "variable": "$customer_data"
638
- },
639
- {
640
- "name": "return",
641
- "content": "",
642
- "types": [
643
- "array"
644
- ]
645
- }
646
- ],
647
- "long_description_html": "<p>This hook filters customer data. It allows user data to be changed, for example, username, password, email, first name, last name, and role.</p>"
648
- },
649
- "args": 1
650
- },
651
- {
652
- "name": "woocommerce_registration_errors",
653
- "file": "Domain/Services/CreateAccount.php",
654
- "type": "filter",
655
- "doc": {
656
- "description": "Filters registration errors before a customer account is registered.",
657
- "long_description": "This hook filters registration errors. This can be used to manipulate the array of errors before they are displayed.",
658
- "tags": [
659
- {
660
- "name": "param",
661
- "content": "Error object.",
662
- "types": [
663
- "\\WP_Error"
664
- ],
665
- "variable": "$errors"
666
- },
667
- {
668
- "name": "param",
669
- "content": "Customer username.",
670
- "types": [
671
- "string"
672
- ],
673
- "variable": "$username"
674
- },
675
- {
676
- "name": "param",
677
- "content": "Customer email address.",
678
- "types": [
679
- "string"
680
- ],
681
- "variable": "$user_email"
682
- },
683
- {
684
- "name": "return",
685
- "content": "",
686
- "types": [
687
- "\\WP_Error"
688
- ]
689
- }
690
- ],
691
- "long_description_html": "<p>This hook filters registration errors. This can be used to manipulate the array of errors before they are displayed.</p>"
692
- },
693
- "args": 3
694
- },
695
- {
696
- "name": "woocommerce_shared_settings",
697
- "file": "Assets/AssetDataRegistry.php",
698
- "type": "filter",
699
- "doc": {
700
- "description": "Filters the array of shared settings.",
701
- "long_description": "Low level hook for registration of new data late in the cycle. This is deprecated. Instead, use the data api:\n ```php Automattic\\WooCommerce\\Blocks\\Package::container()->get( Automattic\\WooCommerce\\Blocks\\Assets\\AssetDataRegistry::class )->add( $key, $value ) ```",
702
- "tags": [
703
- {
704
- "name": "deprecated",
705
- "content": ""
706
- },
707
- {
708
- "name": "param",
709
- "content": "Settings data.",
710
- "types": [
711
- "array"
712
- ],
713
- "variable": "$data"
714
- },
715
- {
716
- "name": "return",
717
- "content": "",
718
- "types": [
719
- "array"
720
- ]
721
- }
722
- ],
723
- "long_description_html": "<p>Low level hook for registration of new data late in the cycle. This is deprecated. Instead, use the data api:</p> <pre><code class=\"language-php\">Automattic\\WooCommerce\\Blocks\\Package::container()-&gt;get( Automattic\\WooCommerce\\Blocks\\Assets\\AssetDataRegistry::class )-&gt;add( $key, $value )</code></pre>"
724
- },
725
- "args": 1
726
- },
727
- {
728
- "name": "woocommerce_shipping_package_name",
729
- "file": "StoreApi/Utilities/CartController.php",
730
- "type": "filter",
731
- "doc": {
732
- "description": "Filters the shipping package name.",
733
- "long_description": "",
734
- "tags": [
735
- {
736
- "name": "param",
737
- "content": "Shipping package name.",
738
- "types": [
739
- "string"
740
- ],
741
- "variable": "$shipping_package_name"
742
- },
743
- {
744
- "name": "param",
745
- "content": "Shipping package ID.",
746
- "types": [
747
- "string"
748
- ],
749
- "variable": "$package_id"
750
- },
751
- {
752
- "name": "param",
753
- "content": "Shipping package from WooCommerce.",
754
- "types": [
755
- "array"
756
- ],
757
- "variable": "$package"
758
- },
759
- {
760
- "name": "return",
761
- "content": "Shipping package name.",
762
- "types": [
763
- "string"
764
- ]
765
- }
766
- ],
767
- "long_description_html": ""
768
- },
769
- "args": 3
770
- },
771
- {
772
- "name": "woocommerce_show_page_title",
773
- "file": "BlockTypes/LegacyTemplate.php",
774
- "type": "filter",
775
- "doc": {
776
- "description": "We need to load the scripts here because when using block templates wp_head() gets run after the block template. As a result we are trying to enqueue required scripts before we have even registered them.",
777
- "long_description": "",
778
- "tags": [
779
- {
780
- "name": "see",
781
- "content": "",
782
- "refers": "https://github.com/woocommerce/woocommerce-gutenberg-products-block/issues/5328#issuecomment-989013447"
783
- }
784
- ],
785
- "long_description_html": ""
786
- },
787
- "args": 1
788
- },
789
- {
790
- "name": "woocommerce_store_api_disable_nonce_check",
791
- "file": "StoreApi/Routes/AbstractCartRoute.php",
792
- "type": "filter",
793
- "doc": {
794
- "description": "Filters the Store API nonce check.",
795
- "long_description": "This can be used to disable the nonce check when testing API endpoints via a REST API client.",
796
- "tags": [
797
- {
798
- "name": "param",
799
- "content": "If true, nonce checks will be disabled.",
800
- "types": [
801
- "boolean"
802
- ],
803
- "variable": "$disable_nonce_check"
804
- },
805
- {
806
- "name": "return",
807
- "content": "",
808
- "types": [
809
- "boolean"
810
- ]
811
- }
812
- ],
813
- "long_description_html": "<p>This can be used to disable the nonce check when testing API endpoints via a REST API client.</p>"
814
- },
815
- "args": 1
816
- },
817
- {
818
- "name": "woocommerce_store_api_product_quantity_limit",
819
- "file": "StoreApi/Utilities/QuantityLimits.php",
820
- "type": "filter",
821
- "doc": {
822
- "description": "Filters the quantity limit for a product being added to the cart via the Store API.",
823
- "long_description": "Filters the variation option name for custom option slugs.",
824
- "tags": [
825
- {
826
- "name": "param",
827
- "content": "Quantity limit which defaults to 99 unless sold individually.",
828
- "types": [
829
- "integer"
830
- ],
831
- "variable": "$quantity_limit"
832
- },
833
- {
834
- "name": "param",
835
- "content": "Product instance.",
836
- "types": [
837
- "\\WC_Product"
838
- ],
839
- "variable": "$product"
840
- },
841
- {
842
- "name": "return",
843
- "content": "",
844
- "types": [
845
- "integer"
846
- ]
847
- }
848
- ],
849
- "long_description_html": "<p>Filters the variation option name for custom option slugs.</p>"
850
- },
851
- "args": 2
852
- },
853
- {
854
- "name": "woocommerce_store_api_product_quantity_{$value_type}",
855
- "file": "StoreApi/Utilities/QuantityLimits.php",
856
- "type": "filter",
857
- "doc": {
858
- "description": "Filters the quantity minimum for a cart item in Store API. This allows extensions to control the minimum qty of items already within the cart.",
859
- "long_description": "The suffix of the hook will vary depending on the value being filtered. For example, minimum, maximum, multiple_of, editable.",
860
- "tags": [
861
- {
862
- "name": "param",
863
- "content": "The value being filtered.",
864
- "types": [
865
- "mixed"
866
- ],
867
- "variable": "$value"
868
- },
869
- {
870
- "name": "param",
871
- "content": "The product object.",
872
- "types": [
873
- "\\WC_Product"
874
- ],
875
- "variable": "$product"
876
- },
877
- {
878
- "name": "param",
879
- "content": "The cart item if the product exists in the cart, or null.",
880
- "types": [
881
- "array",
882
- "null"
883
- ],
884
- "variable": "$cart_item"
885
- },
886
- {
887
- "name": "return",
888
- "content": "",
889
- "types": [
890
- "mixed"
891
- ]
892
- }
893
- ],
894
- "long_description_html": "<p>The suffix of the hook will vary depending on the value being filtered. For example, minimum, maximum, multiple_of, editable.</p>"
895
- },
896
- "args": 3
897
- },
898
- {
899
- "name": "woocommerce_variation_option_name",
900
- "file": "StoreApi/Schemas/CartItemSchema.php",
901
- "type": "filter",
902
- "doc": {
903
- "description": "Filters the variation option name.",
904
- "long_description": "Filters the variation option name for custom option slugs.",
905
- "tags": [
906
- {
907
- "name": "param",
908
- "content": "The name to display.",
909
- "types": [
910
- "string"
911
- ],
912
- "variable": "$value"
913
- },
914
- {
915
- "name": "param",
916
- "content": "Unused because this is not a variation taxonomy.",
917
- "types": [
918
- "null"
919
- ],
920
- "variable": "$unused"
921
- },
922
- {
923
- "name": "param",
924
- "content": "Taxonomy or product attribute name.",
925
- "types": [
926
- "string"
927
- ],
928
- "variable": "$taxonomy"
929
- },
930
- {
931
- "name": "param",
932
- "content": "Product data.",
933
- "types": [
934
- "\\WC_Product"
935
- ],
936
- "variable": "$product"
937
- },
938
- {
939
- "name": "return",
940
- "content": "",
941
- "types": [
942
- "string"
943
- ]
944
- }
945
- ],
946
- "long_description_html": "<p>Filters the variation option name for custom option slugs.</p>"
947
- },
948
- "args": 4
949
- }
950
- ]
951
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/hook-docs/filters/index.js DELETED
@@ -1,66 +0,0 @@
1
- 'use strict';
2
- /* eslint no-console: 0 */
3
-
4
- /**
5
- * External dependencies
6
- */
7
- const chalk = require( 'chalk' );
8
-
9
- /**
10
- * Internal dependencies
11
- */
12
- const {
13
- params,
14
- exceptions,
15
- returns,
16
- example,
17
- related,
18
- files,
19
- } = require( '../format-hook-doc' );
20
- const {
21
- createDocs,
22
- generateHookName,
23
- generateIntroduction,
24
- sectionWithHeading,
25
- contentWithHeading,
26
- generateToc,
27
- } = require( '../utilities' );
28
-
29
- const generate = ( hooks ) => {
30
- console.log( chalk.blue( 'Generating Filter Docs...' ) );
31
-
32
- const jsonDocs = [
33
- { html: '<!-- DO NOT UPDATE THIS DOC DIRECTLY -->' },
34
- {
35
- html:
36
- '<!-- Use `npm run build:docs` to automatically build hook documentation -->',
37
- },
38
- { h1: 'Filters' },
39
- { h2: 'Table of Contents' },
40
- ...generateToc( hooks ),
41
- { hr: '' },
42
- ...hooks.map( ( hook ) => {
43
- const hookDocs = hook.doc || [];
44
-
45
- return [
46
- ...generateHookName( hook ),
47
- ...generateIntroduction( hook ),
48
- ...contentWithHeading(
49
- hook.doc.long_description_html,
50
- 'Description'
51
- ),
52
- ...sectionWithHeading( params( hookDocs ), 'Parameters' ),
53
- ...sectionWithHeading( exceptions( hookDocs ), 'Exceptions' ),
54
- ...sectionWithHeading( returns( hookDocs ), 'Returns' ),
55
- ...sectionWithHeading( example( hookDocs ), 'Example' ),
56
- ...sectionWithHeading( related( hookDocs ), 'See' ),
57
- ...sectionWithHeading( files( hook.file ), 'Source' ),
58
- { hr: '' },
59
- ].filter( Boolean );
60
- } ),
61
- ];
62
- createDocs( 'docs/extensibility/filters.md', jsonDocs );
63
- console.log( chalk.green( 'Done!' ) );
64
- };
65
-
66
- module.exports = { generate };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/hook-docs/format-hook-doc/example.js DELETED
@@ -1,27 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- const fs = require( 'fs' );
5
-
6
- const example = ( hookDoc ) => {
7
- const tags = hookDoc.tags || [];
8
- const exampleDoc =
9
- tags.filter( ( { name: tagName } ) => tagName === 'example' )[ 0 ] ||
10
- undefined;
11
- const exampleSource = exampleDoc ? exampleDoc.content : false;
12
-
13
- if ( ! exampleSource ) {
14
- return null;
15
- }
16
-
17
- const buffer = fs.readFileSync( `${ exampleSource }` );
18
- const exampleContent = buffer.toString();
19
-
20
- return exampleContent
21
- ? {
22
- html: exampleContent,
23
- }
24
- : null;
25
- };
26
-
27
- module.exports = { example };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/hook-docs/format-hook-doc/exceptions.js DELETED
@@ -1,16 +0,0 @@
1
- const exceptions = ( hookDoc ) => {
2
- const tags = hookDoc.tags || [];
3
- const throwsDoc =
4
- tags.filter( ( { name: tagName } ) => tagName === 'throws' )[ 0 ] ||
5
- undefined;
6
-
7
- return throwsDoc
8
- ? {
9
- p: `\`${ throwsDoc.types.join( ', ' ) }\` ${
10
- throwsDoc.content
11
- }`,
12
- }
13
- : null;
14
- };
15
-
16
- module.exports = { exceptions };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/hook-docs/format-hook-doc/files.js DELETED
@@ -1,11 +0,0 @@
1
- const files = ( sources ) => {
2
- return sources && sources.length
3
- ? {
4
- ul: sources.map( ( file ) => {
5
- return `[${ file }](../src/${ file })`;
6
- } ),
7
- }
8
- : null;
9
- };
10
-
11
- module.exports = { files };
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/hook-docs/format-hook-doc/index.js DELETED
@@ -1,8 +0,0 @@
1
- const { params } = require( './params' );
2
- const { returns } = require( './returns' );
3
- const { example } = require( './example' );
4
- const { related } = require( './related' );
5
- const { exceptions } = require( './exceptions' );
6
- const { files } = require( './files' );
7
-
8
- module.exports = { params, returns, example, related, exceptions, files };
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/hook-docs/format-hook-doc/params.js DELETED
@@ -1,24 +0,0 @@
1
- const params = ( hookDoc ) => {
2
- const tags = hookDoc.tags || [];
3
- const paramDocs =
4
- tags.filter( ( { name: tagName } ) => tagName === 'param' ) || [];
5
-
6
- return paramDocs && paramDocs.length
7
- ? {
8
- table: {
9
- headers: [ 'Argument', 'Type', 'Description' ],
10
- rows: [
11
- ...paramDocs.map(
12
- ( { variable, types, content }, index ) => [
13
- variable ? variable : index + 1,
14
- types.join( ', ' ),
15
- content,
16
- ]
17
- ),
18
- ],
19
- },
20
- }
21
- : null;
22
- };
23
-
24
- module.exports = { params };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/hook-docs/format-hook-doc/related.js DELETED
@@ -1,15 +0,0 @@
1
- const related = ( hookDoc ) => {
2
- const tags = hookDoc.tags || [];
3
- const seeDocs =
4
- tags.filter( ( { name: tagName } ) => tagName === 'see' ) || [];
5
-
6
- return seeDocs && seeDocs.length
7
- ? {
8
- ul: seeDocs.map( ( { refers, content = '' } ) => {
9
- return content ? refers + ' - ' + content : refers;
10
- } ),
11
- }
12
- : null;
13
- };
14
-
15
- module.exports = { related };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/hook-docs/format-hook-doc/returns.js DELETED
@@ -1,16 +0,0 @@
1
- const returns = ( hookDoc ) => {
2
- const tags = hookDoc.tags || [];
3
- const returnDoc =
4
- tags.filter( ( { name: tagName } ) => tagName === 'return' )[ 0 ] ||
5
- undefined;
6
-
7
- return returnDoc
8
- ? {
9
- p: `\`${ returnDoc.types.join( ', ' ) }\` ${
10
- returnDoc.content
11
- }`,
12
- }
13
- : null;
14
- };
15
-
16
- module.exports = { returns };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/hook-docs/index.js DELETED
@@ -1,39 +0,0 @@
1
- #!/usr/bin/env node
2
- 'use strict';
3
- /* eslint no-console: 0 */
4
- const chalk = require( 'chalk' );
5
-
6
- const groupByHook = ( hooks, hook ) => {
7
- if ( hooks[ hook.name ] !== undefined ) {
8
- if ( hooks[ hook.name ].file !== hook.file ) {
9
- hooks[ hook.name ].file.push( hook.file );
10
- }
11
- return hooks; // skip or return updated record.
12
- }
13
-
14
- hooks[ hook.name ] = {
15
- ...hook,
16
- file: [ hook.file ], // Use array of files to support hooks used across the codebase.
17
- };
18
-
19
- return hooks;
20
- };
21
-
22
- try {
23
- const { generate: generateActionDocs } = require( './actions' );
24
- const { generate: generateFilterDocs } = require( './filters' );
25
-
26
- console.log( chalk.blue( "Let's create some docs!" ) );
27
-
28
- const rawActions = require( './data/actions.json' ).hooks;
29
- const rawFilters = require( './data/filters.json' ).hooks;
30
-
31
- // Skip duplicates.
32
- const actions = rawActions.reduce( groupByHook, {} );
33
- const filters = rawFilters.reduce( groupByHook, {} );
34
-
35
- generateActionDocs( Object.values( actions ) );
36
- generateFilterDocs( Object.values( filters ) );
37
- } catch ( error ) {
38
- console.log( chalk.red( error.message ) );
39
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/hook-docs/utilities/content-with-heading.js DELETED
@@ -1,7 +0,0 @@
1
- const contentWithHeading = ( content, heading, headingLevel = 'h3' ) => {
2
- return content && content.length
3
- ? [ { [ headingLevel ]: heading }, { html: content } ]
4
- : [];
5
- };
6
-
7
- module.exports = { contentWithHeading };
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/hook-docs/utilities/create-docs.js DELETED
@@ -1,25 +0,0 @@
1
- 'use strict';
2
- /* eslint no-console: 0 */
3
-
4
- /**
5
- * External dependencies
6
- */
7
- const fs = require( 'fs' );
8
- const chalk = require( 'chalk' );
9
-
10
- /**
11
- * Internal dependencies
12
- */
13
- const { json2md } = require( './json2md' );
14
-
15
- const createDocs = ( file, jsonDocs ) => {
16
- console.log( chalk.blue( `Creating file ${ file }...` ) );
17
-
18
- fs.writeFile( file, json2md( jsonDocs ), function ( error ) {
19
- if ( error ) {
20
- throw error;
21
- }
22
- } );
23
- };
24
-
25
- module.exports = { createDocs };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/hook-docs/utilities/generate-hook-name.js DELETED
@@ -1,16 +0,0 @@
1
- const generateHookName = ( hook ) => {
2
- const hookName = hook.name;
3
- const tags = hook.doc.tags || [];
4
-
5
- const isDeprecated = tags.find(
6
- ( { name: tagName } ) => tagName === 'deprecated'
7
- );
8
-
9
- return [
10
- {
11
- h2: isDeprecated ? `~~${ hookName }~~` : `${ hookName }`,
12
- },
13
- ];
14
- };
15
-
16
- module.exports = { generateHookName };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/hook-docs/utilities/generate-introduction.js DELETED
@@ -1,71 +0,0 @@
1
- const getHookFunction = ( hookType ) => {
2
- if ( hookType === 'action' ) {
3
- return 'do_action';
4
- }
5
- if ( hookType === 'action_reference' ) {
6
- return 'do_action_ref_array';
7
- }
8
- if ( hookType === 'filter_reference' ) {
9
- return 'apply_filters_ref_array';
10
- }
11
- return 'apply_filters';
12
- };
13
-
14
- const generateIntroduction = ( hook ) => {
15
- const hookName = hook.name;
16
- const hookType = hook.type;
17
- const hookFunction = getHookFunction( hookType );
18
- const tags = hook.doc.tags || [];
19
-
20
- const deprecated =
21
- tags.filter( ( { name: tagName } ) => tagName === 'deprecated' )[ 0 ] ||
22
- undefined;
23
- const internal =
24
- tags.filter( ( { name: tagName } ) => tagName === 'internal' )[ 0 ] ||
25
- undefined;
26
- const paramDocs =
27
- tags.filter( ( { name: tagName } ) => tagName === 'param' ) || [];
28
-
29
- const hookParams = paramDocs.map( ( { variable, types }, index ) => {
30
- const formattedType = types.join( '|' );
31
- const formattedVariable = variable ? variable : `$argument${ index }`;
32
- return `${ formattedType } ${ formattedVariable }`;
33
- } );
34
-
35
- const hookParamPrefix = hookFunction.includes( 'ref_array' ) ? '[ ' : '';
36
- const hookParamSuffix = hookFunction.includes( 'ref_array' ) ? ' ]' : '';
37
-
38
- const formattedHookParams = hookParams.length
39
- ? ', ' + hookParamPrefix + hookParams.join( ', ' ) + hookParamSuffix
40
- : '';
41
-
42
- return [
43
- { p: hook.doc.description },
44
- {
45
- code: {
46
- language: 'php',
47
- content: `${ hookFunction }( '${ hookName }'${ formattedHookParams } )`,
48
- },
49
- },
50
- deprecated
51
- ? {
52
- p: `**Deprecated: ${
53
- deprecated.content
54
- ? deprecated.content
55
- : 'This hook is deprecated and will be removed'
56
- }**`,
57
- }
58
- : null,
59
- internal
60
- ? {
61
- p: `**Note: ${
62
- internal.content
63
- ? internal.content
64
- : 'This hook is for internal use only'
65
- }**`,
66
- }
67
- : null,
68
- ];
69
- };
70
-
71
- module.exports = { generateIntroduction };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/hook-docs/utilities/generate-toc.js DELETED
@@ -1,38 +0,0 @@
1
- const generateToc = ( hooks ) => {
2
- const usedHeaders = [];
3
-
4
- return [
5
- {
6
- ul: hooks.map( ( hook ) => {
7
- const hookName = hook.name;
8
- const tags = hook.doc.tags || [];
9
- const isDeprecated = tags.find(
10
- ( { name: tagName } ) => tagName === 'deprecated'
11
- );
12
- const heading = isDeprecated
13
- ? `~~${ hookName }~~`
14
- : `${ hookName }`;
15
-
16
- let anchor = heading
17
- .trim()
18
- .toLowerCase()
19
- .replace( /[^\w\- ]+/g, ' ' )
20
- .replace( /\s+/g, '-' )
21
- .replace( /\-+$/, '' );
22
- if ( usedHeaders.indexOf( anchor ) !== -1 ) {
23
- let i = 1;
24
- while (
25
- usedHeaders.indexOf( anchor + '-' + i ) !== -1 &&
26
- i++ <= 10
27
- );
28
- anchor = anchor + '-' + i;
29
- }
30
- usedHeaders.push( anchor );
31
-
32
- return `[${ hook.name }](#${ anchor })`;
33
- } ),
34
- },
35
- ];
36
- };
37
-
38
- module.exports = { generateToc };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/hook-docs/utilities/index.js DELETED
@@ -1,17 +0,0 @@
1
- const { createDocs } = require( './create-docs' );
2
- const { generateHookName } = require( './generate-hook-name' );
3
- const { generateIntroduction } = require( './generate-introduction' );
4
- const { json2md } = require( './json2md' );
5
- const { sectionWithHeading } = require( './section-with-heading' );
6
- const { contentWithHeading } = require( './content-with-heading' );
7
- const { generateToc } = require( './generate-toc' );
8
-
9
- module.exports = {
10
- createDocs,
11
- generateHookName,
12
- generateIntroduction,
13
- json2md,
14
- sectionWithHeading,
15
- contentWithHeading,
16
- generateToc,
17
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/hook-docs/utilities/json2md.js DELETED
@@ -1,12 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * External dependencies
5
- */
6
- const json2md = require( 'json2md' );
7
-
8
- json2md.converters.html = function ( input ) {
9
- return input;
10
- };
11
-
12
- module.exports = { json2md };
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/hook-docs/utilities/section-with-heading.js DELETED
@@ -1,5 +0,0 @@
1
- const sectionWithHeading = ( content, heading, headingLevel = 'h3' ) => {
2
- return content ? [ { [ headingLevel ]: heading }, content ] : [];
3
- };
4
-
5
- module.exports = { sectionWithHeading };
 
 
 
 
 
packages/woocommerce-blocks/bin/remove-files-webpack-plugin.js DELETED
@@ -1,28 +0,0 @@
1
- /*eslint-env node*/
2
- /**
3
- * External dependencies
4
- */
5
- const fs = require( 'fs' );
6
- const glob = require( 'glob' );
7
-
8
- // This is a simple webpack plugin to delete the JS files generated by MiniCssExtractPlugin.
9
-
10
- function RemoveFilesPlugin( filePath = '' ) {
11
- this.filePath = filePath;
12
- }
13
-
14
- RemoveFilesPlugin.prototype.apply = function ( compiler ) {
15
- compiler.hooks.afterEmit.tap( 'afterEmit', () => {
16
- const files = glob.sync( this.filePath );
17
- files.forEach( ( f ) => {
18
- fs.unlink( f, ( err ) => {
19
- if ( err ) {
20
- /* eslint-disable-next-line no-console */
21
- console.log( `There was an error removing ${ f }.`, err );
22
- }
23
- } );
24
- } );
25
- } );
26
- };
27
-
28
- module.exports = RemoveFilesPlugin;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/version-changes.sh DELETED
@@ -1,22 +0,0 @@
1
- #!/bin/sh
2
- VERSION=${VERSION:=\$VID\:\$}
3
- IS_PRE_RELEASE=${IS_PRE_RELEASE:=false}
4
-
5
- # replace all instances of $VID:$ with the release version but only when not pre-release.
6
- if [ $IS_PRE_RELEASE = false ]; then
7
- find ./src woocommerce-gutenberg-products-block.php -name "*.php" -print0 | xargs -0 perl -i -pe 's/\$VID:\$/'${VERSION}'/g'
8
- # Update version number in readme.txt but only if not pre-release
9
- perl -i -pe 's/Stable tag:*.+/Stable tag: '${VERSION}'/' readme.txt
10
- fi
11
-
12
- # Update version in main plugin file
13
- perl -i -pe 's/Version:*.+/Version: '${VERSION}'/' woocommerce-gutenberg-products-block.php
14
-
15
- # Update version in package.json
16
- perl -i -pe 's/"version":*.+/"version": "'${VERSION}'",/' package.json
17
-
18
- # Update version in src/Package.php
19
- perl -i -pe "s/version \= '*.+';/version = '${VERSION}';/" src/Package.php
20
-
21
- # Add version to composer.json
22
- perl -i -pe 's/"type":*.+/"type":"wordpress-plugin",\n\t"version": "'${VERSION}'",/' composer.json
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/webpack-configs.js DELETED
@@ -1,765 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- const path = require( 'path' );
5
- const { kebabCase } = require( 'lodash' );
6
- const RemoveFilesPlugin = require( './remove-files-webpack-plugin' );
7
- const MiniCssExtractPlugin = require( 'mini-css-extract-plugin' );
8
- const ProgressBarPlugin = require( 'progress-bar-webpack-plugin' );
9
- const DependencyExtractionWebpackPlugin = require( '@wordpress/dependency-extraction-webpack-plugin' );
10
- const WebpackRTLPlugin = require( 'webpack-rtl-plugin' );
11
- const TerserPlugin = require( 'terser-webpack-plugin' );
12
- const CreateFileWebpack = require( 'create-file-webpack' );
13
- const CircularDependencyPlugin = require( 'circular-dependency-plugin' );
14
- const { BundleAnalyzerPlugin } = require( 'webpack-bundle-analyzer' );
15
- const CopyWebpackPlugin = require( 'copy-webpack-plugin' );
16
-
17
- /**
18
- * Internal dependencies
19
- */
20
- const { getEntryConfig } = require( './webpack-entries' );
21
- const {
22
- NODE_ENV,
23
- CHECK_CIRCULAR_DEPS,
24
- requestToExternal,
25
- requestToHandle,
26
- findModuleMatch,
27
- getProgressBarPluginConfig,
28
- } = require( './webpack-helpers' );
29
-
30
- const isProduction = NODE_ENV === 'production';
31
-
32
- /**
33
- * Shared config for all script builds.
34
- */
35
- const sharedPlugins = [
36
- CHECK_CIRCULAR_DEPS === 'true'
37
- ? new CircularDependencyPlugin( {
38
- exclude: /node_modules/,
39
- cwd: process.cwd(),
40
- failOnError: 'warn',
41
- } )
42
- : false,
43
- // The WP_BUNDLE_ANALYZER global variable enables a utility that represents bundle
44
- // content as a convenient interactive zoomable treemap.
45
- process.env.WP_BUNDLE_ANALYZER && new BundleAnalyzerPlugin(),
46
- new DependencyExtractionWebpackPlugin( {
47
- injectPolyfill: true,
48
- requestToExternal,
49
- requestToHandle,
50
- } ),
51
- ].filter( Boolean );
52
-
53
- /**
54
- * Build config for core packages.
55
- *
56
- * @param {Object} options Build options.
57
- */
58
- const getCoreConfig = ( options = {} ) => {
59
- const { alias, resolvePlugins = [] } = options;
60
- const resolve = alias
61
- ? {
62
- alias,
63
- plugins: resolvePlugins,
64
- }
65
- : {
66
- plugins: resolvePlugins,
67
- };
68
- return {
69
- entry: getEntryConfig( 'core', options.exclude || [] ),
70
- output: {
71
- filename: ( chunkData ) => {
72
- return `${ kebabCase( chunkData.chunk.name ) }.js`;
73
- },
74
- path: path.resolve( __dirname, '../build/' ),
75
- library: [ 'wc', '[name]' ],
76
- libraryTarget: 'this',
77
- // This fixes an issue with multiple webpack projects using chunking
78
- // overwriting each other's chunk loader function.
79
- // See https://webpack.js.org/configuration/output/#outputjsonpfunction
80
- jsonpFunction: 'webpackWcBlocksJsonp',
81
- },
82
- module: {
83
- rules: [
84
- {
85
- test: /\.(t|j)sx?$/,
86
- exclude: /node_modules/,
87
- use: {
88
- loader: 'babel-loader?cacheDirectory',
89
- options: {
90
- presets: [ '@wordpress/babel-preset-default' ],
91
- },
92
- },
93
- },
94
- {
95
- test: /\.s[c|a]ss$/,
96
- use: {
97
- loader: 'ignore-loader',
98
- },
99
- },
100
- ],
101
- },
102
- plugins: [
103
- ...sharedPlugins,
104
- new ProgressBarPlugin(
105
- getProgressBarPluginConfig( 'Core', options.fileSuffix )
106
- ),
107
- new CreateFileWebpack( {
108
- path: './',
109
- // file name
110
- fileName: 'blocks.ini',
111
- // content of the file
112
- content: `
113
- woocommerce_blocks_phase = ${ process.env.WOOCOMMERCE_BLOCKS_PHASE || 3 }
114
- woocommerce_blocks_env = ${ NODE_ENV }
115
- `.trim(),
116
- } ),
117
- ],
118
- optimization: {
119
- // Only concatenate modules in production, when not analyzing bundles.
120
- concatenateModules:
121
- isProduction && ! process.env.WP_BUNDLE_ANALYZER,
122
- splitChunks: {
123
- automaticNameDelimiter: '--',
124
- },
125
- minimizer: [
126
- new TerserPlugin( {
127
- cache: true,
128
- parallel: true,
129
- terserOptions: {
130
- output: {
131
- comments: /translators:/i,
132
- },
133
- compress: {
134
- passes: 2,
135
- },
136
- mangle: {
137
- reserved: [ '__', '_n', '_nx', '_x' ],
138
- },
139
- },
140
- extractComments: false,
141
- } ),
142
- ],
143
- },
144
- resolve: {
145
- ...resolve,
146
- extensions: [ '.js', '.ts', '.tsx' ],
147
- },
148
- };
149
- };
150
-
151
- /**
152
- * Build config for Blocks in the editor context.
153
- *
154
- * @param {Object} options Build options.
155
- */
156
- const getMainConfig = ( options = {} ) => {
157
- let { fileSuffix } = options;
158
- const { alias, resolvePlugins = [] } = options;
159
- fileSuffix = fileSuffix ? `-${ fileSuffix }` : '';
160
- const resolve = alias
161
- ? {
162
- alias,
163
- plugins: resolvePlugins,
164
- }
165
- : {
166
- plugins: resolvePlugins,
167
- };
168
- return {
169
- entry: getEntryConfig( 'main', options.exclude || [] ),
170
- output: {
171
- devtoolNamespace: 'wc',
172
- path: path.resolve( __dirname, '../build/' ),
173
- // This is a cache busting mechanism which ensures that the script is loaded via the browser with a ?ver=hash
174
- // string. The hash is based on the built file contents.
175
- // @see https://github.com/webpack/webpack/issues/2329
176
- // Using the ?ver string is needed here so the filename does not change between builds. The WordPress
177
- // i18n system relies on the hash of the filename, so changing that frequently would result in broken
178
- // translations which we must avoid.
179
- // @see https://github.com/Automattic/jetpack/pull/20926
180
- chunkFilename: `[name]${ fileSuffix }.js?ver=[contenthash]`,
181
- filename: `[name]${ fileSuffix }.js`,
182
- library: [ 'wc', 'blocks', '[name]' ],
183
- libraryTarget: 'this',
184
- // This fixes an issue with multiple webpack projects using chunking
185
- // overwriting each other's chunk loader function.
186
- // See https://webpack.js.org/configuration/output/#outputjsonpfunction
187
- // This can be removed when moving to webpack 5:
188
- // https://webpack.js.org/blog/2020-10-10-webpack-5-release/#automatic-unique-naming
189
- jsonpFunction: 'webpackWcBlocksJsonp',
190
- },
191
- module: {
192
- rules: [
193
- {
194
- test: /\.(j|t)sx?$/,
195
- exclude: /node_modules/,
196
- use: {
197
- loader: 'babel-loader?cacheDirectory',
198
- options: {
199
- presets: [ '@wordpress/babel-preset-default' ],
200
- plugins: [
201
- isProduction
202
- ? require.resolve(
203
- 'babel-plugin-transform-react-remove-prop-types'
204
- )
205
- : false,
206
- ].filter( Boolean ),
207
- },
208
- },
209
- },
210
- {
211
- test: /\.s[c|a]ss$/,
212
- use: {
213
- loader: 'ignore-loader',
214
- },
215
- },
216
- ],
217
- },
218
- optimization: {
219
- concatenateModules:
220
- isProduction && ! process.env.WP_BUNDLE_ANALYZER,
221
- splitChunks: {
222
- minSize: 0,
223
- automaticNameDelimiter: '--',
224
- cacheGroups: {
225
- commons: {
226
- test: /[\\/]node_modules[\\/]/,
227
- name: 'wc-blocks-vendors',
228
- chunks: 'all',
229
- enforce: true,
230
- },
231
- },
232
- },
233
- minimizer: [
234
- new TerserPlugin( {
235
- cache: true,
236
- parallel: true,
237
- terserOptions: {
238
- output: {
239
- comments: /translators:/i,
240
- },
241
- compress: {
242
- passes: 2,
243
- },
244
- mangle: {
245
- reserved: [ '__', '_n', '_nx', '_x' ],
246
- },
247
- },
248
- extractComments: false,
249
- } ),
250
- ],
251
- },
252
- plugins: [
253
- ...sharedPlugins,
254
- new ProgressBarPlugin(
255
- getProgressBarPluginConfig( 'Main', options.fileSuffix )
256
- ),
257
- new CopyWebpackPlugin( {
258
- patterns: [
259
- {
260
- from: './assets/js/blocks/checkout/block.json',
261
- to: './checkout/block.json',
262
- },
263
- ],
264
- } ),
265
- ],
266
- resolve: {
267
- ...resolve,
268
- extensions: [ '.js', '.jsx', '.ts', '.tsx' ],
269
- },
270
- };
271
- };
272
-
273
- /**
274
- * Build config for Blocks in the frontend context.
275
- *
276
- * @param {Object} options Build options.
277
- */
278
- const getFrontConfig = ( options = {} ) => {
279
- let { fileSuffix } = options;
280
- const { alias, resolvePlugins = [] } = options;
281
- fileSuffix = fileSuffix ? `-${ fileSuffix }` : '';
282
- const resolve = alias
283
- ? {
284
- alias,
285
- plugins: resolvePlugins,
286
- }
287
- : {
288
- plugins: resolvePlugins,
289
- };
290
- return {
291
- entry: getEntryConfig( 'frontend', options.exclude || [] ),
292
- output: {
293
- devtoolNamespace: 'wc',
294
- path: path.resolve( __dirname, '../build/' ),
295
- // This is a cache busting mechanism which ensures that the script is loaded via the browser with a ?ver=hash
296
- // string. The hash is based on the built file contents.
297
- // @see https://github.com/webpack/webpack/issues/2329
298
- // Using the ?ver string is needed here so the filename does not change between builds. The WordPress
299
- // i18n system relies on the hash of the filename, so changing that frequently would result in broken
300
- // translations which we must avoid.
301
- // @see https://github.com/Automattic/jetpack/pull/20926
302
- chunkFilename: `[name]-frontend${ fileSuffix }.js?ver=[contenthash]`,
303
- filename: `[name]-frontend${ fileSuffix }.js`,
304
- // This fixes an issue with multiple webpack projects using chunking
305
- // overwriting each other's chunk loader function.
306
- // See https://webpack.js.org/configuration/output/#outputjsonpfunction
307
- // This can be removed when moving to webpack 5:
308
- // https://webpack.js.org/blog/2020-10-10-webpack-5-release/#automatic-unique-naming
309
- jsonpFunction: 'webpackWcBlocksJsonp',
310
- },
311
- module: {
312
- rules: [
313
- {
314
- test: /\.(j|t)sx?$/,
315
- exclude: /node_modules/,
316
- use: {
317
- loader: 'babel-loader?cacheDirectory',
318
- options: {
319
- presets: [
320
- [
321
- '@wordpress/babel-preset-default',
322
- {
323
- modules: false,
324
- targets: {
325
- browsers: [
326
- 'extends @wordpress/browserslist-config',
327
- ],
328
- },
329
- },
330
- ],
331
- ],
332
- plugins: [
333
- isProduction
334
- ? require.resolve(
335
- 'babel-plugin-transform-react-remove-prop-types'
336
- )
337
- : false,
338
- ].filter( Boolean ),
339
- },
340
- },
341
- },
342
- {
343
- test: /\.s[c|a]ss$/,
344
- use: {
345
- loader: 'ignore-loader',
346
- },
347
- },
348
- ],
349
- },
350
- optimization: {
351
- concatenateModules:
352
- isProduction && ! process.env.WP_BUNDLE_ANALYZER,
353
- splitChunks: {
354
- automaticNameDelimiter: '--',
355
- },
356
- minimizer: [
357
- new TerserPlugin( {
358
- cache: true,
359
- parallel: true,
360
- terserOptions: {
361
- output: {
362
- comments: /translators:/i,
363
- },
364
- compress: {
365
- passes: 2,
366
- },
367
- mangle: {
368
- reserved: [ '__', '_n', '_nx', '_x' ],
369
- },
370
- },
371
- extractComments: false,
372
- } ),
373
- ],
374
- },
375
- plugins: [
376
- ...sharedPlugins,
377
- new ProgressBarPlugin(
378
- getProgressBarPluginConfig( 'Frontend', options.fileSuffix )
379
- ),
380
- ],
381
- resolve: {
382
- ...resolve,
383
- extensions: [ '.js', '.ts', '.tsx' ],
384
- },
385
- };
386
- };
387
-
388
- /**
389
- * Build config for built-in payment gateway integrations.
390
- *
391
- * @param {Object} options Build options.
392
- */
393
- const getPaymentsConfig = ( options = {} ) => {
394
- const { alias, resolvePlugins = [] } = options;
395
- const resolve = alias
396
- ? {
397
- alias,
398
- plugins: resolvePlugins,
399
- }
400
- : {
401
- plugins: resolvePlugins,
402
- };
403
- return {
404
- entry: getEntryConfig( 'payments', options.exclude || [] ),
405
- output: {
406
- devtoolNamespace: 'wc',
407
- path: path.resolve( __dirname, '../build/' ),
408
- filename: `[name].js`,
409
- // This fixes an issue with multiple webpack projects using chunking
410
- // overwriting each other's chunk loader function.
411
- // See https://webpack.js.org/configuration/output/#outputjsonpfunction
412
- jsonpFunction: 'webpackWcBlocksPaymentMethodExtensionJsonp',
413
- },
414
- module: {
415
- rules: [
416
- {
417
- test: /\.(j|t)sx?$/,
418
- exclude: /node_modules/,
419
- use: {
420
- loader: 'babel-loader?cacheDirectory',
421
- options: {
422
- presets: [
423
- [
424
- '@wordpress/babel-preset-default',
425
- {
426
- modules: false,
427
- targets: {
428
- browsers: [
429
- 'extends @wordpress/browserslist-config',
430
- ],
431
- },
432
- },
433
- ],
434
- ],
435
- plugins: [
436
- isProduction
437
- ? require.resolve(
438
- 'babel-plugin-transform-react-remove-prop-types'
439
- )
440
- : false,
441
- ].filter( Boolean ),
442
- },
443
- },
444
- },
445
- {
446
- test: /\.s[c|a]ss$/,
447
- use: {
448
- loader: 'ignore-loader',
449
- },
450
- },
451
- ],
452
- },
453
- optimization: {
454
- concatenateModules:
455
- isProduction && ! process.env.WP_BUNDLE_ANALYZER,
456
- splitChunks: {
457
- automaticNameDelimiter: '--',
458
- },
459
- minimizer: [
460
- new TerserPlugin( {
461
- cache: true,
462
- parallel: true,
463
- terserOptions: {
464
- output: {
465
- comments: /translators:/i,
466
- },
467
- compress: {
468
- passes: 2,
469
- },
470
- mangle: {
471
- reserved: [ '__', '_n', '_nx', '_x' ],
472
- },
473
- },
474
- extractComments: false,
475
- } ),
476
- ],
477
- },
478
- plugins: [
479
- ...sharedPlugins,
480
- new ProgressBarPlugin(
481
- getProgressBarPluginConfig(
482
- 'Payment Method Extensions',
483
- options.fileSuffix
484
- )
485
- ),
486
- ],
487
- resolve: {
488
- ...resolve,
489
- extensions: [ '.js', '.ts', '.tsx' ],
490
- },
491
- };
492
- };
493
-
494
- /**
495
- * Build config for extension integrations.
496
- *
497
- * @param {Object} options Build options.
498
- */
499
- const getExtensionsConfig = ( options = {} ) => {
500
- const { alias, resolvePlugins = [] } = options;
501
- const resolve = alias
502
- ? {
503
- alias,
504
- plugins: resolvePlugins,
505
- }
506
- : {
507
- plugins: resolvePlugins,
508
- };
509
- return {
510
- entry: getEntryConfig( 'extensions', options.exclude || [] ),
511
- output: {
512
- devtoolNamespace: 'wc',
513
- path: path.resolve( __dirname, '../build/' ),
514
- filename: `[name].js`,
515
- jsonpFunction: 'webpackWcBlocksExtensionsMethodExtensionJsonp',
516
- },
517
- module: {
518
- rules: [
519
- {
520
- test: /\.(j|t)sx?$/,
521
- exclude: /node_modules/,
522
- use: {
523
- loader: 'babel-loader?cacheDirectory',
524
- options: {
525
- presets: [
526
- [
527
- '@wordpress/babel-preset-default',
528
- {
529
- modules: false,
530
- targets: {
531
- browsers: [
532
- 'extends @wordpress/browserslist-config',
533
- ],
534
- },
535
- },
536
- ],
537
- ],
538
- plugins: [
539
- isProduction
540
- ? require.resolve(
541
- 'babel-plugin-transform-react-remove-prop-types'
542
- )
543
- : false,
544
- ].filter( Boolean ),
545
- },
546
- },
547
- },
548
- ],
549
- },
550
- optimization: {
551
- concatenateModules:
552
- isProduction && ! process.env.WP_BUNDLE_ANALYZER,
553
- splitChunks: {
554
- automaticNameDelimiter: '--',
555
- },
556
- minimizer: [
557
- new TerserPlugin( {
558
- cache: true,
559
- parallel: true,
560
- terserOptions: {
561
- output: {
562
- comments: /translators:/i,
563
- },
564
- compress: {
565
- passes: 2,
566
- },
567
- mangle: {
568
- reserved: [ '__', '_n', '_nx', '_x' ],
569
- },
570
- },
571
- extractComments: false,
572
- } ),
573
- ],
574
- },
575
- plugins: [
576
- ...sharedPlugins,
577
- new ProgressBarPlugin(
578
- getProgressBarPluginConfig(
579
- 'Experimental Extensions',
580
- options.fileSuffix
581
- )
582
- ),
583
- ],
584
- resolve: {
585
- ...resolve,
586
- extensions: [ '.js', '.ts', '.tsx' ],
587
- },
588
- };
589
- };
590
-
591
- /**
592
- * Build config for CSS Styles.
593
- *
594
- * @param {Object} options Build options.
595
- */
596
- const getStylingConfig = ( options = {} ) => {
597
- let { fileSuffix } = options;
598
- const { alias, resolvePlugins = [] } = options;
599
- fileSuffix = fileSuffix ? `-${ fileSuffix }` : '';
600
- const resolve = alias
601
- ? {
602
- alias,
603
- plugins: resolvePlugins,
604
- }
605
- : {
606
- plugins: resolvePlugins,
607
- };
608
- return {
609
- entry: getEntryConfig( 'styling', options.exclude || [] ),
610
- output: {
611
- devtoolNamespace: 'wc',
612
- path: path.resolve( __dirname, '../build/' ),
613
- filename: `[name]-style${ fileSuffix }.js`,
614
- library: [ 'wc', 'blocks', '[name]' ],
615
- libraryTarget: 'this',
616
- // This fixes an issue with multiple webpack projects using chunking
617
- // overwriting each other's chunk loader function.
618
- // See https://webpack.js.org/configuration/output/#outputjsonpfunction
619
- jsonpFunction: 'webpackWcBlocksJsonp',
620
- },
621
- optimization: {
622
- splitChunks: {
623
- minSize: 0,
624
- automaticNameDelimiter: '--',
625
- cacheGroups: {
626
- editorStyle: {
627
- // Capture all `editor` stylesheets and editor-components stylesheets.
628
- test: ( module = {} ) =>
629
- module.constructor.name === 'CssModule' &&
630
- ( findModuleMatch( module, /editor\.scss$/ ) ||
631
- findModuleMatch(
632
- module,
633
- /[\\/]assets[\\/]js[\\/]editor-components[\\/]/
634
- ) ),
635
- name: 'wc-blocks-editor-style',
636
- chunks: 'all',
637
- priority: 10,
638
- },
639
- vendorsStyle: {
640
- test: /\/node_modules\/.*?style\.s?css$/,
641
- name: 'wc-blocks-vendors-style',
642
- chunks: 'all',
643
- priority: 7,
644
- },
645
- blocksStyle: {
646
- // Capture all stylesheets with name `style` or name that starts with underscore (abstracts).
647
- test: /(style|_.*)\.scss$/,
648
- name: 'wc-blocks-style',
649
- chunks: 'all',
650
- priority: 5,
651
- },
652
- },
653
- },
654
- },
655
- module: {
656
- rules: [
657
- {
658
- test: /\/node_modules\/.*?style\.s?css$/,
659
- use: [
660
- MiniCssExtractPlugin.loader,
661
- { loader: 'css-loader', options: { importLoaders: 1 } },
662
- 'postcss-loader',
663
- {
664
- loader: 'sass-loader',
665
- options: {
666
- sassOptions: {
667
- includePaths: [ 'node_modules' ],
668
- },
669
- additionalData: ( content ) => {
670
- const styleImports = [
671
- 'colors',
672
- 'breakpoints',
673
- 'variables',
674
- 'mixins',
675
- 'animations',
676
- 'z-index',
677
- ]
678
- .map(
679
- ( imported ) =>
680
- `@import "~@wordpress/base-styles/${ imported }";`
681
- )
682
- .join( ' ' );
683
- return styleImports + content;
684
- },
685
- },
686
- },
687
- ],
688
- },
689
- {
690
- test: /\.s?css$/,
691
- exclude: /node_modules/,
692
- use: [
693
- MiniCssExtractPlugin.loader,
694
- { loader: 'css-loader', options: { importLoaders: 1 } },
695
- 'postcss-loader',
696
- {
697
- loader: 'sass-loader',
698
- options: {
699
- sassOptions: {
700
- includePaths: [ 'assets/css/abstracts' ],
701
- },
702
- additionalData: ( content, loaderContext ) => {
703
- const {
704
- resourcePath,
705
- rootContext,
706
- } = loaderContext;
707
- const relativePath = path.relative(
708
- rootContext,
709
- resourcePath
710
- );
711
-
712
- if (
713
- relativePath.startsWith(
714
- 'assets/css/abstracts/'
715
- )
716
- ) {
717
- return content;
718
- }
719
-
720
- return (
721
- '@use "sass:math";' +
722
- '@import "_colors"; ' +
723
- '@import "_variables"; ' +
724
- '@import "_breakpoints"; ' +
725
- '@import "_mixins"; ' +
726
- content
727
- );
728
- },
729
- },
730
- },
731
- ],
732
- },
733
- ],
734
- },
735
- plugins: [
736
- new ProgressBarPlugin(
737
- getProgressBarPluginConfig( 'Styles', options.fileSuffix )
738
- ),
739
- new WebpackRTLPlugin( {
740
- filename: `[name]${ fileSuffix }-rtl.css`,
741
- minify: {
742
- safe: true,
743
- },
744
- } ),
745
- new MiniCssExtractPlugin( {
746
- filename: `[name]${ fileSuffix }.css`,
747
- } ),
748
- // Remove JS files generated by MiniCssExtractPlugin.
749
- new RemoveFilesPlugin( `./build/*style${ fileSuffix }.js` ),
750
- ],
751
- resolve: {
752
- ...resolve,
753
- extensions: [ '.js', '.ts', '.tsx' ],
754
- },
755
- };
756
- };
757
-
758
- module.exports = {
759
- getCoreConfig,
760
- getFrontConfig,
761
- getMainConfig,
762
- getPaymentsConfig,
763
- getExtensionsConfig,
764
- getStylingConfig,
765
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/webpack-entries.js DELETED
@@ -1,156 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- const { omit } = require( 'lodash' );
5
- const glob = require( 'glob' );
6
-
7
- // List of blocks that should be used as webpack entry points. They are expected
8
- // to be in `/assets/js/blocks/[BLOCK_NAME]`. If they are not, their relative
9
- // path should be defined in the `customDir` property. The scripts below will
10
- // take care of looking for `index.js`, `frontend.js` and `*.scss` files in each
11
- // block directory.
12
- // If a block is experimental, it should be marked with the `isExperimental`
13
- // property.
14
- const blocks = {
15
- 'handpicked-products': {},
16
- 'product-best-sellers': {},
17
- 'product-category': {},
18
- 'product-categories': {},
19
- 'product-new': {},
20
- 'product-on-sale': {},
21
- 'product-top-rated': {},
22
- 'products-by-attribute': {},
23
- 'featured-product': {},
24
- 'all-reviews': {
25
- customDir: 'reviews/all-reviews',
26
- },
27
- 'reviews-by-product': {
28
- customDir: 'reviews/reviews-by-product',
29
- },
30
- 'reviews-by-category': {
31
- customDir: 'reviews/reviews-by-category',
32
- },
33
- 'product-search': {},
34
- 'product-tag': {},
35
- 'featured-category': {},
36
- 'all-products': {
37
- customDir: 'products/all-products',
38
- },
39
- 'price-filter': {},
40
- 'attribute-filter': {},
41
- 'stock-filter': {},
42
- 'active-filters': {},
43
- cart: {
44
- customDir: 'cart-checkout/cart',
45
- },
46
- checkout: {},
47
- 'mini-cart': {
48
- customDir: 'cart-checkout/mini-cart',
49
- isExperimental: true,
50
- },
51
- 'mini-cart-contents': {
52
- customDir: 'cart-checkout/mini-cart-contents',
53
- isExperimental: true,
54
- },
55
- 'single-product': {
56
- isExperimental: true,
57
- },
58
- 'legacy-template': {},
59
- };
60
-
61
- // Returns the entries for each block given a relative path (ie: `index.js`,
62
- // `**/*.scss`...).
63
- // It also filters out elements with undefined props and experimental blocks.
64
- const getBlockEntries = ( relativePath ) => {
65
- const experimental =
66
- ! parseInt( process.env.WOOCOMMERCE_BLOCKS_PHASE, 10 ) < 3;
67
-
68
- return Object.fromEntries(
69
- Object.entries( blocks )
70
- .filter(
71
- ( [ , config ] ) =>
72
- ! config.isExperimental ||
73
- config.isExperimental === experimental
74
- )
75
- .map( ( [ blockCode, config ] ) => {
76
- const filePaths = glob.sync(
77
- `./assets/js/blocks/${ config.customDir || blockCode }/` +
78
- relativePath
79
- );
80
- if ( filePaths.length > 0 ) {
81
- return [ blockCode, filePaths ];
82
- }
83
- return null;
84
- } )
85
- .filter( Boolean )
86
- );
87
- };
88
-
89
- const entries = {
90
- styling: {
91
- // @wordpress/components styles
92
- 'custom-select-control-style':
93
- './node_modules/wordpress-components/src/custom-select-control/style.scss',
94
- 'snackbar-notice-style':
95
- './node_modules/wordpress-components/src/snackbar/style.scss',
96
- 'combobox-control-style':
97
- './node_modules/wordpress-components/src/combobox-control/style.scss',
98
-
99
- 'general-style': glob.sync( './assets/**/*.scss', {
100
- ignore: [
101
- // Block styles are added below.
102
- './assets/js/blocks/*/*.scss',
103
- ],
104
- } ),
105
-
106
- 'packages-style': glob.sync( './packages/**/*.scss' ),
107
-
108
- 'reviews-style': './assets/js/blocks/reviews/editor.scss',
109
- ...getBlockEntries( '**/*.scss' ),
110
- },
111
- core: {
112
- wcBlocksRegistry: './assets/js/blocks-registry/index.js',
113
- wcSettings: './assets/js/settings/shared/index.ts',
114
- wcBlocksData: './assets/js/data/index.ts',
115
- wcBlocksMiddleware: './assets/js/middleware/index.js',
116
- wcBlocksSharedContext: './assets/js/shared/context/index.js',
117
- wcBlocksSharedHocs: './assets/js/shared/hocs/index.js',
118
- priceFormat: './packages/prices/index.js',
119
- blocksCheckout: './packages/checkout/index.js',
120
- },
121
- main: {
122
- // Shared blocks code
123
- 'wc-blocks': './assets/js/index.js',
124
-
125
- // Blocks
126
- ...getBlockEntries( 'index.{t,j}s{,x}' ),
127
- },
128
- frontend: {
129
- reviews: './assets/js/blocks/reviews/frontend.js',
130
- ...getBlockEntries( 'frontend.{t,j}s{,x}' ),
131
- 'mini-cart-component':
132
- './assets/js/blocks/cart-checkout/mini-cart/component-frontend.tsx',
133
- },
134
- payments: {
135
- 'wc-payment-method-cheque':
136
- './assets/js/payment-method-extensions/payment-methods/cheque/index.js',
137
- 'wc-payment-method-paypal':
138
- './assets/js/payment-method-extensions/payment-methods/paypal/index.js',
139
- 'wc-payment-method-bacs':
140
- './assets/js/payment-method-extensions/payment-methods/bacs/index.js',
141
- 'wc-payment-method-cod':
142
- './assets/js/payment-method-extensions/payment-methods/cod/index.js',
143
- },
144
- extensions: {
145
- 'wc-blocks-google-analytics':
146
- './assets/js/extensions/google-analytics/index.ts',
147
- },
148
- };
149
-
150
- const getEntryConfig = ( type = 'main', exclude = [] ) => {
151
- return omit( entries[ type ], exclude );
152
- };
153
-
154
- module.exports = {
155
- getEntryConfig,
156
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/webpack-helpers.js DELETED
@@ -1,147 +0,0 @@
1
- /* eslint-disable no-console */
2
- /**
3
- * External dependencies
4
- */
5
- const path = require( 'path' );
6
- const chalk = require( 'chalk' );
7
- const NODE_ENV = process.env.NODE_ENV || 'development';
8
- const CHECK_CIRCULAR_DEPS = process.env.CHECK_CIRCULAR_DEPS || false;
9
-
10
- // If a package is not available, or missing functionality, in an old but __supported__ version of WordPress, it should be listed here.
11
- // Some packages are not available in legacy versions of WordPress, so we don't want to extract them.
12
- const requiredPackagesInWPLegacy = [];
13
-
14
- const wcDepMap = {
15
- '@woocommerce/blocks-registry': [ 'wc', 'wcBlocksRegistry' ],
16
- '@woocommerce/settings': [ 'wc', 'wcSettings' ],
17
- '@woocommerce/block-data': [ 'wc', 'wcBlocksData' ],
18
- '@woocommerce/shared-context': [ 'wc', 'wcBlocksSharedContext' ],
19
- '@woocommerce/shared-hocs': [ 'wc', 'wcBlocksSharedHocs' ],
20
- '@woocommerce/price-format': [ 'wc', 'priceFormat' ],
21
- '@woocommerce/blocks-checkout': [ 'wc', 'blocksCheckout' ],
22
- };
23
-
24
- const wcHandleMap = {
25
- '@woocommerce/blocks-registry': 'wc-blocks-registry',
26
- '@woocommerce/settings': 'wc-settings',
27
- '@woocommerce/block-settings': 'wc-settings',
28
- '@woocommerce/block-data': 'wc-blocks-data-store',
29
- '@woocommerce/shared-context': 'wc-blocks-shared-context',
30
- '@woocommerce/shared-hocs': 'wc-blocks-shared-hocs',
31
- '@woocommerce/price-format': 'wc-price-format',
32
- '@woocommerce/blocks-checkout': 'wc-blocks-checkout',
33
- };
34
-
35
- const getAlias = ( options = {} ) => {
36
- let { pathPart } = options;
37
- pathPart = pathPart ? `${ pathPart }/` : '';
38
- return {
39
- '@woocommerce/atomic-blocks': path.resolve(
40
- __dirname,
41
- `../assets/js/${ pathPart }atomic/blocks`
42
- ),
43
- '@woocommerce/atomic-utils': path.resolve(
44
- __dirname,
45
- `../assets/js/${ pathPart }atomic/utils`
46
- ),
47
- '@woocommerce/base-components': path.resolve(
48
- __dirname,
49
- `../assets/js/${ pathPart }base/components/`
50
- ),
51
- '@woocommerce/base-context': path.resolve(
52
- __dirname,
53
- `../assets/js/${ pathPart }base/context/`
54
- ),
55
- '@woocommerce/base-hocs': path.resolve(
56
- __dirname,
57
- `../assets/js/${ pathPart }base/hocs/`
58
- ),
59
- '@woocommerce/base-hooks': path.resolve(
60
- __dirname,
61
- `../assets/js/${ pathPart }base/hooks/`
62
- ),
63
- '@woocommerce/base-utils': path.resolve(
64
- __dirname,
65
- `../assets/js/${ pathPart }base/utils/`
66
- ),
67
- '@woocommerce/editor-components': path.resolve(
68
- __dirname,
69
- `../assets/js/${ pathPart }editor-components/`
70
- ),
71
- '@woocommerce/block-hocs': path.resolve(
72
- __dirname,
73
- `../assets/js/${ pathPart }hocs`
74
- ),
75
- '@woocommerce/blocks-registry': path.resolve(
76
- __dirname,
77
- '../assets/js/blocks-registry'
78
- ),
79
- '@woocommerce/block-settings': path.resolve(
80
- __dirname,
81
- '../assets/js/settings/blocks'
82
- ),
83
- '@woocommerce/icons': path.resolve( __dirname, `../assets/js/icons` ),
84
- '@woocommerce/resource-previews': path.resolve(
85
- __dirname,
86
- `../assets/js/${ pathPart }previews/`
87
- ),
88
- '@woocommerce/types': path.resolve( __dirname, `../assets/js/types/` ),
89
- };
90
- };
91
-
92
- function findModuleMatch( module, match ) {
93
- if ( module.request && match.test( module.request ) ) {
94
- return true;
95
- } else if ( module.issuer ) {
96
- return findModuleMatch( module.issuer, match );
97
- }
98
- return false;
99
- }
100
-
101
- const requestToExternal = ( request ) => {
102
- if ( requiredPackagesInWPLegacy.includes( request ) ) {
103
- return false;
104
- }
105
- if ( wcDepMap[ request ] ) {
106
- return wcDepMap[ request ];
107
- }
108
- };
109
-
110
- const requestToHandle = ( request ) => {
111
- if ( requiredPackagesInWPLegacy.includes( request ) ) {
112
- return false;
113
- }
114
- if ( wcHandleMap[ request ] ) {
115
- return wcHandleMap[ request ];
116
- }
117
- };
118
-
119
- const getProgressBarPluginConfig = ( name, fileSuffix ) => {
120
- const isLegacy = fileSuffix && fileSuffix === 'legacy';
121
- const progressBarPrefix = isLegacy ? 'Legacy ' : '';
122
- return {
123
- format:
124
- chalk.blue( `Building ${ progressBarPrefix }${ name }` ) +
125
- ' [:bar] ' +
126
- chalk.green( ':percent' ) +
127
- ' :msg (:elapsed seconds)',
128
- summary: false,
129
- customSummary: ( time ) => {
130
- console.log(
131
- chalk.green.bold(
132
- `${ progressBarPrefix }${ name } assets build completed (${ time })`
133
- )
134
- );
135
- },
136
- };
137
- };
138
-
139
- module.exports = {
140
- NODE_ENV,
141
- CHECK_CIRCULAR_DEPS,
142
- getAlias,
143
- findModuleMatch,
144
- requestToHandle,
145
- requestToExternal,
146
- getProgressBarPluginConfig,
147
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/wordpress-deploy.sh DELETED
@@ -1,176 +0,0 @@
1
- #!/bin/sh
2
-
3
- RELEASER_PATH=$(pwd)
4
- PLUGIN_SLUG="woo-gutenberg-products-block"
5
- GITHUB_ORG="woocommerce"
6
- GITHUB_SLUG="woocommerce-gutenberg-products-block"
7
- IS_PRE_RELEASE=false
8
- BUILD_PATH="${HOME}/blocks-deployment"
9
-
10
- # Functions
11
- # Check if string contains substring
12
- is_substring() {
13
- case "$2" in
14
- *$1*)
15
- return 0
16
- ;;
17
- *)
18
- return 1
19
- ;;
20
- esac
21
- }
22
-
23
- # Output colorized strings
24
- #
25
- # Color codes:
26
- # 0 - black
27
- # 1 - red
28
- # 2 - green
29
- # 3 - yellow
30
- # 4 - blue
31
- # 5 - magenta
32
- # 6 - cian
33
- # 7 - white
34
- output() {
35
- echo "$(tput setaf "$1")$2$(tput sgr0)"
36
- }
37
-
38
- # Output colorized list
39
- output_list() {
40
- echo "$(tput setaf "$1") • $2:$(tput sgr0) \"$3\""
41
- }
42
-
43
- # Release script
44
- echo
45
- output 4 "BLOCKS->WordPress.org RELEASE SCRIPT"
46
- output 4 "===================================="
47
- echo
48
- printf "This script prepares a GitHub tag/release for WordPress.org SVN."
49
- echo
50
- echo
51
- echo "Before proceeding:"
52
- echo " • Ensure you have already created the release on GitHub. You can use '$ npm run deploy'."
53
- echo
54
- output 3 "Do you want to continue? [y/N]: "
55
- read -r PROCEED
56
- echo
57
-
58
- if [ "$(echo "${PROCEED:-n}" | tr "[:upper:]" "[:lower:]")" != "y" ]; then
59
- output 1 "Release cancelled!"
60
- exit 1
61
- fi
62
- echo
63
- output 3 "Please enter the version number to tag, for example, 1.0.0:"
64
- read -r VERSION
65
- echo
66
-
67
- # Check if is a pre-release.
68
- if is_substring "-" "${VERSION}"; then
69
- IS_PRE_RELEASE=true
70
- output 2 "Detected pre-release version!"
71
- fi
72
-
73
- # Set deploy variables
74
- SVN_REPO="http://plugins.svn.wordpress.org/${PLUGIN_SLUG}/"
75
- GIT_REPO="https://github.com/${GITHUB_ORG}/${GITHUB_SLUG}.git"
76
- SVN_PATH="${BUILD_PATH}/${PLUGIN_SLUG}-svn"
77
- GIT_PATH="${BUILD_PATH}/${PLUGIN_SLUG}-git"
78
- BRANCH="v$VERSION"
79
-
80
- echo
81
- echo "-------------------------------------------"
82
- echo
83
- echo "Review all data before proceeding:"
84
- echo
85
- output_list 3 "Version to release" "${VERSION}"
86
- output_list 3 "GIT tag to release" "${BRANCH}"
87
- output_list 3 "GIT repository" "${GIT_REPO}"
88
- output_list 3 "wp.org repository" "${SVN_REPO}"
89
- echo
90
- output 3 "Do you want to continue? [y/N]: "
91
- read -r PROCEED
92
- echo
93
-
94
- if [ "$(echo "${PROCEED:-n}" | tr "[:upper:]" "[:lower:]")" != "y" ]; then
95
- output 1 "Release cancelled!"
96
- exit 1
97
- fi
98
-
99
- # Create build directory if does not exists
100
- if [ ! -d "$BUILD_PATH" ]; then
101
- mkdir -p "$BUILD_PATH"
102
- fi
103
-
104
- # Delete old GIT directory
105
- rm -rf "$GIT_PATH"
106
-
107
- # Clone GIT repository
108
- output 2 "Cloning GIT repository..."
109
- git clone "$GIT_REPO" "$GIT_PATH" --branch "$BRANCH" --single-branch || exit "$?"
110
-
111
- if [ ! -d "$GIT_PATH/build" ]; then
112
- output 3 "Build directory not found in tag. Aborting."
113
- exit 1
114
- fi
115
-
116
- if [ ! -d "$GIT_PATH/vendor" ]; then
117
- output 3 "Vendor directory not found in tag. Aborting."
118
- exit 1
119
- fi
120
-
121
- # Checkout SVN repository if not exists
122
- if [ ! -d "$SVN_PATH" ]; then
123
- output 2 "No SVN directory found, fetching files..."
124
- # Checkout project without any file
125
- svn co --depth=files "$SVN_REPO" "$SVN_PATH"
126
-
127
- cd "$SVN_PATH" || exit
128
-
129
- # Fetch main directories
130
- svn up assets branches trunk
131
-
132
- # Fetch tags directories without content
133
- svn up --set-depth=immediates tags
134
- # To fetch content for a tag, use:
135
- # svn up --set-depth=infinity tags/<tag_number>
136
- else
137
- # Update SVN
138
- cd "$SVN_PATH" || exit
139
- output 2 "Updating SVN..."
140
- svn up
141
- fi
142
-
143
- # Copy GIT directory to trunk
144
- output 2 "Copying project files to SVN trunk..."
145
- sh "${RELEASER_PATH}/bin/copy-plugin-files.sh" "$GIT_PATH" "$SVN_PATH/trunk"
146
- cd "$SVN_PATH"
147
-
148
- # Update stable tag on trunk/readme.txt
149
- if [ $IS_PRE_RELEASE = false ]; then
150
- output 2 "Updating \"Stable tag\" to ${VERSION} on trunk/readme.txt..."
151
- perl -i -pe"s/Stable tag: .*/Stable tag: ${VERSION}/" trunk/readme.txt
152
- fi
153
-
154
- # Do the remove all deleted files
155
- svn st | grep -v "^.[ \t]*\..*" | grep "^\!" | awk '{print $2"@"}' | xargs svn rm
156
-
157
- # Do the add all not know files
158
- svn st | grep -v "^.[ \t]*\..*" | grep "^?" | awk '{print $2"@"}' | xargs svn add
159
-
160
- # Copy trunk to tag/$VERSION
161
- if [ ! -d "tags/${VERSION}" ]; then
162
- output 2 "Creating SVN tags/${VERSION}..."
163
- svn cp trunk tags/"${VERSION}"
164
- fi
165
-
166
- # Remove the GIT directory
167
- output 2 "Removing GIT directory..."
168
- rm -rf "$GIT_PATH"
169
-
170
- # SVN commit messsage
171
- output 2 "Ready to commit into WordPress.org Plugin's Directory!"
172
- echo
173
- echo "-------------------------------------------"
174
- echo
175
- output 3 "Run the following command to commit to SVN:"
176
- echo "cd ${SVN_PATH} && svn ci -m \"Release ${VERSION}, see readme.txt for changelog.\""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/wp-env-config.sh DELETED
@@ -1,22 +0,0 @@
1
- #!/bin/bash
2
-
3
- ## Check if user already exists
4
- wp user get customer 2> /dev/null
5
-
6
- ## if 0 is the exit code then we can leave otherwise we'll try creating the user
7
- if [ $? -eq 0 ]
8
- then
9
- EXIT_CODE=0
10
- else
11
- wp user create customer customer@woocommercecoree2etestsuite.com --user_pass=password --role=customer
12
- EXIT_CODE=$?
13
- fi
14
-
15
- ## set permalinks for easier wp-json
16
- wp rewrite structure '/%postname%/'
17
- wp rewrite flush
18
- wp core version --extra
19
- wp plugin list
20
- wp theme activate storefront
21
-
22
- exit $EXIT_CODE
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/bin/wp-env-phpunit-pre-config.sh DELETED
@@ -1,6 +0,0 @@
1
- #!/bin/sh
2
- BASENAME=$(basename "`pwd`")
3
-
4
- npm run wp-env run composer 'install --no-interaction'
5
- npm run wp-env run phpunit 'php -v'
6
- npm run wp-env run phpunit "phpunit -c /var/www/html/wp-content/plugins/${BASENAME}/phpunit.xml.dist --verbose"
 
 
 
 
 
 
packages/woocommerce-blocks/bin/wp-env-pre-config.sh DELETED
@@ -1,3 +0,0 @@
1
- #!/bin/sh
2
- BASENAME=$(basename "`pwd`")
3
- npm run wp-env run tests-cli './wp-content/plugins/'$BASENAME'/bin/wp-env-config.sh'
 
 
 
packages/woocommerce-blocks/docker-compose.yml DELETED
@@ -1,82 +0,0 @@
1
- version: "3.3"
2
-
3
- services:
4
- db:
5
- image: mariadb:10.5
6
- restart: on-failure
7
- environment:
8
- MYSQL_DATABASE: wordpress
9
- MYSQL_USER: wordpress
10
- MYSQL_PASSWORD: wordpress
11
- MYSQL_RANDOM_ROOT_PASSWORD: "yes"
12
- volumes:
13
- - db:/var/lib/mysql
14
-
15
- wordpress-unit-tests:
16
- container_name: wordpress_test
17
- depends_on:
18
- - db
19
- build:
20
- context: ./tests/bin
21
- args:
22
- WOO_INSTALL_VERSION: ${WOO_VERSION}
23
- ports:
24
- - 8085:80
25
- restart: on-failure
26
- environment:
27
- - WORDPRESS_DB_HOST
28
- - WORDPRESS_DB_NAME
29
- - WORDPRESS_DB_USER
30
- - WORDPRESS_DB_PASSWORD
31
- - WORDPRESS_TABLE_PREFIX=wp_test_
32
- - WP_CORE_DIR=/var/www/html
33
- - WP_TESTS_DIR=/tmp/wordpress-tests-lib
34
- - WOO_VERSION
35
- volumes:
36
- - "./:/var/www/html/wp-content/plugins/woocommerce-gutenberg-products-block"
37
- - wordpress:/var/www/html
38
-
39
- wordpress-www:
40
- depends_on:
41
- - db
42
- build:
43
- context: ./bin/docker/wordpress
44
- args:
45
- WP_VERSION: ${WP_VERSION}
46
- ports:
47
- - ${WORDPRESS_PORT}:80
48
- restart: on-failure
49
- environment:
50
- WORDPRESS_DB_HOST:
51
- WORDPRESS_DB_NAME:
52
- WORDPRESS_DB_USER:
53
- WORDPRESS_DB_PASSWORD:
54
- WORDPRESS_TABLE_PREFIX: wp_
55
- WORDPRESS_DEBUG: 1
56
- volumes:
57
- - "./:/var/www/html/wp-content/plugins/woocommerce-gutenberg-products-block"
58
- - wordpress:/var/www/html
59
-
60
- wordpress-cli:
61
- depends_on:
62
- - db
63
- - wordpress-www
64
- build:
65
- context: ./bin/docker/wp-cli
66
- restart: on-failure
67
- environment:
68
- WORDPRESS_HOST:
69
- WORDPRESS_TITLE:
70
- WORDPRESS_LOGIN:
71
- WORDPRESS_PASSWORD:
72
- WORDPRESS_PORT:
73
- WORDPRESS_EMAIL:
74
- DOMAIN_NAME:
75
- GUTENBERG_LATEST:
76
- volumes:
77
- - ./:/var/www/html/wp-content/plugins/woocommerce-gutenberg-products-block
78
- - wordpress:/var/www/html
79
-
80
- volumes:
81
- db:
82
- wordpress:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/docs/blocks/checkout.jpg DELETED
Binary file
packages/woocommerce-blocks/docs/blocks/reserve-stock.jpg DELETED
Binary file
packages/woocommerce-blocks/postcss.config.js DELETED
@@ -1,6 +0,0 @@
1
- module.exports = ( { env } ) => ( {
2
- plugins: {
3
- autoprefixer: { grid: true },
4
- cssnano: env === 'production',
5
- },
6
- } );
 
 
 
 
 
 
packages/woocommerce-blocks/storybook/__mocks__/woocommerce-base-hooks.js DELETED
@@ -1,33 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import {
5
- previewCart,
6
- previewShippingRates,
7
- } from '@woocommerce/resource-previews';
8
-
9
- export * from '../../assets/js/base/hooks/index.js';
10
- export const useStoreCart = () => ( {
11
- cartCoupons: previewCart.coupons,
12
- cartItems: previewCart.items,
13
- cartItemsCount: previewCart.items_count,
14
- cartItemsWeight: previewCart.items_weight,
15
- cartNeedsPayment: previewCart.needs_payment,
16
- cartNeedsShipping: previewCart.needs_shipping,
17
- cartItemErrors: [],
18
- cartTotals: previewCart.totals,
19
- cartIsLoading: false,
20
- cartErrors: [],
21
- cartFees: [],
22
- billingAddress: {},
23
- shippingAddress: {},
24
- shippingRates: previewShippingRates,
25
- shippingRatesLoading: false,
26
- cartHasCalculatedShipping: previewCart.has_calculated_shipping,
27
- receiveCart: () => void null,
28
- } );
29
- export const useSelectShippingRate = () => ( {
30
- selectShippingRate: () => void null,
31
- selectedShippingRates: [],
32
- isSelectingRate: false,
33
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/storybook/__mocks__/woocommerce-block-settings.js DELETED
@@ -1 +0,0 @@
1
- export * from '../../assets/js/settings/blocks/index.ts';
 
packages/woocommerce-blocks/storybook/custom-controls/currency.ts DELETED
@@ -1,43 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import { Currency, CurrencyResponse } from '@woocommerce/types';
5
- import snakecaseKeys from 'snakecase-keys';
6
-
7
- export const currencies: Record< string, Currency > = {
8
- EUR: {
9
- code: 'EUR',
10
- symbol: '€',
11
- thousandSeparator: '.',
12
- decimalSeparator: ',',
13
- minorUnit: 2,
14
- prefix: '',
15
- suffix: '€',
16
- },
17
- USD: {
18
- code: 'USD',
19
- symbol: '$',
20
- thousandSeparator: ',',
21
- decimalSeparator: '.',
22
- minorUnit: 2,
23
- prefix: '$',
24
- suffix: '',
25
- },
26
- } as const;
27
-
28
- export const currenciesAPIShape: Record<
29
- string,
30
- CurrencyResponse
31
- > = Object.fromEntries(
32
- Object.entries( currencies ).map( ( [ key, value ] ) => [
33
- key,
34
- snakecaseKeys( value ),
35
- ] )
36
- );
37
-
38
- export const currencyControl = {
39
- control: 'select',
40
- defaultValue: currencies.USD,
41
- mapping: currencies,
42
- options: Object.keys( currencies ),
43
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/storybook/custom-controls/index.ts DELETED
@@ -1,3 +0,0 @@
1
- export * from './currency';
2
-
3
- export const INTERACTION_TIMEOUT = 1500;
 
 
 
packages/woocommerce-blocks/storybook/main.js DELETED
@@ -1,17 +0,0 @@
1
- module.exports = {
2
- stories: [
3
- // WooCommerce Blocks stuff (anywhere in repo!)
4
- '../assets/js/**/stories/*.@(js|jsx|ts|tsx)',
5
- '../packages/**/stories/*.@(js|jsx|ts|tsx)',
6
- ],
7
- addons: [
8
- '@storybook/addon-essentials',
9
- '@storybook/addon-a11y',
10
- '@storybook/addon-links',
11
- 'storybook-addon-react-docgen',
12
- ],
13
- features: {
14
- babelModeV7: true,
15
- emotionAlias: false,
16
- },
17
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/storybook/preview.js DELETED
@@ -1,23 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import { withA11y } from '@storybook/addon-a11y';
5
- import { addDecorator } from '@storybook/react';
6
-
7
- /**
8
- * Internal dependencies
9
- */
10
- import './style.scss';
11
-
12
- addDecorator( withA11y );
13
-
14
- export const parameters = {
15
- actions: { argTypesRegex: '^on[A-Z].*' },
16
- controls: {
17
- expanded: true,
18
- matchers: {
19
- color: /(background|color)$/i,
20
- date: /Date$/,
21
- },
22
- },
23
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/storybook/style.scss DELETED
@@ -1,32 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- @import "@wordpress/components/build-style/style";
5
-
6
- // Use system font, consistent with WordPress core (wp-admin)
7
- body {
8
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
9
- }
10
-
11
- // screen-reader-text applied in WP environment
12
-
13
- /* Hide visually but not from screen readers */
14
- .screen-reader-text,
15
- .screen-reader-text span,
16
- .ui-helper-hidden-accessible {
17
- border: 0;
18
- clip: rect(1px, 1px, 1px, 1px);
19
- -webkit-clip-path: inset(50%);
20
- clip-path: inset(50%);
21
- height: 1px;
22
- margin: -1px;
23
- overflow: hidden;
24
- padding: 0;
25
- position: absolute;
26
- width: 1px;
27
- word-wrap: normal !important; /* many screen reader and browser combinations announce broken words as they would appear visually */
28
- }
29
-
30
- .button .screen-reader-text {
31
- height: auto; /* Fixes a Safari+VoiceOver bug, see ticket #42006 */
32
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/bootstrap.php DELETED
@@ -1,52 +0,0 @@
1
- <?php
2
- namespace Automattic\WooCommerce\Blocks\Tests;
3
-
4
- // Require composer dependencies.
5
- require_once dirname( __DIR__ ) . '/vendor/autoload.php';
6
-
7
- // Determine the tests directory (from a WP dev checkout).
8
- // Try the WP_TESTS_DIR environment variable first.
9
- $_wc_tests_framework_dir = dirname( dirname( __DIR__ ) ) . '/woocommerce/tests/legacy';
10
- $_tests_dir = getenv( 'WP_TESTS_DIR' );
11
-
12
- // Next, try the WP_PHPUNIT composer package.
13
- if ( ! $_tests_dir ) {
14
- $_tests_dir = getenv( 'WP_PHPUNIT__DIR' );
15
- }
16
-
17
- // See if we're installed inside an existing WP dev instance.
18
- if ( ! $_tests_dir ) {
19
- $_try_tests_dir = __DIR__ . '/../../../../../tests/phpunit';
20
- if ( file_exists( $_try_tests_dir . '/includes/functions.php' ) ) {
21
- $_tests_dir = $_try_tests_dir;
22
- }
23
- }
24
- // Fallback.
25
- if ( ! $_tests_dir ) {
26
- $_tests_dir = '/tmp/wordpress-tests-lib';
27
- }
28
-
29
- // Give access to tests_add_filter() function.
30
- require_once $_tests_dir . '/includes/functions.php';
31
-
32
- /**
33
- * Manually load the plugin being tested.
34
- */
35
- function manually_load_plugins() {
36
- require dirname( dirname( __DIR__ ) ) . '/woocommerce/woocommerce.php';
37
- require dirname( __DIR__ ) . '/woocommerce-gutenberg-products-block.php';
38
- }
39
-
40
- tests_add_filter( 'muplugins_loaded', __NAMESPACE__ . '\\manually_load_plugins' );
41
-
42
- /**
43
- * Manually install plugins being tested.
44
- */
45
- function manually_install_plugins() {
46
- \Automattic\WooCommerce\Blocks\Package::container()->get( \Automattic\WooCommerce\Blocks\Installer::class )->maybe_create_tables();
47
- }
48
-
49
- tests_add_filter( 'setup_theme', __NAMESPACE__ . '\\manually_install_plugins' );
50
-
51
- // Start up the WP testing environment.
52
- require $_tests_dir . '/includes/bootstrap.php';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/config/custom-matchers/__fixtures__/best-selling-products.fixture.json DELETED
@@ -1 +0,0 @@
1
- {"title":"Best Selling Products Block","pageContent":"<!-- wp:woocommerce/product-best-sellers /-->"}
 
packages/woocommerce-blocks/tests/e2e/config/custom-matchers/__fixtures__/featured-category.fixture.json DELETED
@@ -1 +0,0 @@
1
- {"title":"Featured Category Block","pageContent":"<!-- wp:woocommerce/featured-category /-->"}
 
packages/woocommerce-blocks/tests/e2e/config/custom-matchers/__fixtures__/hand-picked-products.fixture.json DELETED
@@ -1 +0,0 @@
1
- {"title":"Hand-picked Products Block","pageContent":"<!-- wp:woocommerce/handpicked-products /-->"}
 
packages/woocommerce-blocks/tests/e2e/config/custom-matchers/__fixtures__/newest-products.fixture.json DELETED
@@ -1 +0,0 @@
1
- {"title":"Newest Products Block","pageContent":"<!-- wp:woocommerce/product-new /-->"}
 
packages/woocommerce-blocks/tests/e2e/config/custom-matchers/__fixtures__/product-categories-list.fixture.json DELETED
@@ -1 +0,0 @@
1
- {"title":"Product Categories List Block","pageContent":"<!-- wp:woocommerce/product-categories /-->"}
 
packages/woocommerce-blocks/tests/e2e/config/custom-matchers/__fixtures__/top-rated-products.fixture.json DELETED
@@ -1 +0,0 @@
1
- {"title":"Top Rated Products Block","pageContent":"<!-- wp:woocommerce/product-top-rated /-->"}
 
packages/woocommerce-blocks/tests/e2e/config/custom-matchers/index.js DELETED
@@ -1,6 +0,0 @@
1
- /**
2
- * Internal dependencies
3
- */
4
- import './to-render-block.js';
5
- import './to-toggle-required-attr-of.js';
6
- import './to-toggle-element.js';
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/config/custom-matchers/to-render-block.js DELETED
@@ -1,58 +0,0 @@
1
- expect.extend( {
2
- async toRenderBlock( page, block = {} ) {
3
- const gutenbergNotFoundError = ( await page.content() ).match(
4
- /Your site doesn’t include support for/gi
5
- );
6
- if ( gutenbergNotFoundError !== null ) {
7
- return {
8
- message: () =>
9
- `the ${
10
- block.name || 'block'
11
- } is not registered and not loading in the editor.`,
12
- pass: false,
13
- };
14
- }
15
-
16
- const gutenbergValidationError = ( await page.content() ).match(
17
- /This block contains unexpected or invalid content/gi
18
- );
19
- if ( gutenbergValidationError !== null ) {
20
- return {
21
- message: () =>
22
- `the ${
23
- block.name || 'block'
24
- } had a validation error while trying to render.`,
25
- pass: false,
26
- };
27
- }
28
-
29
- const errorBoundary = ( await page.content() ).match(
30
- /There was an error whilst rendering/gi
31
- );
32
- if ( errorBoundary !== null ) {
33
- return {
34
- message: () =>
35
- `the ${
36
- block.name || 'block'
37
- } had a js error that was caught by our errorBoundary.`,
38
- pass: false,
39
- };
40
- }
41
-
42
- const blockElement = await page.$( block.class );
43
- if ( blockElement === null ) {
44
- return {
45
- message: () =>
46
- `the ${ block.name || 'block' } with classname \`${
47
- block.class
48
- }\` did not render.`,
49
- pass: false,
50
- };
51
- }
52
-
53
- return {
54
- message: () => `expected block to render without breaking.`,
55
- pass: true,
56
- };
57
- },
58
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/config/custom-matchers/to-toggle-element.js DELETED
@@ -1,47 +0,0 @@
1
- /**
2
- * Internal dependencies
3
- */
4
- import { findLabelWithText } from '../../../utils';
5
-
6
- expect.extend( {
7
- async toToggleElement( toggleLabel, selector ) {
8
- if ( ! selector ) {
9
- return {
10
- message: () =>
11
- `a selector is required to test element's presence`,
12
- pass: false,
13
- };
14
- }
15
-
16
- const hasSelectorMatch = async () => !! ( await page.$( selector ) );
17
- const initiallyHadSelectorMatch = await hasSelectorMatch();
18
- const noChangeError = {
19
- message: () =>
20
- `element presence did not change after clicking the toggle`,
21
- pass: false,
22
- };
23
-
24
- await ( typeof toggleLabel === 'string'
25
- ? await findLabelWithText( toggleLabel )
26
- : toggleLabel
27
- ).click();
28
-
29
- if ( initiallyHadSelectorMatch === ( await hasSelectorMatch() ) ) {
30
- return noChangeError;
31
- }
32
-
33
- await ( typeof toggleLabel === 'string'
34
- ? await findLabelWithText( toggleLabel )
35
- : toggleLabel
36
- ).click();
37
-
38
- if ( initiallyHadSelectorMatch !== ( await hasSelectorMatch() ) ) {
39
- return noChangeError;
40
- }
41
-
42
- return {
43
- message: () => `element presence reacted to toggle changes.`,
44
- pass: true,
45
- };
46
- },
47
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/config/custom-matchers/to-toggle-required-attr-of.js DELETED
@@ -1,49 +0,0 @@
1
- /**
2
- * Internal dependencies
3
- */
4
- import { findLabelWithText } from '../../../utils';
5
-
6
- expect.extend( {
7
- async toToggleRequiredAttrOf( checkboxLabel, selector ) {
8
- if ( ! selector ) {
9
- return {
10
- message: () =>
11
- `a selector is required to test element's required attribute`,
12
- pass: false,
13
- };
14
- }
15
-
16
- const isRequired = async () =>
17
- !! ( await page.$eval( selector, ( e ) => e.required ) );
18
- const wasInitiallyRequired = await isRequired();
19
- const noChangeError = {
20
- message: () =>
21
- `input's (${ selector }) required attribute did not change after clicking the checkbox`,
22
- pass: false,
23
- };
24
-
25
- await ( typeof checkboxLabel === 'string'
26
- ? await findLabelWithText( checkboxLabel )
27
- : checkboxLabel
28
- ).click();
29
-
30
- if ( wasInitiallyRequired === ( await isRequired() ) ) {
31
- return noChangeError;
32
- }
33
-
34
- await ( typeof checkboxLabel === 'string'
35
- ? await findLabelWithText( checkboxLabel )
36
- : checkboxLabel
37
- ).click();
38
-
39
- if ( wasInitiallyRequired !== ( await isRequired() ) ) {
40
- return noChangeError;
41
- }
42
-
43
- return {
44
- message: () =>
45
- `input's (${ selector }) required attribute reacted to checkbox changes.`,
46
- pass: true,
47
- };
48
- },
49
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/config/default.json DELETED
@@ -1,63 +0,0 @@
1
- {
2
- "url": "http://localhost:8889/",
3
- "users": {
4
- "admin": {
5
- "username": "admin",
6
- "password": "password"
7
- },
8
- "customer": {
9
- "username": "customer",
10
- "password": "password"
11
- }
12
- },
13
- "products": {
14
- "simple": {
15
- "name": "Simple product"
16
- },
17
- "variable": {
18
- "name": "Variable Product with Three Variations"
19
- },
20
- "grouped": {}
21
- },
22
- "addresses": {
23
- "admin": {
24
- "store": {
25
- "firstname": "John",
26
- "lastname": "Doe",
27
- "company": "Automattic",
28
- "country": "United States (US)",
29
- "addressfirstline": "addr 1",
30
- "addresssecondline": "addr 2",
31
- "city": "San Francisco",
32
- "state": "CA",
33
- "postcode": "94107"
34
- }
35
- },
36
- "customer": {
37
- "billing": {
38
- "firstname": "John",
39
- "lastname": "Doe",
40
- "company": "Automattic",
41
- "country": "United States (US)",
42
- "addressfirstline": "addr 1",
43
- "addresssecondline": "addr 2",
44
- "city": "San Francisco",
45
- "state": "CA",
46
- "postcode": "94107",
47
- "phone": "123456789",
48
- "email": "john.doe@example.com"
49
- },
50
- "shipping": {
51
- "firstname": "John",
52
- "lastname": "Doe",
53
- "company": "Automattic",
54
- "country": "United States (US)",
55
- "addressfirstline": "addr 1",
56
- "addresssecondline": "addr 2",
57
- "city": "San Francisco",
58
- "state": "CA",
59
- "postcode": "94107"
60
- }
61
- }
62
- }
63
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/config/environment.js DELETED
@@ -1,16 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- const PuppeteerEnvironment = require( 'jest-environment-puppeteer' );
5
- const { addAttach } = require( 'jest-html-reporters/helper' );
6
-
7
- class E2EEnvironment extends PuppeteerEnvironment {
8
- async handleTestEvent( event ) {
9
- if ( event.name === 'test_fn_failure' ) {
10
- const data = await this.global.page.screenshot();
11
- await addAttach( data, 'Full Page Screenshot', this.global );
12
- }
13
- }
14
- }
15
-
16
- module.exports = E2EEnvironment;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/config/jest.config.js DELETED
@@ -1,38 +0,0 @@
1
- module.exports = {
2
- ...require( '@wordpress/scripts/config/jest-e2e.config' ),
3
- rootDir: '../../../',
4
- // Automatically clear mock calls and instances between every test
5
- clearMocks: true,
6
-
7
- // An array of file extensions your modules use
8
- moduleFileExtensions: [ 'js', 'ts' ],
9
-
10
- moduleNameMapper: {
11
- '@woocommerce/blocks-test-utils': '<rootDir>/tests/utils',
12
- },
13
-
14
- reporters: [
15
- 'default',
16
- [
17
- 'jest-html-reporters',
18
- { publicPath: './reports/e2e', filename: 'index.html' },
19
- ],
20
- ],
21
-
22
- testEnvironment: '<rootDir>/tests/e2e/config/environment.js',
23
- testRunner: 'jest-circus/runner',
24
- // Where to look for test files
25
- roots: [ '<rootDir>/tests/e2e/specs' ],
26
- globalSetup: '<rootDir>/tests/e2e/config/setup.js',
27
- globalTeardown: '<rootDir>/tests/e2e/config/teardown.js',
28
- setupFiles: [],
29
- // A list of paths to modules that run some code to configure or set up the testing framework
30
- // before each test
31
- setupFilesAfterEnv: [
32
- '<rootDir>/tests/e2e/config/custom-matchers/index.js',
33
- '<rootDir>/tests/e2e/config/jest.setup.js',
34
- 'expect-puppeteer',
35
- ],
36
-
37
- transformIgnorePatterns: [ 'node_modules/(?!(woocommerce)/)' ],
38
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/config/jest.setup.js DELETED
@@ -1,151 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import {
5
- enablePageDialogAccept,
6
- isOfflineMode,
7
- setBrowserViewport,
8
- switchUserToAdmin,
9
- switchUserToTest,
10
- visitAdminPage,
11
- } from '@wordpress/e2e-test-utils';
12
-
13
- // Set the default test timeout.
14
- jest.setTimeout( 60000 );
15
-
16
- /**
17
- * Array of page event tuples of [ eventName, handler ].
18
- *
19
- * @type {Array}
20
- */
21
- const pageEvents = [];
22
- /**
23
- * Set of console logging types observed to protect against unexpected yet
24
- * handled (i.e. not catastrophic) errors or warnings. Each key corresponds
25
- * to the Puppeteer ConsoleMessage type, its value the corresponding function
26
- * on the console global object.
27
- *
28
- * @type {Object<string,string>}
29
- */
30
- const OBSERVED_CONSOLE_MESSAGE_TYPES = {
31
- error: 'error',
32
- };
33
- async function setupBrowser() {
34
- await setBrowserViewport( 'large' );
35
- }
36
-
37
- /**
38
- * Navigates to WooCommerce's import page and imports sample products.
39
- *
40
- * @return {Promise} Promise resolving once products have been imported.
41
- */
42
- async function importSampleProducts() {
43
- await switchUserToAdmin();
44
- // Visit `/wp-admin/edit.php?post_type=product` so we can see a list of products and decide if we should import them or not.
45
- await visitAdminPage( 'edit.php', 'post_type=product' );
46
- const emptyState = await page.evaluate( () =>
47
- window.find( 'Ready to start selling something awesome' )
48
- );
49
- const noProduct = await page.evaluate( () =>
50
- window.find( 'No products found' )
51
- );
52
- if ( emptyState || noProduct ) {
53
- // Visit Import Products page.
54
- await visitAdminPage(
55
- 'edit.php',
56
- 'post_type=product&page=product_importer'
57
- );
58
- await page.click( 'a.woocommerce-importer-toggle-advanced-options' );
59
- await page.focus( '#woocommerce-importer-file-url' );
60
- // local path for sample data that is included with woo.
61
- await page.keyboard.type(
62
- 'wp-content/plugins/woocommerce/sample-data/sample_products.csv'
63
- );
64
- await page.click( '.wc-actions .button-next' );
65
- await page.waitForSelector( '.wc-importer-mapping-table' );
66
- await page.select(
67
- '.wc-importer-mapping-table tr:nth-child(29) select',
68
- ''
69
- );
70
- await page.click( '.wc-actions .button-next' );
71
- await page.waitForXPath(
72
- "//*[@class='woocommerce-importer-done' and contains(., 'Import complete! ')]"
73
- );
74
- await switchUserToTest();
75
- }
76
- }
77
-
78
- /**
79
- * Adds an event listener to the page to handle additions of page event
80
- * handlers, to assure that they are removed at test teardown.
81
- */
82
- function capturePageEventsForTearDown() {
83
- page.on( 'newListener', ( eventName, listener ) => {
84
- pageEvents.push( [ eventName, listener ] );
85
- } );
86
- }
87
-
88
- /**
89
- * Removes all bound page event handlers.
90
- */
91
- function removePageEvents() {
92
- pageEvents.forEach( ( [ eventName, handler ] ) => {
93
- page.removeListener( eventName, handler );
94
- } );
95
- }
96
-
97
- /**
98
- * Adds a page event handler to emit uncaught exception to process if one of
99
- * the observed console logging types is encountered.
100
- */
101
- function observeConsoleLogging() {
102
- page.on( 'console', ( message ) => {
103
- const type = message.type();
104
- if ( ! OBSERVED_CONSOLE_MESSAGE_TYPES.hasOwnProperty( type ) ) {
105
- return;
106
- }
107
- const text = message.text();
108
-
109
- // Viewing posts on the front end can result in this error, which
110
- // has nothing to do with Gutenberg.
111
- if ( text.includes( 'net::ERR_UNKNOWN_URL_SCHEME' ) ) {
112
- return;
113
- }
114
-
115
- // Network errors are ignored only if we are intentionally testing
116
- // offline mode.
117
- if (
118
- text.includes( 'net::ERR_INTERNET_DISCONNECTED' ) &&
119
- isOfflineMode()
120
- ) {
121
- return;
122
- }
123
-
124
- const logFunction = OBSERVED_CONSOLE_MESSAGE_TYPES[ type ];
125
-
126
- // Disable reason: We intentionally bubble up console error messages
127
- // for debugging reasons. If you need to test explicitly the logging,
128
- // use @wordpress/jest-console
129
- // eslint-disable-next-line no-console
130
- console[ logFunction ]( text );
131
- } );
132
- }
133
-
134
- // Before every test suite run, delete all content created by the test. This ensures
135
- // other posts/comments/etc. aren't dirtying tests and tests don't depend on
136
- // each other's side-effects.
137
- beforeAll( async () => {
138
- capturePageEventsForTearDown();
139
- enablePageDialogAccept();
140
- observeConsoleLogging();
141
- await setupBrowser();
142
- await importSampleProducts();
143
- } );
144
-
145
- afterEach( async () => {
146
- await setupBrowser();
147
- } );
148
-
149
- afterAll( () => {
150
- removePageEvents();
151
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/config/setup.js DELETED
@@ -1,75 +0,0 @@
1
- /* eslint-disable no-console */
2
- /**
3
- * External dependencies
4
- */
5
- import { setup as setupPuppeteer } from 'jest-environment-puppeteer';
6
- /**
7
- * Internal dependencies
8
- */
9
- import {
10
- setupSettings,
11
- setupPageSettings,
12
- createTaxes,
13
- createCoupons,
14
- createProducts,
15
- createReviews,
16
- createCategories,
17
- createShippingZones,
18
- createBlockPages,
19
- enablePaymentGateways,
20
- createProductAttributes,
21
- } from '../fixtures/fixture-loaders';
22
-
23
- module.exports = async ( globalConfig ) => {
24
- // we need to load puppeteer global setup here.
25
- await setupPuppeteer( globalConfig );
26
-
27
- try {
28
- // do setupSettings separately which hopefully gives a chance for WooCommerce
29
- // to be configured before the others are executed.
30
- await setupSettings();
31
- const pages = await createBlockPages();
32
-
33
- /**
34
- * Promise.all will return an array of all promises resolved values.
35
- * Some functions like setupSettings and enablePaymentGateways resolve
36
- * to server data so we ignore the values here.
37
- */
38
- const results = await Promise.all( [
39
- createTaxes(),
40
- createCoupons(),
41
- createCategories(),
42
- createShippingZones(),
43
- createProductAttributes(),
44
- enablePaymentGateways(),
45
- setupPageSettings(),
46
- ] );
47
- const [
48
- taxes,
49
- coupons,
50
- categories,
51
- shippingZones,
52
- attributes,
53
- ] = results;
54
- // Create products after categories.
55
-
56
- const products = await createProducts( categories, attributes );
57
- /**
58
- * Create fixture reviews data for each product.
59
- */
60
- products.forEach( async ( productId ) => {
61
- await createReviews( productId );
62
- } );
63
-
64
- global.fixtureData = {
65
- taxes,
66
- coupons,
67
- products,
68
- shippingZones,
69
- pages,
70
- attributes,
71
- };
72
- } catch ( e ) {
73
- console.log( e );
74
- }
75
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/config/teardown.js DELETED
@@ -1,37 +0,0 @@
1
- /* eslint-disable no-console */
2
- /**
3
- * External dependencies
4
- */
5
- import { teardown as teardownPuppeteer } from 'jest-environment-puppeteer';
6
-
7
- /**
8
- * Internal dependencies
9
- */
10
- import {
11
- deleteTaxes,
12
- deleteCoupons,
13
- deleteProducts,
14
- deleteShippingZones,
15
- deleteBlockPages,
16
- deleteProductAttributes,
17
- } from '../fixtures/fixture-loaders';
18
-
19
- module.exports = async ( globalConfig ) => {
20
- await teardownPuppeteer( globalConfig );
21
- const {
22
- taxes,
23
- coupons,
24
- products,
25
- shippingZones,
26
- pages,
27
- attributes,
28
- } = global.fixtureData;
29
- return Promise.allSettled( [
30
- deleteTaxes( taxes ),
31
- deleteCoupons( coupons ),
32
- deleteProducts( products ),
33
- deleteShippingZones( shippingZones ),
34
- deleteBlockPages( pages ),
35
- deleteProductAttributes( attributes ),
36
- ] ).catch( console.log );
37
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/config/test.json DELETED
@@ -1 +0,0 @@
1
- {}
 
packages/woocommerce-blocks/tests/e2e/fixtures/fixture-data.js DELETED
@@ -1,374 +0,0 @@
1
- /**
2
- * The default fixtures data is shaped according to WC REST API
3
- *
4
- * @see {@link https://woocommerce.github.io/woocommerce-rest-api-docs|WooCommerce REST API}
5
- */
6
-
7
- /**
8
- * Product attributes fixture data, using the create attribute and batch create terms.
9
- *
10
- * @see {@link https://woocommerce.github.io/woocommerce-rest-api-docs/#create-a-product-attribute|Create a product attribute}
11
- * @see {@link https://woocommerce.github.io/woocommerce-rest-api-docs/#batch-update-attribute-terms|Batch update attribute terms}
12
- */
13
- const Attributes = () => [
14
- {
15
- attribute: { name: 'Capacity' },
16
- terms: [
17
- {
18
- name: '32gb',
19
- },
20
- {
21
- name: '64gb',
22
- },
23
- {
24
- name: '128gb',
25
- },
26
- ],
27
- },
28
- {
29
- attribute: { name: 'Shade' },
30
- terms: [
31
- {
32
- name: 'Red',
33
- },
34
- {
35
- name: 'Blue',
36
- },
37
- {
38
- name: 'Black',
39
- },
40
- ],
41
- },
42
- ];
43
-
44
- /**
45
- * Coupons fixture data, using the create batch endpoint
46
- *
47
- * @see {@link https://woocommerce.github.io/woocommerce-rest-api-docs/#batch-update-coupons|Batch update coupons}
48
- */
49
- const Coupons = () => [
50
- {
51
- code: 'coupon',
52
- discount_type: 'fixed_cart',
53
- amount: '5',
54
- },
55
- {
56
- code: 'oldcoupon',
57
- discount_type: 'fixed_cart',
58
- amount: '5',
59
- date_expires: '2020-01-01',
60
- },
61
- {
62
- code: 'below100',
63
- discount_type: 'percent',
64
- amount: '20',
65
- maximum_amount: '100.00',
66
- },
67
- {
68
- code: 'above50',
69
- discount_type: 'percent',
70
- amount: '20',
71
- minimum_amount: '50.00',
72
- },
73
- {
74
- code: 'a12s',
75
- discount_type: 'percent',
76
- amount: '100',
77
- individual_use: true,
78
- email_restrictions: '*@automattic.com%2C *@a8c.com',
79
- },
80
- {
81
- code: 'freeshipping',
82
- discount_type: 'percent',
83
- amount: '0',
84
- free_shipping: true,
85
- },
86
- ];
87
-
88
- /**
89
- * Reviews fixture data, using the create batch endpoint
90
- *
91
- * @see {@link https://woocommerce.github.io/woocommerce-rest-api-docs/#batch-update-product-reviews|Batch update product reviews}
92
- * @param {number} id Product ID to add reviews to.
93
- */
94
- const ReviewsInProduct = ( id ) => [
95
- {
96
- product_id: id,
97
- review: 'Looks fine',
98
- reviewer: 'John Doe',
99
- reviewer_email: 'john.doe@example.com',
100
- rating: 4,
101
- },
102
- {
103
- product_id: id,
104
- review: 'I love this album',
105
- reviewer: 'John Doe',
106
- reviewer_email: 'john.doe@example.com',
107
- rating: 5,
108
- },
109
- {
110
- product_id: id,
111
- review: 'a fine review',
112
- reviewer: "John Doe' niece",
113
- reviewer_email: 'john.doe@example.com',
114
- rating: 5,
115
- },
116
- ];
117
-
118
- /**
119
- * Product category fixture data, using the create batch endpoint
120
- *
121
- * @see {@link https://woocommerce.github.io/woocommerce-rest-api-docs/#batch-update-product-categories|Batch update product categories}
122
- */
123
- const Categories = () => [
124
- {
125
- name: 'Music',
126
- },
127
- ];
128
-
129
- /**
130
- * Product fixture data, using the create batch endpoint
131
- *
132
- * @see {@link https://woocommerce.github.io/woocommerce-rest-api-docs/#batch-update-products|Batch update products}
133
- */
134
- const Products = () => [
135
- {
136
- name: 'Woo Single #1',
137
- type: 'simple',
138
- regular_price: '21.99',
139
- virtual: true,
140
- downloadable: true,
141
- downloads: [
142
- {
143
- name: 'Woo Single',
144
- file:
145
- 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/cd_4_angle.jpg',
146
- },
147
- ],
148
- images: [
149
- {
150
- src:
151
- 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/cd_4_angle.jpg',
152
- },
153
- ],
154
- categories: [ 'Music' ],
155
- },
156
- {
157
- name: '128GB USB Stick',
158
- type: 'simple',
159
- regular_price: '2.99',
160
- virtual: false,
161
- downloadable: false,
162
- images: [
163
- {
164
- src:
165
- 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/cd_4_angle.jpg',
166
- },
167
- ],
168
- attributes: [
169
- {
170
- name: 'Capacity',
171
- position: 0,
172
- visible: true,
173
- options: [ '128gb' ],
174
- },
175
- ],
176
- },
177
- {
178
- name: '32GB USB Stick',
179
- type: 'simple',
180
- regular_price: '1.99',
181
- virtual: false,
182
- downloadable: false,
183
- images: [
184
- {
185
- src:
186
- 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/cd_4_angle.jpg',
187
- },
188
- ],
189
- attributes: [
190
- {
191
- name: 'Capacity',
192
- position: 0,
193
- visible: true,
194
- options: [ '32gb' ],
195
- },
196
- ],
197
- },
198
- {
199
- name: 'Woo Single #2',
200
- type: 'simple',
201
- regular_price: '25.99',
202
- virtual: true,
203
- downloadable: true,
204
- downloads: [
205
- {
206
- name: 'Woo Single 2',
207
- file:
208
- 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/cd_4_angle.jpg',
209
- },
210
- ],
211
- images: [
212
- {
213
- src:
214
- 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/cd_4_angle.jpg',
215
- },
216
- ],
217
- categories: [ 'Music' ],
218
- },
219
- ];
220
-
221
- /**
222
- * Settings fixture data, using the update batch endpoint.
223
- *
224
- * @see {@link https://woocommerce.github.io/woocommerce-rest-api-docs/#batch-update-setting-options|Batch update setting options}
225
- */
226
- const Settings = () => [
227
- {
228
- id: 'woocommerce_store_address',
229
- value: '60 29th Street #343',
230
- },
231
- {
232
- id: 'woocommerce_store_city',
233
- value: 'San Francisco',
234
- },
235
- {
236
- id: 'woocommerce_store_country',
237
- value: 'US:CA',
238
- },
239
- {
240
- id: 'woocommerce_store_postcode',
241
- value: '94110',
242
- },
243
- {
244
- id: 'woocommerce_allowed_countries',
245
- value: 'specific',
246
- },
247
- {
248
- id: 'woocommerce_specific_allowed_countries',
249
- value: [ 'DZ', 'CA', 'NZ', 'ES', 'GB', 'US' ],
250
- },
251
- {
252
- id: 'woocommerce_ship_to_countries',
253
- value: 'specific',
254
- },
255
- {
256
- id: 'woocommerce_specific_ship_to_countries',
257
- value: [ 'DZ', 'CA', 'NZ', 'ES', 'GB', 'US' ],
258
- },
259
- {
260
- id: 'woocommerce_enable_coupons',
261
- value: 'yes',
262
- },
263
- {
264
- id: 'woocommerce_calc_taxes',
265
- value: 'yes',
266
- },
267
- {
268
- id: 'woocommerce_currency',
269
- value: 'USD',
270
- },
271
- ];
272
-
273
- /**
274
- * Page settings fixture data, using the update batch endpoint.
275
- *
276
- * @param {Array} pages
277
- *
278
- * @see {@link https://woocommerce.github.io/woocommerce-rest-api-docs/#batch-update-setting-options|Batch update setting options}
279
- */
280
- const PageSettings = ( pages = [] ) => {
281
- const cartPage = pages.find( ( page ) =>
282
- page.slug.includes( 'cart-block' )
283
- );
284
- const checkoutPage = pages.find( ( page ) =>
285
- page.slug.includes( 'checkout-block' )
286
- );
287
-
288
- return [
289
- {
290
- id: 'woocommerce_cart_page_id',
291
- value: cartPage?.id.toString() || '',
292
- },
293
- {
294
- id: 'woocommerce_checkout_page_id',
295
- value: checkoutPage?.id.toString() || '',
296
- },
297
- ];
298
- };
299
-
300
- /**
301
- * Shipping Zones fixture data, using the shipping zone endpoint, shipping
302
- * location, and shipping method endpoint.
303
- *
304
- * @see {@link https://woocommerce.github.io/woocommerce-rest-api-docs/#create-a-shipping-zone|Create a shipping zone}
305
- * * @see {@link https://woocommerce.github.io/woocommerce-rest-api-docs/#update-a-locations-of-a-shipping-zone|Update a locations of a shipping zone}
306
- * * @see {@link https://woocommerce.github.io/woocommerce-rest-api-docs/#include-a-shipping-method-to-a-shipping-zone|Include a shipping method to a shipping zone}
307
- */
308
- const Shipping = () => [
309
- {
310
- name: 'UK',
311
- locations: [
312
- {
313
- code: 'UK',
314
- },
315
- ],
316
- methods: [
317
- {
318
- method_id: 'flat_rate',
319
- settings: {
320
- title: 'Normal Shipping',
321
- cost: '20.00',
322
- },
323
- },
324
- {
325
- method_id: 'free_shipping',
326
- settings: {
327
- title: 'Free Shipping',
328
- cost: '00.00',
329
- requires: 'coupon',
330
- },
331
- },
332
- ],
333
- },
334
- ];
335
-
336
- /**
337
- * Taxes rates fixture data, using the create batch endpoint.
338
- *
339
- * @see {@link https://woocommerce.github.io/woocommerce-rest-api-docs/#batch-update-tax-rates|Batch update tax rates}
340
- */
341
- const Taxes = () => [
342
- {
343
- country: 'US',
344
- rate: '5.0000',
345
- name: 'State Tax',
346
- shipping: false,
347
- priority: 1,
348
- },
349
- {
350
- country: 'US',
351
- rate: '10.000',
352
- name: 'Sale Tax',
353
- shipping: false,
354
- priority: 2,
355
- },
356
- {
357
- country: 'UK',
358
- rate: '20.000',
359
- name: 'VAT',
360
- shipping: false,
361
- },
362
- ];
363
-
364
- module.exports = {
365
- Attributes,
366
- Coupons,
367
- ReviewsInProduct,
368
- Categories,
369
- Products,
370
- Settings,
371
- PageSettings,
372
- Shipping,
373
- Taxes,
374
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/fixtures/fixture-loaders.js DELETED
@@ -1,426 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- const WooCommerceRestApi = require( '@woocommerce/woocommerce-rest-api' )
5
- .default;
6
- const glob = require( 'glob-promise' );
7
- const { dirname } = require( 'path' );
8
- const { readJson } = require( 'fs-extra' );
9
- const axios = require( 'axios' ).default;
10
- require( 'dotenv' ).config();
11
-
12
- /**
13
- * Internal dependencies
14
- */
15
- const fixtures = require( './fixture-data' );
16
-
17
- // global.process.env.WORDPRESS_BASE_URL = `${ process.env.WORDPRESS_BASE_URL }:8889`;
18
-
19
- /**
20
- * ConsumerKey and ConsumerSecret are not used, we use basic auth, but
21
- * not providing them will throw an error.
22
- */
23
- const WooCommerce = new WooCommerceRestApi( {
24
- url: `${ process.env.WORDPRESS_BASE_URL }/`,
25
- consumerKey: 'consumer_key', // Your consumer key
26
- consumerSecret: 'consumer_secret', // Your consumer secret
27
- version: 'wc/v3',
28
- axiosConfig: {
29
- auth: {
30
- username: process.env.WORDPRESS_LOGIN,
31
- password: process.env.WORDPRESS_PASSWORD,
32
- },
33
- },
34
- } );
35
-
36
- const WPAPI = `${ process.env.WORDPRESS_BASE_URL }/wp-json/wp/v2/pages`;
37
-
38
- /**
39
- * prepare some store settings.
40
- *
41
- * @param {Object[]} fixture An array of objects describing our data, defaults
42
- * to our fixture.
43
- * @return {Promise} return a promise that resolves to the created data or
44
- * reject if the request failed.
45
- */
46
- const setupSettings = ( fixture = fixtures.Settings() ) =>
47
- WooCommerce.post( 'settings/general/batch', {
48
- update: fixture,
49
- } );
50
-
51
- const setupPageSettings = () => {
52
- axios.get( WPAPI ).then( ( response ) => {
53
- const fixture = fixtures.PageSettings( response.data );
54
- WooCommerce.post( 'settings/advanced/batch', {
55
- update: fixture,
56
- } );
57
- } );
58
- };
59
-
60
- /**
61
- * Create taxes.
62
- *
63
- * @param {Object[]} fixture An array of objects describing our data, defaults
64
- * to our fixture.
65
- * @return {Promise} a promise that resolves to an array of newly created taxes,
66
- * or rejects if the request failed.
67
- */
68
- const createTaxes = ( fixture = fixtures.Taxes() ) =>
69
- WooCommerce.post( 'taxes/batch', {
70
- create: fixture,
71
- } ).then( ( response ) =>
72
- response.data.create.map( ( taxes ) => taxes.id )
73
- );
74
- /**
75
- * Delete taxes.
76
- *
77
- * @param {number[]} ids an array of taxes IDs to delete.
78
- *
79
- * @return {Promise} return a promise that resolves to the deleted data or
80
- * reject if the request failed.
81
- */
82
- const deleteTaxes = ( ids ) =>
83
- WooCommerce.post( 'taxes/batch', {
84
- delete: ids,
85
- } );
86
-
87
- /**
88
- * Create Coupons.
89
- *
90
- * @param {Object[]} fixture An array of objects describing our data, defaults
91
- * to our fixture.
92
- * @return {Promise} a promise that resolves to an array of newly created coupons,
93
- * or rejects if the request failed.
94
- */
95
- const createCoupons = ( fixture = fixtures.Coupons() ) =>
96
- WooCommerce.post( 'coupons/batch', {
97
- create: fixture,
98
- } ).then( ( response ) =>
99
- response.data.create.map( ( coupon ) => coupon.id )
100
- );
101
-
102
- /**
103
- * Delete coupons.
104
- *
105
- * @param {number[]} ids an array of coupons IDs to delete.
106
- *
107
- * @return {Promise} return a promise that resolves to the deleted data or
108
- * reject if the request failed.
109
- */
110
- const deleteCoupons = ( ids ) =>
111
- WooCommerce.post( 'coupons/batch', {
112
- delete: ids,
113
- } );
114
-
115
- /**
116
- * Create Product Categories.
117
- *
118
- * @param {Object[]} fixture An array of objects describing our data, defaults
119
- * to our fixture.
120
- * @return {Promise} a promise that resolves to an array of newly created categories,
121
- * or rejects if the request failed.
122
- */
123
- const createCategories = ( fixture = fixtures.Categories() ) =>
124
- WooCommerce.post( 'products/categories/batch', {
125
- create: fixture,
126
- } ).then( ( response ) => response.data.create );
127
-
128
- /**
129
- * Delete Product Categories.
130
- *
131
- * @param {Object[]} categories an array of categories to delete.
132
- *
133
- * @return {Promise} return a promise that resolves to the deleted data or
134
- * reject if the request failed.
135
- */
136
- const deleteCategories = ( categories ) => {
137
- const ids = categories.map( ( category ) => category.id );
138
-
139
- return WooCommerce.post( 'products/categories/batch', {
140
- delete: ids,
141
- } );
142
- };
143
-
144
- /**
145
- * Create Products.
146
- *
147
- * currently this only creates a single product for the sake of reviews.
148
- *
149
- * @todo add more products to e2e fixtures data.
150
- *
151
- * @param {Array} categories Array of category objects so we can replace names with ids in the request.
152
- * @param {Array} attributes Array of attribute objects so we can replace names with ids in the request.
153
- * @param {Object[]} fixture An array of objects describing our data, defaults
154
- * to our fixture.
155
- * @return {Promise} a promise that resolves to an array of newly created products,
156
- * or rejects if the request failed.
157
- */
158
- const createProducts = (
159
- categories,
160
- attributes,
161
- fixture = fixtures.Products()
162
- ) => {
163
- const hydratedFixture = fixture.map( ( product ) => {
164
- if ( categories && product.categories ) {
165
- product.categories = product.categories.map( ( categoryName ) =>
166
- categories.find(
167
- ( category ) => category.name === categoryName
168
- )
169
- );
170
- }
171
- if ( attributes && product.attributes ) {
172
- product.attributes = product.attributes.map(
173
- ( productAttribute ) => {
174
- return {
175
- ...attributes.find(
176
- ( attribute ) =>
177
- attribute.name === productAttribute.name
178
- ),
179
- ...productAttribute,
180
- };
181
- }
182
- );
183
- }
184
- return product;
185
- } );
186
- return WooCommerce.post( 'products/batch', {
187
- create: hydratedFixture,
188
- } ).then( ( products ) => {
189
- return products.data.create.map( ( product ) => product.id );
190
- } );
191
- };
192
-
193
- /**
194
- * Delete products.
195
- *
196
- * Deleting products will also delete review.
197
- *
198
- * @param {number[]} ids an array of products IDs to delete.
199
- *
200
- * @return {Promise} return a promise that resolves to the deleted data or
201
- * reject if the request failed.
202
- */
203
- const deleteProducts = ( ids ) =>
204
- WooCommerce.post( 'products/batch', {
205
- delete: ids,
206
- } );
207
-
208
- /**
209
- * Create Reviews.
210
- *
211
- * @param {number} id product id to assign reviews to.
212
- * @param {Object[]} fixture An array of objects describing our reviews, defaults
213
- * to our fixture.
214
- * @return {Promise} a promise that resolves to an server response data, or
215
- * rejects if the request failed.
216
- */
217
- const createReviews = ( id, fixture = fixtures.ReviewsInProduct( id ) ) =>
218
- WooCommerce.post( 'products/reviews/batch', {
219
- create: fixture,
220
- } );
221
-
222
- /**
223
- * Enable Cheque payments.
224
- *
225
- * This is not called directly but is called within enablePaymentGateways.
226
- *
227
- * @return {Promise} a promise that resolves to an server response data, or
228
- * rejects if the request failed.
229
- */
230
- const enableCheque = () =>
231
- WooCommerce.post( 'payment_gateways/cheque', {
232
- enabled: true,
233
- } );
234
-
235
- /**
236
- * Enable payment gateways.
237
- *
238
- * It calls other individual payment gateway functions.
239
- *
240
- * @return {Promise} a promise that resolves to an array of server response
241
- * data, or rejects if the request failed.
242
- */
243
- const enablePaymentGateways = () => Promise.all( [ enableCheque() ] );
244
-
245
- /**
246
- * Create shipping zones.
247
- *
248
- * Shipping locations need to be assigned to a zone, and shipping methods need
249
- * to be assigned to a shipping location, this create a shipping zone and
250
- * location and methods.
251
- *
252
- * @param {Object[]} fixture An array of objects describing our data, defaults
253
- * to our fixture.
254
- * @return {Promise} a promise that resolves to an array of newly created shipping
255
- * zones IDs, or rejects if the request failed.
256
- */
257
- const createShippingZones = ( fixture = fixtures.Shipping() ) => {
258
- return Promise.all(
259
- fixture.map( ( { name, locations, methods } ) => {
260
- return WooCommerce.post( 'shipping/zones', { name } )
261
- .then( ( response ) => {
262
- return response.data.id;
263
- } )
264
- .then( ( zoneId ) => {
265
- const locationsPromise = WooCommerce.put(
266
- `shipping/zones/${ zoneId }/locations`,
267
- locations
268
- );
269
-
270
- return [ zoneId, locationsPromise ];
271
- } )
272
- .then( ( [ zoneId, locationsPromise ] ) => {
273
- const methodPromise = Promise.all(
274
- methods.map( ( method ) =>
275
- WooCommerce.post(
276
- `shipping/zones/${ zoneId }/methods`,
277
- method
278
- )
279
- )
280
- );
281
- return [ zoneId, methodPromise, locationsPromise ];
282
- } )
283
- .then( ( [ zoneId, methodPromise, locationsPromise ] ) =>
284
- Promise.all( [ methodPromise, locationsPromise ] ).then(
285
- () => zoneId
286
- )
287
- );
288
- } )
289
- );
290
- };
291
-
292
- /**
293
- * Delete Shipping zones.
294
- *
295
- * Deleting a shipping will also delete location and methods defined within it.
296
- *
297
- * @param {number[]} ids an array of shipping zones IDs to delete.
298
- *
299
- * @return {Promise} return a promise that resolves to an array of deleted data or
300
- * reject if the request failed.
301
- */
302
- const deleteShippingZones = ( ids ) => {
303
- const deleteZone = ( id ) =>
304
- WooCommerce.delete( `shipping/zones/${ id }`, {
305
- force: true,
306
- } );
307
- return Promise.all( ids.map( deleteZone ) );
308
- };
309
-
310
- const createBlockPages = () => {
311
- return glob( `${ dirname( __filename ) }/../specs/**/*.fixture.json` ).then(
312
- ( files ) => {
313
- return Promise.all(
314
- files.map( async ( filePath ) => {
315
- const file = await readJson( filePath );
316
- const { title, pageContent: content } = file;
317
- return axios
318
- .post(
319
- WPAPI,
320
- {
321
- title,
322
- content,
323
- status: 'publish',
324
- },
325
- {
326
- auth: {
327
- username: process.env.WORDPRESS_LOGIN,
328
- password: process.env.WORDPRESS_PASSWORD,
329
- },
330
- }
331
- )
332
- .then( ( response ) => response.data.id );
333
- } )
334
- );
335
- }
336
- );
337
- };
338
-
339
- const deleteBlockPages = ( ids ) => {
340
- return Promise.all(
341
- ids.map( ( id ) =>
342
- axios.delete( `${ WPAPI }/${ id }`, {
343
- params: {
344
- force: true,
345
- },
346
- auth: {
347
- username: process.env.WORDPRESS_LOGIN,
348
- password: process.env.WORDPRESS_PASSWORD,
349
- },
350
- } )
351
- )
352
- );
353
- };
354
-
355
- /**
356
- * Create Products attributes and terms.
357
- *
358
- * @param {Object[]} fixture An array of objects describing our data, defaults
359
- * to our fixture.
360
- * @return {Promise} a promise that resolves to an array of newly created product attributes IDs, or rejects if the request failed.
361
- */
362
- const createProductAttributes = ( fixture = fixtures.Attributes() ) => {
363
- return Promise.all(
364
- fixture.map( ( { attribute, terms } ) => {
365
- return WooCommerce.post( 'products/attributes', attribute )
366
- .then( ( response ) => {
367
- return response.data.id;
368
- } )
369
- .then( ( attributeId ) => {
370
- const termsPromise = WooCommerce.put(
371
- `products/attributes/${ attributeId }/terms/batch`,
372
- { create: terms }
373
- );
374
-
375
- return [ attributeId, termsPromise ];
376
- } )
377
- .then( ( [ attributeId, termsPromise ] ) =>
378
- Promise.all( [ attributeId, termsPromise ] ).then( () => ( {
379
- name: attribute.name,
380
- id: attributeId,
381
- } ) )
382
- )
383
- .catch( () => {
384
- // At this point, the attributes probably already exist. Get them and return them instead.
385
- return WooCommerce.get( 'products/attributes' ).then(
386
- ( response ) => response.data
387
- );
388
- } );
389
- } )
390
- );
391
- };
392
-
393
- /**
394
- * Delete Products attributes.
395
- *
396
- * Deleting all passed product attributes, will also delete terms within it.
397
- *
398
- * @param {number[]} ids an array of product attributes IDs to delete.
399
- *
400
- * @return {Promise} return a promise that resolves to an array of deleted data or
401
- * reject if the request failed.
402
- */
403
- const deleteProductAttributes = ( ids ) => {
404
- return WooCommerce.post( 'products/attributes/batch', { delete: ids } );
405
- };
406
-
407
- module.exports = {
408
- createProductAttributes,
409
- deleteProductAttributes,
410
- setupSettings,
411
- setupPageSettings,
412
- createTaxes,
413
- deleteTaxes,
414
- createCoupons,
415
- deleteCoupons,
416
- createCategories,
417
- deleteCategories,
418
- createProducts,
419
- deleteProducts,
420
- createReviews,
421
- enablePaymentGateways,
422
- createShippingZones,
423
- deleteShippingZones,
424
- createBlockPages,
425
- deleteBlockPages,
426
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/active-product-filters.fixture.json DELETED
@@ -1 +0,0 @@
1
- {"title":"Active Product Filters Block","pageContent":"<!-- wp:woocommerce/active-filters -->\n<div class=\"wp-block-woocommerce-active-filters is-loading\" data-display-style=\"list\" data-heading=\"Active filters\" data-heading-level=\"3\"><span aria-hidden=\"true\" class=\"wc-block-active-product-filters__placeholder\"></span></div>\n<!-- /wp:woocommerce/active-filters -->"}
 
packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/all-products.fixture.json DELETED
@@ -1 +0,0 @@
1
- {"title":"All Products Block","pageContent":"<!-- wp:woocommerce/all-products {\"columns\":3,\"rows\":3,\"alignButtons\":false,\"contentVisibility\":{\"orderBy\":true},\"orderby\":\"date\",\"layoutConfig\":[[\"woocommerce/product-image\"],[\"woocommerce/product-title\"],[\"woocommerce/product-price\"],[\"woocommerce/product-rating\"],[\"woocommerce/product-button\"]]} -->\n<div class=\"wp-block-woocommerce-all-products wc-block-all-products\" data-attributes=\"{&quot;alignButtons&quot;:false,&quot;columns&quot;:3,&quot;contentVisibility&quot;:{&quot;orderBy&quot;:true},&quot;isPreview&quot;:false,&quot;layoutConfig&quot;:[[&quot;woocommerce/product-image&quot;],[&quot;woocommerce/product-title&quot;],[&quot;woocommerce/product-price&quot;],[&quot;woocommerce/product-rating&quot;],[&quot;woocommerce/product-button&quot;]],&quot;orderby&quot;:&quot;date&quot;,&quot;rows&quot;:3}\"></div>\n<!-- /wp:woocommerce/all-products -->"}
 
packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/all-reviews.fixture.json DELETED
@@ -1 +0,0 @@
1
- {"title":"All Reviews Block","pageContent":"<!-- wp:woocommerce/all-reviews -->\n<div class=\"wp-block-woocommerce-all-reviews wc-block-all-reviews has-image has-name has-date has-rating has-content has-product-name\" data-image-type=\"reviewer\" data-orderby=\"most-recent\" data-reviews-on-page-load=\"10\" data-reviews-on-load-more=\"10\" data-show-load-more=\"true\" data-show-orderby=\"true\"></div>\n<!-- /wp:woocommerce/all-reviews -->"}
 
packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/cart.fixture.json DELETED
@@ -1 +0,0 @@
1
- {"title":"Cart Block","pageContent":"<!-- wp:woocommerce/cart -->\n<div class=\"wp-block-woocommerce-cart is-loading\"><!-- wp:image {\"align\":\"center\",\"sizeSlug\":\"small\"} -->\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-small\"><img src=\"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzgiIGhlaWdodD0iMzgiIHZpZXdCb3g9IjAgMCAzOCAzOCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTE5IDBDOC41MDQwMyAwIDAgOC41MDQwMyAwIDE5QzAgMjkuNDk2IDguNTA0MDMgMzggMTkgMzhDMjkuNDk2IDM4IDM4IDI5LjQ5NiAzOCAxOUMzOCA4LjUwNDAzIDI5LjQ5NiAwIDE5IDBaTTI1LjEyOSAxMi44NzFDMjYuNDg1MSAxMi44NzEgMjcuNTgwNiAxMy45NjY1IDI3LjU4MDYgMTUuMzIyNkMyNy41ODA2IDE2LjY3ODYgMjYuNDg1MSAxNy43NzQyIDI1LjEyOSAxNy43NzQyQzIzLjc3MyAxNy43NzQyIDIyLjY3NzQgMTYuNjc4NiAyMi42Nzc0IDE1LjMyMjZDMjIuNjc3NCAxMy45NjY1IDIzLjc3MyAxMi44NzEgMjUuMTI5IDEyLjg3MVpNMTEuNjQ1MiAzMS4yNTgxQzkuNjE0OTIgMzEuMjU4MSA3Ljk2Nzc0IDI5LjY0OTIgNy45Njc3NCAyNy42NTczQzcuOTY3NzQgMjYuMTI1IDEwLjE1MTIgMjMuMDI5OCAxMS4xNTQ4IDIxLjY5NjhDMTEuNCAyMS4zNjczIDExLjg5MDMgMjEuMzY3MyAxMi4xMzU1IDIxLjY5NjhDMTMuMTM5MSAyMy4wMjk4IDE1LjMyMjYgMjYuMTI1IDE1LjMyMjYgMjcuNjU3M0MxNS4zMjI2IDI5LjY0OTIgMTMuNjc1NCAzMS4yNTgxIDExLjY0NTIgMzEuMjU4MVpNMTIuODcxIDE3Ljc3NDJDMTEuNTE0OSAxNy43NzQyIDEwLjQxOTQgMTYuNjc4NiAxMC40MTk0IDE1LjMyMjZDMTAuNDE5NCAxMy45NjY1IDExLjUxNDkgMTIuODcxIDEyLjg3MSAxMi44NzFDMTQuMjI3IDEyLjg3MSAxNS4zMjI2IDEzLjk2NjUgMTUuMzIyNiAxNS4zMjI2QzE1LjMyMjYgMTYuNjc4NiAxNC4yMjcgMTcuNzc0MiAxMi44NzEgMTcuNzc0MlpNMjUuOTEwNSAyOS41ODc5QzI0LjE5NDQgMjcuNTM0NyAyMS42NzM4IDI2LjM1NDggMTkgMjYuMzU0OEMxNy4zNzU4IDI2LjM1NDggMTcuMzc1OCAyMy45MDMyIDE5IDIzLjkwMzJDMjIuNDAxNiAyMy45MDMyIDI1LjYxMTcgMjUuNDA0OCAyNy43ODc1IDI4LjAyNUMyOC44NDQ4IDI5LjI4MTUgMjYuOTI5NCAzMC44MjE0IDI1LjkxMDUgMjkuNTg3OVoiIGZpbGw9ImJsYWNrIi8+Cjwvc3ZnPgo=\" alt=\"\"/></figure></div>\n<!-- /wp:image -->\n\n<!-- wp:heading {\"align\":\"center\",\"className\":\"wc-block-cart__empty-cart__title\"} -->\n<h2 class=\"has-text-align-center wc-block-cart__empty-cart__title\">Your cart is currently empty!</h2>\n<!-- /wp:heading -->\n\n<!-- wp:paragraph {\"align\":\"center\"} -->\n<p class=\"has-text-align-center\"><a href=\"http://localhost:8889/shop/\">Browse store</a>.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:separator {\"className\":\"is-style-dots\"} -->\n<hr class=\"wp-block-separator is-style-dots\"/>\n<!-- /wp:separator -->\n\n<!-- wp:heading {\"align\":\"center\"} -->\n<h2 class=\"has-text-align-center\">New in store</h2>\n<!-- /wp:heading -->\n\n<!-- wp:woocommerce/product-new {\"rows\":1} /--></div>\n<!-- /wp:woocommerce/cart -->"}
 
packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/checkout.fixture.json DELETED
@@ -1 +0,0 @@
1
- {"title":"Checkout Block","pageContent":"<!-- wp:woocommerce/checkout -->\n<div class=\"wp-block-woocommerce-checkout wc-block-checkout is-loading\"><!-- wp:woocommerce/checkout-fields-block -->\n<div class=\"wp-block-woocommerce-checkout-fields-block\"><!-- wp:woocommerce/checkout-express-payment-block -->\n<div class=\"wp-block-woocommerce-checkout-express-payment-block\"></div>\n<!-- /wp:woocommerce/checkout-express-payment-block -->\n\n<!-- wp:woocommerce/checkout-contact-information-block -->\n<div class=\"wp-block-woocommerce-checkout-contact-information-block\"></div>\n<!-- /wp:woocommerce/checkout-contact-information-block -->\n\n<!-- wp:woocommerce/checkout-shipping-address-block -->\n<div class=\"wp-block-woocommerce-checkout-shipping-address-block\"></div>\n<!-- /wp:woocommerce/checkout-shipping-address-block -->\n\n<!-- wp:woocommerce/checkout-billing-address-block -->\n<div class=\"wp-block-woocommerce-checkout-billing-address-block\"></div>\n<!-- /wp:woocommerce/checkout-billing-address-block -->\n\n<!-- wp:woocommerce/checkout-shipping-methods-block -->\n<div class=\"wp-block-woocommerce-checkout-shipping-methods-block\"></div>\n<!-- /wp:woocommerce/checkout-shipping-methods-block -->\n\n<!-- wp:woocommerce/checkout-payment-block -->\n<div class=\"wp-block-woocommerce-checkout-payment-block\"></div>\n<!-- /wp:woocommerce/checkout-payment-block -->\n\n<!-- wp:woocommerce/checkout-order-note-block -->\n<div class=\"wp-block-woocommerce-checkout-order-note-block\"></div>\n<!-- /wp:woocommerce/checkout-order-note-block -->\n\n<!-- wp:woocommerce/checkout-terms-block -->\n<div class=\"wp-block-woocommerce-checkout-terms-block\"></div>\n<!-- /wp:woocommerce/checkout-terms-block -->\n\n<!-- wp:woocommerce/checkout-actions-block -->\n<div class=\"wp-block-woocommerce-checkout-actions-block\"></div>\n<!-- /wp:woocommerce/checkout-actions-block --></div>\n<!-- /wp:woocommerce/checkout-fields-block -->\n\n<!-- wp:woocommerce/checkout-totals-block -->\n<div class=\"wp-block-woocommerce-checkout-totals-block\"><!-- wp:woocommerce/checkout-order-summary-block -->\n<div class=\"wp-block-woocommerce-checkout-order-summary-block\"></div>\n<!-- /wp:woocommerce/checkout-order-summary-block --></div>\n<!-- /wp:woocommerce/checkout-totals-block --></div>\n<!-- /wp:woocommerce/checkout -->"}
 
packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/featured-product.fixture.json DELETED
@@ -1 +0,0 @@
1
- {"title":"Featured Product Block","pageContent":"<!-- wp:woocommerce/featured-product /-->"}
 
packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/filter-products-by-attribute.fixture.json DELETED
@@ -1 +0,0 @@
1
- {"title":"Filter Products by Attribute Block","pageContent":"<!-- wp:woocommerce/attribute-filter -->\n<div class=\"wp-block-woocommerce-attribute-filter is-loading\" data-attribute-id=\"0\" data-show-counts=\"true\" data-query-type=\"or\" data-heading=\"Filter by attribute\" data-heading-level=\"3\"><span aria-hidden=\"true\" class=\"wc-block-product-attribute-filter__placeholder\"></span></div>\n<!-- /wp:woocommerce/attribute-filter -->"}
 
packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/filter-products-by-price.fixture.json DELETED
@@ -1 +0,0 @@
1
- {"title":"Filter Products by Price Block","pageContent":"<!-- wp:woocommerce/price-filter -->\n<div class=\"wp-block-woocommerce-price-filter is-loading\" data-showinputfields=\"true\" data-showfilterbutton=\"false\" data-heading=\"Filter by price\" data-heading-level=\"3\"><span aria-hidden=\"true\" class=\"wc-block-product-categories__placeholder\"></span></div>\n<!-- /wp:woocommerce/price-filter -->"}
 
packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/filter-products-by-stock.fixture.json DELETED
@@ -1 +0,0 @@
1
- {"title":"Filter Products by Stock Block","pageContent":"<!-- wp:woocommerce/stock-filter -->\n<div class=\"wp-block-woocommerce-stock-filter is-loading\" data-show-counts=\"true\" data-heading=\"Filter by stock status\" data-heading-level=\"3\"><span aria-hidden=\"true\" class=\"wc-block-product-stock-filter__placeholder\"></span></div>\n<!-- /wp:woocommerce/stock-filter -->"}
 
packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/mini-cart.fixture.json DELETED
@@ -1 +0,0 @@
1
- {"title":"Mini Cart Block","pageContent":"<!-- wp:woocommerce/mini-cart /-->"}
 
packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/product-category.fixture.json DELETED
@@ -1 +0,0 @@
1
- {"title":"Products by Category Block","pageContent":"<!-- wp:woocommerce/product-category /-->"}
 
packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/product-on-sale.fixture.json DELETED
@@ -1 +0,0 @@
1
- {"title":"On Sale Products Block","pageContent":"<!-- wp:woocommerce/product-on-sale /-->"}
 
packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/product-search.fixture.json DELETED
@@ -1,4 +0,0 @@
1
- {
2
- "title": "Product Search Block",
3
- "pageContent": "<!-- wp:woocommerce/product-search {\"formId\":\"wc-block-product-search-1\"} -->\n<div class=\"wp-block-woocommerce-product-search\"><div class=\"wc-block-product-search\"><form role=\"search\" method=\"get\" action=\"http://localhost:8889/\"><label for=\"wc-block-product-search-1\" class=\"wc-block-product-search__label\">Search</label><div class=\"wc-block-product-search__fields\"><input type=\"search\" id=\"wc-block-product-search-1\" class=\"wc-block-product-search__field\" placeholder=\"Search products…\" name=\"s\"/><input type=\"hidden\" name=\"post_type\" value=\"product\"/><button type=\"submit\" class=\"wc-block-product-search__button\" label=\"Search\"><svg aria-hidden=\"true\" role=\"img\" focusable=\"false\" class=\"dashicon dashicons-arrow-right-alt2\" xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\" viewbox=\"0 0 20 20\"><path d=\"M6 15l5-5-5-5 1-2 7 7-7 7z\"></path></svg></button></div></form></div></div>\n<!-- /wp:woocommerce/product-search -->"
4
- }
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/product-tag.fixture.json DELETED
@@ -1 +0,0 @@
1
- {"title":"Products by Tag Block","pageContent":"<!-- wp:woocommerce/product-tag /-->"}
 
packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/products-by-attribute.fixture.json DELETED
@@ -1 +0,0 @@
1
- {"title":"Products by Attribute Block","pageContent":"<!-- wp:woocommerce/products-by-attribute /-->"}
 
packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/reviews-by-category.fixture.json DELETED
@@ -1 +0,0 @@
1
- {"title":"Reviews by Category Block","pageContent":"<!-- wp:woocommerce/reviews-by-category -->\n<div class=\"wp-block-woocommerce-reviews-by-category wc-block-reviews-by-category has-image has-name has-date has-rating has-content has-product-name\" data-image-type=\"reviewer\" data-orderby=\"most-recent\" data-reviews-on-page-load=\"10\" data-reviews-on-load-more=\"10\" data-show-load-more=\"true\" data-show-orderby=\"true\" data-category-ids=\"\"></div>\n<!-- /wp:woocommerce/reviews-by-category -->"}
 
packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/reviews-by-product.fixture.json DELETED
@@ -1 +0,0 @@
1
- {"title":"Reviews by Product Block","pageContent":"<!-- wp:woocommerce/reviews-by-product -->\n<div class=\"wp-block-woocommerce-reviews-by-product wc-block-all-reviews has-image has-name has-date has-rating has-content\" data-image-type=\"reviewer\" data-orderby=\"most-recent\" data-reviews-on-page-load=\"10\" data-reviews-on-load-more=\"10\" data-show-load-more=\"true\" data-show-orderby=\"true\"></div>\n<!-- /wp:woocommerce/reviews-by-product -->"}
 
packages/woocommerce-blocks/tests/e2e/specs/backend/__fixtures__/single-product.fixture.json DELETED
@@ -1 +0,0 @@
1
- {"title":"Single Product Block","pageContent":"<!-- wp:woocommerce/single-product -->\n<div class=\"wp-block-woocommerce-single-product is-loading\"></div>\n<!-- /wp:woocommerce/single-product -->"}
 
packages/woocommerce-blocks/tests/e2e/specs/backend/__snapshots__/product-search.test.js.snap DELETED
@@ -1,3 +0,0 @@
1
- // Jest Snapshot v1, https://goo.gl/fbAQLP
2
-
3
- exports[`Product Search Block can change field labels in editor 1`] = `"<!-- wp:woocommerce/product-search {\\"label\\":\\"The Label\\",\\"placeholder\\":\\"The Placeholder\\",\\"formId\\":\\"wc-block-product-search-1\\"} /-->"`;
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/active-filters.test.js DELETED
@@ -1,81 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import {
5
- getEditedPostContent,
6
- getAllBlocks,
7
- switchUserToAdmin,
8
- openDocumentSettingsSidebar,
9
- } from '@wordpress/e2e-test-utils';
10
-
11
- import {
12
- visitBlockPage,
13
- selectBlockByName,
14
- } from '@woocommerce/blocks-test-utils';
15
-
16
- /**
17
- * Internal dependencies
18
- */
19
- import { insertBlockDontWaitForInsertClose } from '../../utils';
20
-
21
- const block = {
22
- name: 'Active Product Filters',
23
- slug: 'woocommerce/active-filters',
24
- class: '.wc-block-active-filters',
25
- };
26
-
27
- describe( `${ block.name } Block`, () => {
28
- beforeAll( async () => {
29
- await switchUserToAdmin();
30
- await visitBlockPage( `${ block.name } Block` );
31
- } );
32
-
33
- it( 'can only be inserted once', async () => {
34
- await insertBlockDontWaitForInsertClose( block.name );
35
- expect( await getAllBlocks() ).toHaveLength( 1 );
36
- } );
37
-
38
- it( 'renders without crashing', async () => {
39
- await expect( page ).toRenderBlock( block );
40
- } );
41
-
42
- describe( 'attributes', () => {
43
- beforeEach( async () => {
44
- await openDocumentSettingsSidebar();
45
- await selectBlockByName( block.slug );
46
- } );
47
-
48
- it( "allows changing the block's title", async () => {
49
- const textareaSelector = `.wp-block[data-type="${ block.slug }"] textarea.wc-block-editor-components-title`;
50
- await expect( page ).toFill( textareaSelector, 'New Title' );
51
- await page.click(
52
- '.components-toolbar button[aria-label="Heading 6"]'
53
- );
54
- await expect(
55
- page
56
- ).toMatchElement(
57
- `.wp-block[data-type="${ block.slug }"] h6 textarea`,
58
- { text: 'New Title' }
59
- );
60
- // reset
61
- await expect( page ).toFill( textareaSelector, block.name );
62
- await page.click(
63
- '.components-toolbar button[aria-label="Heading 3"]'
64
- );
65
- } );
66
-
67
- it( 'allows changing the Display Style', async () => {
68
- // Click the button to convert the display style to Chips.
69
- await expect( page ).toClick( 'button', { text: 'Chips' } );
70
- await expect( page ).toMatchElement(
71
- '.wc-block-active-filters__list.wc-block-active-filters__list--chips'
72
- );
73
-
74
- // Click the button to convert the display style to List.
75
- await expect( page ).toClick( 'button', { text: 'List' } );
76
- await expect( page ).not.toMatchElement(
77
- '.wc-block-active-filters__list.wc-block-active-filters__list--chips'
78
- );
79
- } );
80
- } );
81
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/all-products.test.js DELETED
@@ -1,53 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import { getAllBlocks, switchUserToAdmin } from '@wordpress/e2e-test-utils';
5
- import { visitBlockPage } from '@woocommerce/blocks-test-utils';
6
- import { merchant } from '@woocommerce/e2e-utils';
7
-
8
- import {
9
- searchForBlock,
10
- insertBlockDontWaitForInsertClose,
11
- openWidgetEditor,
12
- closeModalIfExists,
13
- openWidgetsEditorBlockInserter,
14
- } from '../../utils.js';
15
-
16
- const block = {
17
- name: 'All Products',
18
- slug: 'woocommerce/all-products',
19
- class: '.wc-block-all-products',
20
- };
21
-
22
- describe( `${ block.name } Block`, () => {
23
- describe( 'in page editor', () => {
24
- beforeAll( async () => {
25
- await switchUserToAdmin();
26
- await visitBlockPage( `${ block.name } Block` );
27
- } );
28
-
29
- it( 'can only be inserted once', async () => {
30
- await insertBlockDontWaitForInsertClose( block.name );
31
- expect( await getAllBlocks() ).toHaveLength( 1 );
32
- } );
33
-
34
- it( 'renders without crashing', async () => {
35
- await expect( page ).toRenderBlock( block );
36
- } );
37
- } );
38
-
39
- describe( 'in widget editor', () => {
40
- it( "can't be inserted in a widget area", async () => {
41
- await merchant.login();
42
- await openWidgetEditor();
43
- await closeModalIfExists();
44
- await openWidgetsEditorBlockInserter();
45
- await searchForBlock( block.name );
46
- const allProductsButton = await page.$x(
47
- `//button//span[text()='${ block.name }']`
48
- );
49
-
50
- expect( allProductsButton ).toHaveLength( 0 );
51
- } );
52
- } );
53
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/all-reviews.test.js DELETED
@@ -1,35 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import { switchUserToAdmin } from '@wordpress/e2e-test-utils';
5
-
6
- import { visitBlockPage } from '@woocommerce/blocks-test-utils';
7
-
8
- const block = {
9
- name: 'All Reviews',
10
- slug: 'woocommerce/all-reviews',
11
- class: '.wc-block-all-reviews',
12
- };
13
-
14
- describe( `${ block.name } Block`, () => {
15
- beforeAll( async () => {
16
- await switchUserToAdmin();
17
- await visitBlockPage( `${ block.name } Block` );
18
- } );
19
-
20
- it( 'renders without crashing', async () => {
21
- await expect( page ).toRenderBlock( block );
22
- } );
23
-
24
- it( 'shows reviews', async () => {
25
- await page.waitForSelector(
26
- '.wc-block-review-list .wc-block-review-list-item__item:not(.is-loading)'
27
- );
28
- expect(
29
- await page.$$eval(
30
- '.wc-block-review-list .wc-block-review-list-item__item',
31
- ( reviews ) => reviews.length
32
- )
33
- ).toBeGreaterThanOrEqual( 6 ); // Fixture data has three reviews per product.
34
- } );
35
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/attribute-filter.test.js DELETED
@@ -1,167 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import {
5
- switchUserToAdmin,
6
- openDocumentSettingsSidebar,
7
- } from '@wordpress/e2e-test-utils';
8
-
9
- import {
10
- visitBlockPage,
11
- saveOrPublish,
12
- selectBlockByName,
13
- } from '@woocommerce/blocks-test-utils';
14
-
15
- const block = {
16
- name: 'Filter Products by Attribute',
17
- slug: 'woocommerce/attribute-filter',
18
- class: '.wc-block-attribute-filter',
19
- };
20
-
21
- describe( `${ block.name } Block`, () => {
22
- beforeAll( async () => {
23
- await switchUserToAdmin();
24
- await visitBlockPage( `${ block.name } Block` );
25
-
26
- await expect( page ).toClick( 'span.woocommerce-search-list__item-name', { text: 'Capacity' } );
27
- //needed for attributes list to load correctly
28
- await page.waitFor(1000);
29
-
30
- await expect( page ).toClick( 'button', { text: 'Done' } );
31
- await page.waitForNetworkIdle();
32
- } );
33
-
34
- it( 'renders without crashing', async () => {
35
- await expect( page ).toRenderBlock( block );
36
- } );
37
-
38
- it( 'renders correctly', async () => {
39
- expect(
40
- await page.$$eval(
41
- '.wc-block-attribute-filter-list li',
42
- ( attributes ) => attributes.length
43
- )
44
- // our test data loads 2 for the Capacity attribute.
45
- ).toBeGreaterThanOrEqual( 2 );
46
- } );
47
-
48
- describe( 'Attributes', () => {
49
- beforeEach( async () => {
50
- await openDocumentSettingsSidebar();
51
- await selectBlockByName( block.slug );
52
- } );
53
-
54
- it( "allows changing the block's title", async () => {
55
- const textareaSelector = `.wp-block[data-type="${ block.slug }"] textarea.wc-block-editor-components-title`;
56
- await expect( page ).toFill( textareaSelector, 'New Title' );
57
- await page.click(
58
- '.components-toolbar button[aria-label="Heading 6"]'
59
- );
60
- await expect(
61
- page
62
- ).toMatchElement(
63
- `.wp-block[data-type="${ block.slug }"] h6 textarea`,
64
- { text: 'New Title' }
65
- );
66
- await expect( page ).toFill(
67
- textareaSelector,
68
- 'Filter by Capacity'
69
- );
70
- await page.click(
71
- '.components-toolbar button[aria-label="Heading 3"]'
72
- );
73
- } );
74
-
75
- it( 'can hide product count', async () => {
76
- await expect( page ).toMatchElement(
77
- '.wc-filter-element-label-list-count'
78
- );
79
- await expect( page ).toClick( 'label', { text: 'Product count' } );
80
- await expect( page ).not.toMatchElement(
81
- '.wc-filter-element-label-list-count'
82
- );
83
- // reset
84
- await expect( page ).toClick( 'label', { text: 'Product count' } );
85
- } );
86
-
87
- it( 'can toggle go button', async () => {
88
- await expect( page ).not.toMatchElement(
89
- '.wc-block-filter-submit-button'
90
- );
91
- await expect( page ).toClick( 'label', { text: 'Filter button' } );
92
- await expect( page ).toMatchElement(
93
- '.wc-block-filter-submit-button'
94
- );
95
- // reset
96
- await expect( page ).toClick( 'label', { text: 'Filter button' } );
97
- } );
98
-
99
- it( 'can switch attribute', async () => {
100
- await expect( page ).toClick( 'button', {
101
- text: 'Filter Products by Attribute',
102
- } );
103
-
104
- await expect( page ).toClick(
105
- 'span.woocommerce-search-list__item-name',
106
- {
107
- text: 'Capacity',
108
- }
109
- );
110
- await page.waitForSelector(
111
- '.wc-block-attribute-filter-list:not(.is-loading)'
112
- );
113
- expect(
114
- await page.$$eval(
115
- '.wc-block-attribute-filter-list li',
116
- ( reviews ) => reviews.length
117
- )
118
- // Capacity has only 2 attributes
119
- ).toEqual( 2 );
120
-
121
-
122
- await expect( page ).toClick(
123
- 'span.woocommerce-search-list__item-name',
124
- {
125
- text: 'Shade',
126
- }
127
- );
128
- //needed for attributes list to load correctly
129
- await page.waitFor(1000);
130
-
131
- // reset
132
- await expect( page ).toClick(
133
- 'span.woocommerce-search-list__item-name',
134
- {
135
- text: 'Capacity',
136
- }
137
- );
138
- //needed for attributes list to load correctly
139
- await page.waitFor(1000);
140
- } );
141
-
142
- it( 'renders on the frontend', async () => {
143
- await saveOrPublish();
144
- const link = await page.evaluate( () =>
145
- wp.data.select( 'core/editor' ).getPermalink()
146
- );
147
- await page.goto( link, { waitUntil: 'networkidle2' } );
148
- await page.waitForSelector(
149
- '.wp-block-woocommerce-attribute-filter'
150
- );
151
- await expect( page ).toMatchElement(
152
- '.wp-block-woocommerce-attribute-filter h3',
153
- {
154
- text: 'Filter by Capacity',
155
- }
156
- );
157
-
158
- expect(
159
- await page.$$eval(
160
- '.wc-block-attribute-filter-list li',
161
- ( reviews ) => reviews.length
162
- )
163
- // Capacity has only two attributes
164
- ).toEqual( 2 );
165
- } );
166
- } );
167
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/cart.test.js DELETED
@@ -1,172 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import {
5
- clickBlockToolbarButton,
6
- openDocumentSettingsSidebar,
7
- switchUserToAdmin,
8
- getAllBlocks,
9
- } from '@wordpress/e2e-test-utils';
10
- import {
11
- findLabelWithText,
12
- visitBlockPage,
13
- selectBlockByName,
14
- } from '@woocommerce/blocks-test-utils';
15
- import { merchant } from '@woocommerce/e2e-utils';
16
-
17
- import {
18
- searchForBlock,
19
- insertBlockDontWaitForInsertClose,
20
- openWidgetEditor,
21
- closeModalIfExists,
22
- openWidgetsEditorBlockInserter,
23
- } from '../../utils.js';
24
-
25
- const block = {
26
- name: 'Cart',
27
- slug: 'woocommerce/cart',
28
- class: '.wp-block-woocommerce-cart',
29
- };
30
-
31
- const filledCartBlock = {
32
- name: 'Filled Cart',
33
- slug: 'woocommerce/filled-cart-block',
34
- class: '.wp-block-woocommerce-filled-cart-block',
35
- };
36
-
37
- const emptyCartBlock = {
38
- name: 'Empty Cart',
39
- slug: 'woocommerce/empty-cart-block',
40
- class: '.wp-block-woocommerce-empty-cart-block',
41
- };
42
-
43
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE < 2 ) {
44
- // eslint-disable-next-line jest/no-focused-tests
45
- test.only( `skipping ${ block.name } tests`, () => {} );
46
- }
47
-
48
- describe( `${ block.name } Block`, () => {
49
- describe( 'in page editor', () => {
50
- describe( `before compatibility notice is dismissed`, () => {
51
- beforeAll( async () => {
52
- // make sure CartCheckoutCompatibilityNotice will appear
53
- await page.evaluate( () => {
54
- localStorage.removeItem(
55
- 'wc-blocks_dismissed_compatibility_notices'
56
- );
57
- } );
58
- await visitBlockPage( `${ block.name } Block` );
59
- } );
60
-
61
- it( 'shows compatibility notice', async () => {
62
- const compatibilityNoticeTitle = await page.$x(
63
- `//h1[contains(text(), 'Compatibility notice')]`
64
- );
65
- expect( compatibilityNoticeTitle.length ).toBe( 1 );
66
- } );
67
- } );
68
-
69
- describe( 'after compatibility notice is dismissed', () => {
70
- beforeAll( async () => {
71
- await page.evaluate( () => {
72
- localStorage.setItem(
73
- 'wc-blocks_dismissed_compatibility_notices',
74
- '["cart"]'
75
- );
76
- } );
77
- await switchUserToAdmin();
78
- await visitBlockPage( `${ block.name } Block` );
79
- } );
80
-
81
- afterAll( async () => {
82
- await page.evaluate( () => {
83
- localStorage.removeItem(
84
- 'wc-blocks_dismissed_compatibility_notices'
85
- );
86
- } );
87
- } );
88
-
89
- it( 'can only be inserted once', async () => {
90
- await insertBlockDontWaitForInsertClose( block.name );
91
- expect( await getAllBlocks() ).toHaveLength( 1 );
92
- } );
93
-
94
- it( 'renders without crashing', async () => {
95
- await expect( page ).toRenderBlock( block );
96
- await expect( page ).toRenderBlock( filledCartBlock );
97
- await expect( page ).toRenderBlock( emptyCartBlock );
98
- } );
99
-
100
- it( 'shows empty cart when changing the view', async () => {
101
- await page.waitForSelector( block.class ).catch( () => {
102
- throw new Error(
103
- `Could not find an element with class ${ block.class } - the block probably did not load correctly.`
104
- );
105
- } );
106
- await selectBlockByName( block.slug );
107
- await clickBlockToolbarButton( 'Switch view', 'ariaLabel' );
108
- const emptyCartButton = await page.waitForXPath(
109
- `//button[contains(@class,'components-dropdown-menu__menu-item')]//span[contains(text(), 'Empty Cart')]`
110
- );
111
- // Clicks the element by running the JavaScript HTMLElement.click() method on the given element in the
112
- // browser context, which fires a click event. It doesn't scroll the page or move the mouse and works
113
- // even if the element is off-screen.
114
- await emptyCartButton.evaluate( ( b ) => b.click() );
115
-
116
- await expect( page ).not.toMatchElement(
117
- `${ emptyCartBlock.class }[hidden]`
118
- );
119
- await expect( page ).toMatchElement(
120
- `${ filledCartBlock.class }[hidden]`
121
- );
122
-
123
- await selectBlockByName( block.slug );
124
- await clickBlockToolbarButton( 'Switch view', 'ariaLabel' );
125
- const filledCartButton = await page.waitForXPath(
126
- `//button[contains(@class,'components-dropdown-menu__menu-item')]//span[contains(text(), 'Filled Cart')]`
127
- );
128
- await filledCartButton.evaluate( ( b ) => b.click() );
129
-
130
- await expect( page ).toMatchElement(
131
- `${ emptyCartBlock.class }[hidden]`
132
- );
133
- await expect( page ).not.toMatchElement(
134
- `${ filledCartBlock.class }[hidden]`
135
- );
136
- } );
137
-
138
- describe( 'attributes', () => {
139
- beforeEach( async () => {
140
- await openDocumentSettingsSidebar();
141
- await selectBlockByName(
142
- 'woocommerce/cart-order-summary-block'
143
- );
144
- } );
145
-
146
- it( 'can toggle Shipping calculator', async () => {
147
- const selector = `${ block.class } .wc-block-components-totals-shipping__change-address-button`;
148
- const toggleLabel = await findLabelWithText(
149
- 'Shipping calculator'
150
- );
151
- await expect( toggleLabel ).toToggleElement( selector );
152
- } );
153
- } );
154
- } );
155
- } );
156
-
157
- describe( 'in widget editor', () => {
158
- it( "can't be inserted in a widget area", async () => {
159
- await merchant.login();
160
- await openWidgetEditor();
161
- await closeModalIfExists();
162
- await openWidgetsEditorBlockInserter();
163
- await searchForBlock( block.name );
164
- const cartButton = await page.$x(
165
- `//button//span[text()='${ block.name }']`
166
- );
167
-
168
- // This one match is the Cart widget.
169
- expect( cartButton ).toHaveLength( 1 );
170
- } );
171
- } );
172
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/checkout.test.js DELETED
@@ -1,196 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import {
5
- getAllBlocks,
6
- openDocumentSettingsSidebar,
7
- switchUserToAdmin,
8
- } from '@wordpress/e2e-test-utils';
9
- import {
10
- findLabelWithText,
11
- visitBlockPage,
12
- selectBlockByName,
13
- } from '@woocommerce/blocks-test-utils';
14
- import { merchant } from '@woocommerce/e2e-utils';
15
-
16
- import {
17
- searchForBlock,
18
- insertBlockDontWaitForInsertClose,
19
- openWidgetEditor,
20
- closeModalIfExists,
21
- openWidgetsEditorBlockInserter,
22
- closeInserter,
23
- } from '../../utils.js';
24
-
25
- const block = {
26
- name: 'Checkout',
27
- slug: 'woocommerce/checkout',
28
- class: '.wp-block-woocommerce-checkout',
29
- };
30
-
31
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE < 2 ) {
32
- // eslint-disable-next-line jest/no-focused-tests
33
- test.only( `skipping ${ block.name } tests`, () => {} );
34
- }
35
-
36
- describe( `${ block.name } Block`, () => {
37
- describe( 'in page editor', () => {
38
- describe( `before compatibility notice is dismissed`, () => {
39
- beforeAll( async () => {
40
- // make sure CartCheckoutCompatibilityNotice will appear
41
- await page.evaluate( () => {
42
- localStorage.removeItem(
43
- 'wc-blocks_dismissed_compatibility_notices'
44
- );
45
- } );
46
- await visitBlockPage( `${ block.name } Block` );
47
- } );
48
-
49
- it( 'shows compatibility notice', async () => {
50
- const compatibilityNoticeTitle = await page.$x(
51
- `//h1[contains(text(), 'Compatibility notice')]`
52
- );
53
- expect( compatibilityNoticeTitle.length ).toBe( 1 );
54
- } );
55
- } );
56
-
57
- describe( 'after compatibility notice is dismissed', () => {
58
- beforeAll( async () => {
59
- await page.evaluate( () => {
60
- localStorage.setItem(
61
- 'wc-blocks_dismissed_compatibility_notices',
62
- '["checkout"]'
63
- );
64
- } );
65
- await switchUserToAdmin();
66
- await visitBlockPage( `${ block.name } Block` );
67
- } );
68
- afterAll( async () => {
69
- await page.evaluate( () => {
70
- localStorage.removeItem(
71
- 'wc-blocks_dismissed_compatibility_notices'
72
- );
73
- } );
74
- } );
75
-
76
- it( 'can only be inserted once', async () => {
77
- await insertBlockDontWaitForInsertClose( block.name );
78
- await closeInserter();
79
- expect( await getAllBlocks() ).toHaveLength( 1 );
80
- } );
81
-
82
- it( 'renders without crashing', async () => {
83
- await expect( page ).toRenderBlock( block );
84
- } );
85
-
86
- describe( 'attributes', () => {
87
- beforeEach( async () => {
88
- await openDocumentSettingsSidebar();
89
- await selectBlockByName( block.slug );
90
- } );
91
-
92
- it( 'can enable dark mode inputs', async () => {
93
- const toggleLabel = await findLabelWithText(
94
- 'Dark mode inputs'
95
- );
96
- await toggleLabel.click();
97
-
98
- await expect( page ).toMatchElement(
99
- `.wc-block-checkout.has-dark-controls`
100
- );
101
-
102
- await toggleLabel.click();
103
-
104
- await expect( page ).not.toMatchElement(
105
- `.wc-block-checkout.has-dark-controls`
106
- );
107
- } );
108
- } );
109
-
110
- describe( 'shipping address block attributes', () => {
111
- beforeEach( async () => {
112
- await openDocumentSettingsSidebar();
113
- await selectBlockByName(
114
- 'woocommerce/checkout-shipping-address-block'
115
- );
116
- } );
117
-
118
- describe( 'Company input', () => {
119
- const selector = `${ block.class } #shipping-company`;
120
-
121
- it( 'visibility can be toggled', async () => {
122
- await expect( 'Company' ).toToggleElement( selector );
123
- } );
124
-
125
- it( 'required attribute can be toggled', async () => {
126
- // Company is disabled by default, so first we need to enable it.
127
- const toggleLabel = await findLabelWithText(
128
- 'Company'
129
- );
130
- await toggleLabel.click();
131
- await expect(
132
- 'Require company name?'
133
- ).toToggleRequiredAttrOf( selector );
134
- } );
135
- } );
136
-
137
- describe( 'Apartment input', () => {
138
- it( 'visibility can be toggled', async () => {
139
- const selector = `${ block.class } #shipping-address_2`;
140
- await expect(
141
- 'Apartment, suite, etc.'
142
- ).toToggleElement( selector );
143
- } );
144
- } );
145
-
146
- describe( 'Phone input', () => {
147
- const selector = `${ block.class } #shipping-phone`;
148
-
149
- it( 'visibility can be toggled', async () => {
150
- await expect( 'Phone' ).toToggleElement( selector );
151
- } );
152
-
153
- it( 'required attribute can be toggled', async () => {
154
- await expect(
155
- 'Require phone number?'
156
- ).toToggleRequiredAttrOf( selector );
157
- } );
158
- } );
159
- } );
160
-
161
- describe( 'action block attributes', () => {
162
- beforeEach( async () => {
163
- await openDocumentSettingsSidebar();
164
- await selectBlockByName(
165
- 'woocommerce/checkout-actions-block'
166
- );
167
- } );
168
-
169
- describe( 'Return to cart link', () => {
170
- it( 'visibility can be toggled', async () => {
171
- const selector = `${ block.class } .wc-block-components-checkout-return-to-cart-button`;
172
- const toggleLabel = await findLabelWithText(
173
- 'Show a "Return to Cart" link'
174
- );
175
- await expect( toggleLabel ).toToggleElement( selector );
176
- } );
177
- } );
178
- } );
179
- } );
180
- } );
181
-
182
- describe( 'in widget editor', () => {
183
- it( "can't be inserted in a widget area", async () => {
184
- await merchant.login();
185
- await openWidgetEditor();
186
- await closeModalIfExists();
187
- await openWidgetsEditorBlockInserter();
188
- await searchForBlock( block.name );
189
- const checkoutButton = await page.$x(
190
- `//button//span[text()='${ block.name }']`
191
- );
192
-
193
- expect( checkoutButton ).toHaveLength( 0 );
194
- } );
195
- } );
196
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/featured-category.test.js DELETED
@@ -1,30 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import { getAllBlocks, switchUserToAdmin } from '@wordpress/e2e-test-utils';
5
-
6
- import { visitBlockPage } from '@woocommerce/blocks-test-utils';
7
-
8
- import { insertBlockDontWaitForInsertClose } from '../../utils.js';
9
-
10
- const block = {
11
- name: 'Featured Category',
12
- slug: 'woocommerce/featured-category',
13
- class: '.wc-block-featured-category',
14
- };
15
-
16
- describe( `${ block.name } Block`, () => {
17
- beforeAll( async () => {
18
- await switchUserToAdmin();
19
- await visitBlockPage( `${ block.name } Block` );
20
- } );
21
-
22
- it( 'can be inserted more than once', async () => {
23
- await insertBlockDontWaitForInsertClose( block.name );
24
- expect( await getAllBlocks() ).toHaveLength( 2 );
25
- } );
26
-
27
- it( 'renders without crashing', async () => {
28
- await expect( page ).toRenderBlock( block );
29
- } );
30
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/featured-product.test.js DELETED
@@ -1,30 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import { getAllBlocks, switchUserToAdmin } from '@wordpress/e2e-test-utils';
5
-
6
- import { visitBlockPage } from '@woocommerce/blocks-test-utils';
7
-
8
- import { insertBlockDontWaitForInsertClose } from '../../utils.js';
9
-
10
- const block = {
11
- name: 'Featured Product',
12
- slug: 'woocommerce/featured-product',
13
- class: '.wc-block-featured-product',
14
- };
15
-
16
- describe( `${ block.name } Block`, () => {
17
- beforeAll( async () => {
18
- await switchUserToAdmin();
19
- await visitBlockPage( `${ block.name } Block` );
20
- } );
21
-
22
- it( 'can be inserted more than once', async () => {
23
- await insertBlockDontWaitForInsertClose( block.name );
24
- expect( await getAllBlocks() ).toHaveLength( 2 );
25
- } );
26
-
27
- it( 'renders without crashing', async () => {
28
- await expect( page ).toRenderBlock( block );
29
- } );
30
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/filter-products-by-stock.test.js DELETED
@@ -1,60 +0,0 @@
1
- /**
2
- * Internal dependencies
3
- */
4
- import { closeInserter, insertBlockDontWaitForInsertClose } from '../../utils';
5
- import { findLabelWithText } from '../../../utils';
6
-
7
- /**
8
- * External dependencies
9
- */
10
- import {
11
- switchUserToAdmin,
12
- clickButton,
13
- getAllBlocks,
14
- openDocumentSettingsSidebar,
15
- } from '@wordpress/e2e-test-utils';
16
- import { visitBlockPage } from '@woocommerce/blocks-test-utils';
17
-
18
- const block = {
19
- name: 'Filter Products by Stock',
20
- slug: 'woocommerce/stock-filter',
21
- class: '.wc-block-stock-filter',
22
- };
23
-
24
- describe( `${ block.name } Block`, () => {
25
- beforeAll( async () => {
26
- await switchUserToAdmin();
27
- await visitBlockPage( `${ block.name } Block` );
28
- } );
29
-
30
- it( 'renders without crashing', async () => {
31
- await expect( page ).toRenderBlock( block );
32
- } );
33
-
34
- it( 'can only be inserted once', async () => {
35
- await insertBlockDontWaitForInsertClose( block.name );
36
- await closeInserter();
37
- expect( await getAllBlocks() ).toHaveLength( 1 );
38
- } );
39
-
40
- describe( 'attributes', () => {
41
- beforeEach( async () => {
42
- await openDocumentSettingsSidebar();
43
- await page.click( block.class );
44
- } );
45
-
46
- it( 'product count can be toggled', async () => {
47
- const toggleLabel = await findLabelWithText( 'Product count' );
48
- await expect( toggleLabel ).toToggleElement(
49
- `${ block.class } .wc-filter-element-label-list-count`
50
- );
51
- } );
52
-
53
- it( 'filter button can be toggled', async () => {
54
- const toggleLabel = await findLabelWithText( 'Filter button' );
55
- await expect( toggleLabel ).toToggleElement(
56
- `${ block.class } .wc-block-filter-submit-button`
57
- );
58
- } );
59
- } );
60
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/handpicked-products.test.js DELETED
@@ -1,30 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import { getAllBlocks, switchUserToAdmin } from '@wordpress/e2e-test-utils';
5
-
6
- import { visitBlockPage } from '@woocommerce/blocks-test-utils';
7
-
8
- import { insertBlockDontWaitForInsertClose } from '../../utils.js';
9
-
10
- const block = {
11
- name: 'Hand-picked Products',
12
- slug: 'woocommerce/handpicked-products',
13
- class: '.wc-block-handpicked-products',
14
- };
15
-
16
- describe( `${ block.name } Block`, () => {
17
- beforeAll( async () => {
18
- await switchUserToAdmin();
19
- await visitBlockPage( `${ block.name } Block` );
20
- } );
21
-
22
- it( 'renders without crashing', async () => {
23
- await expect( page ).toRenderBlock( block );
24
- } );
25
-
26
- it( 'can be inserted more than once', async () => {
27
- await insertBlockDontWaitForInsertClose( block.name );
28
- expect( await getAllBlocks() ).toHaveLength( 2 );
29
- } );
30
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/mini-cart.test.js DELETED
@@ -1,71 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import { switchUserToAdmin, getAllBlocks } from '@wordpress/e2e-test-utils';
5
- import { visitBlockPage } from '@woocommerce/blocks-test-utils';
6
-
7
- /**
8
- * Internal dependencies
9
- */
10
- import { insertBlockDontWaitForInsertClose } from '../../utils.js';
11
-
12
- const block = {
13
- name: 'Mini Cart',
14
- slug: 'woocommerce/mini-cart',
15
- class: '.wc-block-mini-cart',
16
- };
17
-
18
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE < 3 ) {
19
- // eslint-disable-next-line jest/no-focused-tests
20
- test.only( `skipping ${ block.name } tests`, () => {} );
21
- }
22
-
23
- describe( `${ block.name } Block`, () => {
24
- describe( `before compatibility notice is dismissed`, () => {
25
- beforeAll( async () => {
26
- // make sure CartCheckoutCompatibilityNotice will appear
27
- await page.evaluate( () => {
28
- localStorage.removeItem(
29
- 'wc-blocks_dismissed_compatibility_notices'
30
- );
31
- } );
32
- await visitBlockPage( `${ block.name } Block` );
33
- } );
34
-
35
- it( 'shows compatibility notice', async () => {
36
- const compatibilityNoticeTitle = await page.$x(
37
- `//h1[contains(text(), 'Compatibility notice')]`
38
- );
39
- expect( compatibilityNoticeTitle.length ).toBe( 1 );
40
- } );
41
- } );
42
-
43
- describe( 'after compatibility notice is dismissed', () => {
44
- beforeAll( async () => {
45
- await page.evaluate( () => {
46
- localStorage.setItem(
47
- 'wc-blocks_dismissed_compatibility_notices',
48
- '["mini-cart"]'
49
- );
50
- } );
51
- await switchUserToAdmin();
52
- await visitBlockPage( `${ block.name } Block` );
53
- } );
54
-
55
- afterAll( async () => {
56
- await page.evaluate( () => {
57
- localStorage.removeItem(
58
- 'wc-blocks_dismissed_compatibility_notices'
59
- );
60
- } );
61
- } );
62
- it( 'can only be inserted once', async () => {
63
- await insertBlockDontWaitForInsertClose( block.name );
64
- expect( await getAllBlocks() ).toHaveLength( 1 );
65
- } );
66
-
67
- it( 'renders without crashing', async () => {
68
- await expect( page ).toRenderBlock( block );
69
- } );
70
- } );
71
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/price-filter.test.js DELETED
@@ -1,112 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import {
5
- openDocumentSettingsSidebar,
6
- switchUserToAdmin,
7
- getAllBlocks,
8
- getEditedPostContent,
9
- } from '@wordpress/e2e-test-utils';
10
- import {
11
- visitBlockPage,
12
- selectBlockByName,
13
- } from '@woocommerce/blocks-test-utils';
14
-
15
- /**
16
- * Internal dependencies
17
- */
18
- import { insertBlockDontWaitForInsertClose } from '../../utils.js';
19
-
20
- const block = {
21
- name: 'Filter Products by Price',
22
- slug: 'woocommerce/price-filter',
23
- class: '.wp-block-woocommerce-price-filter',
24
- };
25
-
26
- describe( `${ block.name } Block`, () => {
27
- describe( 'after compatibility notice is dismissed', () => {
28
- beforeAll( async () => {
29
- await switchUserToAdmin();
30
- await visitBlockPage( `${ block.name } Block` );
31
- } );
32
-
33
- it( 'can only be inserted once', async () => {
34
- await insertBlockDontWaitForInsertClose( block.name );
35
- expect( await getAllBlocks() ).toHaveLength( 1 );
36
- } );
37
-
38
- it( 'renders without crashing', async () => {
39
- await expect( page ).toRenderBlock( block );
40
- } );
41
-
42
- describe( 'Attributes', () => {
43
- beforeEach( async () => {
44
- await openDocumentSettingsSidebar();
45
- await selectBlockByName( block.slug );
46
- } );
47
-
48
- it( "allows changing the block's title", async () => {
49
- const textareaSelector = `.wp-block[data-type="${ block.slug }"] textarea.wc-block-editor-components-title`;
50
- await expect( page ).toFill( textareaSelector, 'New Title' );
51
- await page.click( block.class );
52
-
53
- // Change title to h6.
54
- await page.click(
55
- '.components-toolbar button[aria-label="Heading 6"]'
56
- );
57
- await expect(
58
- page
59
- ).toMatchElement(
60
- `.wp-block[data-type="${ block.slug }"] h6 textarea`,
61
- { text: 'New Title' }
62
- );
63
- await expect( page ).toFill(
64
- textareaSelector,
65
- 'Filter by price'
66
- );
67
- // Change title to h3.
68
- await page.click(
69
- '.components-toolbar button[aria-label="Heading 3"]'
70
- );
71
- await expect(
72
- page
73
- ).not.toMatchElement(
74
- `.wp-block[data-type="${ block.slug }"] h6 textarea`,
75
- { text: 'New Title' }
76
- );
77
- } );
78
-
79
- it( 'allows changing the Display Style', async () => {
80
- // Turn the display style to Price Range: Text
81
- await expect( page ).toClick( 'button', { text: 'Text' } );
82
-
83
- await page.waitForSelector(
84
- '.wc-block-price-filter__range-text'
85
- );
86
- await expect( page ).toMatchElement(
87
- '.wc-block-price-filter__range-text'
88
- );
89
- // Turn the display style to Price Range: Editable
90
- await expect( page ).toClick( 'button', {
91
- text: 'Editable',
92
- } );
93
-
94
- await expect( page ).not.toMatchElement(
95
- '.wc-block-price-filter__range-text'
96
- );
97
- } );
98
-
99
- it( 'allows you to toggle go button', async () => {
100
- await expect( page ).toClick( 'label', {
101
- text: 'Filter button',
102
- } );
103
- await expect( page ).toMatchElement(
104
- 'button.wc-block-filter-submit-button.wc-block-price-filter__button'
105
- );
106
- await expect( page ).toClick( 'label', {
107
- text: 'Filter button',
108
- } );
109
- } );
110
- } );
111
- } );
112
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/product-best-sellers.test.js DELETED
@@ -1,30 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import { getAllBlocks, switchUserToAdmin } from '@wordpress/e2e-test-utils';
5
-
6
- import { visitBlockPage } from '@woocommerce/blocks-test-utils';
7
-
8
- import { insertBlockDontWaitForInsertClose } from '../../utils.js';
9
-
10
- const block = {
11
- name: 'Best Selling Products',
12
- slug: 'woocommerce/product-best-sellers',
13
- class: '.wc-block-product-best-sellers',
14
- };
15
-
16
- describe( `${ block.name } Block`, () => {
17
- beforeAll( async () => {
18
- await switchUserToAdmin();
19
- await visitBlockPage( `${ block.name } Block` );
20
- } );
21
-
22
- it( 'renders without crashing', async () => {
23
- await expect( page ).toRenderBlock( block );
24
- } );
25
-
26
- it( 'can be inserted more than once', async () => {
27
- await insertBlockDontWaitForInsertClose( block.name );
28
- expect( await getAllBlocks() ).toHaveLength( 2 );
29
- } );
30
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/product-categories.test.js DELETED
@@ -1,30 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import { getAllBlocks, switchUserToAdmin } from '@wordpress/e2e-test-utils';
5
-
6
- import { visitBlockPage } from '@woocommerce/blocks-test-utils';
7
-
8
- import { insertBlockDontWaitForInsertClose } from '../../utils.js';
9
-
10
- const block = {
11
- name: 'Product Categories List',
12
- slug: 'woocommerce/product-categories',
13
- class: '.wc-block-product-categories',
14
- };
15
-
16
- describe( `${ block.name } Block`, () => {
17
- beforeAll( async () => {
18
- await switchUserToAdmin();
19
- await visitBlockPage( `${ block.name } Block` );
20
- } );
21
-
22
- it( 'can be inserted more than once', async () => {
23
- await insertBlockDontWaitForInsertClose( block.name );
24
- expect( await getAllBlocks() ).toHaveLength( 2 );
25
- } );
26
-
27
- it( 'renders without crashing', async () => {
28
- await expect( page ).toRenderBlock( block );
29
- } );
30
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/product-category.test.js DELETED
@@ -1,30 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import { getAllBlocks, switchUserToAdmin } from '@wordpress/e2e-test-utils';
5
-
6
- import { visitBlockPage } from '@woocommerce/blocks-test-utils';
7
-
8
- import { insertBlockDontWaitForInsertClose } from '../../utils.js';
9
-
10
- const block = {
11
- name: 'Products by Category',
12
- slug: 'woocommerce/product-category',
13
- class: '.wc-block-products-category',
14
- };
15
-
16
- describe( `${ block.name } Block`, () => {
17
- beforeAll( async () => {
18
- await switchUserToAdmin();
19
- await visitBlockPage( `${ block.name } Block` );
20
- } );
21
-
22
- it( 'can be inserted more than once', async () => {
23
- await insertBlockDontWaitForInsertClose( block.name );
24
- expect( await getAllBlocks() ).toHaveLength( 2 );
25
- } );
26
-
27
- it( 'renders without crashing', async () => {
28
- await expect( page ).toRenderBlock( block );
29
- } );
30
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/product-new.test.js DELETED
@@ -1,30 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import { getAllBlocks, switchUserToAdmin } from '@wordpress/e2e-test-utils';
5
-
6
- import { visitBlockPage } from '@woocommerce/blocks-test-utils';
7
-
8
- import { insertBlockDontWaitForInsertClose } from '../../utils.js';
9
-
10
- const block = {
11
- name: 'Newest Products',
12
- slug: 'woocommerce/product-new',
13
- class: '.wc-block-product-new',
14
- };
15
-
16
- describe( `${ block.name } Block`, () => {
17
- beforeAll( async () => {
18
- await switchUserToAdmin();
19
- await visitBlockPage( `${ block.name } Block` );
20
- } );
21
-
22
- it( 'renders without crashing', async () => {
23
- await expect( page ).toRenderBlock( block );
24
- } );
25
-
26
- it( 'can be inserted more than once', async () => {
27
- await insertBlockDontWaitForInsertClose( block.name );
28
- expect( await getAllBlocks() ).toHaveLength( 2 );
29
- } );
30
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/product-on-sale.test.js DELETED
@@ -1,30 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import { getAllBlocks, switchUserToAdmin } from '@wordpress/e2e-test-utils';
5
-
6
- import { visitBlockPage } from '@woocommerce/blocks-test-utils';
7
-
8
- import { insertBlockDontWaitForInsertClose } from '../../utils.js';
9
-
10
- const block = {
11
- name: 'On Sale Products',
12
- slug: 'woocommerce/product-on-sale',
13
- class: '.wc-block-product-on-sale',
14
- };
15
-
16
- describe( `${ block.name } Block`, () => {
17
- beforeAll( async () => {
18
- await switchUserToAdmin();
19
- await visitBlockPage( `${ block.name } Block` );
20
- } );
21
-
22
- it( 'can be inserted more than once', async () => {
23
- await insertBlockDontWaitForInsertClose( block.name );
24
- expect( await getAllBlocks() ).toHaveLength( 2 );
25
- } );
26
-
27
- it( 'renders without crashing', async () => {
28
- await expect( page ).toRenderBlock( block );
29
- } );
30
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/product-search.test.js DELETED
@@ -1,63 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import {
5
- switchUserToAdmin,
6
- getEditedPostContent,
7
- openDocumentSettingsSidebar,
8
- } from '@wordpress/e2e-test-utils';
9
- import { clearAndFillInput } from '@woocommerce/e2e-utils';
10
- import {
11
- findLabelWithText,
12
- visitBlockPage,
13
- } from '@woocommerce/blocks-test-utils';
14
-
15
- const block = {
16
- name: 'Product Search',
17
- slug: 'woocommerce/product-search',
18
- class: '.wc-block-product-search',
19
- };
20
-
21
- describe( `${ block.name } Block`, () => {
22
- beforeAll( async () => {
23
- await switchUserToAdmin();
24
- await visitBlockPage( `${ block.name } Block` );
25
- } );
26
-
27
- it( 'renders without crashing', async () => {
28
- await expect( page ).toRenderBlock( block );
29
- } );
30
-
31
- it( 'can toggle field label', async () => {
32
- await openDocumentSettingsSidebar();
33
- await page.click( block.class );
34
- const selector = `${ block.class } .wc-block-product-search__label`;
35
- const toggleLabel = await findLabelWithText(
36
- 'Show search field label'
37
- );
38
- await expect( toggleLabel ).toToggleElement( selector );
39
- } );
40
-
41
- it( 'can change field labels in editor', async () => {
42
- await expect( page ).toFill(
43
- 'textarea.wc-block-product-search__label',
44
- 'I am a new label'
45
- );
46
-
47
- await expect( page ).toFill(
48
- '.wc-block-product-search__field input',
49
- 'I am a new placeholder'
50
- );
51
-
52
- await clearAndFillInput(
53
- 'textarea.wc-block-product-search__label',
54
- 'The Label'
55
- );
56
- await clearAndFillInput(
57
- '.wc-block-product-search__field input',
58
- 'The Placeholder'
59
- );
60
-
61
- expect( await getEditedPostContent() ).toMatchSnapshot();
62
- } );
63
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/product-tag.test.js DELETED
@@ -1,30 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import { getAllBlocks, switchUserToAdmin } from '@wordpress/e2e-test-utils';
5
-
6
- import { visitBlockPage } from '@woocommerce/blocks-test-utils';
7
-
8
- import { insertBlockDontWaitForInsertClose } from '../../utils.js';
9
-
10
- const block = {
11
- name: 'Products by Tag',
12
- slug: 'woocommerce/product-tag',
13
- class: '.wc-block-product-tag',
14
- };
15
-
16
- describe( `${ block.name } Block`, () => {
17
- beforeAll( async () => {
18
- await switchUserToAdmin();
19
- await visitBlockPage( `${ block.name } Block` );
20
- } );
21
-
22
- it( 'can be inserted more than once', async () => {
23
- await insertBlockDontWaitForInsertClose( block.name );
24
- expect( await getAllBlocks() ).toHaveLength( 2 );
25
- } );
26
-
27
- it( 'renders without crashing', async () => {
28
- await expect( page ).toRenderBlock( block );
29
- } );
30
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/product-top-rated.test.js DELETED
@@ -1,30 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import { getAllBlocks, switchUserToAdmin } from '@wordpress/e2e-test-utils';
5
-
6
- import { visitBlockPage } from '@woocommerce/blocks-test-utils';
7
-
8
- import { insertBlockDontWaitForInsertClose } from '../../utils.js';
9
-
10
- const block = {
11
- name: 'Top Rated Products',
12
- slug: 'woocommerce/product-top-rated',
13
- class: '.wc-block-product-top-rated',
14
- };
15
-
16
- describe( `${ block.name } Block`, () => {
17
- beforeAll( async () => {
18
- await switchUserToAdmin();
19
- await visitBlockPage( `${ block.name } Block` );
20
- } );
21
-
22
- it( 'renders without crashing', async () => {
23
- await expect( page ).toRenderBlock( block );
24
- } );
25
-
26
- it( 'can be inserted more than once', async () => {
27
- await insertBlockDontWaitForInsertClose( block.name );
28
- expect( await getAllBlocks() ).toHaveLength( 2 );
29
- } );
30
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/products-by-attribute.test.js DELETED
@@ -1,30 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import { getAllBlocks, switchUserToAdmin } from '@wordpress/e2e-test-utils';
5
-
6
- import { visitBlockPage } from '@woocommerce/blocks-test-utils';
7
-
8
- import { insertBlockDontWaitForInsertClose } from '../../utils.js';
9
-
10
- const block = {
11
- name: 'Products by Attribute',
12
- slug: 'woocommerce/products-by-attribute',
13
- class: '.wc-block-products-by-attribute',
14
- };
15
-
16
- describe( `${ block.name } Block`, () => {
17
- beforeAll( async () => {
18
- await switchUserToAdmin();
19
- await visitBlockPage( `${ block.name } Block` );
20
- } );
21
-
22
- it( 'can be inserted more than once', async () => {
23
- await insertBlockDontWaitForInsertClose( block.name );
24
- expect( await getAllBlocks() ).toHaveLength( 2 );
25
- } );
26
-
27
- it( 'renders without crashing', async () => {
28
- await expect( page ).toRenderBlock( block );
29
- } );
30
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/reviews-by-category.test.js DELETED
@@ -1,48 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import { switchUserToAdmin, clickButton } from '@wordpress/e2e-test-utils';
5
- import { visitBlockPage } from '@woocommerce/blocks-test-utils';
6
-
7
- const block = {
8
- name: 'Reviews by Category',
9
- slug: 'woocommerce/reviews-by-category',
10
- class: '.wc-block-reviews-by-category',
11
- };
12
-
13
- describe( `${ block.name } Block`, () => {
14
- beforeAll( async () => {
15
- await switchUserToAdmin();
16
- await visitBlockPage( `${ block.name } Block` );
17
- } );
18
-
19
- it( 'renders without crashing', async () => {
20
- await expect( page ).toRenderBlock( block );
21
- } );
22
-
23
- it( 'shows category selector', async () => {
24
- await expect( page ).toMatchElement(
25
- `${ block.class } .woocommerce-search-list`
26
- );
27
- } );
28
-
29
- it( 'can select a category and show reviews', async () => {
30
- // we focus on the block
31
- await page.click( block.class );
32
- await page.waitForSelector(
33
- `${ block.class } .woocommerce-search-list__item`
34
- );
35
- await page.click( `${ block.class } .woocommerce-search-list__item` );
36
- await clickButton( 'Done' );
37
- // Selected.
38
- await page.waitForSelector(
39
- '.wc-block-review-list .wc-block-review-list-item__item:not(.is-loading)'
40
- );
41
- expect(
42
- await page.$$eval(
43
- '.wc-block-review-list .wc-block-review-list-item__item',
44
- ( reviews ) => reviews.length
45
- )
46
- ).toBeGreaterThanOrEqual( 6 ); // Fixture data has three reviews per product, and there are multiple products.
47
- } );
48
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/reviews-by-product.test.js DELETED
@@ -1,62 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import { switchUserToAdmin, clickButton } from '@wordpress/e2e-test-utils';
5
- import { visitBlockPage } from '@woocommerce/blocks-test-utils';
6
-
7
- const block = {
8
- name: 'Reviews by Product',
9
- slug: 'woocommerce/reviews-by-product',
10
- class: '.wc-block-reviews-by-product',
11
- };
12
-
13
- describe( `${ block.name } Block`, () => {
14
- beforeAll( async () => {
15
- await switchUserToAdmin();
16
- await visitBlockPage( `${ block.name } Block` );
17
- } );
18
-
19
- it( 'renders without crashing', async () => {
20
- await expect( page ).toRenderBlock( block );
21
- } );
22
-
23
- it( 'shows product selector', async () => {
24
- await expect( page ).toMatchElement(
25
- `${ block.class } .woocommerce-search-list`
26
- );
27
- } );
28
-
29
- it( 'can select a product and show reviews', async () => {
30
- // we focus on the block
31
- await page.click( block.class );
32
- await page.waitForSelector(
33
- `${ block.class } .woocommerce-search-list__item`
34
- );
35
- do {
36
- await page.click(
37
- `${ block.class } .woocommerce-search-list__item`
38
- );
39
- } while (
40
- await page.evaluate(
41
- ( blockClass ) =>
42
- document
43
- .querySelector(
44
- `${ blockClass } .woocommerce-search-list__item`
45
- )
46
- .getAttribute( 'aria-checked' ) === 'false',
47
- block.class
48
- )
49
- );
50
- await clickButton( 'Done' );
51
- // Selected.
52
- await page.waitForSelector(
53
- '.wc-block-review-list .wc-block-review-list-item__item:not(.is-loading)'
54
- );
55
- expect(
56
- await page.$$eval(
57
- '.wc-block-review-list .wc-block-review-list-item__item',
58
- ( reviews ) => reviews.length
59
- )
60
- ).toBeGreaterThanOrEqual( 3 ); // Fixture data has three reviews per product.
61
- } );
62
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/backend/single-product.test.js DELETED
@@ -1,32 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import { getAllBlocks, switchUserToAdmin } from '@wordpress/e2e-test-utils';
5
- import { insertBlockDontWaitForInsertClose } from '../../utils.js';
6
- import { visitBlockPage } from '@woocommerce/blocks-test-utils';
7
-
8
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE < 3 )
9
- // eslint-disable-next-line jest/no-focused-tests
10
- test.only( 'skipping all other things', () => {} );
11
-
12
- const block = {
13
- name: 'Single Product',
14
- slug: 'woocommerce/single-product',
15
- class: '.wc-block-single-product',
16
- };
17
-
18
- describe( `${ block.name } Block`, () => {
19
- beforeAll( async () => {
20
- await switchUserToAdmin();
21
- await visitBlockPage( `${ block.name } Block` );
22
- } );
23
-
24
- it( 'can be inserted more than once', async () => {
25
- await insertBlockDontWaitForInsertClose( block.name );
26
- expect( await getAllBlocks() ).toHaveLength( 2 );
27
- } );
28
-
29
- it( 'renders without crashing', async () => {
30
- await expect( page ).toRenderBlock( block );
31
- } );
32
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/specs/frontend/checkout.test.js DELETED
@@ -1,163 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import {
5
- merchant,
6
- setCheckbox,
7
- settingsPageSaveChanges,
8
- verifyCheckboxIsSet,
9
- } from '@woocommerce/e2e-utils';
10
-
11
- /**
12
- * Internal dependencies
13
- */
14
- import {
15
- getNormalPagePermalink,
16
- scrollTo,
17
- shopper,
18
- visitPostOfType,
19
- } from '../../../utils';
20
-
21
- const block = {
22
- name: 'Checkout',
23
- };
24
-
25
- const productPrice = 21.99;
26
- const simpleProductName = 'Woo Single #1';
27
- const singleProductPrice = `$${ productPrice }`;
28
- const twoProductPrice = `$${ productPrice * 2 }`;
29
-
30
- if ( process.env.WOOCOMMERCE_BLOCKS_PHASE < 2 )
31
- // eslint-disable-next-line jest/no-focused-tests
32
- test.only( `skipping ${ block.name } tests`, () => {} );
33
-
34
- describe( `${ block.name } Block (frontend)`, () => {
35
- let productPermalink;
36
-
37
- beforeAll( async () => {
38
- // prevent CartCheckoutCompatibilityNotice from appearing
39
- await page.evaluate( () => {
40
- localStorage.setItem(
41
- 'wc-blocks_dismissed_compatibility_notices',
42
- '["checkout"]'
43
- );
44
- } );
45
- await merchant.login();
46
-
47
- // Go to general settings page
48
- await merchant.openSettings( 'general' );
49
-
50
- // Set base location with state CA.
51
- await expect( page ).toSelect(
52
- 'select[name="woocommerce_default_country"]',
53
- 'United States (US) — California'
54
- );
55
- // Sell to all countries
56
- await expect( page ).toSelect(
57
- '#woocommerce_allowed_countries',
58
- 'Sell to all countries'
59
- );
60
- // Set currency to USD
61
- await expect( page ).toSelect(
62
- '#woocommerce_currency',
63
- 'United States (US) dollar ($)'
64
- );
65
- // Save
66
- await settingsPageSaveChanges();
67
-
68
- // Verify that settings have been saved
69
- await Promise.all( [
70
- expect( page ).toMatchElement( '#message', {
71
- text: 'Your settings have been saved.',
72
- } ),
73
- expect( page ).toMatchElement(
74
- 'select[name="woocommerce_default_country"]',
75
- {
76
- text: 'United States (US) — California',
77
- }
78
- ),
79
- expect( page ).toMatchElement( '#woocommerce_allowed_countries', {
80
- text: 'Sell to all countries',
81
- } ),
82
- expect( page ).toMatchElement( '#woocommerce_currency', {
83
- text: 'United States (US) dollar ($)',
84
- } ),
85
- ] );
86
-
87
- // Enable BACS payment method
88
- await merchant.openSettings( 'checkout', 'bacs' );
89
- await setCheckbox( '#woocommerce_bacs_enabled' );
90
- await settingsPageSaveChanges();
91
-
92
- // Verify that settings have been saved
93
- await verifyCheckboxIsSet( '#woocommerce_bacs_enabled' );
94
-
95
- // Enable COD payment method
96
- await merchant.openSettings( 'checkout', 'cod' );
97
- await setCheckbox( '#woocommerce_cod_enabled' );
98
- await settingsPageSaveChanges();
99
-
100
- // Verify that settings have been saved
101
- await verifyCheckboxIsSet( '#woocommerce_cod_enabled' );
102
-
103
- // Get product page permalink.
104
- await visitPostOfType( simpleProductName, 'product' );
105
- productPermalink = await getNormalPagePermalink();
106
-
107
- await merchant.logout();
108
- } );
109
-
110
- afterAll( async () => {
111
- // empty cart from shortcode page
112
- await shopper.goToCart();
113
- await shopper.removeFromCart( 'Woo Single #1' );
114
- await page.evaluate( () => {
115
- localStorage.removeItem(
116
- 'wc-blocks_dismissed_compatibility_notices'
117
- );
118
- } );
119
- } );
120
-
121
- it( 'should display an empty cart message when cart is empty', async () => {
122
- await shopper.goToCheckoutBlock();
123
- const html = await page.content();
124
-
125
- await page.waitForSelector( 'h1', { text: 'Checkout block' } );
126
- await page.waitForSelector( 'strong', { text: 'Your cart is empty!' } );
127
- } );
128
-
129
- it( 'allows customer to choose available payment methods', async () => {
130
- await page.goto( productPermalink );
131
- await shopper.addToCart();
132
- await shopper.goToCheckoutBlock();
133
-
134
- await shopper.productIsInCheckoutBlock(
135
- simpleProductName,
136
- `1`,
137
- singleProductPrice
138
- );
139
- await page.goBack( { waitUntil: 'networkidle2' } );
140
- await shopper.addToCart();
141
- await shopper.goToCheckoutBlock();
142
- await shopper.productIsInCheckoutBlock(
143
- simpleProductName,
144
- `2`,
145
- twoProductPrice
146
- );
147
-
148
- await scrollTo( '.wc-block-components-radio-control__input' );
149
-
150
- await expect( page ).toClick(
151
- '.wc-block-components-payment-method-label',
152
- {
153
- text: 'Direct bank transfer',
154
- }
155
- );
156
- await expect( page ).toClick(
157
- '.wc-block-components-payment-method-label',
158
- {
159
- text: 'Cash on delivery',
160
- }
161
- );
162
- } );
163
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/e2e/utils.js DELETED
@@ -1,82 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import {
5
- openGlobalBlockInserter,
6
- pressKeyWithModifier,
7
- } from '@wordpress/e2e-test-utils';
8
- import { WP_ADMIN_DASHBOARD } from '@woocommerce/e2e-utils';
9
-
10
- const INSERTER_SEARCH_SELECTOR =
11
- '.components-search-control__input,.block-editor-inserter__search input,.block-editor-inserter__search-input,input.block-editor-inserter__search';
12
-
13
- /**
14
- * Search for block in the global inserter.
15
- *
16
- * @see https://github.com/WordPress/gutenberg/blob/2356b2d3165acd0af980d52bc93fb1e42748bb25/packages/e2e-test-utils/src/inserter.js#L95
17
- *
18
- * @param {string} searchTerm The text to search the inserter for.
19
- */
20
- export async function searchForBlock( searchTerm ) {
21
- await page.waitForSelector( INSERTER_SEARCH_SELECTOR );
22
- await page.focus( INSERTER_SEARCH_SELECTOR );
23
- await pressKeyWithModifier( 'primary', 'a' );
24
- await page.keyboard.type( searchTerm );
25
- }
26
-
27
- /**
28
- * Opens the inserter, searches for the given term, then selects the first
29
- * result that appears.
30
- *
31
- * @param {string} searchTerm The text to search the inserter for.
32
- */
33
- export async function insertBlockDontWaitForInsertClose( searchTerm ) {
34
- await openGlobalBlockInserter();
35
- await searchForBlock( searchTerm );
36
- const insertButton = (
37
- await page.$x( `//button//span[text()='${ searchTerm }']` )
38
- )[ 0 ];
39
- await insertButton.click();
40
- }
41
-
42
- export const closeInserter = async () => {
43
- if (
44
- await page.evaluate( () => {
45
- return !! document.querySelector(
46
- '.edit-post-header [aria-label="Add block"]'
47
- );
48
- } )
49
- ) {
50
- await page.click( '.edit-post-header [aria-label="Add block"]' );
51
- return;
52
- }
53
- await page.click(
54
- '.edit-post-header [aria-label="Toggle block inserter"]'
55
- );
56
- };
57
-
58
- const WP_ADMIN_WIDGETS_EDITOR = WP_ADMIN_DASHBOARD + 'widgets.php';
59
-
60
- export const openWidgetEditor = async () => {
61
- await page.goto( WP_ADMIN_WIDGETS_EDITOR, {
62
- waitUntil: 'networkidle0',
63
- } );
64
- };
65
-
66
- export const closeModalIfExists = async () => {
67
- if (
68
- await page.evaluate( () => {
69
- return !! document.querySelector( '.components-modal__header' );
70
- } )
71
- ) {
72
- await page.click(
73
- '.components-modal__header [aria-label="Close dialog"]'
74
- );
75
- }
76
- };
77
-
78
- export const openWidgetsEditorBlockInserter = async () => {
79
- await page.click(
80
- '.edit-widgets-header [aria-label="Add block"],.edit-widgets-header [aria-label="Toggle block inserter"]'
81
- );
82
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/js/jest.config.json DELETED
@@ -1,55 +0,0 @@
1
- {
2
- "rootDir": "../../",
3
- "collectCoverageFrom": [
4
- "assets/js/**/*.js",
5
- "!**/node_modules/**",
6
- "!**/vendor/**",
7
- "!**/test/**"
8
- ],
9
- "moduleDirectories": [ "node_modules" ],
10
- "moduleNameMapper": {
11
- "@woocommerce/atomic-blocks": "assets/js/atomic/blocks",
12
- "@woocommerce/atomic-utils": "assets/js/atomic/utils",
13
- "@woocommerce/icons": "assets/js/icons",
14
- "@woocommerce/settings": "assets/js/settings/shared",
15
- "@woocommerce/block-settings": "assets/js/settings/blocks",
16
- "@woocommerce/editor-components(.*)$": "assets/js/editor-components/$1",
17
- "@woocommerce/blocks-registry": "assets/js/blocks-registry",
18
- "@woocommerce/blocks-checkout": "packages/checkout",
19
- "@woocommerce/price-format": "packages/prices",
20
- "@woocommerce/block-hocs(.*)$": "assets/js/hocs/$1",
21
- "@woocommerce/base-components(.*)$": "assets/js/base/components/$1",
22
- "@woocommerce/base-context(.*)$": "assets/js/base/context/$1",
23
- "@woocommerce/base-hocs(.*)$": "assets/js/base/hocs/$1",
24
- "@woocommerce/base-hooks(.*)$": "assets/js/base/hooks/$1",
25
- "@woocommerce/base-utils(.*)$": "assets/js/base/utils",
26
- "@woocommerce/block-data": "assets/js/data",
27
- "@woocommerce/resource-previews": "assets/js/previews",
28
- "@woocommerce/shared-context": "assets/js/shared/context",
29
- "@woocommerce/shared-hocs": "assets/js/shared/hocs",
30
- "@woocommerce/blocks-test-utils": "tests/utils",
31
- "@woocommerce/types": "assets/js/types"
32
- },
33
- "setupFiles": [
34
- "@wordpress/jest-preset-default/scripts/setup-globals.js",
35
- "<rootDir>/tests/js/setup-globals.js",
36
- "<rootDir>/tests/js/setup-fetch.js"
37
- ],
38
- "setupFilesAfterEnv": [
39
- "<rootDir>/tests/js/setup-after-env.js",
40
- "@wordpress/jest-console"
41
- ],
42
- "testPathIgnorePatterns": [
43
- "<rootDir>/tests/",
44
- "<rootDir>/node_modules/",
45
- "<rootDir>/vendor/"
46
- ],
47
- "transformIgnorePatterns": [ "node_modules/(?!(simple-html-tokenizer)/)" ],
48
- "testEnvironment": "jest-environment-jsdom-sixteen",
49
- "preset": "@wordpress/jest-preset-default",
50
- "transform": {
51
- "^.+\\.(js|ts|tsx)$": "<rootDir>/tests/js/jestPreprocess.js"
52
- },
53
- "verbose": true,
54
- "moduleFileExtensions": ["js", "jsx", "ts", "tsx", "json", "node"]
55
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/js/jestPreprocess.js DELETED
@@ -1,6 +0,0 @@
1
- const babelOptions = {
2
- presets: [ '@babel/preset-typescript', '@wordpress/babel-preset-default' ],
3
- plugins: [ '@babel/plugin-proposal-class-properties' ],
4
- };
5
-
6
- module.exports = require( 'babel-jest' ).createTransformer( babelOptions );
 
 
 
 
 
 
packages/woocommerce-blocks/tests/js/setup-after-env.js DELETED
@@ -1,4 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import '@testing-library/jest-dom';
 
 
 
 
packages/woocommerce-blocks/tests/js/setup-fetch.js DELETED
@@ -1,2 +0,0 @@
1
- // This ensures you can use `window.fetch()` in your Jest tests.
2
- require( 'jest-fetch-mock' ).enableMocks();
 
 
packages/woocommerce-blocks/tests/js/setup-globals.js DELETED
@@ -1,104 +0,0 @@
1
- // Set up `wp.*` aliases. Doing this because any tests importing wp stuff will likely run into this.
2
- global.wp = {};
3
-
4
- // wcSettings is required by @woocommerce/* packages
5
- global.wcSettings = {
6
- adminUrl: 'https://vagrant.local/wp/wp-admin/',
7
- shippingMethodsExist: true,
8
- countries: [],
9
- currency: {
10
- code: 'USD',
11
- precision: 2,
12
- symbol: '&#36;',
13
- },
14
- currentUserIsAdmin: false,
15
- date: {
16
- dow: 0,
17
- },
18
- orderStatuses: {
19
- pending: 'Pending payment',
20
- processing: 'Processing',
21
- 'on-hold': 'On hold',
22
- completed: 'Completed',
23
- cancelled: 'Cancelled',
24
- refunded: 'Refunded',
25
- failed: 'Failed',
26
- },
27
- placeholderImgSrc: 'placeholder.jpg',
28
- productCount: 101,
29
- locale: {
30
- siteLocale: 'en_US',
31
- userLocale: 'en_US',
32
- weekdaysShort: [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ],
33
- },
34
- shippingCountries: {
35
- AT: 'Austria',
36
- CA: 'Canada',
37
- GB: 'United Kingdom (UK)',
38
- },
39
- shippingStates: {
40
- CA: {
41
- ON: 'Ontario',
42
- },
43
- },
44
- storePages: {
45
- myaccount: {
46
- id: 0,
47
- title: '',
48
- permalink: '',
49
- },
50
- shop: {
51
- id: 0,
52
- title: '',
53
- permalink: '',
54
- },
55
- cart: {
56
- id: 0,
57
- title: '',
58
- permalink: '',
59
- },
60
- checkout: {
61
- id: 0,
62
- title: '',
63
- permalink: '',
64
- },
65
- privacy: {
66
- id: 0,
67
- title: '',
68
- permalink: '',
69
- },
70
- terms: {
71
- id: 0,
72
- title: '',
73
- permalink: '',
74
- },
75
- },
76
- countryLocale: {
77
- GB: {
78
- postcode: { label: 'Postcode' },
79
- state: { label: 'County', required: false },
80
- },
81
- AT: {
82
- postcode: { priority: 65 },
83
- state: { required: false, hidden: true },
84
- },
85
- CA: {
86
- postcode: { label: 'Postal code' },
87
- state: { label: 'Province' },
88
- },
89
- },
90
- };
91
-
92
- global.jQuery = () => ( {
93
- on: () => void null,
94
- off: () => void null,
95
- } );
96
-
97
- global.IntersectionObserver = function () {
98
- return {
99
- observe: () => void null,
100
- unobserve: () => void null,
101
- };
102
- };
103
-
104
- global.__webpack_public_path__ = '';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/Assets/AssetDataRegistry.php DELETED
@@ -1,98 +0,0 @@
1
- <?php
2
-
3
- namespace Automattic\WooCommerce\Blocks\Tests\Assets;
4
-
5
- use Yoast\PHPUnitPolyfills\Polyfills\ExpectException;
6
- use Automattic\WooCommerce\Blocks\Assets\Api;
7
- use Automattic\WooCommerce\Blocks\Tests\Mocks\AssetDataRegistryMock;
8
- use Automattic\WooCommerce\Blocks\Package;
9
- use InvalidArgumentException;
10
-
11
- /**
12
- * Tests for the AssetDataRegistry class.
13
- *
14
- * @since $VID:$
15
- */
16
- class AssetDataRegistry extends \WP_UnitTestCase {
17
- use ExpectException;
18
-
19
- private $registry;
20
-
21
- public function setUp() {
22
- $this->registry = new AssetDataRegistryMock(
23
- Package::container()->get( API::class )
24
- );
25
- }
26
-
27
- public function test_initial_data() {
28
- $this->assertEmpty( $this->registry->get() );
29
- }
30
-
31
- public function test_add_data() {
32
- $this->registry->add( 'test', 'foo' );
33
- $this->assertEquals( [ 'test' => 'foo' ], $this->registry->get() );
34
- }
35
-
36
- public function test_data_exists() {
37
- $this->registry->add( 'foo', 'lorem-ipsum' );
38
- $this->assertEquals( true, $this->registry->exists( 'foo' ) );
39
- $this->assertEquals( false, $this->registry->exists( 'bar' ) );
40
- }
41
-
42
- public function test_add_lazy_data() {
43
- $lazy = function () {
44
- return 'bar';
45
- };
46
- $this->registry->add( 'foo', $lazy );
47
- // should not be in data yet
48
- $this->assertEmpty( $this->registry->get() );
49
- $this->registry->execute_lazy_data();
50
- // should be in data now
51
- $this->assertEquals( [ 'foo' => 'bar' ], $this->registry->get() );
52
- }
53
-
54
- public function test_invalid_key_on_adding_data() {
55
- $this->expectException( InvalidArgumentException::class );
56
- $this->registry->add( [ 'some_value' ], 'foo' );
57
- }
58
-
59
- public function test_already_existing_key_on_adding_data() {
60
- $this->registry->add( 'foo', 'bar' );
61
- $this->expectException( InvalidArgumentException::class );
62
- $this->registry->add( 'foo', 'yar' );
63
- }
64
-
65
- /**
66
- * This tests the 'woocommerce_shared_settings' filter.
67
- */
68
- public function test_woocommerce_filter_with_protected_data() {
69
- $this->registry->initialize_core_data();
70
- $original_data = $this->registry->get();
71
- add_filter( 'woocommerce_shared_settings', [ self::class, 'pdatcallback' ] );
72
- $data = $this->registry->get();
73
- $this->registry->initialize_core_data();
74
- $this->assertEquals( $original_data, $data );
75
- remove_filter( 'woocommerce_shared_settings', [ self::class, 'pdatcallback' ] );
76
- }
77
-
78
- public static function pdatcallback( $existing_data ) {
79
- $existing_data['locale']['siteLocale'] = 'cheeseburger';
80
- return $existing_data;
81
- }
82
-
83
- public static function ndcallback( $existing_data ) {
84
- $existing_data['cheeseburger'] = 'fries';
85
- return $existing_data;
86
- }
87
-
88
- public function test_woocommerce_filter_with_new_data() {
89
- $this->registry->initialize_core_data();
90
- $original_data = $this->registry->get();
91
- add_filter( 'woocommerce_shared_settings', [ self::class, 'ndcallback' ] );
92
- $this->registry->initialize_core_data();
93
- $data = $this->registry->get();
94
- $original_data['cheeseburger'] = 'fries';
95
- $this->assertEquals( $original_data, $data );
96
- remove_filter( 'woocommerce_shared_settings', [ self::class, 'ndcallback' ] );
97
- }
98
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/Bootstrap/MainFile.php DELETED
@@ -1,48 +0,0 @@
1
- <?php
2
- /**
3
- * Contains Tests for the main file (woocommerce-gutenberg-products-blocks.php)
4
- * bootstrap.
5
- */
6
-
7
- namespace Automattic\WooCommerce\Blocks\Tests\Bootstrap;
8
-
9
- use \WP_UnitTestCase;
10
- use Automattic\WooCommerce\Blocks\Domain\Bootstrap;
11
- use Automattic\WooCommerce\Blocks\Registry\Container;
12
- use Automattic\WooCommerce\Blocks\Package;
13
-
14
- /**
15
- * Test class for the bootstrap in the plugin main file
16
- *
17
- * @since $VID:$
18
- */
19
- class MainFile extends WP_UnitTestCase {
20
- /**
21
- * Holds an instance of the dependency injection container
22
- *
23
- * @var Container
24
- */
25
- private $container;
26
-
27
- /**
28
- * Ensure that container is reset between tests.
29
- */
30
- public function setUp() {
31
- // reset container
32
- $this->container = Package::container( true );
33
- }
34
-
35
- public function test_container_returns_same_instance() {
36
- $container = Package::container();
37
- $this->assertSame( $container, $this->container );
38
- }
39
-
40
- public function test_container_reset() {
41
- $container = Package::container( true );
42
- $this->assertNotSame( $container, $this->container );
43
- }
44
-
45
- public function wc_blocks_bootstrap() {
46
- $this->assertInstanceOf( Bootstrap::class, wc_blocks_bootstrap() );
47
- }
48
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/Domain/Package.php DELETED
@@ -1,46 +0,0 @@
1
- <?php
2
-
3
- namespace Automattic\WooCommerce\Blocks\Tests\Domain\Package;
4
-
5
- use \WP_UnitTestCase;
6
- use Automattic\WooCommerce\Blocks\Domain\Package as TestedPackage;
7
- use Automattic\WooCommerce\Blocks\Domain\Services\FeatureGating;
8
-
9
- /**
10
- * Tests the Package class
11
- *
12
- * @since $VID:$
13
- */
14
- class Package extends WP_UnitTestCase {
15
-
16
- private function get_package() {
17
- return new TestedPackage( '1.0.0', __DIR__, new FeatureGating() );
18
- }
19
-
20
- public function test_get_version() {
21
- $this->assertEquals( '1.0.0', $this->get_package()->get_version() );
22
- }
23
-
24
- public function test_get_path() {
25
- $package = $this->get_package();
26
- // test without relative
27
- $this->assertEquals( __DIR__ . '/', $package->get_path() );
28
-
29
- //test with relative
30
- $expect = __DIR__ . '/build/test';
31
- $this->assertEquals( $expect, $package->get_path( 'build/test') );
32
- }
33
-
34
- public function test_get_url() {
35
- $package = $this->get_package();
36
- $test_url = plugin_dir_url( __FILE__ );
37
- // test without relative
38
- $this->assertEquals( $test_url, $package->get_url() );
39
-
40
- //test with relative
41
- $this->assertEquals(
42
- $test_url . 'build/test',
43
- $package->get_url( 'build/test' )
44
- );
45
- }
46
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/Domain/Services/CreateAccount.php DELETED
@@ -1,240 +0,0 @@
1
- <?php
2
-
3
- namespace Automattic\WooCommerce\Blocks\Tests\Library;
4
-
5
- use Yoast\PHPUnitPolyfills\Polyfills\ExpectException;
6
- use Automattic\WooCommerce\Blocks\Package;
7
- use Automattic\WooCommerce\Blocks\Domain\Package as NewPackage;
8
- use Automattic\WooCommerce\Blocks\Domain\Services\FeatureGating;
9
- use Automattic\WooCommerce\Blocks\Domain\Services\Email\CustomerNewAccount;
10
-
11
- use Automattic\WooCommerce\Blocks\Domain\Services\CreateAccount as TestedCreateAccount;
12
-
13
- /**
14
- * Tests CreateAccount service class.
15
- *
16
- * Note: this feature is currently feature gated. This test class assumes
17
- * that woocommerce_blocks_phase===3, i.e. dev build. Tests will fail
18
- * with other builds (release feature plugin, woo core package).
19
- * Related: https://github.com/woocommerce/woocommerce-gutenberg-products-block/issues/3211
20
- *
21
- * @since $VID:$
22
- */
23
- class CreateAccount extends \WP_UnitTestCase {
24
- use ExpectException;
25
-
26
- private function get_test_instance() {
27
- return new TestedCreateAccount( new NewPackage( 'test', './', new FeatureGating( 2 ) ) );
28
- }
29
-
30
- /**
31
- * Generalised routine for setting up test input and store state
32
- * and calling from_order_request. Used for all tests.
33
- *
34
- * Note – this requires (assumes) that there is no logged-in user.
35
- *
36
- * @return assoc array with keys [ 'user_id', 'order' ] if successful.
37
- */
38
- private function execute_create_customer_from_order( $email, $first_name, $last_name, $options = [] ) {
39
- /// -- Test-specific setup start.
40
-
41
- $tmp_enable_guest_checkout = get_option( 'woocommerce_enable_guest_checkout' );
42
- $tmp_can_register = get_option('woocommerce_enable_signup_and_login_from_checkout');
43
- $enable_guest_checkout = array_key_exists( 'enable_guest_checkout', $options ) ? $options['enable_guest_checkout'] : 'no';
44
- $can_register = array_key_exists( 'can_register', $options ) ? $options['can_register'] : 'yes';
45
- update_option( 'woocommerce_enable_guest_checkout', $enable_guest_checkout );
46
- update_option( 'woocommerce_enable_signup_and_login_from_checkout', $can_register );
47
-
48
- $test_request = new \WP_REST_Request();
49
- $should_create_account = array_key_exists( 'should_create_account', $options ) ? $options['should_create_account'] : 'no';
50
- $test_request->set_param( 'should_create_account', $should_create_account );
51
- $test_request->set_param( 'billing_address', [
52
- 'email' => $email,
53
- 'first_name' => $first_name,
54
- 'last_name' => $last_name
55
- ] );
56
-
57
- $test_order = new \WC_Order();
58
-
59
- /// -- End test-specific setup.
60
-
61
- $user_id = $this->get_test_instance()->from_order_request( $test_request );
62
- $test_order->set_customer_id( $user_id );
63
-
64
- /// -- Undo test-specific setup; restore previous state.
65
- update_option( 'woocommerce_enable_guest_checkout', $tmp_enable_guest_checkout );
66
- update_option( 'woocommerce_enable_signup_and_login_from_checkout', $tmp_can_register );
67
-
68
- return [
69
- 'user_id' => $user_id,
70
- 'order' => $test_order,
71
- ];
72
- }
73
-
74
- /**
75
- * Test successful user signup cases.
76
- *
77
- * @dataProvider create_customer_data
78
- */
79
- public function test_create_customer_from_order( $email, $first_name, $last_name, $options ) {
80
- $result = $this->execute_create_customer_from_order(
81
- $email,
82
- $first_name,
83
- $last_name,
84
- $options
85
- );
86
-
87
- $test_user = $this->factory()->user->get_object_by_id( $result['user_id'] );
88
- $test_order = $result['order'];
89
-
90
- $this->assertEquals( get_current_user_id(), $result['user_id'] );
91
-
92
- $this->assertEquals( $test_user->first_name, $first_name );
93
- $this->assertEquals( $test_user->last_name, $last_name );
94
- $this->assertEquals( $test_user->user_email, $email );
95
- $this->assertArraySubset( $test_user->roles, [ 'customer' ] );
96
-
97
- $this->assertEquals( $test_order->get_customer_id(), $result['user_id'] );
98
- }
99
-
100
- public function create_customer_data() {
101
- return [
102
- // User requested an account.
103
- [
104
- 'maryjones@testperson.net',
105
- 'Mary',
106
- 'Jones',
107
- [
108
- 'should_create_account' => 'yes',
109
- 'enable_guest_checkout' => 'yes',
110
- ],
111
- ],
112
- // User requested an account + site doesn't allow guest.
113
- [
114
- 'maryjones@testperson.net',
115
- 'Mary',
116
- 'Jones',
117
- [
118
- 'should_create_account' => 'yes',
119
- 'enable_guest_checkout' => 'no',
120
- ],
121
- ],
122
- // User requested an account; name fields are not required.
123
- [
124
- 'private_person@hotmail.com',
125
- '',
126
- '',
127
- [
128
- 'should_create_account' => 'yes',
129
- 'enable_guest_checkout' => 'yes',
130
- ],
131
- ],
132
- // Store does not allow guest - signup is required (automatic).
133
- [
134
- 'henrykissinger@fbi.gov',
135
- 'Henry',
136
- 'Kissinger',
137
- [
138
- 'should_create_account' => 'no',
139
- 'enable_guest_checkout' => 'no',
140
- ],
141
- ],
142
- ];
143
- }
144
-
145
- /**
146
- * Test exception is thrown if user already signed up.
147
- */
148
- public function test_customer_already_exists() {
149
- $user_id = $this->factory()->user->create( [
150
- 'user_email' => 'maryjones@testperson.net',
151
- ] );
152
-
153
- $this->expectException( \Exception::class );
154
-
155
- $result = $this->execute_create_customer_from_order(
156
- 'maryjones@testperson.net',
157
- 'Mary',
158
- 'Jones',
159
- [
160
- 'should_create_account' => 'yes',
161
- 'enable_guest_checkout' => 'yes',
162
- ],
163
- );
164
- }
165
-
166
- /**
167
- * Test exception is thrown if email is invalid or malformed.
168
- *
169
- * @dataProvider invalid_email_data
170
- */
171
- public function test_invalid_email( $email ) {
172
- $this->expectException( \Exception::class );
173
-
174
- $result = $this->execute_create_customer_from_order(
175
- $email,
176
- 'Mary',
177
- 'Jones',
178
- [
179
- 'should_create_account' => 'yes',
180
- 'enable_guest_checkout' => 'yes',
181
- ],
182
- );
183
- }
184
-
185
- public function invalid_email_data() {
186
- return [
187
- [ 'maryjones AT testperson DOT net' ],
188
- [ 'lean@fast' ],
189
- [ '' ],
190
- [ ' ' ],
191
- ];
192
- }
193
-
194
- /**
195
- * Test cases where a user should not be created (no signup should occur).
196
- */
197
- public function test_no_account_created() {
198
- $site_user_counts = count_users();
199
-
200
- $this->execute_create_customer_from_order(
201
- 'maryjones@testperson.net',
202
- 'Mary',
203
- 'Jones',
204
- [
205
- 'should_create_account' => 'no',
206
- 'enable_guest_checkout' => 'yes',
207
- ],
208
- );
209
-
210
-
211
- // test with explicitly turning off global registration
212
- $this->execute_create_customer_from_order(
213
- 'maryjones@testperson.net',
214
- 'Mary',
215
- 'Jones',
216
- [
217
- 'can_register' => 'no',
218
- 'should_create_account' => 'yes',
219
- 'enable_guest_checkout' => 'yes',
220
- ],
221
- );
222
-
223
- // test with guest checkout off and global registration off.
224
- $this->execute_create_customer_from_order(
225
- 'maryjones@testperson.net',
226
- 'Mary',
227
- 'Jones',
228
- [
229
- 'can_register' => 'no',
230
- 'should_create_account' => 'yes',
231
- 'enable_guest_checkout' => 'no',
232
- ],
233
- );
234
-
235
- $site_user_counts_after = count_users();
236
-
237
- $this->assertEquals( $site_user_counts['total_users'], $site_user_counts_after['total_users'] );
238
- }
239
-
240
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/Domain/Services/DeleteDraftOrders.php DELETED
@@ -1,200 +0,0 @@
1
- <?php
2
-
3
- namespace Automattic\WooCommerce\Blocks\Tests\Library;
4
-
5
- use Yoast\PHPUnitPolyfills\TestCases\TestCase;
6
- use \WC_Order;
7
- use Automattic\WooCommerce\Blocks\Domain\Services\DraftOrders;
8
- use Automattic\WooCommerce\Blocks\Domain\Services\FeatureGating;
9
- use Automattic\WooCommerce\Blocks\Domain\Package;
10
-
11
- /**
12
- * Tests Delete Draft Orders functionality
13
- *
14
- * @since $VID:$
15
- */
16
- class DeleteDraftOrders extends TestCase {
17
-
18
- private $draft_orders_instance;
19
- private $caught_exception;
20
- private $original_logging_destination;
21
-
22
- /**
23
- * During setup create some draft orders.
24
- *
25
- * @return void
26
- */
27
- public function setUp() {
28
- global $wpdb;
29
-
30
- $this->draft_orders_instance = new DraftOrders( new Package( 'test', './', new FeatureGating( 2 ) ) );
31
-
32
- $order = new WC_Order();
33
- $order->set_status( DraftOrders::STATUS );
34
- $order->save();
35
-
36
- $order = new WC_Order();
37
- $order->set_status( DraftOrders::STATUS );
38
- $order->save();
39
- $wpdb->update(
40
- $wpdb->posts,
41
- array(
42
- 'post_modified' => date( 'Y-m-d H:i:s', strtotime( '-1 DAY', current_time( 'timestamp' ) ) ),
43
- 'post_modified_gmt' => gmdate( 'Y-m-d H:i:s', strtotime( '-1 DAY' ) )
44
- ),
45
- array(
46
- 'ID' => $order->get_id()
47
- )
48
- );
49
-
50
- $order = new WC_Order();
51
- $order->set_status( DraftOrders::STATUS );
52
- $order->save();
53
- $wpdb->update(
54
- $wpdb->posts,
55
- array(
56
- 'post_modified' => date( 'Y-m-d H:i:s', strtotime( '-2 DAY', current_time( 'timestamp' ) ) ),
57
- 'post_modified_gmt' => gmdate( 'Y-m-d H:i:s', strtotime( '-2 DAY' ) )
58
- ),
59
- array(
60
- 'ID' => $order->get_id()
61
- )
62
- );
63
-
64
- // set a non-draft order to make sure it's unaffected
65
- $order = new WC_Order();
66
- $order->set_status( 'on-hold' );
67
- $order->save();
68
- $wpdb->update(
69
- $wpdb->posts,
70
- array(
71
- 'post_modified' => date( 'Y-m-d H:i:s', strtotime( '-2 DAY', current_time( 'timestamp' ) ) ),
72
- 'post_modified_gmt' => gmdate( 'Y-m-d H:i:s', strtotime( '-2 DAY' ) )
73
- ),
74
- array(
75
- 'ID' => $order->get_id()
76
- )
77
- );
78
-
79
- // set listening for exceptions
80
- add_action( 'woocommerce_caught_exception', function($exception_object){
81
- $this->caught_exception = $exception_object;
82
- });
83
-
84
- // temporarily hide error logging we don't care about (and keeps from polluting stdout)
85
- $this->original_logging_destination = ini_get('error_log');
86
- ini_set('error_log', '/dev/null');
87
- parent::setUp();
88
- }
89
-
90
- public function tearDown() {
91
- $this->draft_orders_instance = null;
92
- // delete all orders
93
- $orders = wc_get_orders([]);
94
- foreach( $orders as $order ) {
95
- $order->delete( true );
96
- }
97
- remove_all_actions( 'woocommerce_caught_exception' );
98
- //restore original logging destination
99
- ini_set('error_log', $this->original_logging_destination);
100
- parent::tearDown();
101
- }
102
-
103
- /**
104
- * Delete draft orders older than a day.
105
- *
106
- * Ran on a daily cron schedule.
107
- */
108
- public function test_delete_expired_draft_orders() {
109
- global $wpdb;
110
- $status = DraftOrders::DB_STATUS;
111
-
112
- // Check there are 3 draft orders from our setup before running tests.
113
- $this->assertEquals( 3, (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(ID) from $wpdb->posts posts WHERE posts.post_status = '%s'", [ $status ] ) ) );
114
-
115
- // Run delete query.
116
- $this->draft_orders_instance->delete_expired_draft_orders();
117
-
118
- // Only 1 should remain.
119
- $this->assertEquals( 1, (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(ID) from $wpdb->posts posts WHERE posts.post_status = '%s'", [ $status ] ) ) );
120
-
121
- // The non-draft order should still be present
122
- $this->assertEquals( 1, (int) $wpdb->get_var( "SELECT COUNT(ID) from $wpdb->posts posts WHERE posts.post_status = 'wc-on-hold'" ) );
123
- }
124
-
125
- public function test_greater_than_batch_results_error() {
126
- $sample_results = function( $results, $args ) {
127
- if ( isset( $args[ 'status' ] ) && DraftOrders::DB_STATUS === $args[ 'status' ] ) {
128
- return array_fill( 0, 21, ( new WC_Order ) );
129
- }
130
- return $results;
131
- };
132
- $this->mock_results_for_wc_query($sample_results);
133
- $this->draft_orders_instance->delete_expired_draft_orders();
134
- $this->assertContains( 'unexpected number of results', $this->caught_exception->getMessage() );
135
- $this->unset_mock_results_for_wc_query( $sample_results );
136
- }
137
-
138
- public function test_order_not_instance_of_wc_order_error() {
139
- $sample_results = function( $results, $args ) {
140
- if ( isset( $args[ 'status' ] ) && DraftOrders::DB_STATUS === $args[ 'status' ] ) {
141
- return [ 10 ];
142
- }
143
- return $results;
144
- };
145
- $this->mock_results_for_wc_query( $sample_results );
146
- $this->draft_orders_instance->delete_expired_draft_orders();
147
- $this->assertContains( 'value that is not a WC_Order', $this->caught_exception->getMessage() );
148
- $this->unset_mock_results_for_wc_query( $sample_results );
149
- }
150
-
151
- public function test_order_incorrect_status_error() {
152
- $sample_results = function( $results, $args ) {
153
- if ( isset( $args[ 'status' ] ) && DraftOrders::DB_STATUS === $args[ 'status' ] ) {
154
- $test_order = new WC_Order();
155
- $test_order->set_status( 'on-hold' );
156
- return [ $test_order ];
157
- }
158
- return $results;
159
- };
160
- $this->mock_results_for_wc_query( $sample_results );
161
- $this->draft_orders_instance->delete_expired_draft_orders();
162
- $this->assertContains( 'order that is not a `wc-checkout-draft`', $this->caught_exception->getMessage() );
163
- $this->unset_mock_results_for_wc_query( $sample_results );
164
- }
165
-
166
- public function test_order_status_verification() {
167
- global $wp_post_statuses, $wpdb;
168
- $original_statuses = $wp_post_statuses;
169
- // simulate registered draft status getting clobbered
170
- foreach( $wp_post_statuses as $index => $status ) {
171
- if ( DraftOrders::DB_STATUS === $status->name ) {
172
- unset( $wp_post_statuses[ $index ] );
173
- break;
174
- }
175
- }
176
- $status = DraftOrders::DB_STATUS;
177
- // Check there are 3 draft orders from our setup before running tests.
178
- $this->assertEquals( 3, (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(ID) from $wpdb->posts posts WHERE posts.post_status = '%s'", [ $status ] ) ) );
179
-
180
- // Run delete query.
181
- $this->draft_orders_instance->delete_expired_draft_orders();
182
-
183
- // Only 1 should remain.
184
- $this->assertEquals( 1, (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(ID) from $wpdb->posts posts WHERE posts.post_status = '%s'", [ $status ] ) ) );
185
-
186
- // The non-draft order should still be present
187
- $this->assertEquals( 1, (int) $wpdb->get_var( "SELECT COUNT(ID) from $wpdb->posts posts WHERE posts.post_status = 'wc-on-hold'" ) );
188
- // restore global
189
- $wp_post_statuses = $original_statuses;
190
- }
191
-
192
- private function mock_results_for_wc_query( $mock_callback ) {
193
- add_filter( 'woocommerce_order_query', $mock_callback, 10, 2 );
194
- }
195
-
196
- private function unset_mock_results_for_wc_query( $mock_callback ) {
197
- $removed = remove_filter( 'woocommerce_order_query', $mock_callback );
198
- $this->assertTrue( $removed );
199
- }
200
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/Domain/Services/TestExtendRestApi.php DELETED
@@ -1,110 +0,0 @@
1
- <?php
2
-
3
-
4
- namespace Automattic\WooCommerce\Blocks\Tests\Library;
5
-
6
- use Yoast\PHPUnitPolyfills\TestCases\TestCase;
7
- use Automattic\WooCommerce\Blocks\Domain\Services\ExtendRestApi;
8
- use Automattic\WooCommerce\Blocks\StoreApi\Formatters;
9
- use Automattic\WooCommerce\Blocks\StoreApi\Formatters\CurrencyFormatter;
10
- use Automattic\WooCommerce\Blocks\StoreApi\Formatters\HtmlFormatter;
11
- use Automattic\WooCommerce\Blocks\StoreApi\Formatters\MoneyFormatter;
12
- use Automattic\WooCommerce\Blocks\StoreApi\Routes\RouteException;
13
- use Exception;
14
- use Automattic\WooCommerce\Blocks\Domain\Services\FeatureGating;
15
- use Automattic\WooCommerce\Blocks\Domain\Package as DomainPackage;
16
-
17
- /**
18
- * Tests Delete Draft Orders functionality
19
- *
20
- * @since $VID:$
21
- */
22
- class TestExtendRestApi extends TestCase {
23
- private $mock_extend;
24
-
25
- /**
26
- * Dummy function to ensure API gives the same function back.
27
- * @var \Closure
28
- */
29
- private $dummy;
30
-
31
- /**
32
- * Tracking caught exceptions from API.
33
- */
34
- private $caught_exception;
35
-
36
- /**
37
- * Setup test products data. Called before every test.
38
- */
39
- public function setUp() {
40
- parent::setUp();
41
- $formatters = new Formatters();
42
- $formatters->register( 'money', MoneyFormatter::class );
43
- $formatters->register( 'html', HtmlFormatter::class );
44
- $formatters->register( 'currency', CurrencyFormatter::class );
45
- $this->mock_extend = new ExtendRestApi( new DomainPackage( '', '', new FeatureGating( 2 ) ), $formatters );
46
- $this->dummy = function () {
47
- return null;
48
- };
49
- // set listening for exceptions
50
- add_action( 'woocommerce_caught_exception', function($exception_object){
51
- $this->caught_exception = $exception_object;
52
- throw $exception_object;
53
- });
54
- }
55
-
56
- /**
57
- * Test that we can register a callback and the same function is returned.
58
- */
59
- public function test_register_callback() {
60
- $this->mock_extend->register_update_callback(
61
- [
62
- 'namespace' => 'test-plugin',
63
- 'callback' => $this->dummy,
64
- ]
65
- );
66
- $this->assertSame( $this->dummy, $this->mock_extend->get_update_callback( 'test-plugin' ) );
67
- }
68
-
69
- /**
70
- * Test that we can register a callback and the same function is returned.
71
- */
72
- public function test_fail_register_callback() {
73
- $this->expectException( Exception::class );
74
- $this->expectExceptionMessage('You must provide a plugin namespace when extending a Store REST endpoint.');
75
- $this->mock_extend->register_update_callback(
76
- [
77
- 'callback' => $this->dummy,
78
- ]
79
- );
80
- }
81
-
82
- /**
83
- * Test that we can register a callback and the same function is returned.
84
- */
85
- public function test_fail_get_callback() {
86
- $this->expectException( Exception::class );
87
- $this->expectExceptionMessage('There is no such namespace registered: nonexistent-plugin.');
88
- $this->mock_extend->register_update_callback(
89
- [
90
- 'namespace' => 'test-plugin',
91
- 'callback' => $this->dummy,
92
- ]
93
- );
94
- $this->mock_extend->get_update_callback( 'nonexistent-plugin' );
95
- }
96
-
97
- /**
98
- * Test that we can register a callback and the same function is returned.
99
- */
100
- public function test_fail_get_callback_with_uncallable() {
101
- $this->expectException( Exception::class );
102
- $this->expectExceptionMessage('There is no valid callback supplied to register_update_callback.');
103
- $this->mock_extend->register_update_callback(
104
- [
105
- 'namespace' => 'test-plugin',
106
- ]
107
- );
108
- $this->mock_extend->get_update_callback( 'nonexistent-plugin' );
109
- }
110
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/Helpers/FixtureData.php DELETED
@@ -1,297 +0,0 @@
1
- <?php
2
- /**
3
- * Helper used to create fixture data for tests.
4
- */
5
-
6
- namespace Automattic\WooCommerce\Blocks\Tests\Helpers;
7
-
8
- /**
9
- * FixtureData class.
10
- */
11
- class FixtureData {
12
- /**
13
- * Create a simple product and return the result.
14
- *
15
- * @param array $props Product props.
16
- * @return \WC_Product
17
- */
18
- public function get_simple_product( $props ) {
19
- $product = new \WC_Product_Simple();
20
- $product->set_props(
21
- wp_parse_args(
22
- $props,
23
- array(
24
- 'name' => 'Simple Product',
25
- )
26
- )
27
- );
28
- $product->save();
29
-
30
- return wc_get_product( $product->get_id() );
31
- }
32
-
33
- /**
34
- * Create a variable product and return the result.
35
- *
36
- * @param array $props Product props.
37
- * @param array $attributes Product attributes from which to create variations.
38
- * @return \WC_Product
39
- */
40
- public function get_variable_product( $props, $attributes = array() ) {
41
- $product = new \WC_Product_Variable();
42
- $product->set_props(
43
- wp_parse_args(
44
- $props,
45
- array(
46
- 'name' => 'Variable Product',
47
- )
48
- )
49
- );
50
- $product->save();
51
-
52
- if ( $attributes ) {
53
- $product_attributes = array();
54
-
55
- foreach ( $attributes as $attribute ) {
56
- $product_attribute = new \WC_Product_Attribute();
57
- $product_attribute->set_id( $attribute['attribute_id'] );
58
- $product_attribute->set_name( $attribute['attribute_taxonomy'] );
59
- $product_attribute->set_options( $attribute['term_ids'] );
60
- $product_attribute->set_position( 1 );
61
- $product_attribute->set_visible( true );
62
- $product_attribute->set_variation( true );
63
- $product_attributes[] = $product_attribute;
64
- }
65
-
66
- $product->set_attributes( $product_attributes );
67
- $product->save();
68
- }
69
-
70
- return wc_get_product( $product->get_id() );
71
- }
72
-
73
- /**
74
- * Create and return a variation of a product.
75
- *
76
- * @param integer $parent_id Parent product ID.
77
- * @param array $attributes Variation attributes.
78
- * @param array $props Product props.
79
- * @return \WC_Product_Variation
80
- */
81
- public function get_variation_product( $parent_id, $attributes = array(), $props = array() ) {
82
- $variation = new \WC_Product_Variation();
83
- $variation->set_props(
84
- array_merge(
85
- wp_parse_args(
86
- $props,
87
- array(
88
- 'name' => 'Variation of ' . $parent_id,
89
- 'regular_price' => '10',
90
- )
91
- ),
92
- array(
93
- 'parent_id' => $parent_id,
94
- )
95
- )
96
- );
97
- $variation->set_attributes( $attributes );
98
- $variation->save();
99
- return wc_get_product( $variation->get_id() );
100
- }
101
-
102
- /**
103
- * Create a product attribute.
104
- *
105
- * @param string $raw_name Name of attribute to create.
106
- * @param array $terms Terms to create for the attribute.
107
- * @return array Attribute data and created terms.
108
- */
109
- public static function get_product_attribute( $raw_name = 'size', $terms = array( 'small' ) ) {
110
- global $wpdb, $wc_product_attributes;
111
-
112
- // Make sure caches are clean.
113
- delete_transient( 'wc_attribute_taxonomies' );
114
- \WC_Cache_Helper::invalidate_cache_group( 'woocommerce-attributes' );
115
-
116
- // These are exported as labels, so convert the label to a name if possible first.
117
- $attribute_labels = wp_list_pluck( wc_get_attribute_taxonomies(), 'attribute_label', 'attribute_name' );
118
- $attribute_name = array_search( $raw_name, $attribute_labels, true );
119
-
120
- if ( ! $attribute_name ) {
121
- $attribute_name = wc_sanitize_taxonomy_name( $raw_name );
122
- }
123
-
124
- $attribute_id = wc_attribute_taxonomy_id_by_name( $attribute_name );
125
-
126
- if ( ! $attribute_id ) {
127
- $taxonomy_name = wc_attribute_taxonomy_name( $attribute_name );
128
-
129
- // Unregister taxonomy which other tests may have created...
130
- unregister_taxonomy( $taxonomy_name );
131
-
132
- $attribute_id = wc_create_attribute(
133
- array(
134
- 'name' => $raw_name,
135
- 'slug' => $attribute_name,
136
- 'type' => 'select',
137
- 'order_by' => 'menu_order',
138
- 'has_archives' => 0,
139
- )
140
- );
141
-
142
- // Register as taxonomy.
143
- register_taxonomy(
144
- $taxonomy_name,
145
- apply_filters( 'woocommerce_taxonomy_objects_' . $taxonomy_name, array( 'product' ) ),
146
- apply_filters(
147
- 'woocommerce_taxonomy_args_' . $taxonomy_name,
148
- array(
149
- 'labels' => array(
150
- 'name' => $raw_name,
151
- ),
152
- 'hierarchical' => false,
153
- 'show_ui' => false,
154
- 'query_var' => true,
155
- 'rewrite' => false,
156
- )
157
- )
158
- );
159
-
160
- // Set product attributes global.
161
- $wc_product_attributes = array();
162
-
163
- foreach ( wc_get_attribute_taxonomies() as $taxonomy ) {
164
- $wc_product_attributes[ wc_attribute_taxonomy_name( $taxonomy->attribute_name ) ] = $taxonomy;
165
- }
166
- }
167
-
168
- $attribute = wc_get_attribute( $attribute_id );
169
- $return = array(
170
- 'attribute_name' => $attribute->name,
171
- 'attribute_taxonomy' => $attribute->slug,
172
- 'attribute_id' => $attribute_id,
173
- 'term_ids' => array(),
174
- );
175
-
176
- foreach ( $terms as $term ) {
177
- $result = term_exists( $term, $attribute->slug );
178
-
179
- if ( ! $result ) {
180
- $result = wp_insert_term(
181
- $term,
182
- $attribute->slug,
183
- array(
184
- 'slug' => $term . '-slug',
185
- 'description' => 'Description of ' . $term,
186
- )
187
- );
188
- $return['term_ids'][] = $result['term_id'];
189
- } else {
190
- $return['term_ids'][] = $result['term_id'];
191
- }
192
- }
193
-
194
- return $return;
195
- }
196
-
197
- /**
198
- * Create a coupon and return the result.
199
- *
200
- * @param array $props Product props.
201
- * @return \WC_Coupon
202
- */
203
- public function get_coupon( $props ) {
204
- $coupon = new \WC_Coupon();
205
- $coupon->set_props( $props );
206
- $coupon->save();
207
-
208
- return new \WC_Coupon( $coupon->get_id() );
209
- }
210
-
211
- /**
212
- * Upload a sample image and return it's ID.
213
- *
214
- * @param integer $product_id
215
- * @return void
216
- */
217
- public function sideload_image( $product_id = 0 ) {
218
- global $wpdb;
219
- $image_url = media_sideload_image( 'http://cldup.com/Dr1Bczxq4q.png', $product_id, '', 'src' );
220
- return $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE guid = %s", $image_url ) )[0];
221
- }
222
-
223
- /**
224
- * Add a review to a product and flush cache.
225
- *
226
- * @param integer $product_id Product ID.
227
- * @param integer $rating Review rating.
228
- * @param string $content Review content.
229
- * @param array $props Review props.
230
- * @return void
231
- */
232
- public function add_product_review( $product_id, $rating = 5, $content = 'Product review.', $props = array() ) {
233
- wp_insert_comment(
234
- array_merge(
235
- wp_parse_args(
236
- $props,
237
- array(
238
- 'comment_author' => 'admin',
239
- 'comment_author_email' => 'woo@woo.local',
240
- 'comment_author_url' => '',
241
- 'comment_approved' => 1,
242
- 'comment_type' => 'review',
243
- )
244
- ),
245
- array(
246
- 'comment_post_ID' => $product_id,
247
- 'comment_content' => $content,
248
- 'comment_meta' => array(
249
- 'rating' => $rating,
250
- ),
251
- )
252
- )
253
- );
254
- \WC_Comments::clear_transients( $product_id );
255
- }
256
-
257
- /**
258
- * Create a simple flat rate at the cost of 10.
259
- *
260
- * @param float $cost Optional. Cost of flat rate method.
261
- */
262
- public function shipping_add_flat_rate( $cost = 10 ) {
263
- $flat_rate_settings = array(
264
- 'enabled' => 'yes',
265
- 'title' => 'Flat rate',
266
- 'availability' => 'all',
267
- 'countries' => '',
268
- 'tax_status' => 'taxable',
269
- 'cost' => $cost,
270
- );
271
- update_option( 'woocommerce_flat_rate_settings', $flat_rate_settings );
272
- update_option( 'woocommerce_flat_rate', array() );
273
- \WC_Cache_Helper::get_transient_version( 'shipping', true );
274
- WC()->shipping()->load_shipping_methods();
275
- }
276
-
277
- /**
278
- * Enable bacs payment method.
279
- */
280
- public function payments_enable_bacs() {
281
- $bacs_settings = array(
282
- 'enabled' => 'yes',
283
- 'title' => 'Direct bank transfer',
284
- '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.',
285
- 'instructions' => '',
286
- 'account_details' => '',
287
- 'account_name' => '',
288
- 'account_number' => '',
289
- 'sort_code' => '',
290
- 'bank_name' => '',
291
- 'iban' => '',
292
- 'bic' => '',
293
- );
294
- update_option( 'woocommerce_bacs_settings', $bacs_settings );
295
- WC()->payment_gateways()->init();
296
- }
297
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/Helpers/TestValidateSchema.php DELETED
@@ -1,128 +0,0 @@
1
- <?php
2
- /**
3
- * Ensures the helper works.
4
- */
5
-
6
- namespace Automattic\WooCommerce\Blocks\Tests\Helpers;
7
-
8
- require_once 'ValidateSchema.php';
9
-
10
- /**
11
- * Test Validate schema.
12
- */
13
- class TestValidateSchema extends \WP_UnitTestCase {
14
- /**
15
- * ValidateSchema instance.
16
- *
17
- * @var ValidateSchema
18
- */
19
- protected $validate;
20
-
21
- /**
22
- * Setup schema.
23
- */
24
- public function setUp() {
25
- $this->validate = new ValidateSchema(
26
- [
27
- 'properties' => [
28
- 'test_number' => [
29
- 'type' => 'number',
30
- ],
31
- 'test_string' => [
32
- 'type' => 'string',
33
- ],
34
- 'test_integer' => [
35
- 'type' => 'integer',
36
- ],
37
- 'test_object' => [
38
- 'type' => 'object',
39
- 'properties' => [
40
- 'property_1' => [
41
- 'type' => 'string',
42
- ],
43
- 'property_2' => [
44
- 'type' => 'string',
45
- ],
46
- ],
47
- ],
48
- 'test_array' => [
49
- 'type' => 'array',
50
- 'items' => [
51
- 'type' => 'object',
52
- 'properties' => [
53
- 'property_1' => [
54
- 'type' => 'string',
55
- ],
56
- 'property_2' => [
57
- 'type' => 'string',
58
- ],
59
- ],
60
- ],
61
- ],
62
- 'test_integer_or_null' => [
63
- 'type' => [ 'null', 'integer' ],
64
- ],
65
- ],
66
- ]
67
- );
68
- }
69
-
70
- /**
71
- * Validate an object.
72
- */
73
- public function test_get_diff_from_valid_object() {
74
- $test_object = (object) [
75
- 'test_number' => 1.2,
76
- 'test_string' => 'Hello',
77
- 'test_integer' => 1,
78
- 'test_object' => (object) [
79
- 'property_1' => 'Prop 1',
80
- 'property_2' => 'Prop 2',
81
- ],
82
- 'test_array' => [
83
- (object) [
84
- 'property_1' => 'Prop 1',
85
- 'property_2' => 'Prop 2',
86
- ],
87
- ],
88
- 'test_integer_or_null' => null,
89
- ];
90
-
91
- $diff = $this->validate->get_diff_from_object( $test_object );
92
- $this->assertEmpty( $diff, print_r( $diff, true ) );
93
- }
94
-
95
- /**
96
- * Validate an object.
97
- */
98
- public function test_get_diff_from_invalid_object() {
99
- $test_object = (object) [
100
- 'test_number' => 'Invalid',
101
- 'test_string' => 666,
102
- 'test_integer' => 'Nope',
103
- 'test_object' => (object) [
104
- 'property_1' => 1,
105
- 'property_2' => 2,
106
- ],
107
- 'test_array' => [
108
- (object) [
109
- 'property_1' => 1,
110
- 'invalid_key' => 2,
111
- ],
112
- ],
113
- 'test_integer_or_null' => 'string',
114
- ];
115
-
116
- $diff = $this->validate->get_diff_from_object( $test_object );
117
-
118
- $this->assertContains( 'test_array:property_2', $diff['missing'], print_r( $diff['missing'], true ) );
119
- $this->assertContains( 'test_array:invalid_key', $diff['no_schema'], print_r( $diff['no_schema'], true ) );
120
-
121
- $this->assertContains( 'test_number (string, expected number)', $diff['invalid_type'], print_r( $diff['invalid_type'], true ) );
122
- $this->assertContains( 'test_string (integer, expected string)', $diff['invalid_type'], print_r( $diff['invalid_type'], true ) );
123
- $this->assertContains( 'test_integer (string, expected integer)', $diff['invalid_type'], print_r( $diff['invalid_type'], true ) );
124
- $this->assertContains( 'test_number (string, expected number)', $diff['invalid_type'], print_r( $diff['invalid_type'], true ) );
125
- $this->assertContains( 'test_array:property_1 (integer, expected string)', $diff['invalid_type'], print_r( $diff['invalid_type'], true ) );
126
- $this->assertContains( 'test_integer_or_null (string, expected null, integer)', $diff['invalid_type'], print_r( $diff['invalid_type'], true ) );
127
- }
128
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/Helpers/ValidateSchema.php DELETED
@@ -1,113 +0,0 @@
1
- <?php
2
- /**
3
- * Helper used to validate schema differences.
4
- */
5
-
6
- namespace Automattic\WooCommerce\Blocks\Tests\Helpers;
7
-
8
- /**
9
- * Validate schema.
10
- */
11
- class ValidateSchema {
12
- /**
13
- * The schema.
14
- *
15
- * @var array
16
- */
17
- protected $schema = [];
18
-
19
- /**
20
- * Constructor passed schema object.
21
- *
22
- * @param array $schema API schema representation.
23
- */
24
- public function __construct( $schema ) {
25
- $this->schema = $schema;
26
- }
27
-
28
- /**
29
- * Validate properties and return diff.
30
- *
31
- * @param array|object $object Object to compare.
32
- * @param array $schema Schema to find nested properties under.
33
- * @param string $prefix Prefix to append to diff property names.
34
- * @return array
35
- */
36
- public function get_diff_from_object( $object, $schema = null, $prefix = '' ) {
37
- $missing = [];
38
- $invalid_type = [];
39
- $no_schema = [];
40
-
41
- if ( is_null( $schema ) ) {
42
- $schema = $this->schema['properties'];
43
- }
44
-
45
- if ( ! is_array( $object ) && ! is_object( $object ) ) {
46
- return [];
47
- }
48
-
49
- $object = (array) $object;
50
- $no_schema_diffs = array_diff( array_keys( (array) $object ), array_keys( $schema ) );
51
- foreach ( $no_schema_diffs as $no_schema_diff ) {
52
- $no_schema[] = $prefix . $no_schema_diff;
53
- }
54
-
55
- foreach ( $schema as $property_name => $property_schema ) {
56
- // Validate property is set in object. Avoids isset in case value is NULL.
57
- if ( ( is_array( $object ) && ! array_key_exists( $property_name, $object ) ) || ( is_object( $object ) && ! property_exists( $object, $property_name ) ) ) {
58
- $missing[] = $prefix . $property_name;
59
- continue;
60
- }
61
-
62
- // Validate type.
63
- $type = gettype( $object[ $property_name ] );
64
- if ( $type && ! $this->validate_type( $type, $property_schema['type'] ) ) {
65
- $expected = is_array( $property_schema['type'] ) ? implode( ', ', $property_schema['type'] ) : $property_schema['type'];
66
- $invalid_type[] = $prefix . $property_name . " ({$type}, expected {$expected})";
67
- continue;
68
- }
69
-
70
- // Validate nested props.
71
- if ( isset( $property_schema['items']['properties'] ) ) {
72
- $nested_value = is_array( $object[ $property_name ] ) ? current( $object[ $property_name ] ) : $object[ $property_name ];
73
-
74
- if ( $nested_value ) {
75
- $diff = $this->get_diff_from_object(
76
- $nested_value,
77
- $property_schema['items']['properties'],
78
- $prefix . $property_name . ':'
79
- );
80
- $missing = isset( $diff['missing'] ) ? array_merge( $missing, $diff['missing'] ) : $missing;
81
- $invalid_type = isset( $diff['invalid_type'] ) ? array_merge( $invalid_type, $diff['invalid_type'] ) : $invalid_type;
82
- $no_schema = isset( $diff['no_schema'] ) ? array_merge( $no_schema, $diff['no_schema'] ) : $no_schema;
83
- }
84
- }
85
- }
86
-
87
- return array_filter(
88
- [
89
- 'missing' => array_values( array_filter( $missing ) ),
90
- 'invalid_type' => array_values( array_filter( $invalid_type ) ),
91
- 'no_schema' => array_values( array_filter( $no_schema ) ),
92
- ]
93
- );
94
- }
95
-
96
- /**
97
- * Validate type and return if it matches.
98
- *
99
- * @param string $type Type to check.
100
- * @param string|array $expected Expected types.
101
- * @return boolean
102
- */
103
- protected function validate_type( $type, $expected ) {
104
- $type = strtolower( $type );
105
- $expected = is_array( $expected ) ? $expected : [ $expected ];
106
-
107
- if ( in_array( 'number', $expected ) ) {
108
- $expected = array_merge( $expected, [ 'double', 'float', 'integer' ] );
109
- }
110
-
111
- return in_array( $type, $expected, true );
112
- }
113
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/Registry/Container.php DELETED
@@ -1,78 +0,0 @@
1
- <?php
2
-
3
- namespace Automattic\WooCommerce\Blocks\Tests\Registry;
4
-
5
- use Automattic\WooCommerce\Blocks\Registry\Container as ContainerTest;
6
- use Automattic\WooCommerce\Blocks\Registry\FactoryType;
7
- use Automattic\WooCommerce\Blocks\Tests\Mocks\MockTestDependency;
8
- use Yoast\PHPUnitPolyfills\TestCases\TestCase;
9
-
10
- /**
11
- * Tests the Container functionality
12
- *
13
- * This also implicitly tests the FactoryType and SharedType classes.
14
- *
15
- * @since $VID:$
16
- * @group testing
17
- */
18
- class Container extends TestCase {
19
- private $container;
20
-
21
- public function setUp() {
22
- $this->container = new ContainerTest;
23
- }
24
-
25
- public function test_factory() {
26
- $factory = $this->container->factory( function () { return 'foo'; } );
27
- $this->assertInstanceOf( FactoryType::class, $factory );
28
- }
29
-
30
- public function test_registering_factory_type() {
31
- $this->container->register(
32
- MockTestDependency::class,
33
- $this->container->factory(
34
- function () { return new MockTestDependency; }
35
- )
36
- );
37
- $instanceA = $this->container->get( MockTestDependency::class );
38
- $instanceB = $this->container->get( MockTestDependency::class );
39
-
40
- // should not be the same instance;
41
- $this->assertNotSame( $instanceA, $instanceB );
42
- }
43
-
44
- public function test_registering_shared_type() {
45
- $this->container->register(
46
- MockTestDependency::class,
47
- function () { return new MockTestDependency; }
48
- );
49
- $instanceA = $this->container->get( MockTestDependency::class );
50
- $instanceB = $this->container->get( MockTestDependency::class );
51
-
52
- // should not be the same instance;
53
- $this->assertSame( $instanceA, $instanceB );
54
- }
55
-
56
- public function test_registering_shared_type_dependent_on_another_shared_type() {
57
- $this->container->register(
58
- MockTestDependency::class . 'A',
59
- function() { return new MockTestDependency; }
60
- );
61
- $this->container->register(
62
- MockTestDependency::class . 'B',
63
- function( $container ) {
64
- return new MockTestDependency(
65
- $container->get( MockTestDependency::class . 'A' )
66
- );
67
- }
68
- );
69
- $instanceA = $this->container->get( MockTestDependency::class . 'A' );
70
- $instanceB = $this->container->get( MockTestDependency::class . 'B' );
71
-
72
- // should not be the same instance
73
- $this->assertNotSame( $instanceA, $instanceB );
74
-
75
- // dependency on B should be the same as A
76
- $this->assertSame( $instanceA, $instanceB->dependency );
77
- }
78
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/StoreApi/Formatters/TestCurrencyFormatter.php DELETED
@@ -1,39 +0,0 @@
1
- <?php
2
- /**
3
- * Controller Tests.
4
- */
5
-
6
- namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Formatters;
7
-
8
- use Automattic\WooCommerce\Blocks\StoreApi\Formatters\CurrencyFormatter;
9
-
10
- /**
11
- * TestCurrencyFormatter tests.
12
- */
13
- class TestCurrencyFormatter extends \WP_UnitTestCase {
14
-
15
- private $mock_formatter;
16
-
17
- /**
18
- * Setup test products data. Called before every test.
19
- */
20
- public function setUp() {
21
- parent::setUp();
22
-
23
- $this->mock_formatter = new CurrencyFormatter();
24
- }
25
-
26
- /**
27
- * Test formatting.
28
- */
29
- public function test_format() {
30
- $value = $this->mock_formatter->format( [] );
31
- $this->assertArrayHasKey( 'currency_code', $value );
32
- $this->assertArrayHasKey( 'currency_symbol', $value );
33
- $this->assertArrayHasKey( 'currency_minor_unit', $value );
34
- $this->assertArrayHasKey( 'currency_decimal_separator', $value );
35
- $this->assertArrayHasKey( 'currency_thousand_separator', $value );
36
- $this->assertArrayHasKey( 'currency_prefix', $value );
37
- $this->assertArrayHasKey( 'currency_suffix', $value );
38
- }
39
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/StoreApi/Formatters/TestFormatters.php DELETED
@@ -1,48 +0,0 @@
1
- <?php
2
- /**
3
- * Controller Tests.
4
- */
5
-
6
- namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Formatters;
7
-
8
- use Automattic\WooCommerce\Blocks\StoreApi\Formatters;
9
- use Automattic\WooCommerce\Blocks\StoreApi\Formatters\MoneyFormatter;
10
- use Automattic\WooCommerce\Blocks\StoreApi\Formatters\HtmlFormatter;
11
- use Automattic\WooCommerce\Blocks\StoreApi\Formatters\DefaultFormatter;
12
- use Automattic\WooCommerce\Blocks\StoreApi\Formatters\CurrencyFormatter;
13
-
14
- /**
15
- * TestFormatters tests.
16
- */
17
- class TestFormatters extends \WP_UnitTestCase {
18
-
19
- private $mock_formatters;
20
-
21
- /**
22
- * Setup test products data. Called before every test.
23
- */
24
- public function setUp() {
25
- parent::setUp();
26
-
27
- $this->mock_formatters = new Formatters();
28
- $this->mock_formatters->register( 'money', MoneyFormatter::class );
29
- $this->mock_formatters->register( 'html', HtmlFormatter::class );
30
- $this->mock_formatters->register( 'currency', CurrencyFormatter::class );
31
- }
32
-
33
- /**
34
- * Test get formatter.
35
- */
36
- public function test_get_formatter() {
37
- $this->assertInstanceOf( MoneyFormatter::class, $this->mock_formatters->money );
38
- $this->assertInstanceOf( HtmlFormatter::class, $this->mock_formatters->html );
39
- $this->assertInstanceOf( CurrencyFormatter::class, $this->mock_formatters->currency );
40
- }
41
-
42
- /**
43
- * Test getting non existent formatter.
44
- */
45
- public function test_get_default_formatter() {
46
- $this->assertInstanceOf( DefaultFormatter::class, $this->mock_formatters->wrong );
47
- }
48
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/StoreApi/Formatters/TestHtmlFormatter.php DELETED
@@ -1,32 +0,0 @@
1
- <?php
2
- /**
3
- * Controller Tests.
4
- */
5
-
6
- namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Formatters;
7
-
8
- use Automattic\WooCommerce\Blocks\StoreApi\Formatters\HtmlFormatter;
9
-
10
- /**
11
- * TestHtmlFormatter tests.
12
- */
13
- class TestHtmlFormatter extends \WP_UnitTestCase {
14
-
15
- private $mock_formatter;
16
-
17
- /**
18
- * Setup test products data. Called before every test.
19
- */
20
- public function setUp() {
21
- parent::setUp();
22
-
23
- $this->mock_formatter = new HtmlFormatter();
24
- }
25
-
26
- /**
27
- * Test formatting.
28
- */
29
- public function test_format() {
30
- $this->assertEquals( "&#8220;Quotes&#8221;", $this->mock_formatter->format( '"Quotes"' ) );
31
- }
32
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/StoreApi/Formatters/TestMoneyFormatter.php DELETED
@@ -1,49 +0,0 @@
1
- <?php
2
- /**
3
- * Controller Tests.
4
- */
5
-
6
- namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Formatters;
7
-
8
- use Automattic\WooCommerce\Blocks\StoreApi\Formatters\MoneyFormatter;
9
-
10
- /**
11
- * TestMoneyFormatter tests.
12
- */
13
- class TestMoneyFormatter extends \WP_UnitTestCase {
14
-
15
- private $mock_formatter;
16
-
17
- /**
18
- * Setup test products data. Called before every test.
19
- */
20
- public function setUp() {
21
- parent::setUp();
22
-
23
- $this->mock_formatter = new MoneyFormatter();
24
- }
25
-
26
- /**
27
- * Test formatting.
28
- */
29
- public function test_format() {
30
- $this->assertEquals( "1000", $this->mock_formatter->format( 10 ) );
31
- $this->assertEquals( "1000", $this->mock_formatter->format( "10" ) );
32
- }
33
-
34
- /**
35
- * Test formatting with custom DP.
36
- */
37
- public function test_format_dp() {
38
- $this->assertEquals( "100000", $this->mock_formatter->format( 10, [ 'decimals' => 4 ] ) );
39
- $this->assertEquals( "100000", $this->mock_formatter->format( "10", [ 'decimals' => 4 ] ) );
40
- }
41
-
42
- /**
43
- * Test formatting with custom DP.
44
- */
45
- public function test_format_rounding_mode() {
46
- $this->assertEquals( "156", $this->mock_formatter->format( 1.555, [ 'rounding_mode' => PHP_ROUND_HALF_UP ] ) );
47
- $this->assertEquals( "155", $this->mock_formatter->format( 1.555, [ 'rounding_mode' => PHP_ROUND_HALF_DOWN ] ) );
48
- }
49
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/StoreApi/Routes/Batch.php DELETED
@@ -1,154 +0,0 @@
1
- <?php
2
- /**
3
- * Controller Tests.
4
- */
5
-
6
- namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes;
7
-
8
- use Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes\ControllerTestCase;
9
- use Automattic\WooCommerce\Blocks\Tests\Helpers\FixtureData;
10
-
11
- /**
12
- * Batch Controller Tests.
13
- */
14
- class Batch extends ControllerTestCase {
15
-
16
- /**
17
- * Setup test products data. Called before every test.
18
- */
19
- public function setUp() {
20
- parent::setUp();
21
-
22
- $fixtures = new FixtureData();
23
-
24
- $this->products = [
25
- $fixtures->get_simple_product( [
26
- 'name' => 'Test Product 1',
27
- 'regular_price' => 10,
28
- ] ),
29
- $fixtures->get_simple_product( [
30
- 'name' => 'Test Product 2',
31
- 'regular_price' => 10,
32
- ] ),
33
- ];
34
- }
35
-
36
- /**
37
- * Test route registration.
38
- */
39
- public function test_register_routes() {
40
- $routes = rest_get_server()->get_routes();
41
- $this->assertArrayHasKey( '/wc/store/batch', $routes );
42
- }
43
-
44
- /**
45
- * Test that a batch of requests are successful.
46
- */
47
- public function test_success_cart_route_batch() {
48
- $request = new \WP_REST_Request( 'POST', '/wc/store/batch' );
49
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
50
- $request->set_body_params(
51
- array(
52
- 'requests' => array(
53
- array(
54
- 'method' => 'POST',
55
- 'path' => '/wc/store/cart/add-item',
56
- 'body' => array(
57
- 'id' => $this->products[0]->get_id(),
58
- 'quantity' => 1,
59
- ),
60
- 'headers' => array(
61
- 'X-WC-Store-API-Nonce' => wp_create_nonce( 'wc_store_api' ),
62
- )
63
- ),
64
- array(
65
- 'method' => 'POST',
66
- 'path' => '/wc/store/cart/add-item',
67
- 'body' => array(
68
- 'id' => $this->products[1]->get_id(),
69
- 'quantity' => 1,
70
- ),
71
- 'headers' => array(
72
- 'X-WC-Store-API-Nonce' => wp_create_nonce( 'wc_store_api' ),
73
- )
74
- ),
75
- ),
76
- )
77
- );
78
- $response = rest_get_server()->dispatch( $request );
79
- $response_data = $response->get_data();
80
-
81
- // Assert that there were 2 successful results from the batch.
82
- $this->assertEquals( 2, count( $response_data['responses'] ) );
83
- $this->assertEquals( 201, $response_data['responses'][0]['status'] );
84
- $this->assertEquals( 201, $response_data['responses'][1]['status'] );
85
- }
86
-
87
- /**
88
- * Test for a mixture of successful and non-successful requests in a batch.
89
- */
90
- public function test_mix_cart_route_batch() {
91
- $request = new \WP_REST_Request( 'POST', '/wc/store/batch' );
92
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
93
- $request->set_body_params(
94
- array(
95
- 'requests' => array(
96
- array(
97
- 'method' => 'POST',
98
- 'path' => '/wc/store/cart/add-item',
99
- 'body' => array(
100
- 'id' => 99,
101
- 'quantity' => 1,
102
- ),
103
- 'headers' => array(
104
- 'X-WC-Store-API-Nonce' => wp_create_nonce( 'wc_store_api' ),
105
- )
106
- ),
107
- array(
108
- 'method' => 'POST',
109
- 'path' => '/wc/store/cart/add-item',
110
- 'body' => array(
111
- 'id' => $this->products[1]->get_id(),
112
- 'quantity' => 1,
113
- ),
114
- 'headers' => array(
115
- 'X-WC-Store-API-Nonce' => wp_create_nonce( 'wc_store_api' ),
116
- )
117
- ),
118
- ),
119
- )
120
- );
121
- $response = rest_get_server()->dispatch( $request );
122
- $response_data = $response->get_data();
123
-
124
- $this->assertEquals( 2, count( $response_data['responses'] ) );
125
- $this->assertEquals( 400, $response_data['responses'][0]['status'], $response_data['responses'][0]['status'] );
126
- $this->assertEquals( 201, $response_data['responses'][1]['status'], $response_data['responses'][1]['status'] );
127
- }
128
-
129
- /**
130
- * Get Requests not supported by batch.
131
- */
132
- public function test_get_cart_route_batch() {
133
- $request = new \WP_REST_Request( 'POST', '/wc/store/batch' );
134
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
135
- $request->set_body_params(
136
- array(
137
- 'requests' => array(
138
- array(
139
- 'method' => 'GET',
140
- 'path' => '/wc/store/cart',
141
- 'body' => array(
142
- 'id' => 99,
143
- 'quantity' => 1,
144
- ),
145
- ),
146
- ),
147
- )
148
- );
149
- $response = rest_get_server()->dispatch( $request );
150
- $response_data = $response->get_data();
151
-
152
- $this->assertEquals( 'rest_invalid_param', $response_data['code'], print_r( $response_data, true ) );
153
- }
154
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/StoreApi/Routes/Cart.php DELETED
@@ -1,446 +0,0 @@
1
- <?php
2
- /**
3
- * Controller Tests.
4
- */
5
-
6
- namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes;
7
-
8
- use Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes\ControllerTestCase;
9
- use Automattic\WooCommerce\Blocks\Tests\Helpers\FixtureData;
10
- use Automattic\WooCommerce\Blocks\Tests\Helpers\ValidateSchema;
11
-
12
- /**
13
- * Cart Controller Tests.
14
- */
15
- class Cart extends ControllerTestCase {
16
-
17
- /**
18
- * Setup test products data. Called before every test.
19
- */
20
- public function setUp() {
21
- parent::setUp();
22
-
23
- $fixtures = new FixtureData();
24
- $fixtures->shipping_add_flat_rate();
25
-
26
- $this->products = array(
27
- $fixtures->get_simple_product(
28
- array(
29
- 'name' => 'Test Product 1',
30
- 'stock_status' => 'instock',
31
- 'regular_price' => 10,
32
- 'weight' => 10,
33
- )
34
- ),
35
- $fixtures->get_simple_product(
36
- array(
37
- 'name' => 'Test Product 2',
38
- 'stock_status' => 'instock',
39
- 'regular_price' => 10,
40
- 'weight' => 10,
41
- )
42
- ),
43
- );
44
-
45
- $this->coupon = $fixtures->get_coupon(
46
- array(
47
- 'code' => 'test_coupon',
48
- 'discount_type' => 'fixed_cart',
49
- 'amount' => 1,
50
- )
51
- );
52
-
53
- wc_empty_cart();
54
- $this->keys = array();
55
- $this->keys[] = wc()->cart->add_to_cart( $this->products[0]->get_id(), 2 );
56
- $this->keys[] = wc()->cart->add_to_cart( $this->products[1]->get_id(), 1 );
57
- wc()->cart->apply_coupon( $this->coupon->get_code() );
58
-
59
- // Draft order.
60
- $order = new \WC_Order();
61
- $order->set_status( 'checkout-draft' );
62
- $order->save();
63
- wc()->session->set( 'store_api_draft_order', $order->get_id() );
64
- }
65
-
66
- /**
67
- * Test route registration.
68
- */
69
- public function test_register_routes() {
70
- $routes = rest_get_server()->get_routes();
71
- $this->assertArrayHasKey( '/wc/store/cart', $routes );
72
- $this->assertArrayHasKey( '/wc/store/cart/apply-coupon', $routes );
73
- $this->assertArrayHasKey( '/wc/store/cart/remove-coupon', $routes );
74
- $this->assertArrayHasKey( '/wc/store/cart/update-customer', $routes );
75
- $this->assertArrayHasKey( '/wc/store/cart/select-shipping-rate', $routes );
76
- }
77
-
78
- /**
79
- * Test getting cart.
80
- */
81
- public function test_get_item() {
82
- $response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc/store/cart' ) );
83
- $data = $response->get_data();
84
-
85
- $this->assertEquals( 200, $response->get_status() );
86
- $this->assertEquals( 3, $data['items_count'] );
87
- $this->assertEquals( 2, count( $data['items'] ) );
88
- $this->assertEquals( true, $data['needs_payment'] );
89
- $this->assertEquals( true, $data['needs_shipping'] );
90
- $this->assertEquals( '30', $data['items_weight'] );
91
-
92
- $this->assertEquals( 'USD', $data['totals']->currency_code );
93
- $this->assertEquals( 2, $data['totals']->currency_minor_unit );
94
- $this->assertEquals( '3000', $data['totals']->total_items );
95
- $this->assertEquals( '0', $data['totals']->total_items_tax );
96
- $this->assertEquals( '0', $data['totals']->total_fees );
97
- $this->assertEquals( '0', $data['totals']->total_fees_tax );
98
- $this->assertEquals( '100', $data['totals']->total_discount );
99
- $this->assertEquals( '0', $data['totals']->total_discount_tax );
100
- $this->assertEquals( '0', $data['totals']->total_shipping );
101
- $this->assertEquals( '0', $data['totals']->total_shipping_tax );
102
- $this->assertEquals( '0', $data['totals']->total_tax );
103
- $this->assertEquals( '2900', $data['totals']->total_price );
104
- }
105
-
106
- /**
107
- * Test removing a nonexistent cart item.
108
- */
109
- public function test_remove_bad_cart_item() {
110
- // Test removing a bad cart item - should return 404.
111
- $request = new \WP_REST_Request( 'POST', '/wc/store/cart/remove-item' );
112
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
113
- $request->set_body_params(
114
- array(
115
- 'key' => 'bad_item_key_123',
116
- )
117
- );
118
- $response = rest_get_server()->dispatch( $request );
119
- $data = $response->get_data();
120
-
121
- $this->assertEquals( 409, $response->get_status() );
122
- $this->assertEquals( 'woocommerce_rest_cart_invalid_key', $data['code'] );
123
- }
124
-
125
- /**
126
- * Test remove cart item.
127
- */
128
- public function test_remove_cart_item() {
129
- // Test removing a valid cart item - should return updated cart.
130
- $request = new \WP_REST_Request( 'POST', '/wc/store/cart/remove-item' );
131
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
132
- $request->set_body_params(
133
- array(
134
- 'key' => $this->keys[0],
135
- )
136
- );
137
- $response = rest_get_server()->dispatch( $request );
138
- $data = $response->get_data();
139
-
140
- $this->assertEquals( 200, $response->get_status() );
141
- $this->assertEquals( 1, $data['items_count'] );
142
- $this->assertEquals( 1, count( $data['items'] ) );
143
- $this->assertEquals( '10', $data['items_weight'] );
144
- $this->assertEquals( '1000', $data['totals']->total_items );
145
-
146
- // Test removing same item again - should return 404 (item is already removed).
147
- $response = rest_get_server()->dispatch( $request );
148
- $data = $response->get_data();
149
-
150
- $this->assertEquals( 409, $response->get_status() );
151
- $this->assertEquals( 'woocommerce_rest_cart_invalid_key', $data['code'] );
152
- }
153
-
154
- /**
155
- * Test changing the quantity of a cart item.
156
- */
157
- public function test_update_item() {
158
- $request = new \WP_REST_Request( 'POST', '/wc/store/cart/update-item' );
159
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
160
- $request->set_body_params(
161
- array(
162
- 'key' => $this->keys[0],
163
- 'quantity' => 10,
164
- )
165
- );
166
- $response = rest_get_server()->dispatch( $request );
167
- $data = $response->get_data();
168
-
169
- $this->assertEquals( 200, $response->get_status() );
170
- $this->assertEquals( 10, $data['items'][0]['quantity'] );
171
- $this->assertEquals( 11, $data['items_count'] );
172
- $this->assertEquals( '11000', $data['totals']->total_items );
173
- }
174
-
175
- /**
176
- * Test getting updated shipping.
177
- */
178
- public function test_update_customer() {
179
- $request = new \WP_REST_Request( 'POST', '/wc/store/cart/update-customer' );
180
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
181
- $request->set_body_params(
182
- array(
183
- 'shipping_address' => (object) array(
184
- 'country' => 'US',
185
- ),
186
- )
187
- );
188
-
189
- $action_callback = \Mockery::mock( 'ActionCallback' );
190
- $action_callback->shouldReceive( 'do_customer_callback' )->once();
191
-
192
- add_action( 'woocommerce_blocks_cart_update_customer_from_request', array( $action_callback, 'do_customer_callback' ) );
193
-
194
- $response = rest_get_server()->dispatch( $request );
195
- $data = $response->get_data();
196
-
197
- remove_action( 'woocommerce_blocks_cart_update_customer_from_request', array( $action_callback, 'do_customer_callback' ) );
198
-
199
- $this->assertEquals( 200, $response->get_status(), print_r( $response, true ) );
200
- $this->assertArrayHasKey( 'shipping_rates', $data );
201
-
202
- $this->assertEquals( null, $data['shipping_rates'][0]['destination']->address_1 );
203
- $this->assertEquals( null, $data['shipping_rates'][0]['destination']->address_2 );
204
- $this->assertEquals( null, $data['shipping_rates'][0]['destination']->city );
205
- $this->assertEquals( null, $data['shipping_rates'][0]['destination']->state );
206
- $this->assertEquals( null, $data['shipping_rates'][0]['destination']->postcode );
207
- $this->assertEquals( 'US', $data['shipping_rates'][0]['destination']->country );
208
- }
209
-
210
- /**
211
- * Test shipping address validation.
212
- */
213
- public function test_update_customer_address() {
214
- // US address.
215
- $request = new \WP_REST_Request( 'POST', '/wc/store/cart/update-customer' );
216
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
217
- $request->set_body_params(
218
- array(
219
- 'shipping_address' => (object) array(
220
- 'first_name' => 'Han',
221
- 'last_name' => 'Solo',
222
- 'address_1' => 'Test address 1',
223
- 'address_2' => 'Test address 2',
224
- 'city' => 'Test City',
225
- 'state' => 'AL',
226
- 'postcode' => '90210',
227
- 'country' => 'US',
228
- ),
229
- )
230
- );
231
- $response = rest_get_server()->dispatch( $request );
232
- $data = $response->get_data();
233
-
234
- $this->assertEquals( 200, $response->get_status() );
235
- $this->assertEquals( 'Test address 1', $data['shipping_rates'][0]['destination']->address_1 );
236
- $this->assertEquals( 'Test address 2', $data['shipping_rates'][0]['destination']->address_2 );
237
- $this->assertEquals( 'Test City', $data['shipping_rates'][0]['destination']->city );
238
- $this->assertEquals( 'AL', $data['shipping_rates'][0]['destination']->state );
239
- $this->assertEquals( '90210', $data['shipping_rates'][0]['destination']->postcode );
240
- $this->assertEquals( 'US', $data['shipping_rates'][0]['destination']->country );
241
-
242
- // Address with invalid country.
243
- $request = new \WP_REST_Request( 'POST', '/wc/store/cart/update-customer' );
244
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
245
- $request->set_body_params(
246
- array(
247
- 'shipping_address' => (object) array(
248
- 'first_name' => 'Han',
249
- 'last_name' => 'Solo',
250
- 'address_1' => 'Test address 1',
251
- 'address_2' => 'Test address 2',
252
- 'city' => 'Test City',
253
- 'state' => 'AL',
254
- 'postcode' => '90210',
255
- 'country' => 'ZZZZZZZZ',
256
- ),
257
- )
258
- );
259
- $response = rest_get_server()->dispatch( $request );
260
- $data = $response->get_data();
261
-
262
- $this->assertEquals( 400, $response->get_status() );
263
-
264
- // US address with named state.
265
- $request = new \WP_REST_Request( 'POST', '/wc/store/cart/update-customer' );
266
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
267
- $request->set_body_params(
268
- array(
269
- 'shipping_address' => (object) array(
270
- 'first_name' => 'Han',
271
- 'last_name' => 'Solo',
272
- 'address_1' => 'Test address 1',
273
- 'address_2' => 'Test address 2',
274
- 'city' => 'Test City',
275
- 'state' => 'Alabama',
276
- 'postcode' => '90210',
277
- 'country' => 'US',
278
- ),
279
- )
280
- );
281
- $response = rest_get_server()->dispatch( $request );
282
- $data = $response->get_data();
283
-
284
- $this->assertEquals( 200, $response->get_status() );
285
- $this->assertEquals( 'AL', $data['shipping_rates'][0]['destination']->state );
286
- $this->assertEquals( 'US', $data['shipping_rates'][0]['destination']->country );
287
-
288
- // US address with invalid state.
289
- $request = new \WP_REST_Request( 'POST', '/wc/store/cart/update-customer' );
290
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
291
- $request->set_body_params(
292
- array(
293
- 'shipping_address' => (object) array(
294
- 'first_name' => 'Han',
295
- 'last_name' => 'Solo',
296
- 'address_1' => 'Test address 1',
297
- 'address_2' => 'Test address 2',
298
- 'city' => 'Test City',
299
- 'state' => 'ZZZZZZZZ',
300
- 'postcode' => '90210',
301
- 'country' => 'US',
302
- ),
303
- )
304
- );
305
- $response = rest_get_server()->dispatch( $request );
306
- $data = $response->get_data();
307
-
308
- $this->assertEquals( 400, $response->get_status() );
309
-
310
- // US address with invalid postcode.
311
- $request = new \WP_REST_Request( 'POST', '/wc/store/cart/update-customer' );
312
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
313
- $request->set_body_params(
314
- array(
315
- 'shipping_address' => (object) array(
316
- 'first_name' => 'Han',
317
- 'last_name' => 'Solo',
318
- 'address_1' => 'Test address 1',
319
- 'address_2' => 'Test address 2',
320
- 'city' => 'Test City',
321
- 'state' => 'AL',
322
- 'postcode' => 'ABCDE',
323
- 'country' => 'US',
324
- ),
325
- )
326
- );
327
- $response = rest_get_server()->dispatch( $request );
328
- $data = $response->get_data();
329
-
330
- $this->assertEquals( 400, $response->get_status() );
331
- }
332
-
333
-
334
- /**
335
- * Test applying coupon to cart.
336
- */
337
- public function test_apply_coupon() {
338
- wc()->cart->remove_coupon( $this->coupon->get_code() );
339
-
340
- $request = new \WP_REST_Request( 'POST', '/wc/store/cart/apply-coupon' );
341
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
342
- $request->set_body_params(
343
- array(
344
- 'code' => $this->coupon->get_code(),
345
- )
346
- );
347
- $response = rest_get_server()->dispatch( $request );
348
- $data = $response->get_data();
349
- $this->assertEquals( 200, $response->get_status() );
350
- $this->assertEquals( '100', $data['totals']->total_discount );
351
-
352
- $fixtures = new FixtureData();
353
-
354
- // Test coupons with different case.
355
- $newcoupon = $fixtures->get_coupon( array( 'code' => 'testCoupon' ) );
356
- $request = new \WP_REST_Request( 'POST', '/wc/store/cart/apply-coupon' );
357
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
358
- $request->set_body_params(
359
- array(
360
- 'code' => 'testCoupon',
361
- )
362
- );
363
- $response = rest_get_server()->dispatch( $request );
364
- $data = $response->get_data();
365
- $this->assertEquals( 200, $response->get_status() );
366
-
367
- // Test coupons with special chars in the code.
368
- $newcoupon = $fixtures->get_coupon( array( 'code' => '$5 off' ) );
369
- $request = new \WP_REST_Request( 'POST', '/wc/store/cart/apply-coupon' );
370
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
371
- $request->set_body_params(
372
- array(
373
- 'code' => '$5 off',
374
- )
375
- );
376
- $response = rest_get_server()->dispatch( $request );
377
- $data = $response->get_data();
378
- $this->assertEquals( 200, $response->get_status() );
379
- }
380
-
381
- /**
382
- * Test removing coupon from cart.
383
- */
384
- public function test_remove_coupon() {
385
- // Invalid coupon.
386
- $request = new \WP_REST_Request( 'POST', '/wc/store/cart/remove-coupon' );
387
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
388
- $request->set_body_params(
389
- array(
390
- 'code' => 'doesnotexist',
391
- )
392
- );
393
- $response = rest_get_server()->dispatch( $request );
394
- $data = $response->get_data();
395
- $this->assertEquals( 400, $response->get_status() );
396
-
397
- // Applied coupon.
398
- $request = new \WP_REST_Request( 'POST', '/wc/store/cart/remove-coupon' );
399
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
400
- $request->set_body_params(
401
- array(
402
- 'code' => $this->coupon->get_code(),
403
- )
404
- );
405
- $response = rest_get_server()->dispatch( $request );
406
- $data = $response->get_data();
407
- $this->assertEquals( 200, $response->get_status() );
408
- $this->assertEquals( '0', $data['totals']->total_discount );
409
- }
410
-
411
- /**
412
- * Test conversion of cart item to rest response.
413
- */
414
- public function test_prepare_item() {
415
- $routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController( $this->mock_extend ) );
416
- $controller = $routes->get( 'cart' );
417
- $cart = wc()->cart;
418
- $response = $controller->prepare_item_for_response( $cart, new \WP_REST_Request() );
419
- $data = $response->get_data();
420
-
421
- $this->assertArrayHasKey( 'items_count', $data );
422
- $this->assertArrayHasKey( 'items', $data );
423
- $this->assertArrayHasKey( 'shipping_rates', $data );
424
- $this->assertArrayHasKey( 'coupons', $data );
425
- $this->assertArrayHasKey( 'needs_payment', $data );
426
- $this->assertArrayHasKey( 'needs_shipping', $data );
427
- $this->assertArrayHasKey( 'items_weight', $data );
428
- $this->assertArrayHasKey( 'totals', $data );
429
- }
430
-
431
- /**
432
- * Test schema matches responses.
433
- */
434
- public function test_get_item_schema() {
435
- $routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController( $this->mock_extend ) );
436
- $controller = $routes->get( 'cart' );
437
- $schema = $controller->get_item_schema();
438
- $cart = wc()->cart;
439
- $response = $controller->prepare_item_for_response( $cart, new \WP_REST_Request() );
440
- $schema = $controller->get_item_schema();
441
- $validate = new ValidateSchema( $schema );
442
-
443
- $diff = $validate->get_diff_from_object( $response->get_data() );
444
- $this->assertEmpty( $diff, print_r( $diff, true ) );
445
- }
446
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/StoreApi/Routes/CartCoupons.php DELETED
@@ -1,183 +0,0 @@
1
- <?php
2
- /**
3
- * Controller Tests.
4
- */
5
-
6
- namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes;
7
-
8
- use Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes\ControllerTestCase;
9
- use Automattic\WooCommerce\Blocks\Tests\Helpers\FixtureData;
10
- use Automattic\WooCommerce\Blocks\Tests\Helpers\ValidateSchema;
11
-
12
- /**
13
- * Cart Coupons Controller Tests.
14
- */
15
- class CartCoupons extends ControllerTestCase {
16
-
17
- /**
18
- * Setup test products data. Called before every test.
19
- */
20
- public function setUp() {
21
- parent::setUp();
22
-
23
- $fixtures = new FixtureData();
24
-
25
- $this->product = $fixtures->get_simple_product( [
26
- 'name' => 'Test Product 1',
27
- 'regular_price' => 10,
28
- ] );
29
- $this->coupon = $fixtures->get_coupon( ['code' => 'test_coupon'] );
30
-
31
- wc_empty_cart();
32
-
33
- wc()->cart->add_to_cart( $this->product->get_id(), 2 );
34
- wc()->cart->apply_coupon( $this->coupon->get_code() );
35
- }
36
-
37
- /**
38
- * Test route registration.
39
- */
40
- public function test_register_routes() {
41
- $routes = rest_get_server()->get_routes();
42
- $this->assertArrayHasKey( '/wc/store/cart/coupons', $routes );
43
- $this->assertArrayHasKey( '/wc/store/cart/coupons/(?P<code>[\w-]+)', $routes );
44
- }
45
-
46
- /**
47
- * Test getting cart.
48
- */
49
- public function test_get_items() {
50
- $response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc/store/cart/coupons' ) );
51
- $data = $response->get_data();
52
-
53
- $this->assertEquals( 200, $response->get_status() );
54
- $this->assertEquals( 1, count( $data ) );
55
- }
56
-
57
- /**
58
- * Test getting cart item by key.
59
- */
60
- public function test_get_item() {
61
- $response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc/store/cart/coupons/' . $this->coupon->get_code() ) );
62
- $data = $response->get_data();
63
-
64
- $this->assertEquals( 200, $response->get_status() );
65
- $this->assertEquals( $this->coupon->get_code(), $data['code'] );
66
- $this->assertEquals( '0', $data['totals']->total_discount );
67
- $this->assertEquals( '0', $data['totals']->total_discount_tax );
68
- }
69
-
70
- /**
71
- * Test add to cart.
72
- */
73
- public function test_create_item() {
74
- wc()->cart->remove_coupons();
75
-
76
- $request = new \WP_REST_Request( 'POST', '/wc/store/cart/coupons' );
77
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
78
- $request->set_body_params(
79
- array(
80
- 'code' => $this->coupon->get_code(),
81
- )
82
- );
83
- $response = rest_get_server()->dispatch( $request );
84
- $data = $response->get_data();
85
-
86
- $this->assertEquals( 201, $response->get_status() );
87
- $this->assertEquals( $this->coupon->get_code(), $data['code'] );
88
- }
89
-
90
- /**
91
- * Test add to cart does not allow invalid items.
92
- */
93
- public function test_invalid_create_item() {
94
- wc()->cart->remove_coupons();
95
-
96
- $request = new \WP_REST_Request( 'POST', '/wc/store/cart/coupons' );
97
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
98
- $request->set_body_params(
99
- array(
100
- 'code' => 'IDONOTEXIST',
101
- )
102
- );
103
- $response = rest_get_server()->dispatch( $request );
104
- $data = $response->get_data();
105
-
106
- $this->assertEquals( 400, $response->get_status() );
107
- }
108
-
109
- /**
110
- * Test delete item.
111
- */
112
- public function test_delete_item() {
113
- $request = new \WP_REST_Request( 'DELETE', '/wc/store/cart/coupons/' . $this->coupon->get_code() );
114
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
115
- $response = rest_get_server()->dispatch( $request );
116
- $data = $response->get_data();
117
-
118
- $this->assertEquals( 204, $response->get_status() );
119
- $this->assertEmpty( $data );
120
-
121
- $request = new \WP_REST_Request( 'DELETE', '/wc/store/cart/coupons/' . $this->coupon->get_code() );
122
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
123
- $response = rest_get_server()->dispatch( $request );
124
- $data = $response->get_data();
125
-
126
- $this->assertEquals( 404, $response->get_status() );
127
-
128
- $request = new \WP_REST_Request( 'DELETE', '/wc/store/cart/coupons/i-do-not-exist' );
129
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
130
- $response = rest_get_server()->dispatch( $request );
131
- $data = $response->get_data();
132
-
133
- $this->assertEquals( 404, $response->get_status() );
134
- }
135
-
136
- /**
137
- * Test delete all items.
138
- */
139
- public function test_delete_items() {
140
- $request = new \WP_REST_Request( 'DELETE', '/wc/store/cart/coupons' );
141
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
142
- $response = rest_get_server()->dispatch( $request );
143
- $data = $response->get_data();
144
-
145
- $this->assertEquals( 200, $response->get_status() );
146
- $this->assertEquals( [], $data );
147
-
148
- $response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc/store/cart/coupons' ) );
149
- $data = $response->get_data();
150
-
151
- $this->assertEquals( 200, $response->get_status() );
152
- $this->assertEquals( 0, count( $data ) );
153
- }
154
-
155
- /**
156
- * Test conversion of cart item to rest response.
157
- */
158
- public function test_prepare_item() {
159
- $routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController( $this->mock_extend ) );
160
- $controller = $routes->get( 'cart-coupons' );
161
-
162
- $response = $controller->prepare_item_for_response( $this->coupon->get_code(), new \WP_REST_Request() );
163
- $data = $response->get_data();
164
-
165
- $this->assertArrayHasKey( 'code', $data );
166
- $this->assertArrayHasKey( 'totals', $data );
167
- }
168
-
169
- /**
170
- * Test schema matches responses.
171
- */
172
- public function test_get_item_schema() {
173
- $routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController( $this->mock_extend ) );
174
- $controller = $routes->get( 'cart-coupons' );
175
- $schema = $controller->get_item_schema();
176
- $response = $controller->prepare_item_for_response( $this->coupon->get_code(), new \WP_REST_Request() );
177
- $schema = $controller->get_item_schema();
178
- $validate = new ValidateSchema( $schema );
179
-
180
- $diff = $validate->get_diff_from_object( $response->get_data() );
181
- $this->assertEmpty( $diff, print_r( $diff, true ) );
182
- }
183
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/StoreApi/Routes/CartExtensions.php DELETED
@@ -1,39 +0,0 @@
1
- <?php
2
- /**
3
- * Cart extensions route tests.
4
- */
5
-
6
- namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes;
7
-
8
- use Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes\ControllerTestCase;
9
- use Automattic\WooCommerce\Blocks\StoreApi\Routes\RouteException;
10
- use Automattic\WooCommerce\Blocks\Tests\Helpers\ValidateSchema;
11
-
12
- /**
13
- * Cart Controller Tests.
14
- */
15
- class CartExtensions extends ControllerTestCase {
16
-
17
- /**
18
- * Test route registration.
19
- */
20
- public function test_register_routes() {
21
- $routes = rest_get_server()->get_routes();
22
- $this->assertArrayHasKey( '/wc/store/cart/extensions', $routes );
23
- }
24
-
25
- /**
26
- * Test getting cart with invalid namespace.
27
- */
28
- public function test_post() {
29
- $request = new \WP_REST_Request( 'POST', '/wc/store/cart/extensions' );
30
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
31
- $request->set_body_params(
32
- array(
33
- 'namespace' => 'test-plugin',
34
- )
35
- );
36
- $response = rest_get_server()->dispatch( $request );
37
- $this->assertEquals( 400, $response->get_status() );
38
- }
39
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/StoreApi/Routes/CartItems.php DELETED
@@ -1,271 +0,0 @@
1
- <?php
2
- /**
3
- * Controller Tests.
4
- */
5
-
6
- namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes;
7
-
8
- use Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes\ControllerTestCase;
9
- use Automattic\WooCommerce\Blocks\Tests\Helpers\FixtureData;
10
- use Automattic\WooCommerce\Blocks\Tests\Helpers\ValidateSchema;
11
-
12
- /**
13
- * Cart Controller Tests.
14
- */
15
- class CartItems extends ControllerTestCase {
16
-
17
- /**
18
- * Setup test products data. Called before every test.
19
- */
20
- public function setUp() {
21
- parent::setUp();
22
-
23
- $fixtures = new FixtureData();
24
-
25
- $this->products = [
26
- $fixtures->get_simple_product( [
27
- 'name' => 'Test Product 1',
28
- 'stock_status' => 'instock',
29
- 'regular_price' => 10,
30
- 'weight' => 10,
31
- 'image_id' => $fixtures->sideload_image(),
32
- ] ),
33
- ];
34
-
35
- $variable_product = $fixtures->get_variable_product(
36
- [
37
- 'name' => 'Test Product 2',
38
- 'stock_status' => 'instock',
39
- 'regular_price' => 10,
40
- 'weight' => 10,
41
- 'image_id' => $fixtures->sideload_image(),
42
- ],
43
- [
44
- $fixtures->get_product_attribute( 'color', [ 'red', 'green', 'blue' ] ),
45
- $fixtures->get_product_attribute( 'size', [ 'small', 'medium', 'large' ] )
46
- ]
47
- );
48
- $variation = $fixtures->get_variation_product( $variable_product->get_id(), [ 'pa_color' => 'red', 'pa_size' => 'small' ] );
49
-
50
- $this->products[] = $variable_product;
51
-
52
- wc_empty_cart();
53
- $this->keys = [];
54
- $this->keys[] = wc()->cart->add_to_cart( $this->products[0]->get_id(), 2 );
55
- $this->keys[] = wc()->cart->add_to_cart(
56
- $this->products[1]->get_id(),
57
- 1,
58
- $variation->get_id(),
59
- array(
60
- 'attribute_pa_color' => 'red',
61
- 'attribute_pa_size' => 'small',
62
- )
63
- );
64
- }
65
-
66
- /**
67
- * Test route registration.
68
- */
69
- public function test_register_routes() {
70
- $routes = rest_get_server()->get_routes();
71
- $this->assertArrayHasKey( '/wc/store/cart/items', $routes );
72
- $this->assertArrayHasKey( '/wc/store/cart/items/(?P<key>[\w-]{32})', $routes );
73
- }
74
-
75
- /**
76
- * Test getting cart.
77
- */
78
- public function test_get_items() {
79
- $response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc/store/cart/items' ) );
80
- $data = $response->get_data();
81
-
82
- $this->assertEquals( 200, $response->get_status() );
83
- $this->assertEquals( 2, count( $data ) );
84
- }
85
-
86
- /**
87
- * Test getting cart item by key.
88
- */
89
- public function test_get_item() {
90
- $response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc/store/cart/items/' . $this->keys[0] ) );
91
- $data = $response->get_data();
92
-
93
- $this->assertEquals( 200, $response->get_status() );
94
- $this->assertEquals( $this->keys[0], $data['key'] );
95
- $this->assertEquals( $this->products[0]->get_id(), $data['id'] );
96
- $this->assertEquals( $this->products[0]->get_name(), $data['name'] );
97
- $this->assertEquals( $this->products[0]->get_sku(), $data['sku'] );
98
- $this->assertEquals( $this->products[0]->get_permalink(), $data['permalink'] );
99
- $this->assertEquals( 2, $data['quantity'] );
100
- $this->assertEquals( '2000', $data['totals']->line_subtotal );
101
- $this->assertEquals( '2000', $data['totals']->line_total );
102
-
103
- $request = new \WP_REST_Request( 'DELETE', '/wc/store/cart/items/XXX815416f775098fe977004015c6193' );
104
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
105
- $response = rest_get_server()->dispatch( $request );
106
- $data = $response->get_data();
107
-
108
- $this->assertEquals( 404, $response->get_status() );
109
- }
110
-
111
- /**
112
- * Test add to cart.
113
- */
114
- public function test_create_item() {
115
- wc_empty_cart();
116
-
117
- $request = new \WP_REST_Request( 'POST', '/wc/store/cart/items' );
118
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
119
- $request->set_body_params(
120
- array(
121
- 'id' => $this->products[0]->get_id(),
122
- 'quantity' => '10',
123
- )
124
- );
125
- $response = rest_get_server()->dispatch( $request );
126
- $data = $response->get_data();
127
-
128
- $this->assertEquals( 201, $response->get_status() );
129
- $this->assertEquals( $this->products[0]->get_id(), $data['id'] );
130
- $this->assertEquals( 10, $data['quantity'] );
131
-
132
- $response = rest_get_server()->dispatch( $request );
133
- $data = $response->get_data();
134
-
135
- $this->assertEquals( 201, $response->get_status() );
136
- $this->assertEquals( $this->products[0]->get_id(), $data['id'] );
137
- $this->assertEquals( 20, $data['quantity'] );
138
- }
139
-
140
- /**
141
- * Test add to cart does not allow invalid items.
142
- */
143
- public function test_invalid_create_item() {
144
- wc_empty_cart();
145
-
146
- $fixtures = new FixtureData();
147
- $invalid_product = $fixtures->get_simple_product( [
148
- 'name' => 'Invalid Product',
149
- 'regular_price' => '',
150
- ] );
151
-
152
- $request = new \WP_REST_Request( 'POST', '/wc/store/cart/items' );
153
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
154
- $request->set_body_params(
155
- array(
156
- 'id' => $invalid_product->get_id(),
157
- 'quantity' => '10',
158
- )
159
- );
160
- $response = rest_get_server()->dispatch( $request );
161
-
162
- $this->assertEquals( 400, $response->get_status() );
163
- }
164
-
165
- /**
166
- * Test updating an item.
167
- */
168
- public function test_update_item() {
169
- $request = new \WP_REST_Request( 'PUT', '/wc/store/cart/items/' . $this->keys[0] );
170
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
171
- $request->set_body_params(
172
- array(
173
- 'quantity' => '10',
174
- )
175
- );
176
- $response = rest_get_server()->dispatch( $request );
177
- $data = $response->get_data();
178
-
179
- $this->assertEquals( 200, $response->get_status() );
180
- $this->assertEquals( 10, $data['quantity'] );
181
- }
182
-
183
- /**
184
- * Test delete item.
185
- */
186
- public function test_delete_item() {
187
- $request = new \WP_REST_Request( 'DELETE', '/wc/store/cart/items/' . $this->keys[0] );
188
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
189
- $response = rest_get_server()->dispatch( $request );
190
- $data = $response->get_data();
191
-
192
- $this->assertEquals( 204, $response->get_status() );
193
- $this->assertEmpty( $data );
194
-
195
- $request = new \WP_REST_Request( 'DELETE', '/wc/store/cart/items/' . $this->keys[0] );
196
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
197
- $response = rest_get_server()->dispatch( $request );
198
- $data = $response->get_data();
199
-
200
- $this->assertEquals( 404, $response->get_status() );
201
- }
202
-
203
- /**
204
- * Test delete all items.
205
- */
206
- public function test_delete_items() {
207
- $request = new \WP_REST_Request( 'DELETE', '/wc/store/cart/items' );
208
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
209
- $response = rest_get_server()->dispatch( $request );
210
- $data = $response->get_data();
211
-
212
- $this->assertEquals( 200, $response->get_status() );
213
- $this->assertEquals( [], $data );
214
-
215
- $response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc/store/cart/items' ) );
216
- $data = $response->get_data();
217
-
218
- $this->assertEquals( 200, $response->get_status() );
219
- $this->assertEquals( 0, count( $data ) );
220
- }
221
-
222
- /**
223
- * Test conversion of cart item to rest response.
224
- */
225
- public function test_prepare_item() {
226
- $routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController( $this->mock_extend ) );
227
- $controller = $routes->get( 'cart-items' );
228
- $cart = wc()->cart->get_cart();
229
- $response = $controller->prepare_item_for_response( current( $cart ), new \WP_REST_Request() );
230
- $data = $response->get_data();
231
-
232
- $this->assertArrayHasKey( 'key', $data );
233
- $this->assertArrayHasKey( 'id', $data );
234
- $this->assertArrayHasKey( 'quantity', $data );
235
- $this->assertArrayHasKey( 'name', $data );
236
- $this->assertArrayHasKey( 'sku', $data );
237
- $this->assertArrayHasKey( 'permalink', $data );
238
- $this->assertArrayHasKey( 'images', $data );
239
- $this->assertArrayHasKey( 'totals', $data );
240
- $this->assertArrayHasKey( 'variation', $data );
241
- $this->assertArrayHasKey( 'item_data', $data );
242
- $this->assertArrayHasKey( 'low_stock_remaining', $data );
243
- $this->assertArrayHasKey( 'backorders_allowed', $data );
244
- $this->assertArrayHasKey( 'show_backorder_badge', $data );
245
- $this->assertArrayHasKey( 'short_description', $data );
246
- $this->assertArrayHasKey( 'catalog_visibility', $data );
247
- }
248
-
249
- /**
250
- * Test schema matches responses.
251
- *
252
- * Tests schema of both products in cart to cover as much schema as possible.
253
- */
254
- public function test_get_item_schema() {
255
- $routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController( $this->mock_extend ) );
256
- $controller = $routes->get( 'cart-items' );
257
- $schema = $controller->get_item_schema();
258
- $cart = wc()->cart->get_cart();
259
- $validate = new ValidateSchema( $schema );
260
-
261
- // Simple product.
262
- $response = $controller->prepare_item_for_response( current( $cart ), new \WP_REST_Request() );
263
- $diff = $validate->get_diff_from_object( $response->get_data() );
264
- $this->assertEmpty( $diff, print_r( $diff, true ) );
265
-
266
- // Variable product.
267
- $response = $controller->prepare_item_for_response( end( $cart ), new \WP_REST_Request() );
268
- $diff = $validate->get_diff_from_object( $response->get_data() );
269
- $this->assertEmpty( $diff, print_r( $diff, true ) );
270
- }
271
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/StoreApi/Routes/Checkout.php DELETED
@@ -1,225 +0,0 @@
1
- <?php
2
- /**
3
- * Controller Tests.
4
- */
5
-
6
- namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes;
7
-
8
- use Automattic\WooCommerce\Blocks\Domain\Services\ExtendRestApi;
9
- use Automattic\WooCommerce\Blocks\Domain\Package as DomainPackage;
10
- use Automattic\WooCommerce\Blocks\StoreApi\Formatters;
11
- use Automattic\WooCommerce\Blocks\StoreApi\Formatters\MoneyFormatter;
12
- use Automattic\WooCommerce\Blocks\StoreApi\Formatters\HtmlFormatter;
13
- use Automattic\WooCommerce\Blocks\StoreApi\Formatters\CurrencyFormatter;
14
- use Automattic\WooCommerce\Blocks\Domain\Services\FeatureGating;
15
- use Automattic\WooCommerce\Blocks\StoreApi\Schemas\CheckoutSchema;
16
- use Automattic\WooCommerce\Blocks\Tests\Helpers\FixtureData;
17
- use Automattic\WooCommerce\Blocks\StoreApi\Routes\Checkout as CheckoutRoute;
18
- use Automattic\WooCommerce\Blocks\StoreApi\Utilities\CartController;
19
- use Automattic\WooCommerce\Blocks\StoreApi\Utilities\OrderController;
20
- use Automattic\WooCommerce\Blocks\StoreApi\SchemaController;
21
-
22
- use Mockery\Adapter\Phpunit\MockeryTestCase;
23
-
24
- /**
25
- * Checkout Controller Tests.
26
- */
27
- class Checkout extends MockeryTestCase {
28
- /**
29
- * Setup test products data. Called before every test.
30
- */
31
- protected function setUp(): void {
32
- parent::setUp();
33
-
34
- global $wp_rest_server;
35
- $wp_rest_server = new \Spy_REST_Server();
36
- do_action( 'rest_api_init', $wp_rest_server );
37
-
38
- $formatters = new Formatters();
39
- $formatters->register( 'money', MoneyFormatter::class );
40
- $formatters->register( 'html', HtmlFormatter::class );
41
- $formatters->register( 'currency', CurrencyFormatter::class );
42
-
43
- $this->mock_extend = new ExtendRestApi( new DomainPackage( '', '', new FeatureGating( 2 ) ), $formatters );
44
- $this->mock_extend->register_endpoint_data(
45
- array(
46
- 'endpoint' => CheckoutSchema::IDENTIFIER,
47
- 'namespace' => 'extension_namespace',
48
- 'schema_callback' => function() {
49
- return array(
50
- 'extension_key' => array(
51
- 'description' => 'Test key',
52
- 'type' => 'boolean',
53
- ),
54
- );
55
- },
56
- )
57
- );
58
- $schema_controller = new SchemaController( $this->mock_extend );
59
- $route = new CheckoutRoute( $schema_controller->get( 'cart' ), $schema_controller->get( 'checkout' ), new CartController(), new OrderController() );
60
- register_rest_route( $route->get_namespace(), $route->get_path(), $route->get_args(), true );
61
-
62
- $fixtures = new FixtureData();
63
- $fixtures->shipping_add_flat_rate();
64
- $fixtures->payments_enable_bacs();
65
- $this->products = array(
66
- $fixtures->get_simple_product(
67
- array(
68
- 'name' => 'Test Product 1',
69
- 'stock_status' => 'instock',
70
- 'regular_price' => 10,
71
- 'weight' => 10,
72
- )
73
- ),
74
- $fixtures->get_simple_product(
75
- array(
76
- 'name' => 'Test Product 2',
77
- 'stock_status' => 'instock',
78
- 'regular_price' => 10,
79
- 'weight' => 10,
80
- )
81
- ),
82
- );
83
- wc_empty_cart();
84
- $this->keys = array();
85
- $this->keys[] = wc()->cart->add_to_cart( $this->products[0]->get_id(), 2 );
86
- $this->keys[] = wc()->cart->add_to_cart( $this->products[1]->get_id(), 1 );
87
- }
88
-
89
- /**
90
- * Tear down Rest API server.
91
- */
92
- protected function tearDown(): void {
93
- parent::tearDown();
94
- global $wp_rest_server;
95
- $wp_rest_server = null;
96
- }
97
-
98
- /**
99
- * Test route registration.
100
- */
101
- public function test_register_routes() {
102
- $routes = rest_get_server()->get_routes();
103
- $this->assertArrayHasKey( '/wc/store/checkout', $routes );
104
- }
105
-
106
- /**
107
- * Ensure that registered extension data is correctly shown on options requests.
108
- */
109
- public function test_options_extension_data() {
110
- $request = new \WP_REST_Request( 'OPTIONS', '/wc/store/checkout' );
111
- $response = rest_get_server()->dispatch( $request );
112
- $data = $response->get_data();
113
- $this->assertEquals(
114
- array(
115
- 'description' => 'Test key',
116
- 'type' => 'boolean',
117
- ),
118
- $data['schema']['properties']['extensions']['properties']['extension_namespace']['properties']['extension_key']
119
- );
120
- }
121
-
122
- /**
123
- * Ensure that registered extension data is correctly posted and visible on the server after sanitization.
124
- */
125
- public function test_post_extension_data() {
126
- $request = new \WP_REST_Request( 'POST', '/wc/store/checkout' );
127
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
128
- $request->set_body_params(
129
- array(
130
- 'billing_address' => (object) array(
131
- 'first_name' => 'test',
132
- 'last_name' => 'test',
133
- 'company' => '',
134
- 'address_1' => 'test',
135
- 'address_2' => '',
136
- 'city' => 'test',
137
- 'state' => '',
138
- 'postcode' => 'cb241ab',
139
- 'country' => 'GB',
140
- 'phone' => '',
141
- 'email' => 'test@test.com',
142
- ),
143
- 'shipping_address' => (object) array(
144
- 'first_name' => 'test',
145
- 'last_name' => 'test',
146
- 'company' => '',
147
- 'address_1' => 'test',
148
- 'address_2' => '',
149
- 'city' => 'test',
150
- 'state' => '',
151
- 'postcode' => 'cb241ab',
152
- 'country' => 'GB',
153
- 'phone' => '',
154
- ),
155
- 'payment_method' => 'bacs',
156
- 'extensions' => array(
157
- 'extension_namespace' => array(
158
- 'extension_key' => true,
159
- ),
160
- ),
161
- )
162
- );
163
- $action_callback = \Mockery::mock( 'ActionCallback' );
164
- $action_callback->shouldReceive( 'do_callback' )->withArgs(
165
- array(
166
- \Mockery::any(),
167
- \Mockery::on(
168
- function ( $argument ) {
169
- return true === $argument['extensions']['extension_namespace']['extension_key'];
170
- }
171
- ),
172
- )
173
- )->once();
174
- add_action( 'woocommerce_blocks_checkout_update_order_from_request', array( $action_callback, 'do_callback' ), 10, 2 );
175
- $response = rest_get_server()->dispatch( $request );
176
- $this->assertEquals( 200, $response->get_status() );
177
- remove_action( 'woocommerce_blocks_checkout_update_order_from_request', array( $action_callback, 'do_callback' ), 10, 2 );
178
- }
179
-
180
- /**
181
- * Ensure that registered extension data is correctly posted and visible on the server after sanitization.
182
- */
183
- public function test_post_invalid_extension_data() {
184
- $request = new \WP_REST_Request( 'POST', '/wc/store/checkout' );
185
- $request->set_header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
186
- $request->set_body_params(
187
- array(
188
- 'billing_address' => (object) array(
189
- 'first_name' => 'test',
190
- 'last_name' => 'test',
191
- 'company' => '',
192
- 'address_1' => 'test',
193
- 'address_2' => '',
194
- 'city' => 'test',
195
- 'state' => '',
196
- 'postcode' => 'cb241ab',
197
- 'country' => 'GB',
198
- 'phone' => '',
199
- 'email' => 'test@test.com',
200
- ),
201
- 'shipping_address' => (object) array(
202
- 'first_name' => 'test',
203
- 'last_name' => 'test',
204
- 'company' => '',
205
- 'address_1' => 'test',
206
- 'address_2' => '',
207
- 'city' => 'test',
208
- 'state' => '',
209
- 'postcode' => 'cb241ab',
210
- 'country' => 'GB',
211
- 'phone' => '',
212
- ),
213
- 'payment_method' => 'bacs',
214
- 'extensions' => array(
215
- 'extension_namespace' => array(
216
- 'extension_key' => 'invalid-string',
217
- ),
218
- ),
219
- )
220
- );
221
- $response = rest_get_server()->dispatch( $request );
222
- $this->assertEquals( 400, $response->get_status() );
223
- $this->assertEquals( 'rest_invalid_param', $response->get_data()['code'] );
224
- }
225
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/StoreApi/Routes/ControllerTestCase.php DELETED
@@ -1,49 +0,0 @@
1
- <?php
2
- /**
3
- * ControllerTestCase Tests.
4
- */
5
-
6
- namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes;
7
-
8
- use Automattic\WooCommerce\Blocks\Domain\Services\ExtendRestApi;
9
- use Automattic\WooCommerce\Blocks\Domain\Package as DomainPackage;
10
- use Automattic\WooCommerce\Blocks\StoreApi\Formatters;
11
- use Automattic\WooCommerce\Blocks\StoreApi\Formatters\MoneyFormatter;
12
- use Automattic\WooCommerce\Blocks\StoreApi\Formatters\HtmlFormatter;
13
- use Automattic\WooCommerce\Blocks\StoreApi\Formatters\CurrencyFormatter;
14
- use Automattic\WooCommerce\Blocks\Domain\Services\FeatureGating;
15
-
16
- abstract class ControllerTestCase extends \WP_Test_REST_TestCase {
17
- protected $mock_extend;
18
-
19
- /**
20
- * Setup Rest API server.
21
- */
22
- public function setUp() {
23
- parent::setUp();
24
-
25
- /** @var \WP_REST_Server $wp_rest_server */
26
- global $wp_rest_server;
27
- $wp_rest_server = new \Spy_REST_Server;
28
- do_action( 'rest_api_init', $wp_rest_server );
29
-
30
- wp_set_current_user( 0 );
31
- update_option( 'woocommerce_weight_unit', 'g' );
32
-
33
- $formatters = new Formatters();
34
- $formatters->register( 'money', MoneyFormatter::class );
35
- $formatters->register( 'html', HtmlFormatter::class );
36
- $formatters->register( 'currency', CurrencyFormatter::class );
37
- $this->mock_extend = new ExtendRestApi( new DomainPackage( '', '', new FeatureGating( 2 ) ), $formatters );
38
- }
39
-
40
- /**
41
- * Tear down Rest API server.
42
- */
43
- public function tearDown() {
44
- parent::tearDown();
45
- /** @var \WP_REST_Server $wp_rest_server */
46
- global $wp_rest_server;
47
- $wp_rest_server = null;
48
- }
49
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/StoreApi/Routes/ProductAttributeTerms.php DELETED
@@ -1,99 +0,0 @@
1
- <?php
2
- /**
3
- * Controller Tests.
4
- */
5
-
6
- namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes;
7
-
8
- use Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes\ControllerTestCase;
9
- use Automattic\WooCommerce\Blocks\Tests\Helpers\FixtureData;
10
- use Automattic\WooCommerce\Blocks\Tests\Helpers\ValidateSchema;
11
-
12
- /**
13
- * Product Attributes Controller Tests.
14
- */
15
- class ProductAttributeTerms extends ControllerTestCase {
16
-
17
- /**
18
- * Setup test products data. Called before every test.
19
- */
20
- public function setUp() {
21
- parent::setUp();
22
-
23
- $fixtures = new FixtureData();
24
-
25
- $this->attributes = [
26
- $fixtures->get_product_attribute( 'color', [ 'red', 'green', 'blue' ] ),
27
- $fixtures->get_product_attribute( 'size', [ 'small', 'medium', 'large' ] )
28
- ];
29
- }
30
-
31
- /**
32
- * Test route registration.
33
- */
34
- public function test_register_routes() {
35
- $routes = rest_get_server()->get_routes();
36
- $this->assertArrayHasKey( '/wc/store/products/attributes/(?P<attribute_id>[\d]+)/terms', $routes );
37
- }
38
-
39
- /**
40
- * Test getting items.
41
- */
42
- public function test_get_items() {
43
- $request = new \WP_REST_Request( 'GET', '/wc/store/products/attributes/' . $this->attributes[0]['attribute_id'] . '/terms' );
44
- $request->set_param( 'hide_empty', false );
45
- $response = rest_get_server()->dispatch( $request );
46
- $data = $response->get_data();
47
-
48
- $this->assertEquals( 200, $response->get_status() );
49
- $this->assertEquals( 3, count( $data ) );
50
- $this->assertArrayHasKey( 'id', $data[0] );
51
- $this->assertArrayHasKey( 'name', $data[0] );
52
- $this->assertArrayHasKey( 'slug', $data[0] );
53
- $this->assertArrayHasKey( 'description', $data[0] );
54
- $this->assertArrayHasKey( 'count', $data[0] );
55
- }
56
-
57
- /**
58
- * Test conversion of product to rest response.
59
- */
60
- public function test_prepare_item() {
61
- $schema = new \Automattic\WooCommerce\Blocks\StoreApi\Schemas\TermSchema( $this->mock_extend );
62
- $controller = new \Automattic\WooCommerce\Blocks\StoreApi\Routes\ProductAttributeTerms( $schema );
63
- $response = $controller->prepare_item_for_response( get_term_by( 'name', 'small', 'pa_size' ), new \WP_REST_Request() );
64
- $data = $response->get_data();
65
-
66
- $this->assertArrayHasKey( 'id', $data );
67
- $this->assertEquals( 'small', $data['name'] );
68
- $this->assertEquals( 'small-slug', $data['slug'] );
69
- $this->assertEquals( 'Description of small', $data['description'] );
70
- $this->assertEquals( 0, $data['count'] );
71
- }
72
-
73
- /**
74
- * Test collection params getter.
75
- */
76
- public function test_get_collection_params() {
77
- $routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController( $this->mock_extend ) );
78
- $controller = $routes->get( 'product-attribute-terms' );
79
- $params = $controller->get_collection_params();
80
-
81
- $this->assertArrayHasKey( 'order', $params );
82
- $this->assertArrayHasKey( 'orderby', $params );
83
- $this->assertArrayHasKey( 'hide_empty', $params );
84
- }
85
-
86
- /**
87
- * Test schema matches responses.
88
- */
89
- public function test_get_item_schema() {
90
- $routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController( $this->mock_extend ) );
91
- $controller = $routes->get( 'product-attribute-terms' );
92
- $schema = $controller->get_item_schema();
93
- $response = $controller->prepare_item_for_response( get_term_by( 'name', 'small', 'pa_size' ), new \WP_REST_Request() );
94
- $validate = new ValidateSchema( $schema );
95
-
96
- $diff = $validate->get_diff_from_object( $response->get_data() );
97
- $this->assertEmpty( $diff, print_r( $diff, true ) );
98
- }
99
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/StoreApi/Routes/ProductAttributes.php DELETED
@@ -1,107 +0,0 @@
1
- <?php
2
- /**
3
- * Controller Tests.
4
- */
5
-
6
- namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes;
7
-
8
- use Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes\ControllerTestCase;
9
- use Automattic\WooCommerce\Blocks\Tests\Helpers\FixtureData;
10
- use Automattic\WooCommerce\Blocks\Tests\Helpers\ValidateSchema;
11
-
12
- /**
13
- * Product Attributes Controller Tests.
14
- */
15
- class ProductAttributes extends ControllerTestCase {
16
-
17
- /**
18
- * Setup test products data. Called before every test.
19
- */
20
- public function setUp() {
21
- parent::setUp();
22
-
23
- $fixtures = new FixtureData();
24
-
25
- $this->attributes = [
26
- $fixtures->get_product_attribute( 'color', [ 'red', 'green', 'blue' ] ),
27
- $fixtures->get_product_attribute( 'size', [ 'small', 'medium', 'large' ] )
28
- ];
29
- }
30
-
31
- /**
32
- * Test route registration.
33
- */
34
- public function test_register_routes() {
35
- $routes = rest_get_server()->get_routes();
36
- $this->assertArrayHasKey( '/wc/store/products/attributes', $routes );
37
- $this->assertArrayHasKey( '/wc/store/products/attributes/(?P<id>[\d]+)', $routes );
38
- }
39
-
40
- /**
41
- * Test getting item.
42
- */
43
- public function test_get_item() {
44
- $attribute = wc_get_attribute( $this->attributes[0]['attribute_id'] );
45
- $response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc/store/products/attributes/' . $attribute->id ) );
46
- $data = $response->get_data();
47
-
48
- $this->assertEquals( 200, $response->get_status() );
49
- $this->assertEquals( $attribute->id, $data['id'] );
50
- $this->assertEquals( $attribute->name, $data['name'] );
51
- $this->assertEquals( $attribute->slug, $data['taxonomy'] );
52
- $this->assertEquals( $attribute->type, $data['type'] );
53
- $this->assertEquals( $attribute->order_by, $data['order'] );
54
- $this->assertEquals( $attribute->has_archives, $data['has_archives'] );
55
- }
56
-
57
- /**
58
- * Test getting items.
59
- */
60
- public function test_get_items() {
61
- $response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc/store/products/attributes' ) );
62
- $data = $response->get_data();
63
-
64
- $this->assertEquals( 200, $response->get_status() );
65
- $this->assertEquals( 2, count( $data ) );
66
- $this->assertArrayHasKey( 'id', $data[0] );
67
- $this->assertArrayHasKey( 'name', $data[0] );
68
- $this->assertArrayHasKey( 'taxonomy', $data[0] );
69
- $this->assertArrayHasKey( 'type', $data[0] );
70
- $this->assertArrayHasKey( 'order', $data[0] );
71
- $this->assertArrayHasKey( 'has_archives', $data[0] );
72
- }
73
-
74
- /**
75
- * Test conversion of product to rest response.
76
- */
77
- public function test_prepare_item() {
78
- $routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController( $this->mock_extend ) );
79
- $controller = $routes->get( 'product-attributes' );
80
- $attribute = wc_get_attribute( $this->attributes[0]['attribute_id'] );
81
- $response = $controller->prepare_item_for_response( $attribute, new \WP_REST_Request() );
82
- $data = $response->get_data();
83
-
84
- $this->assertArrayHasKey( 'id', $data );
85
- $this->assertArrayHasKey( 'name', $data );
86
- $this->assertArrayHasKey( 'taxonomy', $data );
87
- $this->assertArrayHasKey( 'type', $data );
88
- $this->assertArrayHasKey( 'order', $data );
89
- $this->assertArrayHasKey( 'has_archives', $data );
90
- }
91
-
92
- /**
93
- * Test schema matches responses.
94
- */
95
- public function test_get_item_schema() {
96
- $routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController( $this->mock_extend ) );
97
- $controller = $routes->get( 'product-attributes' );
98
- $schema = $controller->get_item_schema();
99
- $attribute = wc_get_attribute( $this->attributes[0]['attribute_id'] );
100
- $response = $controller->prepare_item_for_response( $attribute, new \WP_REST_Request() );
101
- $schema = $controller->get_item_schema();
102
- $validate = new ValidateSchema( $schema );
103
-
104
- $diff = $validate->get_diff_from_object( $response->get_data() );
105
- $this->assertEmpty( $diff, print_r( $diff, true ) );
106
- }
107
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/StoreApi/Routes/ProductCollectionData.php DELETED
@@ -1,185 +0,0 @@
1
- <?php
2
- /**
3
- * Controller Tests.
4
- */
5
-
6
- namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes;
7
-
8
- use Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes\ControllerTestCase;
9
- use Automattic\WooCommerce\Blocks\Tests\Helpers\FixtureData;
10
- use Automattic\WooCommerce\Blocks\Tests\Helpers\ValidateSchema;
11
-
12
- /**
13
- * Controller Tests.
14
- */
15
- class ProductCollectionData extends ControllerTestCase {
16
-
17
- /**
18
- * Setup test products data. Called before every test.
19
- */
20
- public function setUp() {
21
- parent::setUp();
22
-
23
- $fixtures = new FixtureData();
24
-
25
- $this->products = [
26
- $fixtures->get_simple_product( [
27
- 'name' => 'Test Product 1',
28
- 'regular_price' => 10,
29
- ] ),
30
- $fixtures->get_simple_product( [
31
- 'name' => 'Test Product 2',
32
- 'regular_price' => 100,
33
- ] ),
34
- ];
35
-
36
- $fixtures->add_product_review( $this->products[0]->get_id(), 5 );
37
- $fixtures->add_product_review( $this->products[1]->get_id(), 4 );
38
- }
39
-
40
- /**
41
- * Test route registration.
42
- */
43
- public function test_register_routes() {
44
- $routes = rest_get_server()->get_routes();
45
- $this->assertArrayHasKey( '/wc/store/products/collection-data', $routes );
46
- }
47
-
48
- /**
49
- * Test getting items.
50
- */
51
- public function test_get_items() {
52
- $response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc/store/products/collection-data' ) );
53
- $data = $response->get_data();
54
-
55
- $this->assertEquals( 200, $response->get_status() );
56
- $this->assertEquals( null, $data['price_range'] );
57
- $this->assertEquals( null, $data['attribute_counts'] );
58
- $this->assertEquals( null, $data['rating_counts'] );
59
- }
60
-
61
- /**
62
- * Test calculation method.
63
- */
64
- public function test_calculate_price_range() {
65
- $request = new \WP_REST_Request( 'GET', '/wc/store/products/collection-data' );
66
- $request->set_param( 'calculate_price_range', true );
67
- $response = rest_get_server()->dispatch( $request );
68
- $data = $response->get_data();
69
-
70
- $this->assertEquals( 200, $response->get_status() );
71
- $this->assertEquals( 2, $data['price_range']->currency_minor_unit );
72
- $this->assertEquals( '1000', $data['price_range']->min_price );
73
- $this->assertEquals( '10000', $data['price_range']->max_price );
74
- $this->assertEquals( null, $data['attribute_counts'] );
75
- $this->assertEquals( null, $data['rating_counts'] );
76
- }
77
-
78
- /**
79
- * Test calculation method.
80
- */
81
- public function test_calculate_attribute_counts() {
82
- $fixtures = new FixtureData();
83
- $product = $fixtures->get_variable_product(
84
- [],
85
- [
86
- $fixtures->get_product_attribute( 'size', [ 'small', 'medium', 'large' ] )
87
- ]
88
- );
89
-
90
- $request = new \WP_REST_Request( 'GET', '/wc/store/products/collection-data' );
91
- $request->set_param(
92
- 'calculate_attribute_counts',
93
- [
94
- [
95
- 'taxonomy' => 'pa_size',
96
- 'query_type' => 'and',
97
- ],
98
- ]
99
- );
100
- $response = rest_get_server()->dispatch( $request );
101
- $data = $response->get_data();
102
-
103
- $this->assertEquals( 200, $response->get_status() );
104
- $this->assertEquals( null, $data['price_range'] );
105
- $this->assertEquals( null, $data['rating_counts'] );
106
-
107
- $this->assertObjectHasAttribute( 'term', $data['attribute_counts'][0] );
108
- $this->assertObjectHasAttribute( 'count', $data['attribute_counts'][0] );
109
- }
110
-
111
- /**
112
- * Test calculation method.
113
- */
114
- public function test_calculate_rating_counts() {
115
- $request = new \WP_REST_Request( 'GET', '/wc/store/products/collection-data' );
116
- $request->set_param( 'calculate_rating_counts', true );
117
- $response = rest_get_server()->dispatch( $request );
118
- $data = $response->get_data();
119
-
120
- $this->assertEquals( 200, $response->get_status() );
121
- $this->assertEquals( null, $data['price_range'] );
122
- $this->assertEquals( null, $data['attribute_counts'] );
123
- $this->assertEquals(
124
- [
125
- (object) [
126
- 'rating' => 4,
127
- 'count' => 1,
128
- ],
129
- (object) [
130
- 'rating' => 5,
131
- 'count' => 1,
132
- ],
133
- ],
134
- $data['rating_counts']
135
- );
136
- }
137
-
138
- /**
139
- * Test collection params getter.
140
- */
141
- public function test_get_collection_params() {
142
- $routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController( $this->mock_extend ) );
143
- $controller = $routes->get( 'product-collection-data' );
144
- $params = $controller->get_collection_params();
145
-
146
- $this->assertArrayHasKey( 'calculate_price_range', $params );
147
- $this->assertArrayHasKey( 'calculate_attribute_counts', $params );
148
- $this->assertArrayHasKey( 'calculate_rating_counts', $params );
149
- }
150
-
151
- /**
152
- * Test schema matches responses.
153
- */
154
- public function test_get_item_schema() {
155
- $fixtures = new FixtureData();
156
- $product = $fixtures->get_variable_product(
157
- [],
158
- [
159
- $fixtures->get_product_attribute( 'size', [ 'small', 'medium', 'large' ] )
160
- ]
161
- );
162
-
163
- $routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController( $this->mock_extend ) );
164
- $controller = $routes->get( 'product-collection-data' );
165
- $schema = $controller->get_item_schema();
166
-
167
- $request = new \WP_REST_Request( 'GET', '/wc/store/products/collection-data' );
168
- $request->set_param( 'calculate_price_range', true );
169
- $request->set_param(
170
- 'calculate_attribute_counts',
171
- [
172
- [
173
- 'taxonomy' => 'pa_size',
174
- 'query_type' => 'and',
175
- ],
176
- ]
177
- );
178
- $request->set_param( 'calculate_rating_counts', true );
179
- $response = rest_get_server()->dispatch( $request );
180
- $validate = new ValidateSchema( $schema );
181
-
182
- $diff = $validate->get_diff_from_object( $response->get_data() );
183
- $this->assertEmpty( $diff, print_r( $diff, true ) );
184
- }
185
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/StoreApi/Routes/Products.php DELETED
@@ -1,198 +0,0 @@
1
- <?php
2
- /**
3
- * Controller Tests.
4
- */
5
-
6
- namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes;
7
-
8
- use Automattic\WooCommerce\Blocks\Tests\StoreApi\Routes\ControllerTestCase;
9
- use Automattic\WooCommerce\Blocks\Tests\Helpers\FixtureData;
10
- use Automattic\WooCommerce\Blocks\Tests\Helpers\ValidateSchema;
11
-
12
- /**
13
- * Products Controller Tests.
14
- */
15
- class Products extends ControllerTestCase {
16
-
17
- /**
18
- * Setup test products data. Called before every test.
19
- */
20
- public function setUp() {
21
- parent::setUp();
22
-
23
- $fixtures = new FixtureData();
24
-
25
- $this->products = [
26
- $fixtures->get_simple_product( [
27
- 'name' => 'Test Product 1',
28
- 'stock_status' => 'instock',
29
- 'regular_price' => 10,
30
- 'image_id' => $fixtures->sideload_image(),
31
- ] ),
32
- $fixtures->get_simple_product( [
33
- 'name' => 'Test Product 2',
34
- 'stock_status' => 'instock',
35
- 'regular_price' => 10,
36
- 'image_id' => $fixtures->sideload_image(),
37
- ] ),
38
- ];
39
- }
40
-
41
- /**
42
- * Test route registration.
43
- */
44
- public function test_register_routes() {
45
- $routes = rest_get_server()->get_routes();
46
- $this->assertArrayHasKey( '/wc/store/products', $routes );
47
- $this->assertArrayHasKey( '/wc/store/products/(?P<id>[\d]+)', $routes );
48
- }
49
-
50
- /**
51
- * Test getting item.
52
- */
53
- public function test_get_item() {
54
- $response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc/store/products/' . $this->products[0]->get_id() ) );
55
- $data = $response->get_data();
56
-
57
- $this->assertEquals( 200, $response->get_status() );
58
- $this->assertEquals( $this->products[0]->get_id(), $data['id'] );
59
- $this->assertEquals( $this->products[0]->get_title(), $data['name'] );
60
- $this->assertEquals( $this->products[0]->get_permalink(), $data['permalink'] );
61
- $this->assertEquals( $this->products[0]->get_sku(), $data['sku'] );
62
- $this->assertEquals( $this->products[0]->get_price(), $data['prices']->price / ( 10 ** $data['prices']->currency_minor_unit ) );
63
- $this->assertEquals( $this->products[0]->get_average_rating(), $data['average_rating'] );
64
- $this->assertEquals( $this->products[0]->get_review_count(), $data['review_count'] );
65
- $this->assertEquals( $this->products[0]->has_options(), $data['has_options'] );
66
- $this->assertEquals( $this->products[0]->is_purchasable(), $data['is_purchasable'] );
67
- $this->assertEquals( $this->products[0]->is_in_stock(), $data['is_in_stock'] );
68
- $this->assertEquals( $this->products[0]->add_to_cart_text(), $data['add_to_cart']->text );
69
- $this->assertEquals( $this->products[0]->add_to_cart_description(), $data['add_to_cart']->description );
70
- $this->assertEquals( $this->products[0]->is_on_sale(), $data['on_sale'] );
71
- }
72
-
73
- /**
74
- * Test getting items.
75
- */
76
- public function test_get_items() {
77
- $response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc/store/products' ) );
78
- $data = $response->get_data();
79
-
80
- $this->assertEquals( 200, $response->get_status() );
81
- $this->assertEquals( 2, count( $data ) );
82
- $this->assertArrayHasKey( 'id', $data[0] );
83
- $this->assertArrayHasKey( 'name', $data[0] );
84
- $this->assertArrayHasKey( 'variation', $data[0] );
85
- $this->assertArrayHasKey( 'permalink', $data[0] );
86
- $this->assertArrayHasKey( 'description', $data[0] );
87
- $this->assertArrayHasKey( 'on_sale', $data[0] );
88
- $this->assertArrayHasKey( 'sku', $data[0] );
89
- $this->assertArrayHasKey( 'prices', $data[0] );
90
- $this->assertArrayHasKey( 'average_rating', $data[0] );
91
- $this->assertArrayHasKey( 'review_count', $data[0] );
92
- $this->assertArrayHasKey( 'images', $data[0] );
93
- $this->assertArrayHasKey( 'has_options', $data[0] );
94
- $this->assertArrayHasKey( 'is_purchasable', $data[0] );
95
- $this->assertArrayHasKey( 'is_in_stock', $data[0] );
96
- $this->assertArrayHasKey( 'add_to_cart', $data[0] );
97
- }
98
-
99
- /**
100
- * Test searching by SKU
101
- */
102
- public function test_search_by_sku() {
103
- $product = new \WC_Product_Simple();
104
- $product->set_sku( 'search-for-this-value' );
105
- $product->save();
106
-
107
- $request = new \WP_REST_Request( 'GET', '/wc/store/products' );
108
- $request->set_param( 'search', 'search-for-this' );
109
-
110
- $response = rest_get_server()->dispatch( $request );
111
- $data = $response->get_data();
112
-
113
- $this->assertEquals( 200, $response->get_status() );
114
- $this->assertEquals( 1, count( $data ) );
115
- $this->assertArrayHasKey( 'sku', $data[0] );
116
- $this->assertEquals( 'search-for-this-value', $data[0]['sku'] );
117
- }
118
-
119
- /**
120
- * Test conversion of product to rest response.
121
- */
122
- public function test_prepare_item() {
123
- $schemas = new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController( $this->mock_extend );
124
- $routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( $schemas );
125
- $schema = $schemas->get( 'product' );
126
- $controller = $routes->get( 'products' );
127
- $response = $controller->prepare_item_for_response( $this->products[0], new \WP_REST_Request() );
128
- $data = $response->get_data();
129
-
130
- $this->assertArrayHasKey( 'id', $data );
131
- $this->assertArrayHasKey( 'name', $data );
132
- $this->assertArrayHasKey( 'variation', $data );
133
- $this->assertArrayHasKey( 'permalink', $data );
134
- $this->assertArrayHasKey( 'description', $data );
135
- $this->assertArrayHasKey( 'on_sale', $data );
136
- $this->assertArrayHasKey( 'sku', $data );
137
- $this->assertArrayHasKey( 'prices', $data );
138
- $this->assertArrayHasKey( 'average_rating', $data );
139
- $this->assertArrayHasKey( 'review_count', $data );
140
- $this->assertArrayHasKey( 'images', $data );
141
- $this->assertArrayHasKey( 'has_options', $data );
142
- $this->assertArrayHasKey( 'is_purchasable', $data );
143
- $this->assertArrayHasKey( 'is_in_stock', $data );
144
- $this->assertArrayHasKey( 'add_to_cart', $data );
145
- }
146
-
147
- /**
148
- * Test collection params getter.
149
- */
150
- public function test_get_collection_params() {
151
- $routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController($this->mock_extend) );
152
- $controller = $routes->get( 'products' );
153
- $params = $controller->get_collection_params();
154
-
155
- $this->assertArrayHasKey( 'page', $params );
156
- $this->assertArrayHasKey( 'per_page', $params );
157
- $this->assertArrayHasKey( 'search', $params );
158
- $this->assertArrayHasKey( 'after', $params );
159
- $this->assertArrayHasKey( 'before', $params );
160
- $this->assertArrayHasKey( 'date_column', $params );
161
- $this->assertArrayHasKey( 'exclude', $params );
162
- $this->assertArrayHasKey( 'include', $params );
163
- $this->assertArrayHasKey( 'offset', $params );
164
- $this->assertArrayHasKey( 'order', $params );
165
- $this->assertArrayHasKey( 'orderby', $params );
166
- $this->assertArrayHasKey( 'parent', $params );
167
- $this->assertArrayHasKey( 'parent_exclude', $params );
168
- $this->assertArrayHasKey( 'type', $params );
169
- $this->assertArrayHasKey( 'sku', $params );
170
- $this->assertArrayHasKey( 'featured', $params );
171
- $this->assertArrayHasKey( 'category', $params );
172
- $this->assertArrayHasKey( 'tag', $params );
173
- $this->assertArrayHasKey( 'on_sale', $params );
174
- $this->assertArrayHasKey( 'min_price', $params );
175
- $this->assertArrayHasKey( 'max_price', $params );
176
- $this->assertArrayHasKey( 'stock_status', $params );
177
- $this->assertArrayHasKey( 'category_operator', $params );
178
- $this->assertArrayHasKey( 'tag_operator', $params );
179
- $this->assertArrayHasKey( 'attribute_relation', $params );
180
- $this->assertArrayHasKey( 'attributes', $params );
181
- $this->assertArrayHasKey( 'catalog_visibility', $params );
182
- $this->assertArrayHasKey( 'rating', $params );
183
- }
184
-
185
- /**
186
- * Test schema matches responses.
187
- */
188
- public function test_get_item_schema() {
189
- $routes = new \Automattic\WooCommerce\Blocks\StoreApi\RoutesController( new \Automattic\WooCommerce\Blocks\StoreApi\SchemaController($this->mock_extend) );
190
- $controller = $routes->get( 'products' );
191
- $schema = $controller->get_item_schema();
192
- $response = $controller->prepare_item_for_response( $this->products[0], new \WP_REST_Request() );
193
- $validate = new ValidateSchema( $schema );
194
-
195
- $diff = $validate->get_diff_from_object( $response->get_data() );
196
- $this->assertEmpty( $diff, print_r( $diff, true ) );
197
- }
198
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/StoreApi/Utilities/CartController.php DELETED
@@ -1,82 +0,0 @@
1
- <?php
2
- /**
3
- * CartController Tests.
4
- */
5
-
6
- namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Utilities;
7
-
8
- use Automattic\WooCommerce\Blocks\Tests\Helpers\FixtureData;
9
- use Automattic\WooCommerce\Blocks\StoreApi\Utilities\CartController;
10
- use Yoast\PHPUnitPolyfills\TestCases\TestCase;
11
-
12
- class CartControllerTests extends TestCase {
13
-
14
- public function test_get_cart_item_errors() {
15
- $class = new CartController();
16
- $fixtures = new FixtureData();
17
-
18
- // This product will simply be in/out of stock.
19
- $out_of_stock_product = $fixtures->get_simple_product( [
20
- 'name' => 'Test Product 1',
21
- 'regular_price' => 10,
22
- ] );
23
- $out_of_stock_product_key = wc()->cart->add_to_cart( $out_of_stock_product->get_id(), 2 );
24
- $out_of_stock_in_cart = wc()->cart->get_cart_item( $out_of_stock_product_key )['data'];
25
-
26
- // This product will have exact levels of stock known
27
- $partially_out_of_stock_product = $fixtures->get_simple_product( [
28
- 'name' => 'Test Product 2',
29
- 'regular_price' => 10,
30
- ] );
31
- $partially_out_of_stock_key = wc()->cart->add_to_cart( $partially_out_of_stock_product->get_id(), 4 );
32
- $partially_out_of_stock_in_cart = wc()->cart->get_cart_item( $partially_out_of_stock_key )['data'];
33
-
34
- // This product will have exact levels of stock known
35
- $too_many_in_cart_product = $fixtures->get_simple_product( [
36
- 'name' => 'Test Product 3',
37
- 'regular_price' => 10,
38
- ] );
39
- $too_many_in_cart_product_key = wc()->cart->add_to_cart( $too_many_in_cart_product->get_id(), 4 );
40
- $too_many_in_cart_in_cart = wc()->cart->get_cart_item( $too_many_in_cart_product_key )['data'];
41
-
42
- $out_of_stock_in_cart->set_stock_status( 'outofstock' );
43
- $partially_out_of_stock_in_cart->set_manage_stock( true );
44
- $partially_out_of_stock_in_cart->set_stock_quantity( 2 );
45
- $too_many_in_cart_in_cart->set_sold_individually( true );
46
-
47
- // This product will not be purchasable
48
- $not_purchasable_product = $fixtures->get_simple_product( [
49
- 'name' => 'Test Product 4',
50
- 'regular_price' => 10,
51
- ] );
52
- wc()->cart->add_to_cart( $not_purchasable_product->get_id(), 2 );
53
-
54
- // This function will force the $product->is_purchasable() function to return false for our $not_purchasable_product
55
- add_filter( 'woocommerce_is_purchasable', function( $is_purchasable, $product ) use ( $not_purchasable_product ) {
56
- if ( $product->get_id() === $not_purchasable_product->get_id() ) {
57
- return false;
58
- }
59
- return true;
60
- }, 10, 2 );
61
-
62
- $errors = array_map(
63
- function( $error ) {
64
- return $error->get_error_code();
65
- },
66
- $class->get_cart_item_errors()
67
- );
68
-
69
- $expected_errors = [
70
- 'woocommerce-blocks-product-partially-out-of-stock',
71
- 'woocommerce-blocks-product-out-of-stock',
72
- 'woocommerce-blocks-product-not-purchasable',
73
- 'woocommerce-blocks-too-many-of-product-in-cart',
74
- ];
75
-
76
- foreach( $expected_errors as $expected_error ) {
77
- $this->assertContains( $expected_error, $errors );
78
- }
79
-
80
- }
81
-
82
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/StoreApi/Utilities/NoticeHandler.php DELETED
@@ -1,20 +0,0 @@
1
- <?php
2
- /**
3
- * NoticeHandler Tests.
4
- */
5
-
6
- namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Utilities;
7
-
8
- use Automattic\WooCommerce\Blocks\StoreApi\Routes\RouteException;
9
- use Automattic\WooCommerce\Blocks\StoreApi\Utilities\CartController;
10
- use Automattic\WooCommerce\Blocks\StoreApi\Utilities\NoticeHandler;
11
- use Yoast\PHPUnitPolyfills\TestCases\TestCase;
12
-
13
- class NoticeHandlerTests extends TestCase {
14
- public function test_convert_notices_to_exceptions() {
15
- $this->expectException( RouteException::class );
16
- $this->expectExceptionMessage( 'This is an error message with Some HTML in it.' );
17
- wc_add_notice( '<strong>This is an error message with <a href="#">Some HTML in it</a>.', 'error' );
18
- $errors = NoticeHandler::convert_notices_to_exceptions( 'test_error' );
19
- }
20
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/StoreApi/Utilities/OrderController.php DELETED
@@ -1,31 +0,0 @@
1
- <?php
2
- /**
3
- * OrderController Tests.
4
- */
5
-
6
- namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Utilities;
7
-
8
- use Automattic\WooCommerce\Blocks\StoreApi\Routes\RouteException;
9
- use Yoast\PHPUnitPolyfills\Polyfills\ExpectException;
10
- use Automattic\WooCommerce\Blocks\StoreApi\Utilities\OrderController;
11
- use Yoast\PHPUnitPolyfills\TestCases\TestCase;
12
-
13
- class OrderControllerTests extends TestCase {
14
- use ExpectException;
15
-
16
- public function test_validate_selected_shipping_methods_throws() {
17
- $class = new OrderController();
18
-
19
- $this->expectException( RouteException::class );
20
- $class->validate_selected_shipping_methods( true, array( false ) );
21
- }
22
-
23
- public function test_validate_selected_shipping_methods() {
24
- $class = new OrderController();
25
-
26
- // By running this method we assert that it doesn't error because if it does this test will fail.
27
- $class->validate_selected_shipping_methods( true, array( 'free-shipping' ) );
28
- $class->validate_selected_shipping_methods( false, array( 'free-shipping' ) );
29
- $class->validate_selected_shipping_methods( true, null );
30
- }
31
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/StoreApi/Utilities/ProductQueryFilters.php DELETED
@@ -1,55 +0,0 @@
1
- <?php
2
- namespace Automattic\WooCommerce\Blocks\Tests\StoreApi\Utilities;
3
- use Automattic\WooCommerce\Blocks\StoreApi\Utilities\ProductQueryFilters;
4
- use Yoast\PHPUnitPolyfills\TestCases\TestCase;
5
- use Automattic\WooCommerce\Blocks\Tests\Helpers\FixtureData;
6
-
7
- class ProductQueryFiltersTest extends TestCase {
8
- /**
9
- * Setup test products data. Called before every test.
10
- */
11
- public function setUp() {
12
- parent::setUp();
13
-
14
- $fixtures = new FixtureData();
15
-
16
- add_filter( 'woocommerce_product_stock_status_options', function( $status ) {
17
- $status['custom1'] = 'Custom status 1';
18
- $status['custom2'] = 'Custom status 2';
19
- return $status;
20
- }, 10, 1 );
21
-
22
- $this->products = [
23
- $fixtures->get_simple_product( [
24
- 'name' => 'Test Product 1',
25
- 'stock_status' => 'custom1',
26
- 'regular_price' => 10,
27
- 'weight' => 10,
28
- ] ),
29
- $fixtures->get_simple_product( [
30
- 'name' => 'Test Product 2',
31
- 'stock_status' => 'custom2',
32
- 'regular_price' => 10,
33
- 'weight' => 10,
34
- ] ),
35
- $fixtures->get_simple_product( [
36
- 'name' => 'Test Product 3',
37
- 'stock_status' => 'custom2',
38
- 'regular_price' => 10,
39
- 'weight' => 10,
40
- ] ),
41
- ];
42
- }
43
-
44
- /**
45
- * Test that custom stock levels are returned properly with the correct counts.
46
- */
47
- public function test_custom_stock_counts() {
48
- $class = new ProductQueryFilters();
49
- $result = $class->get_stock_status_counts( new \WP_REST_Request( 'GET', '/wc/store/products' ) );
50
- $this->assertArrayHasKey( 'custom1', $result );
51
- $this->assertArrayHasKey( 'custom2', $result );
52
- $this->assertEquals( 1, $result['custom1'] );
53
- $this->assertEquals( 2, $result['custom2'] );
54
- }
55
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/mocks/AssetDataRegistry.php DELETED
@@ -1,30 +0,0 @@
1
- <?php
2
-
3
- namespace Automattic\WooCommerce\Blocks\Tests\Mocks;
4
-
5
- use Automattic\WooCommerce\Blocks\Assets\AssetDataRegistry;
6
-
7
- class AssetDataRegistryMock extends AssetDataRegistry {
8
-
9
- private $debug = true;
10
-
11
- public function execute_lazy_data() {
12
- parent::execute_lazy_data();
13
- }
14
-
15
- public function get() {
16
- return parent::get();
17
- }
18
-
19
- public function set_debug( $debug ) {
20
- $this->debug = $debug;
21
- }
22
-
23
- public function initialize_core_data() {
24
- return parent::initialize_core_data();
25
- }
26
-
27
- protected function debug() {
28
- return $this->debug;
29
- }
30
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/php/mocks/MockTestDependency.php DELETED
@@ -1,11 +0,0 @@
1
- <?php
2
-
3
- namespace Automattic\WooCommerce\Blocks\Tests\Mocks;
4
-
5
- class MockTestDependency {
6
- public $dependency;
7
-
8
- public function __construct( $dependency = null ) {
9
- $this->dependency = $dependency;
10
- }
11
- };
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/utils/find-by-text.ts DELETED
@@ -1,61 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import { MatcherFunction } from '@testing-library/react';
5
-
6
- /**
7
- * This function will match text over several elements, the standard matcher
8
- * will only find strings if they are within the same element.
9
- *
10
- * @param {string} text The text to find.
11
- * @return {function(*, ?)} The matcher function for RTL to use.
12
- */
13
- export const textContentMatcher = ( text: string ): MatcherFunction => {
14
- return ( _content, node ) => {
15
- const hasText = ( _node ) => _node.textContent === text;
16
- const nodeHasText = hasText( node );
17
- const childrenDontHaveText = Array.from( node?.children || [] ).every(
18
- ( child ) => ! hasText( child )
19
- );
20
- return nodeHasText && childrenDontHaveText;
21
- };
22
- };
23
-
24
- /**
25
- * This will check if the text is present an the container, it can be within
26
- * multiple elements, for example:
27
- * <div>
28
- * <span>Text</span>
29
- * <span>is</span>
30
- * <span>present</span>
31
- * </div>
32
- *
33
- * @param {string} text The text to find
34
- * @return {function(*, ?)} the matcher function for RTL to use.
35
- */
36
- export const textContentMatcherAcrossSiblings = (
37
- text: string
38
- ): MatcherFunction => {
39
- return ( _content, node ): boolean => {
40
- /*
41
- If the element in question is not the first child, then skip, as we
42
- will have already run this check for its siblings (when we ran it on the
43
- first child).
44
- */
45
- const siblings =
46
- node?.parentElement?.children[ 0 ] === node
47
- ? node?.parentElement?.children
48
- : [];
49
- let siblingText = '';
50
-
51
- // Get the text of all siblings and put it into a single string.
52
- if ( siblings?.length > 0 ) {
53
- siblingText = Array.from( siblings )
54
- .map( ( child ) => child.textContent )
55
- .filter( Boolean )
56
- .join( ' ' )
57
- .trim();
58
- }
59
- return siblingText !== '' && siblingText === text;
60
- };
61
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/utils/find-label-with-text.js DELETED
@@ -1,15 +0,0 @@
1
- /** @typedef {import('react')} React */
2
-
3
- /**
4
- * Finds the label of a toggle control.
5
- *
6
- * @param {string} label The label associated with a toggle control.
7
- *
8
- * @return {?React.ReactElementHandle} Object that represents an in-page DOM element.
9
- */
10
- export async function findLabelWithText( label ) {
11
- const [ toggle ] = await page.$x(
12
- `//div[contains(@class,"components-base-control")]//label[contains(text(), '${ label }')]`
13
- );
14
- return toggle;
15
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/utils/get-block-page-permalink.js DELETED
@@ -1,50 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import {
5
- ensureSidebarOpened,
6
- findSidebarPanelToggleButtonWithTitle,
7
- } from '@wordpress/e2e-test-utils';
8
-
9
- /**
10
- * Internal dependencies
11
- */
12
- import { visitBlockPage } from './visit-block-page';
13
-
14
- const blockPagePermalinks = {};
15
-
16
- /**
17
- * Gets the permalink of a page where the block editor is in use.
18
- *
19
- * @param {string} blockPage The name of the page whose permalink you want to get.
20
- * @return {Promise<string>} Returns the permalink of the page.
21
- */
22
- export async function getBlockPagePermalink( blockPage ) {
23
- if ( blockPagePermalinks[ blockPage ] ) {
24
- return blockPagePermalinks[ blockPage ];
25
- }
26
- await visitBlockPage( blockPage );
27
- await ensureSidebarOpened();
28
- const panelButton = await findSidebarPanelToggleButtonWithTitle(
29
- 'Permalink'
30
- );
31
- const ensureLinkClickable = async ( page ) => {
32
- let linkVisible =
33
- ( await page.$( '.edit-post-post-link__link' ) ) !== null;
34
- while ( ! linkVisible ) {
35
- await panelButton.click( 'button' );
36
- page.waitForTimeout( 300 );
37
- linkVisible =
38
- ( await page.$( '.edit-post-post-link__link' ) ) !== null;
39
- }
40
- };
41
-
42
- await ensureLinkClickable( page );
43
- const link = await page.$eval( '.edit-post-post-link__link', ( el ) => {
44
- return el.getAttribute( 'href' );
45
- } );
46
- blockPagePermalinks[ blockPage ] = link;
47
- return link;
48
- }
49
-
50
- export default getBlockPagePermalink;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/utils/get-normal-page-permalink.js DELETED
@@ -1,14 +0,0 @@
1
- /**
2
- * Gets the permalink of the current post (being viewed in the editor) if it is a normal page with the classic layout.
3
- * If you need the permalink of a page using the block editor, use the getBlockPagePermalink function.
4
- *
5
- * @return {Promise<string>} The permalink of the page.
6
- */
7
- export async function getNormalPagePermalink() {
8
- await page.waitForSelector( '#sample-permalink a' );
9
- return await page.$eval( '#sample-permalink a', ( el ) =>
10
- el.getAttribute( 'href' )
11
- );
12
- }
13
-
14
- export default getNormalPagePermalink;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/utils/index.js DELETED
@@ -1,8 +0,0 @@
1
- export { scrollTo } from './scroll-to.ts';
2
- export { findLabelWithText } from './find-label-with-text';
3
- export { visitBlockPage, visitPostOfType } from './visit-block-page';
4
- export { getBlockPagePermalink } from './get-block-page-permalink';
5
- export { getNormalPagePermalink } from './get-normal-page-permalink';
6
- export { saveOrPublish } from './save-or-publish';
7
- export { shopper } from './shopper';
8
- export { selectBlockByName } from './select-block-by-name';
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/utils/save-or-publish.js DELETED
@@ -1,22 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import { publishPost } from '@wordpress/e2e-test-utils';
5
-
6
- export async function saveOrPublish() {
7
- const link = await page.evaluate( () =>
8
- wp.data.select( 'core/editor' ).getPermalink()
9
- );
10
- if ( link.match( 'auto-draft' ) ) {
11
- await publishPost();
12
- } else {
13
- const publishButton = await page.$(
14
- '.editor-post-publish-button.editor-post-publish-button__button:not([aria-disabled="true"])'
15
- );
16
- if ( publishButton ) {
17
- await publishButton.click();
18
- // A success notice should show up
19
- await page.waitForSelector( '.components-snackbar' );
20
- }
21
- }
22
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/utils/scroll-to.ts DELETED
@@ -1,13 +0,0 @@
1
- /**
2
- * Function that scrolls to an element after disabling smooth scrolling in the page.
3
- */
4
- export const scrollTo = async ( selectorArg: string ): Promise< void > => {
5
- await page.evaluate( ( selector ) => {
6
- // Disable smooth scrolling so it scrolls instantly.
7
- document.querySelector( 'html' ).style.scrollBehavior = 'auto';
8
- document.querySelector( selector ).scrollIntoView( {
9
- block: 'center',
10
- inline: 'center',
11
- } );
12
- }, selectorArg );
13
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/utils/select-block-by-name.js DELETED
@@ -1,22 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import { getAllBlocks, selectBlockByClientId } from '@wordpress/e2e-test-utils';
5
-
6
- export const selectBlockByName = async ( blockName ) => {
7
- const blocksInEditor = await getAllBlocks();
8
- const flatBlockArray = ( blocks ) =>
9
- blocks
10
- .map( ( block ) => [
11
- { [ block.name ]: block.clientId },
12
- block.innerBlocks ? flatBlockArray( block.innerBlocks ) : [],
13
- ] )
14
- .flat( Infinity );
15
- const blocksObject = Object.fromEntries(
16
- flatBlockArray( blocksInEditor )
17
- .map( ( block ) => Object.entries( block ) )
18
- .flat()
19
- );
20
- const clientId = blocksObject[ blockName ];
21
- return selectBlockByClientId( clientId );
22
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/utils/shopper.js DELETED
@@ -1,49 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import { shopper as wcShopper } from '@woocommerce/e2e-utils';
5
-
6
- /**
7
- * Internal dependencies
8
- */
9
- import { getBlockPagePermalink } from './get-block-page-permalink';
10
-
11
- export const shopper = {
12
- ...wcShopper,
13
-
14
- goToCheckoutBlock: async () => {
15
- const checkoutBlockPermalink = await getBlockPagePermalink(
16
- `Checkout Block`
17
- );
18
-
19
- await page.goto( checkoutBlockPermalink, {
20
- waitUntil: 'networkidle0',
21
- } );
22
- await page.waitForSelector( 'h1', { text: 'Checkout' } );
23
- },
24
-
25
- productIsInCheckoutBlock: async ( productTitle, quantity, total ) => {
26
- // Make sure Order summary is expanded
27
- const [ button ] = await page.$x(
28
- `//button[contains(@aria-expanded, 'false')]//span[contains(text(), 'Order summary')]`
29
- );
30
- if ( button ) {
31
- await button.click();
32
- }
33
- await page.waitForSelector( 'span', {
34
- text: productTitle,
35
- } );
36
- await page.waitForSelector(
37
- 'div.wc-block-components-order-summary-item__quantity',
38
- {
39
- text: quantity,
40
- }
41
- );
42
- await page.waitForSelector(
43
- 'span.wc-block-components-product-price__value',
44
- {
45
- text: total,
46
- }
47
- );
48
- },
49
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/woocommerce-blocks/tests/utils/visit-block-page.js DELETED
@@ -1,123 +0,0 @@
1
- /**
2
- * External dependencies
3
- */
4
- import {
5
- createNewPost,
6
- visitAdminPage,
7
- insertBlock,
8
- getEditedPostContent,
9
- } from '@wordpress/e2e-test-utils';
10
- import { outputFile } from 'fs-extra';
11
- import { dirname } from 'path';
12
- import kebabCase from 'lodash/kebabCase';
13
-
14
- /**
15
- *
16
- * @param {string} link the page or post you want to visit.
17
- *
18
- * This will visit a GB page or post, and will hide the welcome guide.
19
- */
20
- async function visitPage( link ) {
21
- await page.goto( link );
22
- await page.waitForSelector( '.edit-post-layout' );
23
- const isWelcomeGuideActive = await page.evaluate( () =>
24
- wp.data.select( 'core/edit-post' ).isFeatureActive( 'welcomeGuide' )
25
- );
26
-
27
- if ( isWelcomeGuideActive ) {
28
- await page.evaluate( () =>
29
- wp.data.dispatch( 'core/edit-post' ).toggleFeature( 'welcomeGuide' )
30
- );
31
- await page.reload();
32
- await page.waitForSelector( '.edit-post-layout' );
33
- }
34
- }
35
-
36
- /**
37
- *
38
- * @param {string} title the page title, written as `BLOCK_NAME block`
39
- *
40
- * This function will attempt to search for a page with the `title`
41
- * if that block is found, it will open it, if it's not found, it will open
42
- * a new page, insert the block, save the page content and title as a fixture file.
43
- * In both cases, this page will end up with a page open with the block inserted.
44
- */
45
- export async function visitBlockPage( title ) {
46
- let link = '';
47
- // Visit Import Products page.
48
- await visitAdminPage( 'edit.php', 'post_type=page' );
49
- // If the website has no pages, `#post-search-input` will not render.
50
- if ( await page.$( '#post-search-input' ) ) {
51
- // search for the page.
52
- await page.type( '#post-search-input', title );
53
- await page.click( '#search-submit' );
54
- await page.waitForNavigation( { waitUntil: 'domcontentloaded' } );
55
- const pageLink = await page.$x( `//a[contains(text(), '${ title }')]` );
56
- if ( pageLink.length > 0 ) {
57
- // clicking the link directly caused racing issues, so I used goto.
58
- link = await page.evaluate(
59
- ( a ) => a.getAttribute( 'href' ),
60
- pageLink[ 0 ]
61
- );
62
- }
63
- }
64
- if ( link ) {
65
- await visitPage( link );
66
- } else {
67
- await createNewPost( {
68
- postType: 'page',
69
- title,
70
- showWelcomeGuide: false,
71
- } );
72
- await insertBlock( title.replace( /block/i, '' ).trim() );
73
- const pageContent = await getEditedPostContent();
74
- await outputFile(
75
- `${ dirname(
76
- // we want to fetch the path of the test file who triggered this function
77
- // this could be two levels up, or one level up, depending on how you launch the test.
78
- module.parent.parent.filename ||
79
- module.parent.filename ||
80
- module.filename
81
- ) }/__fixtures__/${ kebabCase(
82
- title.replace( /block/i, '' ).trim()
83
- ) }.fixture.json`,
84
- JSON.stringify( {
85
- title,
86
- pageContent,
87
- } )
88
- );
89
- }
90
- }
91
-
92
- /**
93
- * This function will attempt to navigate to a page in the WordPress dashboard
94
- *
95
- * @param {string} title The title of the page/post you want to visit.
96
- * @param {string} postType The post type of the entity you want to visit.
97
- * @return {Promise<void>}
98
- */
99
- export async function visitPostOfType( title, postType ) {
100
- let link = '';
101
- // Visit Import Products page.
102
- await visitAdminPage( 'edit.php', `post_type=${ postType }` );
103
- // If the website has no pages, `#post-search-input` will not render.
104
- if ( await page.$( '#post-search-input' ) ) {
105
- // search for the page.
106
- await page.type( '#post-search-input', title );
107
- await page.click( '#search-submit' );
108
- await page.waitForNavigation( { waitUntil: 'domcontentloaded' } );
109
- const pageLink = await page.$x( `//a[contains(text(), '${ title }')]` );
110
- if ( pageLink.length > 0 ) {
111
- // clicking the link directly caused racing issues, so I used goto.
112
- link = await page.evaluate(
113
- ( a ) => a.getAttribute( 'href' ),
114
- pageLink[ 0 ]
115
- );
116
- }
117
- }
118
- if ( link ) {
119
- await page.goto( link );
120
- } else throw new Error( `Unable to find page with name ${ title }` );
121
- }
122
-
123
- export default visitBlockPage;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
readme.txt CHANGED
@@ -1,10 +1,10 @@
1
  === WooCommerce ===
2
  Contributors: automattic, mikejolley, jameskoster, claudiosanches, rodrigosprimo, peterfabian1000, vedjain, jamosova, obliviousharmony, konamiman, sadowski, wpmuguru, royho, barryhughes-1
3
  Tags: e-commerce, store, sales, sell, woo, shop, cart, checkout, downloadable, downloads, payments, paypal, storefront, stripe, woo commerce
4
- Requires at least: 5.6
5
- Tested up to: 5.8
6
  Requires PHP: 7.0
7
- Stable tag: 6.2.1
8
  License: GPLv3
9
  License URI: https://www.gnu.org/licenses/gpl-3.0.html
10
 
@@ -160,6 +160,6 @@ WooCommerce comes with some sample data you can use to see how products look; im
160
 
161
  == Changelog ==
162
 
163
- = 6.3.0 2022-XX-XX =
164
 
165
  [See changelog for all versions](https://raw.githubusercontent.com/woocommerce/woocommerce/trunk/changelog.txt).
1
  === WooCommerce ===
2
  Contributors: automattic, mikejolley, jameskoster, claudiosanches, rodrigosprimo, peterfabian1000, vedjain, jamosova, obliviousharmony, konamiman, sadowski, wpmuguru, royho, barryhughes-1
3
  Tags: e-commerce, store, sales, sell, woo, shop, cart, checkout, downloadable, downloads, payments, paypal, storefront, stripe, woo commerce
4
+ Requires at least: 5.7
5
+ Tested up to: 5.9
6
  Requires PHP: 7.0
7
+ Stable tag: 6.3.0
8
  License: GPLv3
9
  License URI: https://www.gnu.org/licenses/gpl-3.0.html
10
 
160
 
161
  == Changelog ==
162
 
163
+ = 6.3.0 2022-03-08 =
164
 
165
  [See changelog for all versions](https://raw.githubusercontent.com/woocommerce/woocommerce/trunk/changelog.txt).
vendor/composer/installed.php CHANGED
@@ -5,7 +5,7 @@
5
  'type' => 'wordpress-plugin',
6
  'install_path' => __DIR__ . '/../../',
7
  'aliases' => array(),
8
- 'reference' => '3d53f1b5ff3485de6c67df7432c7f0cb1ef4036e',
9
  'name' => 'woocommerce/woocommerce',
10
  'dev' => false,
11
  ),
@@ -100,7 +100,7 @@
100
  'type' => 'wordpress-plugin',
101
  'install_path' => __DIR__ . '/../../',
102
  'aliases' => array(),
103
- 'reference' => '3d53f1b5ff3485de6c67df7432c7f0cb1ef4036e',
104
  'dev_requirement' => false,
105
  ),
106
  'woocommerce/woocommerce-admin' => array(
5
  'type' => 'wordpress-plugin',
6
  'install_path' => __DIR__ . '/../../',
7
  'aliases' => array(),
8
+ 'reference' => '476fb9e776cb9795075e8caee39071a0fa659766',
9
  'name' => 'woocommerce/woocommerce',
10
  'dev' => false,
11
  ),
100
  'type' => 'wordpress-plugin',
101
  'install_path' => __DIR__ . '/../../',
102
  'aliases' => array(),
103
+ 'reference' => '476fb9e776cb9795075e8caee39071a0fa659766',
104
  'dev_requirement' => false,
105
  ),
106
  'woocommerce/woocommerce-admin' => array(
woocommerce.php CHANGED
@@ -3,12 +3,12 @@
3
  * Plugin Name: WooCommerce
4
  * Plugin URI: https://woocommerce.com/
5
  * Description: An eCommerce toolkit that helps you sell anything. Beautifully.
6
- * Version: 6.3.0-rc.2
7
  * Author: Automattic
8
  * Author URI: https://woocommerce.com
9
  * Text Domain: woocommerce
10
  * Domain Path: /i18n/languages/
11
- * Requires at least: 5.6
12
  * Requires PHP: 7.0
13
  *
14
  * @package WooCommerce
3
  * Plugin Name: WooCommerce
4
  * Plugin URI: https://woocommerce.com/
5
  * Description: An eCommerce toolkit that helps you sell anything. Beautifully.
6
+ * Version: 6.3.0
7
  * Author: Automattic
8
  * Author URI: https://woocommerce.com
9
  * Text Domain: woocommerce
10
  * Domain Path: /i18n/languages/
11
+ * Requires at least: 5.7
12
  * Requires PHP: 7.0
13
  *
14
  * @package WooCommerce