测试类

文章介绍了Python中常用的断言方法,如assertEqual、assertNotEqual、assertTrue、assertFalse等在测试中的应用。通过示例展示了如何测试AnonymousSurvey类,以及如何使用setUp()和tearDown()方法进行测试前的初始化和清理工作。文章强调了合理运用断言在自动化测试中的重要性。
摘要由CSDN通过智能技术生成

目录

❤  断言方法

assertEqual 和 assertNotEqual

assertTrue 和 assertFalse

assertIsNone 和 assertIsNotNone

❤  一个要测试的类

❤  测试AnonymousSurvey类

❤  setUp() 和 teardown() 方法


python从小白到总裁完整教程目录:https://blog.csdn.net/weixin_67859959/article/details/129328397?spm=1001.2014.3001.5502

❤  断言方法

常用的断言方法:

方法

用途

assertEqual(a, b)

核实a == b

assertNotEqual(a, b)

核实a != b

assertTrue(x)

核实x为True

assertFalse(x)

核实x为False

asseertIn(item, list)

核实item在list中

assertNotIn(item, list)

核实item不在list中

assertEqual 和 assertNotEqual

assertEqual:如两个值相等,则pass
assertNotEqual:如两个值不相等,则pass

下面看下具体使用方法

扩展:第一行代码后面会学到

self.assertEqual(self.driver.find_element_by_id('com.boohee.secret:id/tv_title').text,u'超模25','切到超模25tab失败') # 判断两个值是否相等
  • 这边是通过id(com.boohee.secret:id/tv_title)获取它的text值,与预期“超模25”对比,如相等则pass;不相等则fail。
  • 后面的“切到超模25tab失败”是fail时需要打印的信息,可写可不写。

断言assertNotEqual反着用就可以了。

assertTrue 和 assertFalse

assertTrue:判断bool值为True,则pass
assertFalse:判断bool值为False,则Pass
下面看下具体使用方法

self.assertTrue(self.find_element_by_id('com.boohee.secret:id/btn_login').is_enabled(),'未输密码登录按钮为不可点状态,Fail')
  • 这边是通过id(com.boohee.secret:id/btn_login)获取它的激活状态,如为True则pass;反之则fail。
  • 后面的“未输密码登录按钮为不可点状态”是fail时需要打印的信息,可写可不写。断言assertFalse反着用就可以了。

扩展:

assertIsNone 和 assertIsNotNone

assertIsNone:不存在,则pass
assertIsNotNone:存在,则pass
下面看下具体使用方法

self.assertIsNotNone(self.driver.find_element_by_id('com.boohee.secret:id/tv_edit_profile'),'无编辑资料按钮,登录失败,Fail')
  • 这边是通过寻找id(com.boohee.secret:id/tv_edit_profile)的元素是否存在,如存在则pass;不存在则fail。
  •   后面的“无编辑资料按钮,登录失败,Fail”是fail时需要打印的信息,可写可不写。断言assertIsNone反着用就可以了。

总结:这边的断言虽然不能像人工判断预期结果那样准确,但合理灵活地运用,对于重要节点加上断言也是具有一定判断预期的效果的。

❤  一个要测试的类

首先编写一个类:

survey.py

class AnonymousSurvey:
    """收集匿名调查问卷的答案"""

    def __init__(self, question):
        """存储一个问题,并为存储答案做准备"""
        self.question = question
        self.responses = []

    def show_quetion(self):
        """显示调查问卷"""
        print(self.question)

    def store_response(self, new_response):
        """存储单份调查答案"""
        self.responses.append(new_response)

    def show_result(self):
        """显示收集到的所有答卷"""
        print("Survey result:")
        for response in self.responses:
            print('- ' + response)

 为证明AnonymousSurvey类可以正确的工作,编写一个使用它的程序:

language_survey.py

from survey import AnonymousSurvey

# 定义一个问题,并创建一个表示调查的AnonymousSurvey对象
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)

# 显示并存储问题的答案
my_survey.show_quetion()
print("Enter 'q' at any time to quit.\n")
while True:
    response = input("Language: ")
    if response == 'q':
        break
    my_survey.store_response(response)

# 显示调查结果
print("\nThank you to everyone who participated in survey!")
my_survey.show_result()

  运行结果:

What language did you first learn to speak?
Enter 'q' at any time to quit.

Language: English
Language: Spanish
Language: English
Language: Mandarin
Language: q

Thank you to everyone who participated in survey!
Survey result:
- English
- Spanish
- English
- Mandarin

❤  测试AnonymousSurvey类

对AnonymousSurvey类行为的一个方面进行验证:如果用户面对调查问题时只提供了一个答案,这个答案也能被妥善地存储。使用方法assertIn()来核实它包含在答案列表中:

