Python 面试:单元测试unit testing & 使用pytest

这篇具有很好参考价值的文章主要介绍了Python 面试:单元测试unit testing & 使用pytest。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1. 对于函数进行单元测试

calc.py

def add(x, y):
    """Add Function"""
    return x + y

def subtract(x, y):
    """Subtract Function"""
    return x - y

def multiply(x, y):
    """Multiply Function"""
    return x * y

def divide(x, y):
    """Divide Function"""
    if y == 0: 
        raise ValueError('Can not divide by zero!')
    return x / y

test_calc.py

import unittest
import calc

class TestCalc(unittest.TestCase):

    def test_add(self):
        self.assertEqual(calc.add(10, 5), 15)
        self.assertEqual(calc.add(-1, 1), 0)
        self.assertEqual(calc.add(-1, -1), -2)

    def test_subtract(self):
        self.assertEqual(calc.subtract(10, 5), 5)
        self.assertEqual(calc.subtract(-1, 1), -2)
        self.assertEqual(calc.subtract(-1, -1), 0)

    def test_multiply(self):
        self.assertEqual(calc.multiply(10, 5), 50)
        self.assertEqual(calc.multiply(-1, 1), -1)
        self.assertEqual(calc.multiply(-1, -1), 1)

    def test_divide(self):
        self.assertEqual(calc.divide(10, 5), 2)
        self.assertEqual(calc.divide(-1, 1), -1)
        self.assertEqual(calc.divide(-1, -1), 1)

        self.assertRaises(ValueError, calc.divide, 10, 0)


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

2. 对于对象(object)进行单元测试

employee.py

class Employee:
    """A sample Employee class"""

    raise_amt = 1.05

    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay

    @property
    def email(self):
        return '{}.{}@email.com'.format(self.first, self.last)
    
    @property
    def fullname(self):
        return '{} {}'.format(self.first, self.last)
    
    def apply_raise(self):
        self.pay = int(self.pay * self.raise_amt)

test_employee.py

import unittest
from employee import Employee

