From 662ef37c93b4e791b6d4df257eba7e47b4b74c66 Mon Sep 17 00:00:00 2001 From: han0 Date: Tue, 1 Jun 2021 10:45:22 +0800 Subject: [PATCH] =?UTF-8?q?feat(stress=5Ftest):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E5=8E=8B=E5=8A=9B=E6=B5=8B=E8=AF=95=20locust=20=E7=BB=84?= =?UTF-8?q?=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- nc_http/core/stress_test/__init__.py | 81 ++++++++++++++++++++++++++++ requirements.txt | 3 +- 2 files changed, 83 insertions(+), 1 deletion(-) create mode 100644 nc_http/core/stress_test/__init__.py diff --git a/nc_http/core/stress_test/__init__.py b/nc_http/core/stress_test/__init__.py new file mode 100644 index 0000000..3cb3d24 --- /dev/null +++ b/nc_http/core/stress_test/__init__.py @@ -0,0 +1,81 @@ +import json +import subprocess + +import requests +from locust import HttpUser, task, between + + +class SwaggerJsonUrlNotFound(Exception): + """缺少 swagger json url 定义""" + + +class SwaggerApiParser: + def __init__(self, json_url=None): + self.json_url = json_url + self.api_list = None + + @property + def content(self): + """ + :return: [ + ('get', '/application'), + ('post', '/application'), + ] + """ + if not self.api_list: + self.api_list = self._parse_api() + + return self.api_list + + def _parse_api(self): + if not self.json_url: + raise SwaggerJsonUrlNotFound + + swagger_dict = json.loads(requests.get(self.json_url).text) + if swagger_dict.get('host'): + print('host: {}'.format(swagger_dict['host'])) + if swagger_dict.get('asePath'): + print('asePath: {}'.format(swagger_dict['asePath'])) + + if not swagger_dict.get('paths'): + return [] + + result = [] + for path, methods in swagger_dict['paths'].items(): + for method in methods: + result.append((method, path)) + + return result + + +TEST_JSON_URL = 'http://localhost:7071/apispec_1.json' + + +class StressTest(HttpUser): + wait_time = between(1, 2) + parser = SwaggerApiParser(TEST_JSON_URL) + + @task + def index_page(self): + for method, uri in self.parser.content: + run = getattr(self.client, method) + run(uri) + + @staticmethod + def run_locust(file_name=None): + file_name = file_name or __file__ + subprocess.run(['locust', '-f', file_name]) + + +if __name__ == '__main__': + StressTest.run_locust() + +''' +# sample.py + +class SampleStressTest(StressTest): + parser = SwaggerApiParser('http://localhost:7071/apispec_1.json') + +if __name__ == '__main__': + SampleStressTest.run_locust() +''' diff --git a/requirements.txt b/requirements.txt index c91acac..a4c3439 100644 --- a/requirements.txt +++ b/requirements.txt @@ -6,4 +6,5 @@ xlsxwriter xlrd captcha six -requests \ No newline at end of file +requests +locust \ No newline at end of file