Using moto and freezegun to test old AWS IAM User Access Keys

ยท

1 min read

Recently I had to develop a lambda that deletes Access Keys from AWS IAM Users that are past a certain age. To test this I had to create Access Keys that have a create date in the past, however, an access key that is created with boto3's create_access_key() method has the current date.

So I had to do some time traveling, luckily FreezeGun allows me to do exactly that.

Simply install the freezegun module: pip install freezegun and import it in your test: from freezegun import freeze_time. Now you can use the @freeze_time decorator to travel in time!

An example:

@freeze_time("2012-01-14")
def test():
    assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)

For my tests I needed multiple access keys with different create dates.

I've created a test fixture for that:

@pytest.fixture
def test_users(iam_client):
  today = datetime.date.today()

  with freeze_time(today - datetime.timedelta(days=20)):
    iam_client.create_user(
      UserName='20days',
    )
    iam_client.create_access_key(
      UserName='20days'
    )

  with freeze_time(today - datetime.timedelta(days=70)):
    iam_client.create_user(
      UserName='70days',
    )
    iam_client.create_access_key(
      UserName='70days'
    )

  with freeze_time(today - datetime.timedelta(days=100)):
    iam_client.create_user(
      UserName='100days',
    )
    iam_client.create_access_key(
      UserName='100days'
    )

  yield

As you can see I first set the current date. Then I use the timedelta() method to subtract some days from today, resulting in three IAM Users with an Access Key that is 20, 70 and 100 days old.

ย