def test_make_testcase(self): har_path = os.path.join(os.path.dirname(__file__), "data", "demo-quickstart.har") har_parser = HarParser(har_path) testcase = har_parser._make_testcase() testcase_config = testcase[0] self.assertIn("config", testcase_config)
def test_make_testcase_v2(self): har_path = os.path.join(os.path.dirname(__file__), "data", "demo-quickstart.har") har_parser = HarParser(har_path) testcase = har_parser._make_testcase("v2") self.assertIsInstance(testcase, dict) self.assertIn("config", testcase) self.assertIn("teststeps", testcase) self.assertEqual(len(testcase["teststeps"]), 2)
def test_make_testcase_v1(self): har_path = os.path.join(os.path.dirname(__file__), "data", "demo-quickstart.har") har_parser = HarParser(har_path) testcase = har_parser._make_testcase("v1") self.assertIsInstance(testcase, list) self.assertEqual(len(testcase), 3) self.assertIn("config", testcase[0]) self.assertIn("test", testcase[1]) self.assertIn("test", testcase[2])
def test_make_testset(self): har_path = os.path.join( os.path.dirname(__file__), "data", "demo-quickstart.har") har_parser = HarParser(har_path) testset = har_parser.make_testset() testset_config = testset[0] self.assertIn("config", testset_config) self.assertIn("request", testset_config["config"]) self.assertIn("headers", testset_config["config"]["request"]) self.assertEqual(testset_config["config"]["request"]["base_url"], "")
def test_exclude_multiple(self): exclude_str = "httprunner|v2" har_parser = HarParser(self.har_path, exclude_str=exclude_str) testcase = [] har_parser._prepare_teststeps(testcase) self.assertEqual(testcase, []) exclude_str = "http2|v1" har_parser = HarParser(self.har_path, exclude_str=exclude_str) testcase = [] har_parser._prepare_teststeps(testcase) self.assertEqual(testcase, [])
def main(): """ HAR converter: parse command line options and run commands. """ parser = argparse.ArgumentParser(description=__description__) parser.add_argument( '-V', '--version', dest='version', action='store_true', help="show version") parser.add_argument( '--log-level', default='INFO', help="Specify logging level, default is INFO.") parser.add_argument('har_source_file', nargs='?', help="Specify HAR source file") parser.add_argument( '-2y', '--to-yml', '--to-yaml', dest='to_yaml', action='store_true', help="Convert to YAML format, if not specified, convert to JSON format by default.") parser.add_argument( '-fmt', '--format', dest='fmt_version', help="Specify YAML/JSON testcase format version, v2 corresponds to HttpRunner 2.2.0+.") parser.add_argument( '--filter', help="Specify filter keyword, only url include filter string will be converted.") parser.add_argument( '--exclude', help="Specify exclude keyword, url that includes exclude string will be ignored, multiple keywords can be joined with '|'") args = parser.parse_args() if args.version: print("{}".format(__version__)) exit(0) log_level = getattr(logging, args.log_level.upper()) logging.basicConfig(level=log_level) har_source_file = args.har_source_file if not har_source_file or not har_source_file.endswith(".har"): logging.error("HAR file not specified.") sys.exit(1) output_file_type = "YML" if args.to_yaml else "JSON" # set default format version by HttpRunner version if HRUN_VERSION and StrictVersion(HRUN_VERSION) < StrictVersion("2.2.0"): default_fmt_version = "v1" else: default_fmt_version = "v2" fmt_version = args.fmt_version or default_fmt_version HarParser( har_source_file, args.filter, args.exclude ).gen_testcase(output_file_type, fmt_version) return 0
def test_exclude(self): exclude_str = "debugtalk" har_parser = HarParser(self.har_path, exclude_str=exclude_str) testcase = [] har_parser._prepare_teststeps(testcase) self.assertEqual(testcase[0]["test"]["request"]["url"], "https://httprunner.top/api/v1/Account/Login") exclude_str = "httprunner" har_parser = HarParser(self.har_path, exclude_str=exclude_str) testcase = [] har_parser._prepare_teststeps(testcase) self.assertEqual(testcase, [])
def main(): """ HAR converter: parse command line options and run commands. """ parser = argparse.ArgumentParser( description='Convert HAR to YAML/JSON testcases for HttpRunner.') parser.add_argument( '-V', '--version', dest='version', action='store_true', help="show version") parser.add_argument('har_source_file', nargs='?', help="Specify HAR source file") parser.add_argument('output_testset_file', nargs='?', help="Optional. Specify converted YAML/JSON testset file.") parser.add_argument( '--filter', help="Specify filter keyword, only url include filter string will be converted.") parser.add_argument( '--exclude', help="Specify exclude keyword, url that includes exclude string will be ignored.") parser.add_argument( '--log-level', default='INFO', help="Specify logging level, default is INFO.") args = parser.parse_args() if args.version: print("{}".format(__version__)) exit(0) log_level = getattr(logging, args.log_level.upper()) logging.basicConfig(level=log_level) har_source_file = args.har_source_file output_testset_file = args.output_testset_file if not har_source_file or not har_source_file.endswith(".har"): logging.error("HAR file not specified.") sys.exit(1) output_file_type = "JSON" if not output_testset_file: harfile = os.path.splitext(har_source_file)[0] output_testset_file = "{}.{}".format(harfile, output_file_type.lower()) else: output_file_suffix = os.path.splitext(output_testset_file)[1] if output_file_suffix in [".yml", ".yaml"]: output_file_type = "YAML" elif output_file_suffix in [".json"]: output_file_type = "JSON" else: logging.error("Converted file could only be in YAML or JSON format.") sys.exit(1) har_parser = HarParser(har_source_file, args.filter, args.exclude) if output_file_type == "JSON": har_parser.gen_json(output_testset_file) else: har_parser.gen_yaml(output_testset_file) return 0
def test_exclude_multiple(self): exclude_str = "httprunner|v2" har_parser = HarParser(self.har_path, exclude_str=exclude_str) testcases = har_parser.make_testcases() self.assertEqual(testcases, []) exclude_str = "http2|v1" har_parser = HarParser(self.har_path, exclude_str=exclude_str) testcases = har_parser.make_testcases() self.assertEqual(testcases, [])
def test_filter(self): filter_str = "httprunner" har_parser = HarParser(self.har_path, filter_str) teststeps = har_parser._prepare_teststeps("v1") self.assertEqual(teststeps[0]["test"]["request"]["url"], "https://httprunner.top/api/v1/Account/Login") filter_str = "debugtalk" har_parser = HarParser(self.har_path, filter_str) teststeps = har_parser._prepare_teststeps("v1") self.assertEqual(teststeps, [])
def test_exclude(self): exclude_str = "debugtalk" har_parser = HarParser(self.har_path, exclude_str=exclude_str) testcases = har_parser.make_testcases() self.assertEqual(testcases[0]["test"]["request"]["url"], "https://httprunner.top/api/v1/Account/Login") exclude_str = "httprunner" har_parser = HarParser(self.har_path, exclude_str=exclude_str) testcases = har_parser.make_testcases() self.assertEqual(testcases, [])
def setUp(self): self.har_parser = HarParser(self.har_path)
class TestHar(TestUtils): def setUp(self): self.har_parser = HarParser(self.har_path) def test_prepare_teststep(self): log_entries = load_har_log_entries(self.har_path) teststep_dict = self.har_parser._prepare_teststep(log_entries[0]) self.assertIn("name", teststep_dict) self.assertIn("request", teststep_dict) self.assertIn("validate", teststep_dict) validators_mapping = { validator["eq"][0]: validator["eq"][1] for validator in teststep_dict["validate"] } self.assertEqual(validators_mapping["status_code"], 200) self.assertEqual(validators_mapping["content.IsSuccess"], True) self.assertEqual(validators_mapping["content.Code"], 200) self.assertEqual(validators_mapping["content.Message"], None) def test_prepare_teststeps(self): testcase = [] self.har_parser._prepare_teststeps(testcase) self.assertIn("name", testcase[0]["test"]) self.assertIn("request", testcase[0]["test"]) self.assertIn("validate", testcase[0]["test"]) def test_gen_testcase_yaml(self): yaml_file = os.path.join(os.path.dirname(__file__), "data", "demo.yaml") self.har_parser.gen_testcase(file_type="YAML") self.assertTrue(os.path.isfile(yaml_file)) os.remove(yaml_file) def test_gen_testcase_json(self): json_file = os.path.join(os.path.dirname(__file__), "data", "demo.json") self.har_parser.gen_testcase(file_type="JSON") self.assertTrue(os.path.isfile(json_file)) os.remove(json_file) def test_filter(self): filter_str = "httprunner" har_parser = HarParser(self.har_path, filter_str) testcase = [] har_parser._prepare_teststeps(testcase) self.assertEqual(testcase[0]["test"]["request"]["url"], "https://httprunner.top/api/v1/Account/Login") filter_str = "debugtalk" har_parser = HarParser(self.har_path, filter_str) testcase = [] har_parser._prepare_teststeps(testcase) self.assertEqual(testcase, []) def test_exclude(self): exclude_str = "debugtalk" har_parser = HarParser(self.har_path, exclude_str=exclude_str) testcase = [] har_parser._prepare_teststeps(testcase) self.assertEqual(testcase[0]["test"]["request"]["url"], "https://httprunner.top/api/v1/Account/Login") exclude_str = "httprunner" har_parser = HarParser(self.har_path, exclude_str=exclude_str) testcase = [] har_parser._prepare_teststeps(testcase) self.assertEqual(testcase, []) def test_exclude_multiple(self): exclude_str = "httprunner|v2" har_parser = HarParser(self.har_path, exclude_str=exclude_str) testcase = [] har_parser._prepare_teststeps(testcase) self.assertEqual(testcase, []) exclude_str = "http2|v1" har_parser = HarParser(self.har_path, exclude_str=exclude_str) testcase = [] har_parser._prepare_teststeps(testcase) self.assertEqual(testcase, []) def test_make_request_data_params(self): testcase_dict = {"name": "", "request": {}, "validate": []} entry_json = { "request": { "method": "POST", "postData": { "mimeType": "application/x-www-form-urlencoded; charset=utf-8", "params": [{ "name": "a", "value": 1 }, { "name": "b", "value": "2" }] }, } } self.har_parser._make_request_data(testcase_dict, entry_json) self.assertEqual(testcase_dict["request"]["data"]["a"], 1) self.assertEqual(testcase_dict["request"]["data"]["b"], "2") def test_make_request_data_json(self): testcase_dict = {"name": "", "request": {}, "validate": []} entry_json = { "request": { "method": "POST", "postData": { "mimeType": "application/json; charset=utf-8", "text": "{\"a\":\"1\",\"b\":\"2\"}" }, } } self.har_parser._make_request_data(testcase_dict, entry_json) self.assertEqual(testcase_dict["request"]["json"], { 'a': '1', 'b': '2' }) def test_make_request_data_text_empty(self): testcase_dict = {"name": "", "request": {}, "validate": []} entry_json = { "request": { "method": "POST", "postData": { "mimeType": "application/json; charset=utf-8", "text": "" }, } } self.har_parser._make_request_data(testcase_dict, entry_json) self.assertEqual(testcase_dict["request"]["data"], "") def test_make_validate(self): testcase_dict = {"name": "", "request": {}, "validate": []} entry_json = { "request": {}, "response": { "status": 200, "headers": [ { "name": "Content-Type", "value": "application/json; charset=utf-8" }, ], "content": { "size": 71, "mimeType": "application/json; charset=utf-8", # raw response content text is application/jose type "text": "ZXlKaGJHY2lPaUpTVTBFeFh6VWlMQ0psYm1NaU9pSkJNVEk0UTBKRExV", "encoding": "base64" } } } self.har_parser._make_validate(testcase_dict, entry_json) self.assertEqual(testcase_dict["validate"][0], {"eq": ["status_code", 200]}) self.assertEqual(testcase_dict["validate"][1], { "eq": ["headers.Content-Type", "application/json; charset=utf-8"] }) def test_make_testcase(self): har_path = os.path.join(os.path.dirname(__file__), "data", "demo-quickstart.har") har_parser = HarParser(har_path) testcase = har_parser._make_testcase() testcase_config = testcase[0] self.assertIn("config", testcase_config)
def setUp(self): self.har_parser = HarParser(self.har_path) self.log_entries = self.har_parser.log_entries
class TestUtilsParser(TestUtils): def setUp(self): self.har_parser = HarParser(self.har_path) self.log_entries = self.har_parser.log_entries def test_make_testcase(self): testcase = self.har_parser.make_testcase(self.log_entries[0]) self.assertIn("name", testcase) self.assertIn("request", testcase) self.assertIn("validate", testcase) validators_mapping = { validator["check"]: validator["expect"] for validator in testcase["validate"] } self.assertEqual(validators_mapping["status_code"], 200) self.assertEqual(validators_mapping["content.IsSuccess"], True) self.assertEqual(validators_mapping["content.Code"], 200) self.assertEqual(validators_mapping["content.Message"], None) def test_make_testcases(self): testcases = self.har_parser.make_testcases() self.assertIn("name", testcases[0]["test"]) self.assertIn("request", testcases[0]["test"]) self.assertIn("validate", testcases[0]["test"]) def test_gen_yaml(self): yaml_file = os.path.join(os.path.dirname(__file__), "data", "demo.yml") self.har_parser.gen_yaml(yaml_file) os.remove(yaml_file) def test_gen_json(self): json_file = os.path.join(os.path.dirname(__file__), "data", "demo.json") self.har_parser.gen_json(json_file) os.remove(json_file) def test_filter(self): filter_str = "httprunner" har_parser = HarParser(self.har_path, filter_str) testcases = har_parser.make_testcases() self.assertEqual(testcases[0]["test"]["request"]["url"], "https://httprunner.top/api/v1/Account/Login") filter_str = "debugtalk" har_parser = HarParser(self.har_path, filter_str) testcases = har_parser.make_testcases() self.assertEqual(testcases, []) def test_exclude(self): exclude_str = "debugtalk" har_parser = HarParser(self.har_path, exclude_str=exclude_str) testcases = har_parser.make_testcases() self.assertEqual(testcases[0]["test"]["request"]["url"], "https://httprunner.top/api/v1/Account/Login") exclude_str = "httprunner" har_parser = HarParser(self.har_path, exclude_str=exclude_str) testcases = har_parser.make_testcases() self.assertEqual(testcases, []) def test_make_request_data_params(self): testcase_dict = {"name": "", "request": {}, "validate": []} entry_json = { "request": { "method": "POST", "postData": { "mimeType": "application/x-www-form-urlencoded; charset=utf-8", "params": [{ "name": "a", "value": 1 }, { "name": "b", "value": "2" }] }, } } self.har_parser._make_request_data(testcase_dict, entry_json) self.assertEqual(testcase_dict["request"]["method"], "POST") self.assertIn("a=1", testcase_dict["request"]["data"]) self.assertIn("b=2", testcase_dict["request"]["data"]) def test_make_request_data_json(self): testcase_dict = {"name": "", "request": {}, "validate": []} entry_json = { "request": { "method": "POST", "postData": { "mimeType": "application/json; charset=utf-8", "text": "{\"a\":\"1\",\"b\":\"2\"}" }, } } self.har_parser._make_request_data(testcase_dict, entry_json) self.assertEqual(testcase_dict["request"]["method"], "POST") self.assertEqual(testcase_dict["request"]["json"], { 'a': '1', 'b': '2' }) def test_make_validate(self): testcase_dict = {"name": "", "request": {}, "validate": []} entry_json = { "request": {}, "response": { "status": 200, "headers": [ { "name": "Content-Type", "value": "application/json; charset=utf-8" }, ], "content": { "size": 71, "mimeType": "application/json; charset=utf-8", # raw response content text is application/jose type "text": "ZXlKaGJHY2lPaUpTVTBFeFh6VWlMQ0psYm1NaU9pSkJNVEk0UTBKRExV", "encoding": "base64" } } } self.har_parser._make_validate(testcase_dict, entry_json) self.assertEqual(testcase_dict["validate"][0], { "check": "status_code", "expect": 200 }) self.assertEqual( testcase_dict["validate"][1], { "check": "headers.Content-Type", "expect": "application/json; charset=utf-8" })
def upload_file_logic(files, project, module, account): """ 解析yaml或者json用例 :param files: :param project: :param module: :param account: :return: """ is_har = 0 for file in files: file_suffix = os.path.splitext(file)[1].lower() if file_suffix == '.json': with io.open(file, encoding='utf-8') as data_file: try: content = json.load(data_file) except JSONDecodeError: err_msg = u"JSONDecodeError: JSON file format error: {}".format( file) logging.error(err_msg) elif file_suffix in ['.yaml', '.yml']: with io.open(file, 'r', encoding='utf-8') as stream: content = yaml.load(stream) elif file_suffix == '.har': har_parser = HarParser(file) content = har_parser._make_testcase("v1") is_har = 1 version = 1 for test_case in content: test_dict = { 'project': project, 'module': module, 'author': account, 'include': [] } if 'config' in test_case.keys(): test_case.get('config')['config_info'] = test_dict # add_config_data(type=True, **test_case) if 'test' in test_case.keys(): # 忽略config test_case.get('test')['case_info'] = test_dict if 'validate' in test_case.get( 'test').keys(): # 适配validate两种格式 validate = test_case.get('test').pop('validate') new_validate = [] for check in validate: if 'comparator' not in check.keys(): for key, value in check.items(): tmp_check = { "check": value[0], "comparator": key, "expected": value[1] } new_validate.append(tmp_check) test_case.get('test')['validate'] = new_validate '''通过har导入的,如果头信息里面包含apiCode,则将用例名称设置为apiCode''' if is_har == 1: '''验证导入有问题,先不导入''' test_case.get('test')['validate'] = [] req = test_case.get('test').get('request') name = test_case.get('test').get('name') names = name.split('.') suffix = names[len(names) - 1] if suffix == 'js' or suffix == 'css' or suffix == 'svg' or suffix == 'ico' or suffix == 'woff' or suffix == 'png': continue if req is not None: method = req.get('headers').get('method') if method is not None: test_case['test']['name'] = method # 替换用例中名称包含的'/'符号,并追加版本号 if '/' in test_case['test']['name']: test_case['test']['name'] = str( test_case['test']['name']).replace( '/', '-') + '-' + str(version) add_case_data(type=True, **test_case) version = version + 1