LoginSignup
4
7

More than 5 years have passed since last update.

parameterized使ってみた

Posted at

parameterized

Pythonのユニットテストの補助ライブラリー的なもの。
同じメソッドに対して違う値でテストしたいときに、わざわざ違うテストメソッドを書かなくてすむようにできる。

unittest、pytest、noseなどに対応している。
unittest、pytestで多少書き方が異なる。

自分はunittestしか使ったことないので、unittestのでの使い方。

install

pip install parameterized

usage

テスト対象のコード

ただの足し算。

def add(a, b):
    return a + b

テストコード

import unittest
from parameterized import parameterized


class TestAdd1(unittest.TestCase):

    @parameterized.expand([
        (2, 3, 5),
        (1, 1, 2),
        (3, -1, 2)
    ])

    def test_add(self, a, b, exp):
        self.assertEqual(add(a, b), exp)

a、b、expにそれぞれ、値がわたってくる。
キーワード引数に対応させたい場合は以下。param関数を使う。

import unittest
from parameterized import parameterized, param


class TestAdd2(unittest.TestCase):

    @parameterized.expand([
        param(2, -2),
        param(1, -1),
        param(3, -1, exp=2)
    ])

    def test_add(self, a, b, exp=0):
        self.assertEqual(add(a, b), exp)

4
7
0

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
4
7