LoginSignup
11
4
お題は不問!Qiita Engineer Festa 2023で記事投稿!

【Python】Pytestで3種類のテストをやってみる

Last updated at Posted at 2023-07-12

初めに

私は最近QA分野にはまっており、QAエンジニア資格であるJSTQBのシラバスを読んでいます。

シラバス31ページ2.2 テストレベルにはテストの種類が書いてあります。

今回はその3種類のテストをPytestでやってみます。

テスト対象はFizzBuzz

テストする都合上、Fizz&Buzzの判定を関数化しています。

def IsFizz(num: int)-> bool:
    return num % 3 == 0

def IsBuzz(num: int)-> bool:
    return num % 5 == 0

def main():
    for i in range(10, 16):
        if IsFizz(i) and IsBuzz(i):
            print("FizzBuzz")
        elif IsFizz(i):
            print("Fizz")
        elif IsBuzz(i):
            print("Buzz")
        else:
            print(i)

if __name__ == "__main__":
    main()

テストしてみる

コンポーネントテスト

コンポーネントテストは部品単位に焦点を当てたテストです。

別名「単位テスト」とも呼ばれます。

今回であればIsFizz関数IsBuzz関数がテスト対象になります。

また main関数 はシステム全体の統括を担っているためコンポーネントテスト対象外になります。

テスト内容

IsFizz関数IsBuzz関数 が正常に判定ができるかテストします。

class TestComponent:
    """コンポーネントテスト"""
    
    def test_IsFizz(self):
        assert main.IsFizz(3)

    def test_IsBuzz(self):
        assert main.IsBuzz(5)

統合テスト

統合テストはコンポーネントやシステム間に焦点を当てたテストです。

今回はFizzBuzzとなる数字を判定するため、IsFizz関数IsBuzz関数 を組み合わせがテスト対象になります。

テスト内容

FizzBuzzとなる数字をIsFizz関数IsBuzz関数 に渡してFizzBuzzとなるかテストします。

class TestIntegration:
    """コンポーネントテスト"""
    
    def test_FizzBuzz(self):
        num = 15
        assert main.IsFizz(num) and main.IsBuzz(num)

システムテスト

システムテストはシステム全体の振る舞いに焦点を当てたテストです。

今回はシステム全体を統括しているmain関数をテストします。

テスト内容

main関数は10~15の数字にFizzBuzz判定を行ってその結果をprintしています。

そのためprintされた結果をテストします。

class TestSystem:
    """システムテスト"""
    
    def test_main(self, capfd):
        main.main()
        out, err = capfd.readouterr()
        assert out == 'Buzz\n11\nFizz\n13\n14\nFizzBuzz\n'
        assert err is ''

テストコード全体

import main

class TestComponent:
    """コンポーネントテスト"""
    
    def test_IsFizz(self):
        assert main.IsFizz(3)

    def test_IsBuzz(self):
        assert main.IsBuzz(5)

class TestIntegration:
    """コンポーネントテスト"""
    
    def test_FizzBuzz(self):
        num = 15
        assert main.IsFizz(num) and main.IsBuzz(num)

class TestSystem:
    """システムテスト"""
    
    def test_main(self, capfd):
        main.main()
        out, err = capfd.readouterr()
        assert out == 'Buzz\n11\nFizz\n13\n14\nFizzBuzz\n'
        assert err is ''

参考にしたJSTQBのシラバス

11
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
4