Search code examples
pythonpython-unittestmoto

Applying moto on a classmethod fails


Applying a moto mock to the test class as a whole will have no effect on classmethods like the python unittests setupClass method.

@mock_ssm
class SomeClassTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls) -> None:
        boto3.client("ssm").put_parameter(Name="some-name",
                                          Value="some-value")

will result in

botocore.exceptions.NoCredentialsError: Unable to locate credentials

Solution

  • One way to applying moto instances to the class as a whole including the classmethod, is to explicitly instantiate and terminate the moto service

    class SomeClassTest(unittest.TestCase):
    
        @classmethod
        def setUpClass(cls) -> None:
            cls.mock_ssm = mock_ssm()
            cls.mock_ssm.start()
            boto3.client("ssm").put_parameter(Name="some-name",
                                              Value="some-value")
        
        @classmethod
        def tearDownClass(cls) -> None:
            cls.mock_ssm.stop()