Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
MagentoRestDriver.php
Go to the documentation of this file.
1 <?php
8 
9 use Codeception\Module\REST;
12 use Flow\JSONPath;
13 
52 class MagentoRestDriver extends REST
53 {
57  const HTTP_METHOD_GET = 'GET';
58  const HTTP_METHOD_DELETE = 'DELETE';
59  const HTTP_METHOD_PUT = 'PUT';
60  const HTTP_METHOD_POST = 'POST';
61 
67  protected $requiredFields = [
68  'url',
69  'username',
70  'password'
71  ];
72 
78  protected $config = [
79  'url' => '',
80  'username' => '',
81  'password' => ''
82  ];
83 
89  protected static $adminTokens = [];
90 
97  public function _beforeSuite($settings = [])
98  {
99  parent::_beforeSuite($settings);
100  if (empty($this->config['url']) || empty($this->config['username']) || empty($this->config['password'])) {
101  return;
102  }
103 
104  $this->config = ConfigSanitizerUtil::sanitizeWebDriverConfig($this->config, ['url']);
105 
106  $this->haveHttpHeader('Content-Type', 'application/json');
107  $this->sendPOST(
108  'integration/admin/token',
109  ['username' => $this->config['username'], 'password' => $this->config['password']]
110  );
111  $token = substr($this->grabResponse(), 1, strlen($this->grabResponse())-2);
112  $this->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
113  $this->haveHttpHeader('Authorization', 'Bearer ' . $token);
114  self::$adminTokens[$this->config['username']] = $token;
115  // @codingStandardsIgnoreStart
116  $this->getModule('\Magento\FunctionalTestingFramework\Module\MagentoSequence')->_initialize();
117  // @codingStandardsIgnoreEnd
118  }
119 
124  public function _afterSuite()
125  {
126  parent::_afterSuite();
127  $this->deleteHeader('Authorization');
128  }
129 
140  public function getAdminAuthToken($username = null, $password = null, $newToken = false)
141  {
142  $username = $username !== null ? $username : $this->config['username'];
143  $password = $password !== null ? $password : $this->config['password'];
144 
145  // Use existing token if it exists
146  if (!$newToken
147  && (isset(self::$adminTokens[$username]) || array_key_exists($username, self::$adminTokens))) {
148  return self::$adminTokens[$username];
149  }
150  $this->haveHttpHeader('Content-Type', 'application/json');
151  $this->sendPOST('integration/admin/token', ['username' => $username, 'password' => $password]);
152  $token = substr($this->grabResponse(), 1, strlen($this->grabResponse())-2);
153  $this->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
154  self::$adminTokens[$username] = $token;
155  return $token;
156  }
157 
168  public function amAdminTokenAuthenticated($username = null, $password = null, $newToken = false)
169  {
170  $username = $username !== null ? $username : $this->config['username'];
171  $password = $password !== null ? $password : $this->config['password'];
172 
173  $this->haveHttpHeader('Content-Type', 'application/json');
174  if ($newToken || !isset(self::$adminTokens[$username])) {
175  $this->sendPOST('integration/admin/token', ['username' => $username, 'password' => $password]);
176  $token = substr($this->grabResponse(), 1, strlen($this->grabResponse()) - 2);
177  $this->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
178  self::$adminTokens[$username] = $token;
179  }
180  $this->amBearerAuthenticated(self::$adminTokens[$username]);
181  }
182 
196  public function sendRestRequest($endpoint, $httpMethod, $params = [], $grabByJsonPath = null, $decode = true)
197  {
198  $this->amAdminTokenAuthenticated();
199  switch ($httpMethod) {
201  $this->sendGET($endpoint, $params);
202  break;
204  $this->sendPOST($endpoint, $params);
205  break;
207  $this->sendPUT($endpoint, $params);
208  break;
210  $this->sendDELETE($endpoint, $params);
211  break;
212  default:
213  throw new \LogicException("HTTP method '{$httpMethod}' is not supported.");
214  }
215  $this->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
216 
217  if (!$decode && $grabByJsonPath === null) {
218  return $this->grabResponse();
219  } elseif (!$decode) {
220  return $this->grabDataFromResponseByJsonPath($grabByJsonPath);
221  } else {
222  return \GuzzleHttp\json_decode($this->grabResponse());
223  }
224  }
225 
234  public function requireCategory($categoryData = [])
235  {
236  if (!$categoryData) {
237  $categoryData = $this->getCategoryApiData();
238  }
239  $categoryData = $this->sendRestRequest(
240  self::$categoryEndpoint,
241  self::HTTP_METHOD_POST,
242  ['category' => $categoryData]
243  );
244  return $categoryData;
245  }
246 
256  public function requireSimpleProduct($categoryId = 0, $simpleProductData = [])
257  {
258  if (!$simpleProductData) {
259  $simpleProductData = $this->getProductApiData('simple', $categoryId);
260  }
261  $simpleProductData = $this->sendRestRequest(
262  self::$productEndpoint,
263  self::HTTP_METHOD_POST,
264  ['product' => $simpleProductData]
265  );
266  return $simpleProductData;
267  }
268 
278  public function requireConfigurableProduct($categoryId = 0, $configurableProductData = [])
279  {
280  $configurableProductData = $this->getProductApiData('configurable', $categoryId, $configurableProductData);
281  $this->sendRestRequest(
282  self::$productEndpoint,
283  self::HTTP_METHOD_POST,
284  ['product' => $configurableProductData]
285  );
286 
288  $attribute = $this->sendRestRequest(
289  self::$productAttributesEndpoint,
290  self::HTTP_METHOD_POST,
292  );
293  $options = $this->sendRestRequest(
294  sprintf(self::$productAttributesOptionsEndpoint, $attribute->attribute_code),
295  self::HTTP_METHOD_GET
296  );
297 
299  $this->sendRestRequest(
300  self::$productAttributeSetEndpoint,
301  self::HTTP_METHOD_POST,
303  );
304 
305  $simpleProduct1Data = $this->getProductApiData('simple', $categoryId);
306  array_push(
307  $simpleProduct1Data['custom_attributes'],
308  [
309  'attribute_code' => $attribute->attribute_code,
310  'value' => $options[1]->value
311  ]
312  );
313  $simpleProduct1Id = $this->sendRestRequest(
314  self::$productEndpoint,
315  self::HTTP_METHOD_POST,
316  ['product' => $simpleProduct1Data]
317  )->id;
318 
319  $simpleProduct2Data = $this->getProductApiData('simple', $categoryId);
320  array_push(
321  $simpleProduct2Data['custom_attributes'],
322  [
323  'attribute_code' => $attribute->attribute_code,
324  'value' => $options[2]->value
325  ]
326  );
327  $simpleProduct2Id = $this->sendRestRequest(
328  self::$productEndpoint,
329  self::HTTP_METHOD_POST,
330  ['product' => $simpleProduct2Data]
331  )->id;
332 
333  $tAttributes[] = [
334  'id' => $attribute->attribute_id,
335  'code' => $attribute->attribute_code
336  ];
337 
338  $tOptions = [
339  intval($options[1]->value),
340  intval($options[2]->value)
341  ];
342 
343  $configOptions = $this->getConfigurableProductOptionsApiData($tAttributes, $tOptions);
344 
345  $configurableProductData = $this->getConfigurableProductApiData(
346  $configOptions,
347  [$simpleProduct1Id, $simpleProduct2Id],
348  $configurableProductData
349  );
350 
351  $configurableProductData = $this->sendRestRequest(
352  self::$productEndpoint . '/' . $configurableProductData['sku'],
353  self::HTTP_METHOD_PUT,
354  ['product' => $configurableProductData]
355  );
356  return $configurableProductData;
357  }
358 
367  public function requireProductAttribute($code = 'attribute')
368  {
371  self::$productAttributesEndpoint,
372  self::HTTP_METHOD_POST,
374  );
375  return $attributeData;
376  }
377 
387  public function requireCustomer(array $customerData = [], $password = '123123qW')
388  {
389  if (!$customerData) {
391  }
394  self::$customersEndpoint,
395  self::HTTP_METHOD_POST,
397  );
398  return $customerData;
399  }
400 
409  public function getCategoryApiData($categoryData = [])
410  {
411  $faker = \Faker\Factory::create();
412  $sq = sqs();
413  return array_replace_recursive(
414  [
415  'parent_id' => '2',
416  'name' => 'category' . $sq,
417  'is_active' => true,
418  'include_in_menu' => true,
419  'available_sort_by' => ['position', 'name'],
420  'custom_attributes' => [
421  ['attribute_code' => 'url_key', 'value' => 'category' . $sq],
422  ['attribute_code' => 'description', 'value' => $faker->text(20)],
423  ['attribute_code' => 'meta_title', 'value' => $faker->text(20)],
424  ['attribute_code' => 'meta_keywords', 'value' => $faker->text(20)],
425  ['attribute_code' => 'meta_description', 'value' => $faker->text(20)],
426  ['attribute_code' => 'display_mode', 'value' => 'PRODUCTS'],
427  ['attribute_code' => 'landing_page', 'value' => ''],
428  ['attribute_code' => 'is_anchor', 'value' => '0'],
429  ['attribute_code' => 'custom_use_parent_settings', 'value' => '0'],
430  ['attribute_code' => 'custom_apply_to_products', 'value' => '0'],
431  ['attribute_code' => 'custom_design', 'value' => ''],
432  ['attribute_code' => 'page_layout', 'value' => ''],
433  ['attribute_code' => 'custom_design_to', 'value' => $faker->date($format = 'm/d/Y')],
434  ['attribute_code' => 'custom_design_from', 'value' => $faker->date($format = 'm/d/Y', 'now')]
435  ]
436  ],
437  $categoryData
438  );
439  }
440 
451  public function getProductApiData($type = 'simple', $categoryId = 0, $productData = [])
452  {
453  $faker = \Faker\Factory::create();
454  $sq = sqs();
455  return array_replace_recursive(
456  [
457  'sku' => $type . '_product_sku' . $sq,
458  'name' => $type . '_product' . $sq,
459  'visibility' => 4,
460  'type_id' => $type,
461  'price' => $faker->randomFloat(2, 1),
462  'status' => 1,
463  'attribute_set_id' => 4,
464  'extension_attributes' => [
465  'stock_item' => ['is_in_stock' => 1, 'qty' => $faker->numberBetween(100, 9000)]
466  ],
467  'custom_attributes' => [
468  ['attribute_code' => 'url_key', 'value' => $type . '_product' . $sq],
469  ['attribute_code' => 'tax_class_id', 'value' => 2],
470  ['attribute_code' => 'category_ids', 'value' => $categoryId],
471  ],
472  ],
474  );
475  }
476 
485  public function getCustomerApiData($customerData = [])
486  {
487  $faker = \Faker\Factory::create();
488  return array_replace_recursive(
489  [
490  'firstname' => $faker->firstName,
491  'middlename' => $faker->firstName,
492  'lastname' => $faker->lastName,
493  'email' => $faker->email,
494  'gender' => rand(0, 1),
495  'group_id' => 1,
496  'store_id' => 1,
497  'website_id' => 1,
498  'custom_attributes' => [
499  [
500  'attribute_code' => 'disable_auto_group_change',
501  'value' => '0',
502  ],
503  ],
504  ],
506  );
507  }
508 
518  public function getCustomerApiDataWithPassword($customerData = [], $password = '123123qW')
519  {
520  return ['customer' => self::getCustomerApiData($customerData), 'password' => $password];
521  }
522 
530  public function getProductAttributeApiData($code = 'attribute', $attributeData = [])
531  {
532  $sq = sqs();
533  return array_replace_recursive(
534  [
535  'attribute' => [
536  'attribute_code' => $code . $sq,
537  'frontend_labels' => [
538  [
539  'store_id' => 0,
540  'label' => $code . $sq
541  ],
542  ],
543  'is_required' => false,
544  'is_unique' => false,
545  'is_visible' => true,
546  'scope' => 'global',
547  'default_value' => '',
548  'frontend_input' => 'select',
549  'is_visible_on_front' => true,
550  'is_searchable' => true,
551  'is_visible_in_advanced_search' => true,
552  'is_filterable' => true,
553  'is_filterable_in_search' => true,
554  //'is_used_in_grid' => true,
555  //'is_visible_in_grid' => true,
556  //'is_filterable_in_grid' => true,
557  'used_in_product_listing' => true,
558  'is_used_for_promo_rules' => true,
559  'options' => [
560  [
561  'label' => 'option1',
562  'value' => '',
563  'sort_order' => 0,
564  'is_default' => true,
565  'store_labels' => [
566  [
567  'store_id' => 0,
568  'label' => 'option1'
569  ],
570  [
571  'store_id' => 1,
572  'label' => 'option1'
573  ]
574  ]
575  ],
576  [
577  'label' => 'option2',
578  'value' => '',
579  'sort_order' => 1,
580  'is_default' => false,
581  'store_labels' => [
582  [
583  'store_id' => 0,
584  'label' => 'option2'
585  ],
586  [
587  'store_id' => 1,
588  'label' => 'option2'
589  ]
590  ]
591  ]
592  ]
593  ],
594  ],
596  );
597  }
598 
607  {
608  $configurableProductOptions = [];
609  foreach ($attributes as $attribute) {
610  $attributeItem = [
611  'attribute_id' => (string)$attribute['id'],
612  'label' => $attribute['code'],
613  'values' => []
614  ];
615  foreach ($optionIds as $optionId) {
616  $attributeItem['values'][] = ['value_index' => $optionId];
617  }
618  $configurableProductOptions [] = $attributeItem;
619  }
620  return $configurableProductOptions;
621  }
622 
633  array $configurableProductOptions,
634  array $childProductIds,
635  array $configurableProduct = [],
636  int $categoryId = 0
637  ) {
638  if (!$configurableProduct) {
639  $configurableProduct = $this->getProductApiData('configurable', $categoryId);
640  }
641  $configurableProduct = array_merge_recursive(
643  [
644  'extension_attributes' => [
645  'configurable_product_options' => $configurableProductOptions,
646  'configurable_product_links' => $childProductIds,
647  ],
648  ]
649  );
650  return $configurableProduct;
651  }
652 
663  int $attributeSetId = 4,
664  int $attributeGroupId = 7
665  ) {
666  return [
667  'attributeSetId' => $attributeSetId,
668  'attributeGroupId' => $attributeGroupId,
669  'attributeCode' => $attributeCode,
670  'sortOrder' => 0
671  ];
672  }
673 }
$customerData
$block setTitle( 'CMS Block Title') -> setIdentifier('fixture_block') ->setContent('< h1 >Fixture Block Title</h1 >< a href=" store url</a><p> Config value
Definition: block.php:9
static sanitizeWebDriverConfig($config, $params=['url', 'selenium'])
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
$attributeGroupId
sendRestRequest($endpoint, $httpMethod, $params=[], $grabByJsonPath=null, $decode=true)
getProductApiData($type='simple', $categoryId=0, $productData=[])
getConfigurableProductApiData(array $configurableProductOptions, array $childProductIds, array $configurableProduct=[], int $categoryId=0)
getProductAttributeApiData($code='attribute', $attributeData=[])
$type
Definition: item.phtml:13
$format
Definition: list.phtml:12
getAdminAuthToken($username=null, $password=null, $newToken=false)
$attributeCode
Definition: extend.phtml:12
requireSimpleProduct($categoryId=0, $simpleProductData=[])
getAssignAttributeToAttributeSetApiData( $attributeCode, int $attributeSetId=4, int $attributeGroupId=7)
$attributes
Definition: matrix.phtml:13
$productData
$settings
Definition: bootstrap.php:29
requireCustomer(array $customerData=[], $password='123123qW')
amAdminTokenAuthenticated($username=null, $password=null, $newToken=false)
getCustomerApiDataWithPassword($customerData=[], $password='123123qW')
requireConfigurableProduct($categoryId=0, $configurableProductData=[])
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE]
Definition: website.php:18
$code
Definition: info.phtml:12