Python言語の異常処理とテスト

2410 ワード

目次
  • (一)異常処理
  • (二)テスト
  • (一)異常処理


    1.すべての例外の取得
    try:
        x = 5 / 0
    except:
        print(' ')

    2.特定の例外の取得
    try:
        x = 5 / 0
    except ZeroDivisionError as e:
        print(' 0',e)
    except:
        print(' ')
    else:
        print(' ')
    finally:
        print(' ')

    3.手動放出異常
    def method():
        raise NotImplementedError(' ')

    (二)テスト


    Pythonに付属のunittestモジュールを使用する
    example 1:関数をテストする
    import unittest
    from example import get_formatted_name
    
    
    class NameTestCase(unittest.TestCase):
        def test_title_name(self):
            formatted_name = get_formatted_name('tom','lee')
            self.assertEqual(formatted_name,'Tom Lee')
    
    
    if __name__ == '__main__':
        unittest.main()

    example 2:クラスをテストする
    class Coder:
        def __init__(self,name):
            self.name = name
            self.skills = []
    
        def mastering_skill(self,skill):
            self.skills.append(skill)
    
        def show_skills(self):
            print(' :')
            for skill in self.skills:
                print('-',skill)
    import unittest
    from coder import Coder
    
    
    class CoderTestCase(unittest.TestCase):
        def setUp(self):
            self.c = Coder('Tom')
            self.c.mastering_skill('Python')
            self.c.mastering_skill('Java')
            
        def test_skill_in(self):
            self.assertIn("Python",self.c.skills)
            
        def tearDown(self):
            print(' ')
    
    
    if __name__ == '__main__':
        unittest.main()

    一般的なアサーション方法:
    import unittest
    
    person ={'name':'Tom','age':30}
    numbers = [1,23,3,4,4,54]
    s = 'hello world python'
    
    
    class TestAssert(unittest.TestCase):
        def test_assert_method(self):
            self.assertEqual('Tom',person.get('name'))
            self.assertTrue('hello' in s)
            self.assertIn('hello',s)
            #self.assertEqual(3.3,1.1+2.2)
            self.assertAlmostEqual(3.3,1.1+2.2)
            # 
            self.assertIs(True+1,2)
            self.assertIsNone(None)
            # 
            self.assertIsInstance(numbers[0],int)
            # 
            self.assertGreater(5,4)
    
    
    if __name__ == '__main__':
        unittest.main()