python - pytest - Very easy sample in steps

Here assume we have a python script folder, and we want to put test scripts in tests just in the folder of scripts.

Step 0, Create testing target

Create pipeline.py and __init__.py in your folder. Below is the content of pipeline.py.

import logging
logger = logging.getLogger(__name__)

def even_filter(nums):
    for num in nums:
        if num % 2 == 0:
            logger.debug("%s", num)
            yield num

def multiply_by_three(nums):
    for num in nums:
        logger.debug("%s * 3 = %s", num, num * 3)
        yield num * 3

def convert_to_string(nums):
    for num in nums:
        logger.debug("%s", num)
        yield 'The Number: %s' % num

def pipeline_func(data, fns):
    return reduce(lambda a, x: x(a), fns, data)

def main():
    nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    #pipeline = convert_to_string(multiply_by_three(even_filter(nums)))
    pipeline = pipeline_func(nums, [even_filter, multiply_by_three, convert_to_string])
    for num in pipeline:
        logger.info(num)

if __name__ == '__main__':

    logging.basicConfig(
        level=logging.DEBUG,
        format="%(asctime)s %(name)s.%(funcName)s: %(message)s")
    main()


Step 1, Create runTests script

#!/usr/bin/python
import pytest

exit(pytest.main("-q ./tests"))

Step 2, Create test cases

$ mkdir tests
$ cd tests
$ vim test_sample.py

Use below contents in tests/test_sample.py script.

#!/usr/bin/python
import pytest

nums = []


@pytest.fixture(scope="module")
def data_setup(request):
    print ("data_setup")
    global nums
    nums = range(10)


    def data_teardown():
        print ("data_teardown")
    request.addfinalizer(data_teardown)


def test_pipeline_func(data_setup):
    import pipeline
    output = pipeline.pipeline_func(
        nums, [
            pipeline.even_filter, pipeline.multiply_by_three])
    expect = [0, 6, 12, 18, 24]
    assert(output, expect)


Step 3, Run runTests.py

C:\Users\Xiaoqiang\Desktop\pyWorks\funcprog>python runTests.py
.
1 passed in 0.04 seconds

Over




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值