Magento GraphQL功能测试.docx
《Magento GraphQL功能测试.docx》由会员分享,可在线阅读,更多相关《Magento GraphQL功能测试.docx(16页珍藏版)》请在冰点文库上搜索。
MagentoGraphQL功能测试
GraphQL功能测试
Magento提供API功能测试,可以验证GraphQL中的扩展点。
这些测试作为通过GraphQL公开新查询的示例。
1.创建一个新的GraphQL功能测试
所有的GraphQL功能测试都应该位于dev/tests/api-functional/testsuite/Magento/GraphQL/目录中,并继承自通用测试用例Magento\TestFramework\TestCase\GraphQlAbstract。
它定义了graphQlQuery()和graphQlMutation()方法,这些方法应该用于执行来自测试的WebAPI调用。
下面的测试验证模式是否返回正确的属性类型,给出attribute_code和相应的entity_type。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
namespaceMagento\GraphQl\Catalog;
useMagento\TestFramework\TestCase\GraphQlAbstract;
classProductAttributeTypeTestextendsGraphQlAbstract{
publicfunctiontestAttributeTypeResolver()
{
$query
=<<{customAttributeMetadata(attributes:[{attribute_code:"description",entity_type:"catalog_product"},{attribute_code:"status",entity_type:"catalog_product"},{attribute_code:"special_price",entity_type:"catalog_product"},{attribute_code:"disable_auto_group_change",entity_type:"customer"}{attribute_code:"special_price",entity_type:"Magento\\\\Catalog\\\\Api\\\\Data\\\\ProductInterface"}]){items{attribute_codeattribute_typeentity_type}}}QUERY;$response=$this->graphQlQuery($query);$expectedAttributeCodes=['description','status','special_price','disable_auto_group_change','special_price'];$entityType=['catalog_product','catalog_product','catalog_product','customer',\Magento\Catalog\Api\Data\ProductInterface::class];$attributeTypes=['String','Int','Float','Boolean','Float'];$this->assertAttributeType($attributeTypes,$expectedAttributeCodes,$entityType,$response);}2.使用默认的GraphQlQueryTest\Magento\GraphQl\TestModule\GraphQlQueryTest.php测试用例使用两个测试模块来确定GraphQL可扩展性机制是否按预期工作。它说明了扩展现有GraphQL端点的最佳实践。∙TestModuleGraphQlQuery-此准系统模块定义testItem具有可查询属性item_id和的端点name。位于/dev/tests/api-functional/_files/TestModuleGraphQlQuery。∙TestModuleGraphQlQueryExtension-此模块扩展TestModuleGraphQlQuery,添加integer_list扩展属性。位于/dev/tests/api-functional/_files/TestModuleGraphQlQueryExtension。3.创建fixturesixture是测试框架的一部分,它在系统中为进一步的测试准备了先决条件。例如,当您测试将产品添加到购物车的能力时,先决条件是产品必须可用于测试。一个fixture包含两个文件:∙ixture文件,它定义了测试∙回滚文件,该文件将系统还原到运行测试之前的状态每个设备都应该有一个相应的回滚文件。Magento在dev/tests/integration/testsuite/Magento//_files目录中提供fixture。尽可能使用这些装置。当您创建自己的fixture时,也要创建适当的回滚。3.1.Fixture文件下面的fixture创建一个具有预定义属性的简单产品。123456789101112131415161718192021222324252627phpuseMagento\Catalog\Model\ProductFactory;useMagento\TestFramework\Helper\Bootstrap;useMagento\Catalog\Model\ResourceModel\ProductasProductResource;$productFactory=Bootstrap::getObjectManager()->get(ProductFactory::class);$product=$productFactory->create();$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_VIRTUAL)->setId(21)->setAttributeSetId(4)->setWebsiteIds([1])->setName('VirtualProduct')->setSku('virtual-product')->setPrice(10)->setTaxClassId(0)->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)->setStockData(['qty'=>100,'is_in_stock'=>1,'manage_stock'=>1,]);/**@varProductResource$productResource*/$productResource=Bootstrap::getObjectManager()->create(ProductResource::class);$productResource->save($product);要在测试中使用此fixture,请按以下方式将其添加到测试的注释中:1234567/***@magentoApiDataFixtureMagento/Catalog/_files/product_virtual.php*/publicfunctiontestAddVirtualProductToShoppingCart(){//Testbody}您还可以调用多个fixtures:12345678/***@magentoApiDataFixtureMagento/Checkout/_files/quote_with_simple_product_saved.php*@magentoApiDataFixtureMagento/Customer/_files/customer.php*/publicfunctiontestSetNewBillingAddressByRegisteredCustomer(){//Testbody}指定的fixture现在将在每次测试运行时执行。3.2.回滚文件每个fixture都应该有一个回滚文件。回滚是一组操作,用于在测试完成后从系统中删除fixture引入的更改。回滚文件名应该对应于原始fixture文件名postfixedby_rollback关键字。例如,如果fixture文件名是virtual_product。将回滚文件命名为virtual_product_rollback.ph。下面的fixture回滚将从数据库中删除新创建的产品。123456789101112131415161718192021222324phpuseMagento\Catalog\Api\ProductRepositoryInterface;useMagento\Framework\Exception\NoSuchEntityException;useMagento\Framework\Exception\StateException;useMagento\TestFramework\Helper\Bootstrap;$registry=Bootstrap::getObjectManager()->get(\Magento\Framework\Registry::class);$registry->unregister('isSecureArea');$registry->register('isSecureArea',true);$productRepository=Bootstrap::getObjectManager()->create(ProductRepositoryInterface::class);try{$product=$productRepository->get('virtual-product',false,null,true);$productRepository->delete($product);}catch(NoSuchEntityException$exception){//Productalreadyremoved}catch(StateException$exception){}$registry->unregister('isSecureArea');$registry->register('isSecureArea',false);3.3.Fixture配置使用@magentoConfigFixture注释设置自定义配置值。它只支持store范围。●语法123/***@magentoConfigFixture_store*/其中∙-商店代码。请参阅store.code数据库字段值。∙-配置键。请参阅core_config_data.path∙-配置值。请参阅core_config_data.value∙@magentoConfigFixture 不需要回滚。●用法示例下面的例子为GetActiveAgreement()测试中的默认存储的配置键checkout/options/enable_agreements设置store范围值1)1234567/***@magentoConfigFixturedefault_storecheckout/options/enable_agreements1*/publicfunctiontestGetActiveAgreement(){...}@magentoConfigFixture在测试执行之前作为后台进程执行以下操作:INSERTINTO`core_config_data`(scope`,`scope_id`,`path`,`value`)VALUES('stores',1,'checkout/options/enable_agreements','1');测试完成后,fixture会自动从数据库中删除checkout/options/enable_agreements配置键。4.定义预期的异常功能测试应该包括导致异常的事件。因为您的测试预期会发生异常,所以设置您的测试,以便它们能得到适当的响应。您可以定义预期的异常消息在:∙测试的主体∙测试函数注释我们建议您在测试方法主体中声明预期的异常,因为PHPUnit8已弃用带注释的预期异常声明。当Magento需要该版本的PHPUnit或更高版本时,必须对使用注释的现有测试进行更新。4.1.测试正文中的异常消息下面的示例展示了使用expectExceptionMessage函数定义预期异常消息的两种方法。123456789publicfunctiontestMyExceptionTest(){...self::expectExceptionMessage("Expectedexceptionmessagegoeshere...");...}或12345678publicfunctiontestMyExceptionTest(){...$this->expectExceptionMessage("Expectedexceptionmessagegoeshere...");...}在调用生成异常的逻辑之前定义异常消息。例如,考虑客户A尝试检索有关客户B购物车的信息的情况。在这种情况下,客户A遇到以下错误:Thecurrentusercannotperformoperationsoncart"XXXXX"XXXXX 是客户B购物车的唯一ID。下面的示例演示如何使用expectExceptionMessage函数来涵盖此场景:12345678910111213141516/***@magentoApiDataFixtureMagento/Checkout/_files/quote_with_items_saved.php*/publicfunctiontestGetCartFromAnotherCustomer(){$reservedOrderId='test_order_item_with_items';$this->quoteResource->load($this->quote,$reservedOrderId,'reserved_order_id');$maskedQuoteId=$this->quoteIdToMaskedId->execute((int)$this->quote->getId());$query=$this->prepareGetCartQuery($maskedQuoteId);self::expectExceptionMessage("Thecurrentusercannotperformoperationsoncart\"$maskedQuoteId\"");$this->graphQlQuery($query);}4.2.测试函数注释中的异常消息您还可以使用预定义的指令,如@expectedExceptionMessage作为调用expectExceptionMessage方法的另一种方法:1234/***@expectedException\Exception*@expectedExceptionMessageExpectedexceptionmessagegoeshere...*/在以下查询中,客户在尝试检索有关其自己购物车的信息时提供了错误的购物车ID。查询:{cart(cart_id:"YYYYY"){items{__typenameidqty}}}结果:1234567891011121314151617181920{"errors":[{"message":"CouldnotfindacartwithID\"YYYYY\"","category":"graphql-no-such-entity","locations":[{"line":2,"column":3}],"path":["cart"]}],"data":{"cart":null}}@expectExceptionMessage注释为这个测试中的异常提供了文本。1234567891011/***@expectedException\Exception*@expectedExceptionMessageCouldnotfindacartwithID"non_existent_masked_id"*/publicfunctiontestGetNonExistentCart(){$maskedQuoteId='non_existent_masked_id';$query=$this->prepareGetCartQuery($maskedQuoteId);$this->graphQlQuery($query);}使用以下功能来覆盖预期的异常:∙expectException∙expectExceptionCode∙expectExceptionMessage∙expectExceptionMessageRegExp∙expectExceptionObject5.运行功能测试5.1.配置您的实例1.将目录更改为dev/tests/api-functional/并复制phpunit_graphql.xml。到phpunit_graphql.xml的dist文件。$cpphpunit_graphql.xml.distphpunit_graphql.xml 2.编辑phpunit_graphql.xml来设置TESTS_BASE_URL、TESTS_WEBSERVICE_USER、TESTS_WEBSERVICE_APIKEY选项的值:12345678...--WebserverURL-->//magento.url"/>--WebserverAPIuser-->--WebserverAPIkey-->...1.5.2.在API功能测试套件中运行所有测试语法:$vendor/bin/phpunit-cdev/tests/api-functional/phpunit_graphql.xmldev/tests/api-functional/testsuite///.php 例:从dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/GenerateCustomerTokenTest.php运行所有测试,请运行以下命令:$vendor/bin/phpunit-cdev/tests/api-functional/phpunit_graphql.xmldev/tests/api-functional/testsuite/Magento/GraphQl/Customer/GenerateCustomerTokenTest.php5.3.在API功能测试套件中运行单个测试语法:$vendor/bin/phpunit-cdev/tests/api-functional/phpunit_graphql.xml--filterdev/tests/api-functional/testsuite///.php例:从dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/GenerateCustomerTokenTest运行testGene
customAttributeMetadata(attributes:
[
attribute_code:
"description",
entity_type:
"catalog_product"
},
"status",
"special_price",
"disable_auto_group_change",
"customer"
}
"Magento\\\\Catalog\\\\Api\\\\Data\\\\ProductInterface"
]
)
items
attribute_code
attribute_type
entity_type
QUERY;
$response=$this->graphQlQuery($query);
$expectedAttributeCodes=[
'description',
'status',
'special_price',
'disable_auto_group_change',
'special_price'
];
$entityType=[
'catalog_product',
'customer',
\Magento\Catalog\Api\Data\ProductInterface:
:
class
$attributeTypes=['String','Int','Float','Boolean','Float'];
$this->assertAttributeType($attributeTypes,$expectedAttributeCodes,$entityType,$response);
2.使用默认的GraphQlQueryTest
\Magento\GraphQl\TestModule\GraphQlQueryTest.php测试用例使用两个测试模块来确定GraphQL可扩展性机制是否按预期工作。
它说明了扩展现有GraphQL端点的最佳实践。
∙TestModuleGraphQlQuery-此准系统模块定义testItem具有可查询属性item_id和的端点name。
位于/dev/tests/api-functional/_files/TestModuleGraphQlQuery。
∙TestModuleGraphQlQueryExtension-此模块扩展TestModuleGraphQlQuery,添加integer_list扩展属性。
位于/dev/tests/api-functional/_files/TestModuleGraphQlQueryExtension。
3.创建fixtures
ixture是测试框架的一部分,它在系统中为进一步的测试准备了先决条件。
例如,当您测试将产品添加到购物车的能力时,先决条件是产品必须可用于测试。
一个fixture包含两个文件:
∙ixture文件,它定义了测试
∙回滚文件,该文件将系统还原到运行测试之前的状态
每个设备都应该有一个相应的回滚文件。
Magento在dev/tests/integration/testsuite/Magento//_files目录中提供fixture。
尽可能使用这些装置。
当您创建自己的fixture时,也要创建适当的回滚。
3.1.Fixture文件
下面的fixture创建一个具有预定义属性的简单产品。
phpuseMagento\Catalog\Model\ProductFactory;useMagento\TestFramework\Helper\Bootstrap;useMagento\Catalog\Model\ResourceModel\ProductasProductResource;
$productFactory=Bootstrap:
getObjectManager()->get(ProductFactory:
class);$product=$productFactory->create();$product->setTypeId(\Magento\Catalog\Model\Product\Type:
TYPE_VIRTUAL)
->setId(21)
->setAttributeSetId(4)
->setWebsiteIds([1])
->setName('VirtualProduct')
->setSku('virtual-product')
->setPrice(10)
->setTaxClassId(0)
->setVisibility(\Magento\Catalog\Model\Product\Visibility:
VISIBILITY_BOTH)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status:
STATUS_ENABLED)
->setStockData(
'qty'=>100,
'is_in_stock'=>1,
'manage_stock'=>1,
);/**@varProductResource$productResource*/$productResource=Bootstrap:
getObjectManager()->create(ProductResource:
class);$productResource->save($product);
要在测试中使用此fixture,请按以下方式将其添加到测试的注释中:
/**
*@magentoApiDataFixtureMagento/Catalog/_files/product_virtual.php
*/
publicfunctiontestAddVirtualProductToShoppingCart()
//Testbody
您还可以调用多个fixtures:
*@magentoApiDataFixtureMagento/Checkout/_files/quote_with_simple_product_saved.php
*@magentoApiDataFixtureMagento/Customer/_files/customer.php
publicfunctiontestSetNewBillingAddressByRegisteredCustomer()
指定的fixture现在将在每次测试运行时执行。
3.2.回滚文件
每个fixture都应该有一个回滚文件。
回滚是一组操作,用于在测试完成后从系统中删除fixture引入的更改。
回滚文件名应该对应于原始fixture文件名postfixedby_rollback关键字。
例如,如果fixture文件名是virtual_product。
将回滚文件命名为virtual_product_rollback.ph。
下面的fixture回滚将从数据库中删除新创建的产品。
phpuseMagento\Catalog\Api\ProductRepositoryInterface;useMagento\Framework\Exception\NoSuchEntityException;useMagento\Framework\Exception\StateException;useMagento\TestFramework\Helper\Bootstrap;
$registry=Bootstrap:
getObjectManager()->get(\Magento\Framework\Registry:
class);
$registry->unregister('isSecureArea');$registry->register('isSecureArea',true);
$productRepository=Bootstrap:
getObjectManager()
->create(ProductRepositoryInterface:
try{
$product=$productRepository->get('virtual-product',false,null,true);
$productRepository->delete($product);}catch(NoSuchEntityException$exception){
//Productalreadyremoved}catch(StateException$exception){}
$registry->unregister('isSecureArea');$registry->register('isSecureArea',false);
3.3.Fixture配置
使用@magentoConfigFixture注释设置自定义配置值。
它只支持store范围。
●语法
*@magentoConfigFixture_store
其中
∙-商店代码。
请参阅store.code数据库字段值。
∙-配置键。
请参阅core_config_data.path
∙-配置值。
请参阅core_config_data.value
∙
@magentoConfigFixture 不需要回滚。
●用法示例
下面的例子为GetActiveAgreement()测试中的默认存储的配置键checkout/options/enable_agreements设置store范围值1)
*@magentoConfigFixturedefault_storecheckout/options/enable_agreements1
publicfunctiontestGetActiveAgreement()
...
@magentoConfigFixture在测试执行之前作为后台进程执行以下操作:
INSERTINTO`core_config_data`(scope`,`scope_id`,`path`,`value`)
VALUES
('stores',1,'checkout/options/enable_agreements','1');
测试完成后,fixture会自动从数据库中删除checkout/options/enable_agreements配置键。
4.定义预期的异常
功能测试应该包括导致异常的事件。
因为您的测试预期会发生异常,所以设置您的测试,以便它们能得到适当的响应。
您可以定义预期的异常消息在:
∙测试的主体
∙测试函数注释
我们建议您在测试方法主体中声明预期的异常,因为PHPUnit8已弃用带注释的预期异常声明。
当Magento需要该版本的PHPUnit或更高版本时,必须对使用注释的现有测试进行更新。
4.1.测试正文中的异常消息
下面的示例展示了使用expectExceptionMessage函数定义预期异常消息的两种方法。
publicfunctiontestMyExceptionTest(){
self:
expectExceptionMessage("Expectedexceptionmessagegoeshere...");
...}
或
$this->expectExceptionMessage("Expectedexceptionmessagegoeshere...");
在调用生成异常的逻辑之前定义异常消息。
例如,考虑客户A尝试检索有关客户B购物车的信息的情况。
在这种情况下,客户A遇到以下错误:
Thecurrentusercannotperformoperationsoncart"XXXXX"
XXXXX 是客户B购物车的唯一ID。
下面的示例演示如何使用expectExceptionMessage函数来涵盖此场景:
*@magentoApiDataFixtureMagento/Checkout/_files/quote_with_items_saved.php
publicfunctiontestGetCartFromAnotherCustomer()
$reservedOrderId='test_order_item_with_items';
$this->quoteResource->load(
$this->quote,
$reservedOrderId,
'reserved_order_id'
);
$maskedQuoteId=$this->quoteIdToMaskedId->execute((int)$this->quote->getId());
$query=$this->prepareGetCartQuery($maskedQuoteId);
expectExceptionMessage("Thecurrentusercannotperformoperationsoncart\"$maskedQuoteId\"");
$this->graphQlQuery($query);
4.2.测试函数注释中的异常消息
您还可以使用预定义的指令,如@expectedExceptionMessage作为调用expectExceptionMessage方法的另一种方法:
*@expectedException\Exception
*@expectedExceptionMessageExpectedexceptionmessagegoeshere...
在以下查询中,客户在尝试检索有关其自己购物车的信息时提供了错误的购物车ID。
查询:
cart(cart_id:
"YYYYY"){
items{
__typename
id
qty
结果:
"errors":
"message":
"CouldnotfindacartwithID\"YYYYY\"",
"category":
"graphql-no-such-entity",
"locations":
"line":
2,
"column":
],
"path":
"cart"
"data":
"cart":
null
}}
@expectExceptionMessage注释为这个测试中的异常提供了文本。
*@expectedExceptionMessageCouldnotfindacartwithID"non_existent_masked_id"
publicfunctiontestGetNonExistentCart()
$maskedQuoteId='non_existent_masked_id';
使用以下功能来覆盖预期的异常:
∙expectException
∙expectExceptionCode
∙expectExceptionMessage
∙expectExceptionMessageRegExp
∙expectExceptionObject
5.运行功能测试
5.1.配置您的实例
1.将目录更改为dev/tests/api-functional/并复制phpunit_graphql.xml。
到phpunit_graphql.xml的dist文件。
$cpphpunit_graphql.xml.distphpunit_graphql.xml
2.编辑phpunit_graphql.xml来设置TESTS_BASE_URL、TESTS_WEBSERVICE_USER、TESTS_WEBSERVICE_APIKEY选项的值:
--WebserverURL-->//magento.url"/>--WebserverAPIuser-->--WebserverAPIkey-->...1.5.2.在API功能测试套件中运行所有测试语法:$vendor/bin/phpunit-cdev/tests/api-functional/phpunit_graphql.xmldev/tests/api-functional/testsuite///.php 例:从dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/GenerateCustomerTokenTest.php运行所有测试,请运行以下命令:$vendor/bin/phpunit-cdev/tests/api-functional/phpunit_graphql.xmldev/tests/api-functional/testsuite/Magento/GraphQl/Customer/GenerateCustomerTokenTest.php5.3.在API功能测试套件中运行单个测试语法:$vendor/bin/phpunit-cdev/tests/api-functional/phpunit_graphql.xml--filterdev/tests/api-functional/testsuite///.php例:从dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/GenerateCustomerTokenTest运行testGene
//magento.url"/>
--WebserverAPIuser-->
--WebserverAPIkey-->
1.
5.2.在API功能测试套件中运行所有测试
语法:
$vendor/bin/phpunit-cdev/tests/api-functional/phpunit_graphql.xmldev/tests/api-functional/testsuite///.php
例:
从dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/GenerateCustomerTokenTest.php运行所有测试,请运行以下命令:
$vendor/bin/phpunit-cdev/tests/api-functional/phpunit_graphql.xmldev/tests/api-functional/testsuite/Magento/GraphQl/Customer/GenerateCustomerTokenTest.php
5.3.在API功能测试套件中运行单个测试
$vendor/bin/phpunit-cdev/tests/api-functional/phpunit_graphql.xml--filterdev/tests/api-functional/testsuite///.php
从dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/GenerateCustomerTokenTest运行testGene
copyright@ 2008-2023 冰点文库 网站版权所有
经营许可证编号:鄂ICP备19020893号-2