test_survey.py

import unittest
from survey import AnonymousSurvey


class TestAnonymousSurvey(unittest.TestCase):
    """针对AnonymousSurvey类的测试"""

    def test_store_single_response(self):
        """测试单个答案会被妥善地存储"""
        question = "What language did you first learn to speak?"
        my_survey = AnonymousSurvey(question)
        my_survey.store_response('English')

        self.assertIn('English', my_survey.responses)


if __name__ == "__main__":
    unittest.main()

 运行test_survey.py时,测试通过了:

Ran 1 test in 0.010s

OK

只能收集一个答案的调查用途不大。下面核实用户提供三个答案时,它们也将被妥善地存储。为此,在AnonymousSurvey中再添加一个方法:

import unittest
from survey import AnonymousSurvey


class TestAnonymousSurvey(unittest.TestCase):
    """针对AnonymousSurvey类的测试"""

    def test_store_single_response(self):
        ...

    def test_store_three_response(self):
        """测试三个答案会被妥善地存储"""
        question = "What language did you first learn to speak?"
        my_survey = AnonymousSurvey(question)
        responses = ['English', 'Spanish', 'Mandarin']
        for response in responses:
            my_survey.store_response(response)

        for response in responses:
            self.assertIn(response, my_survey.responses)


if __name__ == "__main__":
    unittest.main()        

 再次运行test_survey.py时,两个测试都通过了:

Ran 2 tests in 0.002s

OK

这些还有些重复的地方,怎么更简洁呢?

unittest有两个前置方法,两个后置方法,分别是

  • setup()
  • setupClass()
  • teardown()
  • teardownClass()

Pytest也贴心的提供了类似setup、teardown的方法,并且还超过四个,一共有十种

  • 模块级别:setup_module、teardown_module
  • 函数级别:setup_function、teardown_function,不在类中的方法
  • 类级别:setup_class、teardown_class
  • 方法级别:setup_method、teardown_method
  • 方法细化级别:setup、teardown

这些后面再扩展讲讲

❤  setUp() 和 teardown() 方法

unittest.TestCase类包含方法setUp(),只需创建这些对象一次,并在每个测试方法中使用它们。如果在TestCase类中包含了方法setUp(),Python将先运行它,再运行各个以test_打头的方法。这样,在编写的每个测试方法中都可使用方法setUp()中创建的对象。

setUp():就是在一个类中最先被调用的函数,每次执行一个函数都要先执行这个函数,有几个函数就被调用几次,与放的位置无关,随便放到哪里都会先执行这个函数

tearDown():就是在一个类中最后被调用的函数,每个函数执行之后都会执行一次,与放的位置无关,随便放到哪里都会最后执行这个函数,不管其他函数是否能执行成功,这个函数都会被执行,如果setUp()函数执行失败,则认为这个测试项目失败,所有的函数都不会被执行也不会执行tearDown()这个函数

  使用setUp()来创建一个调查对象和一组答案,供方法test_store_single_response()和test_store_three_responses()使用:

import unittest
from survey import AnonymousSurvey


class TestAnonymousSurvey(unittest.TestCase):
    """针对AnonymousSurvey类的测试"""

    def setUp(self):
        """
        最先执行
        创建一个调查对象和一组答案,供使用的测试方法使用
        """
        question = "What language did you first learn to speak?"
        self.my_survey = AnonymousSurvey(question)
        self.responses = ['English', 'Spanish', 'Mandarin']

    def test_store_single_response(self):
        """测试单个答案会被妥善地存储"""
        self.my_survey.store_response(self.responses[0])
        self.assertIn(self.responses[0], self.my_survey.responses)

    def test_store_three_response(self):
        """测试三个答案会被妥善地存储"""
        for response in self.responses:
            self.my_survey.store_response(response)
        for response in self.responses:
            self.assertIn(response, self.my_survey.responses)
    def teardown(self):
        """
        最后执行
        """
         print("teardown_module:在最后时执行")



if __name__ == "__main__":
    unittest.main()

方法setUp()做了两件事:创建一个调查对象;创建一个答案列表。存储这两样东西的变量名包含前缀self,因此可以在这个类中的任何地方使用。这个让两个测试方法都更加简单,不用创建调查对象和答案。

我们利用这一特性在自动化中setup主要是进行测试前的初始化工作,比如在接口测试前面做一些前置的参数赋值,数据库操作等等 teardown是测试后的清除工作,比如参数还原或销毁,数据库的还原恢复等

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

橙子味冰可乐

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

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

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

打赏作者

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

抵扣说明:

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

余额充值