def test_ddt_data_doc_attribute(): """ Test the ``__doc__`` attribute handling of ``data`` items with ``ddt`` """ def func_w_doc(): """testFunctionDocstring {6} :param: None :return: None """ pass def func_wo_doc(): pass class Myint(int): pass class Mytest(object): pass d1 = Myint(1) d1.__name__ = 'case1' d1.__doc__ = """docstring1""" d2 = Myint(2) d2.__name__ = 'case2' data_hello = data(d1, d2, {'test': True})(func_w_doc) data_hello2 = data(d1, d2, {'test': True})(func_wo_doc) setattr(Mytest, 'first_test', data_hello) setattr(Mytest, 'second_test', data_hello2) ddt_mytest = ddt(Mytest) assert_equal(getattr(getattr(ddt_mytest, 'first_test_1_case1'), '__doc__'), d1.__doc__) assert_equal(getattr(getattr(ddt_mytest, 'first_test_2_case2'), '__doc__'), func_w_doc.__doc__) assert_equal(getattr(getattr(ddt_mytest, 'first_test_3'), '__doc__'), func_w_doc.__doc__) assert_equal( getattr(getattr(ddt_mytest, 'second_test_1_case1'), '__doc__'), d1.__doc__) assert_equal( getattr(getattr(ddt_mytest, 'second_test_2_case2'), '__doc__'), None) assert_equal(getattr(getattr(ddt_mytest, 'second_test_3'), '__doc__'), None)
def test_ddt_data_doc_attribute(): """ Test the ``__doc__`` attribute handling of ``data`` items with ``ddt`` """ def hello(): """testFunctionDocstring {6} :param: None :return: None """ pass class Myint(int): pass class Mytest(object): pass d1 = Myint(1) d1.__name__ = 'case1' d1.__doc__ = """docstring1""" d2 = Myint(2) d2.__name__ = 'case2' data_hello = data(d1, d2)(hello) setattr(Mytest, 'test_hello', data_hello) ddt_mytest = ddt(Mytest) assert_equal(getattr(getattr(ddt_mytest, 'test_hello_1_case1'), '__doc__'), d1.__doc__) assert_equal(getattr(getattr(ddt_mytest, 'test_hello_2_case2'), '__doc__'), hello.__doc__)
def test_ddt_data_name_attribute(): """ Test the ``__name__`` attribute handling of ``data`` items with ``ddt`` """ def hello(): pass class Myint(int): pass class Mytest(object): pass d1 = Myint(1) d1.__name__ = 'data1' d2 = Myint(2) data_hello = data(d1, d2)(hello) setattr(Mytest, 'test_hello', data_hello) ddt_mytest = ddt(Mytest) assert_is_not_none(getattr(ddt_mytest, 'test_hello_1_data1')) assert_is_not_none(getattr(ddt_mytest, 'test_hello_2_2'))
class TestCalc(unittest.TestCase): data(*data1) @ddt.unpack def testAdd(self,a,b,c): ca = Calc() s = ca.add(a,b) self.assertEqual(s,c)
def test_ddt_data_name_attribute(): """ Test the ``__name__`` attribute handling of ``data`` items with ``ddt`` """ def hello(): pass class myint(int): pass class mytest(object): pass d1 = myint(1) d1.__name__ = 'data1' d2 = myint(2) data_hello = data(d1, d2)(hello) setattr(mytest, 'test_hello', data_hello) ddt_mytest = ddt(mytest) assert_is_not_none(getattr(ddt_mytest, 'test_hello_data1')) assert_is_not_none(getattr(ddt_mytest, 'test_hello_2'))
def test_ddt_data_name_attribute(): """ Test the ``__name__`` attribute handling of ``data`` items with ``ddt`` """ def hello(): pass class Myint(int): pass class Mytest(object): pass d1 = Myint(1) d1.__name__ = "data1" d2 = Myint(2) data_hello = data(d1, d2)(hello) setattr(Mytest, "test_hello", data_hello) ddt_mytest = ddt(Mytest) assert_is_not_none(getattr(ddt_mytest, "test_hello_1_data1")) assert_is_not_none(getattr(ddt_mytest, "test_hello_2_2"))
class TestInvest(unittest.TestCase): @classmethod def setUpClass(cls): # 初始化浏览器会话 logging.info("===用例类前置:初始化浏览器会话,登陆前程贷系统=======") cls.driver = webdriver.Chrome() cls.driver.maximize_window() cls.driver.get(CD.web_login_url) LoginPage(cls.driver).login(CD.user, CD.passwd) # 首页 - 选一个标来投资 - 直接选第一个标 -- / 随机选一个 IndexPage(cls.driver).click_first_bid() cls.bid_page = BidPage(cls.driver) @classmethod def tearDownClass(cls): logging.info("=====用例类后置:关闭浏览器会话, 清理环境=======") cls.driver, quit() def tearDown(self): logging.info("=====每一个用例后置: 刷新当前页面=======") self.driver.refresh() time.sleep(0.5) @pytest.mark.smoke def test_invest_l_success(self): logging.info("*******投资用例: 正常场景 - 投资成功*******") # 标页面 - 获取投资前的个人余额 userMoney_beforeInvest = self.bid_page.get_user_money() # 标页面 - 输入投资金额,点击投标按钮 self.bid_page.invest(ID.success["money"]) # 标页面 - 投资成功弹出框,点击查看并激活按钮 self.bid_page.click_activeButton_on_success_popup() # #验证 # 个人页面-获取用户当前余额 userMoney_afterInvest = UserPage(self.driver).get_user_leftMoney() # 1、余额:投资前获取一下,投资后再获取一下。求差值,如果等于投资金额,那正确。 assert ID.success["money"] == int( float(userMoney_beforeInvest) - (float(userMoney_afterInvest))) # PS:自动化测试独立帐号。 # 2、个人页面- 投资记录获取。 ddt.data(*ID.wrong_format_money) def test_invest_0_failed_by_No100(self, data): logging.info("********投资用例: 异常场景:投资金额为非100的整数倍、错误的格式等*****") # 标页面-获取投资前的个人余额 userMoney_beforeInvest = self.bid_page.get_user_money() # 标页面-输入投资金额, 点击投标按钮 self.bid_page.invest(data["money"]) # 获取提示信息 errorMsg = self.bid_page.get_errorMsg_from_pageCenter() # 刷新 self.driver.refresh() # 获取用户余额 userMoney_afterInvest = self.bid_page.get_user_money() # 断言 assert errorMsg == data["check"] assert userMoney_afterInvest == userMoney_beforeInvest
def annotated_data(*args): class List(list): pass new_args = [] for arg in args: new_arg = List(arg) new_arg.__name__ = arg[0] new_args.append(new_arg) return lambda func: data(*new_args)(unpack(func))
class TestBusiness(unittest.TestCase): @classmethod def setUp(self) -> None: pwd = conf.get("generator", "passwrd") phone = get_newphone() setattr(EnvData, "mobile_phone", phone) setattr(EnvData, "pwd", pwd) data(*cases) def test_bus(self, case): if response = send_request(case["method"], case["url"], case["request_data"]) resp = response.json() if
class orderLogin(unittest.TestCase): @classmethod def setUpClass(cls): cls.profilepath = r"C:\Users\liyingfeng\AppData\Roaming\Mozilla\Firefox\Profiles\c1r4vm2f.default" # 打开火狐浏览器 cls.profile = webdriver.FirefoxProfile(cls.profilepath) cls.driver = webdriver.Firefox(cls.profile) cls.driver.maximize_window() cls.driver.implicitly_wait(30) cls.driver.get("https://www.baidu.com/") data() def test_search_001(self): '''验证搜索功能是否正确''' self.driver.find_element_by_id("kw").send_keys(u"龙腾测试") self.driver.find_element_by_id("su").click() self.assertTrue(u"龙腾测试" in self.driver.page_source)
def test_data_decorator(): """Test the ``data`` method decorator""" def hello(): pass pre_size = len(hello.__dict__) keys = hello.__dict__.keys() data_hello = data(1, 2)(hello) dh_keys = data_hello.__dict__.keys() post_size = len(data_hello.__dict__) assert_equal(post_size, pre_size + 1) extra_attrs = set(dh_keys) - set(keys) assert_equal(len(extra_attrs), 1) extra_attr = extra_attrs.pop() assert_equal(getattr(data_hello, extra_attr), (1, 2))
def test_data_decorator(): """ Test the ``data`` method decorator """ def hello(): pass pre_size = len(hello.__dict__) keys = set(hello.__dict__.keys()) data_hello = data(1, 2)(hello) dh_keys = set(data_hello.__dict__.keys()) post_size = len(data_hello.__dict__) assert post_size == pre_size + 1 extra_attrs = dh_keys - keys assert len(extra_attrs) == 1 extra_attr = extra_attrs.pop() assert getattr(data_hello, extra_attr) == (1, 2)
def test_file_data_decorator_with_dict(): """ Test the ``file_data`` method decorator """ def hello(): pass pre_size = len(hello.__dict__) keys = set(hello.__dict__.keys()) data_hello = data("test_data_dict.json")(hello) dh_keys = set(data_hello.__dict__.keys()) post_size = len(data_hello.__dict__) assert_equal(post_size, pre_size + 1) extra_attrs = dh_keys - keys assert_equal(len(extra_attrs), 1) extra_attr = extra_attrs.pop() assert_equal(getattr(data_hello, extra_attr), ("test_data_dict.json", ))
def test_file_data_decorator_with_dict(): """ Test the ``file_data`` method decorator """ def hello(): pass pre_size = len(hello.__dict__) keys = set(hello.__dict__.keys()) data_hello = data("test_data_dict.json")(hello) dh_keys = set(data_hello.__dict__.keys()) post_size = len(data_hello.__dict__) assert_equal(post_size, pre_size + 1) extra_attrs = dh_keys - keys assert_equal(len(extra_attrs), 1) extra_attr = extra_attrs.pop() assert_equal(getattr(data_hello, extra_attr), ("test_data_dict.json",))
def annotated_data(*args): class List(list): pass class Dict(dict): pass new_args = [] for arg in args: if isinstance(arg, (list, tuple)): new_arg = List(arg) new_arg.__name__ = arg[0] elif isinstance(arg, dict): new_arg = Dict(arg) new_arg.__name__ = arg['tag'] else: raise TypeError('annotate_data can only handle dicts, ' 'lists and tuples') new_args.append(new_arg) return lambda func: ddt.data(*new_args)(ddt.unpack(func))
def build_case(index: int, test: dict) -> types.FunctionType: """生成用例方法""" parameters = test.get('parameters') if parameters: keys, data = parse_parameters(parameters) def test_api_ddt(self, values): key_values = dict(zip(keys, values)) print('测试数据', key_values) self.context.update(key_values) do_test(self, test) test_method = ddt.data(*data)(test_api_ddt) else: def test_api(self): do_test(self, test) test_method = test_api test_method.__name__ = f'test_api_{index+1}' test_method.__doc__ = test_method.name = test.get("name") print('test_method_name', test.get("name")) return test_method
def wrapper(func): return ddt.data(*tuplify(data))(ddt.unpack(func))
def wrapper(func): return ddt.data(*tuplify(data, unwrap_keys))(ddt.unpack(func))
import ddt from selenium import webdriver import time import unittest import os curpath = os.path.dirname(os.path.dirname( os.path.realpath(__file__))) #获取到case的路径 ddt.data({ "user": "******", "psw": "123456", "expect": "ok" }, { "user": "******", "psw": "", "expect": "flase" }) if __name__ == "__main__": # filepath = "H:\\Codeall\\WebZd\\Sqldata\\Logindata.xlsx" filepath = os.path.jion data = ExcelUtil(filepath) print(data.dict_data())
def deco(func): return data(*generate_cases(docstring=func.__doc__, **kwargs))( unpack(func))
def decorator(func): return ddt.data(*data_args)(ddt.unpack(func))
def deco(func): return data(*generate_cases(**kwargs))(unpack(func))
def supported_devices(func): """ddt decorator for iterative over supported devices on current system.""" devices = AerSimulator().available_devices() return ddt.data(*devices)(func)
def test_ddt_data_doc_attribute(): """ Test the ``__doc__`` attribute handling of ``data`` items with ``ddt`` """ def func_w_doc(): """testFunctionDocstring {6} :param: None :return: None """ pass def func_wo_doc(): pass class Myint(int): pass class Mytest(object): pass d1 = Myint(1) d1.__name__ = 'case1' d1.__doc__ = """docstring1""" d2 = Myint(2) d2.__name__ = 'case2' data_hello = data(d1, d2, {'test': True})(func_w_doc) data_hello2 = data(d1, d2, {'test': True})(func_wo_doc) setattr(Mytest, 'first_test', data_hello) setattr(Mytest, 'second_test', data_hello2) ddt_mytest = ddt(Mytest) assert_equal( getattr( getattr(ddt_mytest, 'first_test_1_case1'), '__doc__'), d1.__doc__ ) assert_equal( getattr( getattr(ddt_mytest, 'first_test_2_case2'), '__doc__'), func_w_doc.__doc__ ) assert_equal( getattr( getattr(ddt_mytest, 'first_test_3'), '__doc__'), func_w_doc.__doc__ ) assert_equal( getattr( getattr(ddt_mytest, 'second_test_1_case1'), '__doc__'), d1.__doc__ ) assert_equal( getattr( getattr(ddt_mytest, 'second_test_2_case2'), '__doc__'), None ) assert_equal( getattr( getattr(ddt_mytest, 'second_test_3'), '__doc__'), None )
def build_case(self, index: int, case: models.Case): run_case = self.run_case context = self._context parameters = case._parameters if parameters: keys, data = self._parse_parameters(parameters) def _test_method(self, values): nonlocal case nonlocal context key_values = dict(zip(keys, values)) context.register_variables(key_values) run_case(case) test_method = ddt.data(*data)(_test_method) else: def _test_method(self): nonlocal case run_case(case) test_method = _test_method test_method.__name__ = f'test_method_{index + 1}' test_method.__doc__ = test_method.name = case._name test_method.tags = case._tags test_method.level = case._level return test_method def build_suite(self, suite: models.Suite) -> unittest.TestSuite:
import pprint @ddt class TestcomplexMethods(unittest.TestCase): def teardown(self, expected_output=None): pass def startup(self, expected_output=None): """ printer: a pretty_printer """ self.printer = pprint.PrettyPrinter(indent=2).pprint @data( ) @unpack def test_retrieve_resource(self, api, resource_id, query_string='', expected_output=None): """ Retrieves resource info either from a local repo orfrom the remote server """ pass @data( ) @unpack def test_basemodel_resource(self, expected_output=None): """ Returns the model resource ID
def __new__(mcs, name, bases, attributes): """ Adds a create method for the specific class. @param mcs: @param name: @param bases: @param attributes: @return: """ _klass = super( MetaCLITest, mcs).__new__(mcs, name, bases, attributes) # When loading test classes for a test run, the Nose class # loader "transplants" any class that inherits from unittest.TestCase # into an internal class "C". If your test class uses MetaCLI, # then it will automatically also inherit from BaseCLI and # Nose will automatically see a new "C". We want to ignore # this class when using MetaCLITest if name == 'C': return _klass # Only perform attribute tests if instance is MetaCLITest parents = [b for b in bases if isinstance(b, MetaCLITest)] if not parents: return _klass # Make sure test module has required properties if not hasattr(_klass, "factory"): raise AttributeError("No 'factory' attribute found.") if not hasattr(_klass, "factory_obj"): raise AttributeError("No 'factory_obj' attribute found.") if not hasattr(_klass, "search_key"): setattr(_klass, 'search_key', 'name') # If the factory is a "plain" function makes it a staticmethod if isinstance(attributes['factory'], types.FunctionType): setattr(_klass, 'factory', staticmethod(attributes['factory'])) for name in NAMES: test_name = 'test_%s' % name if not test_name in attributes.keys(): data_name = '%s_data' % name # The data provided is a tuple so we need to unpack to pass to # the data decorator e.g. @data(*((a, b), (a, c))) if data_name.upper() in attributes.keys(): # Use data provided by test class params = attributes[data_name.upper()] else: # Use data provided by default_data module params = getattr(default_data, data_name.upper()) # Pass data to @data decorator func = data(*params)(getattr(template_methods, test_name)) # Update method's docstring to include name of object func.__doc__ = func.__doc__.replace( 'FOREMAN_OBJECT', _klass.factory_obj.__name__) # Add method to test class setattr(_klass, test_name, func) # Apply ddt decorator to class _klass = ddt(_klass) return _klass