Locust性能测试从入门到精通(一)

from locust import FastHttpUser, SequentialTaskSet, TaskSet, between, task
from geventhttpclient import HTTPClient  #Nginx
from geventhttpclient.url import URL
import random, string, json



host = 'http://localhost:8000'

# 继承TaskSequence 控制方法按从上往下的顺序执行
class GetProductListSeqTaskSet(SequentialTaskSet):
    login_header={}
    del_params={}

    def on_start(self):
        '''初始化数据'''
        url = URL(host)

    @task
    def login(self):
        self.login_header['content-type'] = "application/json"

        data = r"""{
                    "operationName":"loginWithoutDetails",
                    "variables":{
                        "email":"admin@qq.com",
                        "password":"admin"
                    },
                    "query":"fragment AccountErrorFragment on AccountError {\n  code\n  field\n  message\n  __typename\n}\n\nfragment UserBaseFragment on User {\n  id\n  email\n  firstName\n  lastName\n  isStaff\n  __typename\n}\n\nmutation loginWithoutDetails($email: String!, $password: String!) {\n  tokenCreate(email: $email, password: $password) {\n    csrfToken\n    token\n    errors {\n      ...AccountErrorFragment\n      __typename\n    }\n    user {\n      ...UserBaseFragment\n      __typename\n    }\n    __typename\n  }\n}\n"
                }"""
        _login_complete = self.client.post("/graphql/", data=json.dumps(json.loads(data)), headers=self.login_header)
        dict_login_complete = _login_complete.json()
        # print(dict_login_complete)
        # self.login_header['authorization-bearer'] = _json_login_complete.get("data").get("tokenCreate").get("token")
        self.login_header['authorization-bearer'] = dict_login_complete["data"]["tokenCreate"]["token"]
        self.login_header['Cookie'] = 'refreshToken==' + dict_login_complete["data"]["tokenCreate"]["token"]


    @task
    def get_product_list(self):
        data = r"""{
            "operationName": "ProductList",
            "variables": {
                "first": 20,
                "filter": {
                    "attributes": null,
                    "categories": null,
                    "collections": null,
                    "price": null,
                    "productTypes": null,
                    "search": "juice",
                    "giftCard": null,
                    "stockAvailability": null
                },
                "sort": {
                    "direction": "DESC",
                    "field": "RANK"
                },
                "hasChannel": false,
                "hasSelectedAttributes": false,
                "PERMISSION_MANAGE_USERS": true,
                "PERMISSION_MANAGE_STAFF": true,
                "PERMISSION_IMPERSONATE_USER": true,
                "PERMISSION_MANAGE_APPS": true,
                "PERMISSION_MANAGE_OBSERVABILITY": true,
                "PERMISSION_MANAGE_CHECKOUTS": true,
                "PERMISSION_HANDLE_CHECKOUTS": true,
                "PERMISSION_HANDLE_TAXES": true,
                "PERMISSION_MANAGE_TAXES": true,
                "PERMISSION_MANAGE_CHANNELS": true,
                "PERMISSION_MANAGE_DISCOUNTS": true,
                "PERMISSION_MANAGE_GIFT_CARD": true,
                "PERMISSION_MANAGE_MENUS": true,
                "PERMISSION_MANAGE_ORDERS": true,
                "PERMISSION_MANAGE_PAGES": true,
                "PERMISSION_MANAGE_PAGE_TYPES_AND_ATTRIBUTES": true,
                "PERMISSION_HANDLE_PAYMENTS": true,
                "PERMISSION_MANAGE_PLUGINS": true,
                "PERMISSION_MANAGE_PRODUCTS": true,
                "PERMISSION_MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES": true,
                "PERMISSION_MANAGE_SHIPPING": true,
                "PERMISSION_MANAGE_SETTINGS": true,
                "PERMISSION_MANAGE_TRANSLATIONS": true
            },
            "query": "query ProductList($first: Int, $after: String, $last: Int, $before: String, $filter: ProductFilterInput, $channel: String, $sort: ProductOrder, $hasChannel: Boolean!, $hasSelectedAttributes: Boolean!) {\n  products(\n    before: $before\n    after: $after\n    first: $first\n    last: $last\n    filter: $filter\n    sortBy: $sort\n    channel: $channel\n  ) {\n    edges {\n      node {\n        ...ProductWithChannelListings\n        updatedAt\n        attributes @include(if: $hasSelectedAttributes) {\n          ...ProductListAttribute\n          __typename\n        }\n        __typename\n      }\n      __typename\n    }\n    pageInfo {\n      hasPreviousPage\n      hasNextPage\n      startCursor\n      endCursor\n      __typename\n    }\n    totalCount\n    __typename\n  }\n}\n\nfragment ProductWithChannelListings on Product {\n  id\n  name\n  thumbnail {\n    url\n    __typename\n  }\n  productType {\n    id\n    name\n    hasVariants\n    __typename\n  }\n  channelListings {\n    ...ChannelListingProductWithoutPricing\n    pricing @include(if: $hasChannel) {\n      priceRange {\n        ...PriceRange\n        __typename\n      }\n      __typename\n    }\n    __typename\n  }\n  __typename\n}\n\nfragment ChannelListingProductWithoutPricing on ProductChannelListing {\n  isPublished\n  publicationDate\n  isAvailableForPurchase\n  availableForPurchase\n  visibleInListings\n  channel {\n    id\n    name\n    currencyCode\n    __typename\n  }\n  __typename\n}\n\nfragment PriceRange on TaxedMoneyRange {\n  start {\n    net {\n      ...Money\n      __typename\n    }\n    __typename\n  }\n  stop {\n    net {\n      ...Money\n      __typename\n    }\n    __typename\n  }\n  __typename\n}\n\nfragment Money on Money {\n  amount\n  currency\n  __typename\n}\n\nfragment ProductListAttribute on SelectedAttribute {\n  attribute {\n    id\n    __typename\n  }\n  values {\n    ...AttributeValue\n    __typename\n  }\n  __typename\n}\n\nfragment AttributeValue on AttributeValue {\n  id\n  name\n  slug\n  file {\n    ...File\n    __typename\n  }\n  reference\n  boolean\n  date\n  dateTime\n  value\n  __typename\n}\n\nfragment File on File {\n  url\n  contentType\n  __typename\n}\n"
        }"""
        get_product_list = self.client.post("/graphql/", data=json.dumps(json.loads(data)), headers=self.login_header)
        # print(get_product_list.json())

    # @task
    # def logout(self):
    #     self.http.post("/graphql/")


