![](/img/trans.png)
[英]Python - Create a single Json from multiple Yaml file of a directory
[英]How to dynamically create parameterized test from the file (json or yaml) in python
真的需要一個建議,如何從 python 中的文件(json 或 yaml)動態創建參數化測試。 文件包含網址列表
文件示例:
{ "name":"url_1", "url":"http://check.com","expected": "23"}
或者 :
{ "url_1", "http://check.com","23"}
像這樣的例子:
@parameterized(from the file import name, expected)
def testUrl (self, name, url, expected):
run something (%s) url
assertTrue( expected = result)
輸出 :
test_for_url_1_ (test.TestClass) ... ok
test_for_url_2_ (test.TestClass) ... ok
我正在檢查鼻子參數化:
# An iterable of params
@parameterized(
param.explicit(*json.loads(line))
for line in open("testcases.jsons")
)
def test_from_json_file(...):
...
但不能讓它工作:(
先感謝您
如果您只想將參數從文件傳遞給單個函數:
是的,您可以使用裝飾器,將文件名傳遞給它,從文件加載 json 並用作裝飾函數的參數:
import json
from functools import wraps
def params_from_file(file):
"""Decorator to load params from json file."""
def decorator(func_to_decorate):
@wraps(func_to_decorate)
def wrapper(self, *args, **kwargs):
with open(file, 'r') as fh:
kwargs = json.loads(fh.read())
return func_to_decorate(self, **kwargs)
return wrapper
return decorator
用法:
import unittest
class Test(unittest.TestCase):
@params_from_file('file.txt') # {"name":"url_1", "url":"http://check.com", "expected": "23"}
def test_url(self, name, url, expected):
self.assertEqual(name, 'url_1')
self.assertEqual(url, 'http://check.com')
self.assertEqual(expected, '23')
# print(name, url, expected)
if __name__ == "__main__":
unittest.main()
如果您想從參數集創建多個新測試:
import json
def create_tests(func_name, file):
def decorator(cls):
func = getattr(cls, func_name)
# Set new funcs to class:
with open(file, 'r') as fh:
data = json.loads(fh.read())['data']
for i, params in enumerate(data):
def tmp(params=params): # need for http://stackoverflow.com/q/7546285/1113207
def wrapper(self, *args, **kwargs):
return func(self, **params)
return wrapper
setattr(cls, func_name + '_' + str(i), tmp())
# Remove func from class:
setattr(cls, func_name, None)
return cls
return decorator
用法:
import unittest
@create_tests('test_url', 'file.txt')
class Test(unittest.TestCase):
def test_url(self, name, url, expected):
print(name, url, expected)
if __name__ == "__main__":
unittest.main(verbosity=2)
輸出:
test_url_0 (__main__.Test) ... name1 https://example.com 175
ok
test_url_1 (__main__.Test) ... name2 https://example2.com 15
ok
----------------------------------------------------------------------
Ran 2 tests in 0.000s
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.