LoginSignup
1
1

More than 1 year has passed since last update.

Google Colaboratoryでテストメソッドを指定してunittestを実行する方法

Posted at

Google Colaboratory でテストメソッドを指定して unittest を実行する方法を調べたので書いておきます。

サンプルのテスト対象を作っておきます。テストクラスが2つ、テストメソッドは合計4つです。

サンプルのテスト対象
import unittest

def add(x, y):
  return x + y

class AddTest(unittest.TestCase):
  def test_add(self):
    self.assertEqual(add(1, 2), 3)

class TestStringMethods(unittest.TestCase):
  def test_upper(self):
    self.assertEqual('foo'.upper(), 'FOO')

  def test_isupper(self):
    self.assertTrue('FOO'.isupper())
    self.assertFalse('Foo'.isupper())

  def test_split(self):
    s = 'hello world'
    self.assertEqual(s.split(), ['hello', 'world'])
    # check that s.split fails when the separator is not a string
    with self.assertRaises(TypeError):
      s.split(2)

まず、全部のテストを実行するには、 unittest.main に下記のようなパラメーターをつけて実行します。

全部のテストを実行
unittest.main(argv=[''], verbosity=2, exit=False)
実行結果
test_add (__main__.AddTest) ... ok
test_isupper (__main__.TestStringMethods) ... ok
test_split (__main__.TestStringMethods) ... ok
test_upper (__main__.TestStringMethods) ... ok

----------------------------------------------------------------------
Ran 4 tests in 0.018s

OK

テストクラスを指定して実行するには、 unittest.mainargv の2番目以降にクラス名を書きます。( argv の1番目の値は使われないようです。)

指定したテストクラスを実行
unittest.main(argv=['', 'TestStringMethods'], verbosity=2, exit=False)
実行結果
test_isupper (__main__.TestStringMethods) ... ok
test_split (__main__.TestStringMethods) ... ok
test_upper (__main__.TestStringMethods) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.007s

OK

指定したテストメソッドを実行
unittest.main のargvの2番目以降にクラス名.メソッド名を書く

指定したテストメソッドを実行
unittest.main(argv=['', 'TestStringMethods.test_upper', 'TestStringMethods.test_split'], verbosity=2, exit=False)
実行結果
test_upper (__main__.TestStringMethods) ... ok
test_split (__main__.TestStringMethods) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.010s

OK

Google Colaboratory で動くものも貼っておきます。

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