class TestEmployee(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        print('setupClass')

    @classmethod
    def tearDownClass(cls):
        print('teardownClass')

    def setUp(self):
        print('setUp')
        self.emp_1 = Employee('Elon', 'Musk', 50000)
        self.emp_2 = Employee('Sue', 'Smith', 60000)

    def tearDown(self):
        print('tearDown\n')

    def test_email(self):
        print('test_email')
        self.assertEqual(self.emp_1.email, 'Elon.Musk@email.com')
        self.assertEqual(self.emp_2.email, 'Sue.Smith@email.com')

        self.emp_1.first = 'John'
        self.emp_2.first = 'Jane'

        self.assertEqual(self.emp_1.email, 'John.Musk@email.com')
        self.assertEqual(self.emp_2.email, 'Jane.Smith@email.com')

    def test_fullname(self):
        print('test_fullname')
        self.assertEqual(self.emp_1.fullname, 'Elon Musk')
        self.assertEqual(self.emp_2.fullname, 'Sue Smith')

        self.emp_1.first = 'John'
        self.emp_2.first = 'Jane'

        self.assertEqual(self.emp_1.fullname, 'John Musk')
        self.assertEqual(self.emp_2.fullname, 'Jane Smith')

    def test_apply_raise(self):
        print('test_apply_raise')
        self.emp_1.apply_raise()
        self.emp_2.apply_raise()

        self.assertEqual(self.emp_1.pay, 52500)
        self.assertEqual(self.emp_2.pay, 63000)

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

输出为:
setupClass
setUp
test_apply_raise
tearDown

.setUp
test_email
tearDown

.setUp
test_fullname
tearDown

.teardownClass


Ran 3 tests in 0.001s

OK

3. 使用mock模拟对象库

employee.py

import requests

class Employee:
    """A sample Employee class"""

    raise_amt = 1.05

    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay

    @property
    def email(self):
        return '{}.{}@email.com'.format(self.first, self.last)
    
    @property
    def fullname(self):
        return '{} {}'.format(self.first, self.last)
    
    def apply_raise(self):
        self.pay = int(self.pay * self.raise_amt)

    def monthly_schedule(self, month):
        response = requests.get(f'http://company.com/{self.last}/{month}')
        if response.ok:
            return response.text
        else:
            return 'Bad Response!'

test_employee.py

import unittest
from unittest.mock import patch
from employee import Employee

class TestEmployee(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        print('setupClass')

    @classmethod
    def tearDownClass(cls):
        print('teardownClass')

    def setUp(self):
        print('setUp')
        self.emp_1 = Employee('Elon', 'Musk', 50000)
        self.emp_2 = Employee('Sue', 'Smith', 60000)

    def tearDown(self):
        print('tearDown\n')

    # Test 1
    def test_email(self):
        print('test_email')
        self.assertEqual(self.emp_1.email, 'Elon.Musk@email.com')
        self.assertEqual(self.emp_2.email, 'Sue.Smith@email.com')

        self.emp_1.first = 'John'
        self.emp_2.first = 'Jane'

        self.assertEqual(self.emp_1.email, 'John.Musk@email.com')
        self.assertEqual(self.emp_2.email, 'Jane.Smith@email.com')

    # Test 2
    def test_fullname(self):
        print('test_fullname')
        self.assertEqual(self.emp_1.fullname, 'Elon Musk')
        self.assertEqual(self.emp_2.fullname, 'Sue Smith')

        self.emp_1.first = 'John'
        self.emp_2.first = 'Jane'

        self.assertEqual(self.emp_1.fullname, 'John Musk')
        self.assertEqual(self.emp_2.fullname, 'Jane Smith')

    # Test 3
    def test_apply_raise(self):
        print('test_apply_raise')
        self.emp_1.apply_raise()
        self.emp_2.apply_raise()

        self.assertEqual(self.emp_1.pay, 52500)
        self.assertEqual(self.emp_2.pay, 63000)

    # Test 4
    def test_monthly_schedule(self):
    	# 模拟替换网络请求
        with patch('employee.requests.get') as mocked_get:
            mocked_get.return_value.ok = True
            mocked_get.return_value.text = 'Success'

            schedule = self.emp_1.monthly_schedule('May')
            mocked_get.assert_called_with('http://company.com/Musk/May')
            self.assertEqual(schedule, 'Success')

            mocked_get.return_value.ok = False

            schedule = self.emp_2.monthly_schedule('June')
            mocked_get.assert_called_with('http://company.com/Smith/June')
            self.assertEqual(schedule, 'Bad Response!')

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

输出为:
setupClass
setUp
test_apply_raise
tearDown

.setUp
test_email
tearDown

.setUp
test_fullname
tearDown

.setUp
tearDown

.teardownClass


Ran 4 tests in 0.001s

OK

4. 使用pytest进行测试

binarysearch.py,主要使用assert。

def binary_search(array, target):
    if not array:
        return -1
    begin, end = 0, len(array)
    while begin < end:
        mid = begin + (end - begin) // 2
        if array[mid] == target:
            return mid
        elif array[mid] > target:
            end = mid
        else:
            begin = mid + 1
    return -1

def test():
    assert binary_search([0, 1, 2, 3, 4, 5], 1) == 1
    assert binary_search([0, 1, 2, 3, 4, 5], 6) == -1
    assert binary_search([0, 1, 2, 3, 4, 5], -1) == -1

    assert binary_search([0, 1, 2, 3, 4, 5], 0) == 0
    assert binary_search([0, 1, 2, 3, 4, 5], 5) == 5
    assert binary_search([0], 0) == 0

    assert binary_search([], 1) == -1
在CMD中输入指令:pytest binarysearch.py

输出为:
================================================= test session starts =================================================
platform win32 – Python 3.10.9, pytest-7.1.2, pluggy-1.0.0
rootdir: C:\Users\h13je\Working_Log\01092023\python_learning
plugins: anyio-3.5.0
collected 1 item

binarysearch.py . [100%]

================================================== 1 passed in 0.02s ==================================================文章来源地址https://www.toymoban.com/news/detail-695235.html

到了这里,关于Python 面试:单元测试unit testing & 使用pytest的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 使用Simulink Test进行单元测试

    本文摘要:主要介绍如何利用Simulink Test工具箱,对模型进行单元测试。内容包括,如何创建Test Harness模型,如何自动生成excel格式的测试用例模板来创建测试用例,如何手动填写excel格式的测试用例模板来手动创建测试用例。 单元测试的目的 创建完模型后,我们需要验证模型

    2024年02月16日
    浏览(32)
  • IDEA中 单元测试@Test的使用

    首先我在自己的module-zzz中有hamcrest-core-1.3.jar 和 Junit-4.12.jar两个包 ,并且可以正常使用test测试方法。要想在另外一个module-chapter01中正常使用test,则可以进行如下操作:第一步:File -- Project Structure -- Modules–Dependencies 第二步:点击右上角的+  第三步:点击JARs or directories…

    2024年02月07日
    浏览(37)
  • [C++] 基础教程 - 如何使用google test进行单元测试

    https://download.csdn.net/download/u011775793/88601877 单元测试是一种软件测试方法,用于测试代码中的最小可测试单元。在软件开发中,我们通常将代码分解为多个模块或类,每个模块或类都有自己的功能和行为。单元测试的目的是确保每个模块或类都能正常工作,不会影响其他模块或

    2024年02月04日
    浏览(33)
  • Maven-使用maven mvn命令进行单元测试、指定测试某个类、mvn test

    添加测试插件 运行mvn test命令

    2024年02月05日
    浏览(48)
  • Maven 项目中为什么Junit之@Test 单元测试无法使用

    由于框架项目的使用,会有很多模块,所以Junit中的@Test注解是我们比较常用的注解,但是有些小问题我们需要注意 在创建完Maven项目后,我们通常呢会导入以下这样的依赖包: 但是我们这时候去代码中使用@Test,会出现报红,这是为什么呢?🤨 这里先说明下,org.junit是导入

    2024年02月02日
    浏览(44)
  • Spring Test中使用MockMvc进行上传文件单元测试时,报NullPointerException

    问题 : MockMvc peform在集成测试中返回nullPointerException 原因 : springboot-2.x版本以上,当你添加依赖spring_boot_starter_test后,可以在内部看到自带了jupiter测试核心模块,也就是 junit5,junit5(jupiter测试引擎)不再支持junit4(vintage测试引擎),在使用时自然不再需要spring来提供了,

    2024年02月14日
    浏览(37)
  • 记录使用vue-test-utils + jest 在uniapp中进行单元测试

    uniapp推荐了测试方案 @dcloudio/uni-automator ,属于自动化测试,api提供的示例偏重于渲染组件,判断当前渲染的组件是否和预期一致 vue推荐的测试方案 vue test utils ,属于单元测试,可以搭配jest、mocha等单测运行器 我选了方案2🕶️ 关于vue的组件测试,vue官方提到: 你的 Vue 应用

    2024年02月06日
    浏览(33)
  • GO——单元测试(test)

    go test用来做什么 做单元测试,测试函数是否符合预期 go test在哪个包 testing 如何使用 参考: https://geektutu.com/post/quick-go-test.html 以 my_func.go 中的Add方法为例 在同一个文件夹下添加my_func_test.go文件 测试文件以_test.go为结尾 里面的测试方法以Test开头,但是不一定是要跟方法名,

    2024年01月20日
    浏览(38)
  • 仿真与测试:单元测试与Test Harness

    本文描述单元测试的概念,以及Test Harness建立的方法和简单的单元测试过程。 单元测试,简单来说就是在Simulink模型中只测试一小部分单元的功能。关于单元测试的概念网上有很多资料了,这里不再赘述。博主从实际工作经验的角度来谈谈单元测试的价值。 举个简单的例子,

    2024年02月04日
    浏览(34)
  • Springboot的Test单元测试操作

    Springboot的Test单元测试操作 简单总结需要操作的步骤 1,导入依赖 2,创建目录(目录和启动类的目录保持一致) 3,添加注解 4,写方法测试 1,导入依赖 2,创建目录(目录和启动类的目录保持一致),并test目录绿色标记一下 3,添加注解 注意的是,这里的test的类路径impo

    2024年04月25日
    浏览(28)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包