class TestPerformance(FastHttpUser):
    tasks=[GetProductListSeqTaskSet,]
    # locust_task_weight = 10
    # 定义虚拟用户执行每个task的间隔时间,1s到5s随机选一个值。
    wait_time=between(1.0, 5.0)


if __name__ == '__main__':
    import os
    os.system('locust -f {0} --host=http://192.168.8.208:8000'.format(__file__))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Locust是一个分布式用户负载测试工具,用于对网站或其他系统进行负载测试,以确定系统可以处理多少个并发用户。在测试期间,可以通过定义每个用户的行为,并通过Web UI实时监视测试过程。关于Locust的代码实战和结果分析,可以参考引用\[2\]中提供的链接,该链接提供了深入讨论Locust性能自动化的文章。此外,引用\[3\]中的文章也提供了关于Locust的实战介绍,可以进一步了解Locust性能测试实践。 #### 引用[.reference_title] - *1* [Python性能测试框架Locust实战教程](https://blog.csdn.net/xfw17397388089/article/details/129162109)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [深聊性能测试,从入门到放弃之:Locust性能自动化(二)代码实战](https://blog.csdn.net/wuyoudeyuer/article/details/108596407)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Locust 性能测试实战(一)](https://blog.csdn.net/weixin_43431593/article/details/107710571)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木法星人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值