python - How to edit the attribute of an AWS resource mocked with moto for pytest test case? - Stack Overflow

I am trying to test an AWS Lambda code for deleting available volumes beyond a certain date. I am using

I am trying to test an AWS Lambda code for deleting available volumes beyond a certain date. I am using moto to mock AWS in pytest and the volume created has the creation timestamp set to the current day. How can I make the timestamp to be from, say, 30 days ago?

I have tried using unittest patch as below but it does not work and seems unable to alter the attribute.

@moto.mock_aws()
def test_delete_vol_only_after_expiry(setup):
  # Arrange

  # Create a mock EC2 client
  ec2 = boto3.client('ec2', region_name='us-east-1')
  
  # Create the volume
  volume = ec2.create_volume(
      AvailabilityZone='us-east-1a',
      Size=10,  # Size in GiB
      VolumeType='gp2'
  )
  # Calculate the date 30 days ago
  thirty_days_ago = datetime.now() - timedelta(days=30)
  
  # Access the volume to patch its creation date
  ec2_resource = boto3.resource('ec2', region_name='us-east-1')
  volume = ec2_resource.Volume(volume['VolumeId'])

  # Print the original creation date
  print(f'Original creation date: {volume.create_time}')
  
  # Patch the creation date of the volume
  with patch.object(volume, 'create_time', new=thirty_days_ago):
    print(f'Patched creation date: {volume.create_time}')

  event, context, ec2 = setup

  # Act
  utility.vol_cleanup_utility(event, context)

  # Assert
  response = ec2.describe_volumes()
  assert len(response['Volumes']) == 1

I am getting the following error on running the test.

 try:
>           setattr(self.target, self.attribute, new_attr)
E           AttributeError: can't set attribute 'create_time'

C:\Program Files\Python310\lib\unittest\mock.py:1546: AttributeError

Using monkeypatch gives the same error.

Now I am not sure if this approach is even correct and if patching the object will even update the AWS resource that moto creates in-memory. Or if I am using patching functionality completely wrong.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745042937a4607920.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信