Sai
Sai

Reputation: 689

pass mocked s3 connection to other methods

I wanted to mock the s3 connection once inside a particular method and pass it to other methods instead of using @mock_s3 on top of all methods and reduce repeated code. Any pointers on this would be helpful

class App_Test(unittest.TestCase):
@mock_s3
def get_s3_bucket(self):
    return boto3.resource('s3').create_bucket(Bucket=bucket_name)

def some_test(self):
    s3_bucket = get_s3_bucket()
    ....

def some_test_123(self):
    s3_bucket = get_s3_bucket()
    ....

Thanks in advance.

Upvotes: 0

Views: 438

Answers (1)

Tzane
Tzane

Reputation: 3472

If using pytest fixtures is an option, this something I like to do with AWS mocks when using moto:

@pytest.fixture
def mock_s3_bucket():
    with mock_s3():
        yield boto3.resource('s3').create_bucket(Bucket="test_bucket")

def test_1(mock_s3_bucket):
    ...

It creates a fresh bucket for each test and with ensures cleanup is done properly after each test.

Upvotes: 1

Related Questions