Techdebt: Replace sure with regular assertions in IAM (#6573)

This commit is contained in:
Bert Blommers 2023-07-30 19:37:08 +00:00 committed by GitHub
parent 4263b99aa3
commit cd5beb021a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 843 additions and 839 deletions

File diff suppressed because it is too large Load Diff

View File

@ -20,6 +20,6 @@ def test_invoking_ec2_mark_access_key_as_used():
last_used = c_iam.get_access_key_last_used(
AccessKeyId=key["AccessKey"]["AccessKeyId"]
)["AccessKeyLastUsed"]
last_used.should.have.key("LastUsedDate")
last_used.should.have.key("ServiceName").equals("ec2")
last_used.should.have.key("Region").equals("us-east-2")
assert "LastUsedDate" in last_used
assert last_used["ServiceName"] == "ec2"
assert last_used["Region"] == "us-east-2"

View File

@ -1,5 +1,4 @@
import boto3
import sure # noqa # pylint: disable=unused-import
from moto import mock_iam
@ -9,12 +8,12 @@ def test_account_aliases():
alias = "my-account-name"
aliases = client.list_account_aliases()
aliases.should.have.key("AccountAliases").which.should.equal([])
assert aliases["AccountAliases"] == []
client.create_account_alias(AccountAlias=alias)
aliases = client.list_account_aliases()
aliases.should.have.key("AccountAliases").which.should.equal([alias])
assert aliases["AccountAliases"] == [alias]
client.delete_account_alias(AccountAlias=alias)
aliases = client.list_account_aliases()
aliases.should.have.key("AccountAliases").which.should.equal([])
assert aliases["AccountAliases"] == []

View File

@ -1,7 +1,6 @@
import boto3
import json
import yaml
import sure # noqa # pylint: disable=unused-import
import pytest
from botocore.exceptions import ClientError
@ -87,8 +86,8 @@ Resources:
provisioned_resource = cf_client.list_stack_resources(StackName=stack_name)[
"StackResourceSummaries"
][0]
provisioned_resource["LogicalResourceId"].should.equal("TheUser")
provisioned_resource["PhysicalResourceId"].should.equal(user_name)
assert provisioned_resource["LogicalResourceId"] == "TheUser"
assert provisioned_resource["PhysicalResourceId"] == user_name
@mock_iam
@ -112,7 +111,7 @@ Resources:
iam_client = boto3.client("iam", region_name="us-east-1")
user = iam_client.get_user(UserName=user_name)["User"]
user["Path"].should.equal("/")
assert user["Path"] == "/"
path = "/MyPath/"
template = """
@ -128,7 +127,7 @@ Resources:
cf_client.update_stack(StackName=stack_name, TemplateBody=template)
user = iam_client.get_user(UserName=user_name)["User"]
user["Path"].should.equal(path)
assert user["Path"] == path
@mock_iam
@ -152,7 +151,7 @@ Resources:
iam_client = boto3.client("iam", region_name="us-east-1")
user = iam_client.get_user(UserName=original_user_name)["User"]
user["Path"].should.equal("/")
assert user["Path"] == "/"
new_user_name = "MyUser"
template = """
@ -169,7 +168,7 @@ Resources:
with pytest.raises(ClientError) as e:
iam_client.get_user(UserName=original_user_name)
e.value.response["Error"]["Code"].should.equal("NoSuchEntity")
assert e.value.response["Error"]["Code"] == "NoSuchEntity"
iam_client.get_user(UserName=new_user_name)
@ -222,18 +221,18 @@ Resources:
provisioned_resources = cf_client.list_stack_resources(StackName=stack_name)[
"StackResourceSummaries"
]
len(provisioned_resources).should.equal(1)
assert len(provisioned_resources) == 1
second_provisioned_user = [
resource
for resource in provisioned_resources
if resource["LogicalResourceId"] == "TheSecondUser"
][0]
second_user_name.should.equal(second_provisioned_user["PhysicalResourceId"])
assert second_user_name == second_provisioned_user["PhysicalResourceId"]
iam_client.get_user(UserName=second_user_name)
with pytest.raises(ClientError) as e:
iam_client.get_user(UserName=first_user_name)
e.value.response["Error"]["Code"].should.equal("NoSuchEntity")
assert e.value.response["Error"]["Code"] == "NoSuchEntity"
@mock_iam
@ -263,7 +262,7 @@ Resources:
with pytest.raises(ClientError) as e:
iam_client.get_user(UserName=user_name)
e.value.response["Error"]["Code"].should.equal("NoSuchEntity")
assert e.value.response["Error"]["Code"] == "NoSuchEntity"
@mock_iam
@ -283,7 +282,7 @@ Resources:
provisioned_resource = cf_client.list_stack_resources(StackName=stack_name)[
"StackResourceSummaries"
][0]
provisioned_resource["LogicalResourceId"].should.equal("TheUser")
assert provisioned_resource["LogicalResourceId"] == "TheUser"
user_name = provisioned_resource["PhysicalResourceId"]
iam_client = boto3.client("iam", region_name="us-east-1")
@ -293,7 +292,7 @@ Resources:
with pytest.raises(ClientError) as e:
iam_client.get_user(UserName=user_name)
e.value.response["Error"]["Code"].should.equal("NoSuchEntity")
assert e.value.response["Error"]["Code"] == "NoSuchEntity"
@mock_iam
@ -334,7 +333,7 @@ Outputs:
iam_client = boto3.client("iam", region_name="us-east-1")
user_description = iam_client.get_user(UserName=output_user_name)["User"]
output_user_arn.should.equal(user_description["Arn"])
assert output_user_arn == user_description["Arn"]
# AWS::IAM::ManagedPolicy Tests
@ -364,24 +363,22 @@ Resources:
"StackResourceSummaries"
][0]
logical_resource_id = provisioned_resource["LogicalResourceId"]
logical_resource_id.should.equal("ThePolicy")
assert logical_resource_id == "ThePolicy"
policy_arn = provisioned_resource["PhysicalResourceId"]
policy_arn.should.match(
f"arn:aws:iam::{ACCOUNT_ID}:policy/MyStack-ThePolicy-[A-Z0-9]+"
)
assert policy_arn.startswith(f"arn:aws:iam::{ACCOUNT_ID}:policy/MyStack-ThePolicy-")
expected_name = policy_arn.split("/")[1]
response = iam_client.list_entities_for_policy(PolicyArn=policy_arn)
response.should.have.key("PolicyGroups").equal([])
response.should.have.key("PolicyUsers").equal([])
response.should.have.key("PolicyRoles").equal([])
assert response["PolicyGroups"] == []
assert response["PolicyUsers"] == []
assert response["PolicyRoles"] == []
policy = iam_client.get_policy(PolicyArn=policy_arn)["Policy"]
policy.should.have.key("Arn").equal(policy_arn)
policy.should.have.key("PolicyName").equal(expected_name)
policy.should.have.key("Description").equal("")
policy.should.have.key("Path").equal("/")
assert policy["Arn"] == policy_arn
assert policy["PolicyName"] == expected_name
assert policy["Description"] == ""
assert policy["Path"] == "/"
@mock_iam
@ -417,16 +414,16 @@ Resources:
"StackResourceSummaries"
][0]
logical_resource_id = provisioned_resource["LogicalResourceId"]
logical_resource_id.should.equal("ThePolicy")
assert logical_resource_id == "ThePolicy"
policy_arn = provisioned_resource["PhysicalResourceId"]
policy_arn.should.equal(f"arn:aws:iam::{ACCOUNT_ID}:policy/{name}")
assert policy_arn == f"arn:aws:iam::{ACCOUNT_ID}:policy/{name}"
policy = iam_client.get_policy(PolicyArn=policy_arn)["Policy"]
policy.should.have.key("Arn").equal(policy_arn)
policy.should.have.key("Path").equal("/")
policy.should.have.key("Description").equal(desc)
policy.should.have.key("PolicyName").equal(name)
assert policy["Arn"] == policy_arn
assert policy["Path"] == "/"
assert policy["Description"] == desc
assert policy["PolicyName"] == name
@mock_iam
@ -465,19 +462,17 @@ Resources:
"StackResourceSummaries"
][0]
logical_resource_id = provisioned_resource["LogicalResourceId"]
logical_resource_id.should.equal("ThePolicy")
assert logical_resource_id == "ThePolicy"
policy_arn = provisioned_resource["PhysicalResourceId"]
policy_arn.should.match(
f"rn:aws:iam::{ACCOUNT_ID}:policy/MyStack-ThePolicy-[A-Z0-9]+"
)
assert policy_arn.startswith(f"arn:aws:iam::{ACCOUNT_ID}:policy/MyStack-ThePolicy-")
response = iam_client.list_entities_for_policy(PolicyArn=policy_arn)
response.should.have.key("PolicyUsers").equal([])
response.should.have.key("PolicyRoles").equal([])
assert response["PolicyUsers"] == []
assert response["PolicyRoles"] == []
response["PolicyGroups"][0]["GroupName"].should.be.equal(group_name)
response["PolicyGroups"][0].should.have.key("GroupId")
assert response["PolicyGroups"][0]["GroupName"] == group_name
assert "GroupId" in response["PolicyGroups"][0]
@mock_iam
@ -516,19 +511,17 @@ Resources:
"StackResourceSummaries"
][0]
logical_resource_id = provisioned_resource["LogicalResourceId"]
logical_resource_id.should.equal("ThePolicy")
assert logical_resource_id == "ThePolicy"
policy_arn = provisioned_resource["PhysicalResourceId"]
policy_arn.should.match(
f"rn:aws:iam::{ACCOUNT_ID}:policy/MyStack-ThePolicy-[A-Z0-9]+"
)
assert policy_arn.startswith(f"arn:aws:iam::{ACCOUNT_ID}:policy/MyStack-ThePolicy-")
response = iam_client.list_entities_for_policy(PolicyArn=policy_arn)
response.should.have.key("PolicyGroups").equal([])
response.should.have.key("PolicyRoles").equal([])
assert response["PolicyGroups"] == []
assert response["PolicyRoles"] == []
response["PolicyUsers"][0]["UserName"].should.be.equal(user_name)
response["PolicyUsers"][0].should.have.key("UserId")
assert response["PolicyUsers"][0]["UserName"] == user_name
assert "UserId" in response["PolicyUsers"][0]
@mock_iam
@ -567,19 +560,17 @@ Resources:
"StackResourceSummaries"
][0]
logical_resource_id = provisioned_resource["LogicalResourceId"]
logical_resource_id.should.equal("ThePolicy")
assert logical_resource_id == "ThePolicy"
policy_arn = provisioned_resource["PhysicalResourceId"]
policy_arn.should.match(
f"rn:aws:iam::{ACCOUNT_ID}:policy/MyStack-ThePolicy-[A-Z0-9]+"
)
assert policy_arn.startswith(f"arn:aws:iam::{ACCOUNT_ID}:policy/MyStack-ThePolicy-")
response = iam_client.list_entities_for_policy(PolicyArn=policy_arn)
response.should.have.key("PolicyGroups").equal([])
response.should.have.key("PolicyUsers").equal([])
assert response["PolicyGroups"] == []
assert response["PolicyUsers"] == []
response["PolicyRoles"][0]["RoleName"].should.be.equal(role_name)
response["PolicyRoles"][0].should.have.key("RoleId")
assert response["PolicyRoles"][0]["RoleName"] == role_name
assert "RoleId" in response["PolicyRoles"][0]
# AWS::IAM::Policy Tests
@ -624,13 +615,13 @@ Resources:
"StackResourceSummaries"
][0]
logical_resource_id = provisioned_resource["LogicalResourceId"]
logical_resource_id.should.equal("ThePolicy")
assert logical_resource_id == "ThePolicy"
original_policy_document = yaml.load(template, Loader=yaml.FullLoader)["Resources"][
logical_resource_id
]["Properties"]["PolicyDocument"]
policy = iam_client.get_user_policy(UserName=user_name, PolicyName=policy_name)
policy["PolicyDocument"].should.equal(original_policy_document)
assert policy["PolicyDocument"] == original_policy_document
@mock_s3
@ -676,13 +667,13 @@ Resources:
"StackResourceSummaries"
][0]
logical_resource_id = provisioned_resource["LogicalResourceId"]
logical_resource_id.should.equal("ThePolicy")
assert logical_resource_id == "ThePolicy"
original_policy_document = yaml.load(template, Loader=yaml.FullLoader)["Resources"][
logical_resource_id
]["Properties"]["PolicyDocument"]
policy = iam_client.get_user_policy(UserName=user_name_1, PolicyName=policy_name)
policy["PolicyDocument"].should.equal(original_policy_document)
assert policy["PolicyDocument"] == original_policy_document
# Change template and user
template = """
@ -709,17 +700,16 @@ Resources:
"StackResourceSummaries"
][0]
logical_resource_id = provisioned_resource["LogicalResourceId"]
logical_resource_id.should.equal("ThePolicy")
assert logical_resource_id == "ThePolicy"
original_policy_document = yaml.load(template, Loader=yaml.FullLoader)["Resources"][
logical_resource_id
]["Properties"]["PolicyDocument"]
policy = iam_client.get_user_policy(UserName=user_name_2, PolicyName=policy_name)
policy["PolicyDocument"].should.equal(original_policy_document)
assert policy["PolicyDocument"] == original_policy_document
iam_client.get_user_policy.when.called_with(
UserName=user_name_1, PolicyName=policy_name
).should.throw(iam_client.exceptions.NoSuchEntityException)
with pytest.raises(ClientError):
iam_client.get_user_policy(UserName=user_name_1, PolicyName=policy_name)
@mock_s3
@ -763,18 +753,17 @@ Resources:
"StackResourceSummaries"
][0]
logical_resource_id = provisioned_resource["LogicalResourceId"]
logical_resource_id.should.equal("ThePolicy")
assert logical_resource_id == "ThePolicy"
original_policy_document = yaml.load(template, Loader=yaml.FullLoader)["Resources"][
logical_resource_id
]["Properties"]["PolicyDocument"]
policy = iam_client.get_user_policy(UserName=user_name, PolicyName=policy_name)
policy["PolicyDocument"].should.equal(original_policy_document)
assert policy["PolicyDocument"] == original_policy_document
cf_client.delete_stack(StackName=stack_name)
iam_client.get_user_policy.when.called_with(
UserName=user_name, PolicyName=policy_name
).should.throw(iam_client.exceptions.NoSuchEntityException)
with pytest.raises(ClientError):
iam_client.get_user_policy(UserName=user_name, PolicyName=policy_name)
@mock_s3
@ -818,13 +807,13 @@ Resources:
"StackResourceSummaries"
][0]
logical_resource_id = provisioned_resource["LogicalResourceId"]
logical_resource_id.should.equal("ThePolicy")
assert logical_resource_id == "ThePolicy"
original_policy_document = yaml.load(template, Loader=yaml.FullLoader)["Resources"][
logical_resource_id
]["Properties"]["PolicyDocument"]
policy = iam_client.get_role_policy(RoleName=role_name, PolicyName=policy_name)
policy["PolicyDocument"].should.equal(original_policy_document)
assert policy["PolicyDocument"] == original_policy_document
@mock_s3
@ -870,13 +859,13 @@ Resources:
"StackResourceSummaries"
][0]
logical_resource_id = provisioned_resource["LogicalResourceId"]
logical_resource_id.should.equal("ThePolicy")
assert logical_resource_id == "ThePolicy"
original_policy_document = yaml.load(template, Loader=yaml.FullLoader)["Resources"][
logical_resource_id
]["Properties"]["PolicyDocument"]
policy = iam_client.get_role_policy(RoleName=role_name_1, PolicyName=policy_name)
policy["PolicyDocument"].should.equal(original_policy_document)
assert policy["PolicyDocument"] == original_policy_document
# Change template and user
template = """
@ -903,17 +892,16 @@ Resources:
"StackResourceSummaries"
][0]
logical_resource_id = provisioned_resource["LogicalResourceId"]
logical_resource_id.should.equal("ThePolicy")
assert logical_resource_id == "ThePolicy"
original_policy_document = yaml.load(template, Loader=yaml.FullLoader)["Resources"][
logical_resource_id
]["Properties"]["PolicyDocument"]
policy = iam_client.get_role_policy(RoleName=role_name_2, PolicyName=policy_name)
policy["PolicyDocument"].should.equal(original_policy_document)
assert policy["PolicyDocument"] == original_policy_document
iam_client.get_role_policy.when.called_with(
RoleName=role_name_1, PolicyName=policy_name
).should.throw(iam_client.exceptions.NoSuchEntityException)
with pytest.raises(ClientError):
iam_client.get_role_policy(RoleName=role_name_1, PolicyName=policy_name)
@mock_s3
@ -957,18 +945,18 @@ Resources:
"StackResourceSummaries"
][0]
logical_resource_id = provisioned_resource["LogicalResourceId"]
logical_resource_id.should.equal("ThePolicy")
assert logical_resource_id == "ThePolicy"
original_policy_document = yaml.load(template, Loader=yaml.FullLoader)["Resources"][
logical_resource_id
]["Properties"]["PolicyDocument"]
policy = iam_client.get_role_policy(RoleName=role_name, PolicyName=policy_name)
policy["PolicyDocument"].should.equal(original_policy_document)
assert policy["PolicyDocument"] == original_policy_document
cf_client.delete_stack(StackName=stack_name)
iam_client.get_role_policy.when.called_with(
RoleName=role_name, PolicyName=policy_name
).should.throw(iam_client.exceptions.NoSuchEntityException)
with pytest.raises(ClientError) as exc:
iam_client.get_role_policy(RoleName=role_name, PolicyName=policy_name)
assert exc.value.response["Error"]["Code"] == "NoSuchEntity"
@mock_s3
@ -1012,13 +1000,13 @@ Resources:
"StackResourceSummaries"
][0]
logical_resource_id = provisioned_resource["LogicalResourceId"]
logical_resource_id.should.equal("ThePolicy")
assert logical_resource_id == "ThePolicy"
original_policy_document = yaml.load(template, Loader=yaml.FullLoader)["Resources"][
logical_resource_id
]["Properties"]["PolicyDocument"]
policy = iam_client.get_group_policy(GroupName=group_name, PolicyName=policy_name)
policy["PolicyDocument"].should.equal(original_policy_document)
assert policy["PolicyDocument"] == original_policy_document
@mock_s3
@ -1064,13 +1052,13 @@ Resources:
"StackResourceSummaries"
][0]
logical_resource_id = provisioned_resource["LogicalResourceId"]
logical_resource_id.should.equal("ThePolicy")
assert logical_resource_id == "ThePolicy"
original_policy_document = yaml.load(template, Loader=yaml.FullLoader)["Resources"][
logical_resource_id
]["Properties"]["PolicyDocument"]
policy = iam_client.get_group_policy(GroupName=group_name_1, PolicyName=policy_name)
policy["PolicyDocument"].should.equal(original_policy_document)
assert policy["PolicyDocument"] == original_policy_document
# Change template and user
template = """
@ -1097,17 +1085,17 @@ Resources:
"StackResourceSummaries"
][0]
logical_resource_id = provisioned_resource["LogicalResourceId"]
logical_resource_id.should.equal("ThePolicy")
assert logical_resource_id == "ThePolicy"
original_policy_document = yaml.load(template, Loader=yaml.FullLoader)["Resources"][
logical_resource_id
]["Properties"]["PolicyDocument"]
policy = iam_client.get_group_policy(GroupName=group_name_2, PolicyName=policy_name)
policy["PolicyDocument"].should.equal(original_policy_document)
assert policy["PolicyDocument"] == original_policy_document
iam_client.get_group_policy.when.called_with(
GroupName=group_name_1, PolicyName=policy_name
).should.throw(iam_client.exceptions.NoSuchEntityException)
with pytest.raises(ClientError) as exc:
iam_client.get_group_policy(GroupName=group_name_1, PolicyName=policy_name)
assert exc.value.response["Error"]["Code"] == "NoSuchEntity"
@mock_s3
@ -1151,18 +1139,18 @@ Resources:
"StackResourceSummaries"
][0]
logical_resource_id = provisioned_resource["LogicalResourceId"]
logical_resource_id.should.equal("ThePolicy")
assert logical_resource_id == "ThePolicy"
original_policy_document = yaml.load(template, Loader=yaml.FullLoader)["Resources"][
logical_resource_id
]["Properties"]["PolicyDocument"]
policy = iam_client.get_group_policy(GroupName=group_name, PolicyName=policy_name)
policy["PolicyDocument"].should.equal(original_policy_document)
assert policy["PolicyDocument"] == original_policy_document
cf_client.delete_stack(StackName=stack_name)
iam_client.get_group_policy.when.called_with(
GroupName=group_name, PolicyName=policy_name
).should.throw(iam_client.exceptions.NoSuchEntityException)
with pytest.raises(ClientError) as exc:
iam_client.get_group_policy(GroupName=group_name, PolicyName=policy_name)
assert exc.value.response["Error"]["Code"] == "NoSuchEntity"
# AWS::IAM::User AccessKeys
@ -1201,13 +1189,13 @@ Resources:
for resource in provisioned_resources
if resource["LogicalResourceId"] == "TheAccessKey"
]
len(provisioned_access_keys).should.equal(1)
assert len(provisioned_access_keys) == 1
iam_client = boto3.client("iam", region_name="us-east-1")
user = iam_client.get_user(UserName=user_name)["User"]
user["UserName"].should.equal(user_name)
assert user["UserName"] == user_name
access_keys = iam_client.list_access_keys(UserName=user_name)
access_keys["AccessKeyMetadata"][0]["UserName"].should.equal(user_name)
assert access_keys["AccessKeyMetadata"][0]["UserName"] == user_name
@mock_sts
@ -1264,7 +1252,7 @@ Outputs:
region_name="us-east-1",
)
caller_identity = sts_client.get_caller_identity()
caller_identity["Arn"].split("/")[1].should.equal(user_name)
assert caller_identity["Arn"].split("/")[1] == user_name
pass
@ -1303,25 +1291,26 @@ def test_iam_cloudformation_delete_users_access_key():
for resource in provisioned_resources
if resource["LogicalResourceId"] == "TheAccessKey"
]
provisioned_access_keys.should.have.length_of(1)
assert len(provisioned_access_keys) == 1
access_key_id = provisioned_access_keys[0]["PhysicalResourceId"]
iam_client = boto3.client("iam", region_name="us-east-1")
user = iam_client.get_user(UserName=user_name)["User"]
user["UserName"].should.equal(user_name)
assert user["UserName"] == user_name
access_keys = iam_client.list_access_keys(UserName=user_name)
access_keys["AccessKeyMetadata"][0]["AccessKeyId"].should.equal(access_key_id)
access_keys["AccessKeyMetadata"][0]["UserName"].should.equal(user_name)
access_key_id.should.equal(access_keys["AccessKeyMetadata"][0]["AccessKeyId"])
assert access_keys["AccessKeyMetadata"][0]["AccessKeyId"] == access_key_id
assert access_keys["AccessKeyMetadata"][0]["UserName"] == user_name
assert access_key_id == access_keys["AccessKeyMetadata"][0]["AccessKeyId"]
cf_client.delete_stack(StackName=stack_name)
iam_client.get_user.when.called_with(UserName=user_name).should.throw(
iam_client.exceptions.NoSuchEntityException
)
iam_client.list_access_keys.when.called_with(UserName=user_name).should.throw(
iam_client.exceptions.NoSuchEntityException
)
with pytest.raises(ClientError) as exc:
iam_client.get_user(UserName=user_name)
assert exc.value.response["Error"]["Code"] == "NoSuchEntity"
with pytest.raises(ClientError) as exc:
iam_client.list_access_keys(UserName=user_name)
assert exc.value.response["Error"]["Code"] == "NoSuchEntity"
@mock_iam
@ -1364,7 +1353,7 @@ Resources:
iam_client = boto3.client("iam", region_name="us-east-1")
iam_client.get_user(UserName=user_name)
access_keys = iam_client.list_access_keys(UserName=user_name)
access_key_id.should.equal(access_keys["AccessKeyMetadata"][0]["AccessKeyId"])
assert access_key_id == access_keys["AccessKeyMetadata"][0]["AccessKeyId"]
template = """
Resources:
@ -1378,7 +1367,7 @@ Resources:
cf_client.update_stack(StackName=stack_name, TemplateBody=template)
access_keys = iam_client.list_access_keys(UserName=user_name)
access_keys["AccessKeyMetadata"][0]["Status"].should.equal("Inactive")
assert access_keys["AccessKeyMetadata"][0]["Status"] == "Inactive"
@mock_iam
@ -1421,7 +1410,7 @@ Resources:
iam_client = boto3.client("iam", region_name="us-east-1")
iam_client.get_user(UserName=user_name)
access_keys = iam_client.list_access_keys(UserName=user_name)
access_key_id.should.equal(access_keys["AccessKeyMetadata"][0]["AccessKeyId"])
assert access_key_id == access_keys["AccessKeyMetadata"][0]["AccessKeyId"]
other_user_name = "MyUser"
iam_client.create_user(UserName=other_user_name)
@ -1441,10 +1430,10 @@ Resources:
cf_client.update_stack(StackName=stack_name, TemplateBody=template)
access_keys = iam_client.list_access_keys(UserName=user_name)
len(access_keys["AccessKeyMetadata"]).should.equal(0)
assert len(access_keys["AccessKeyMetadata"]) == 0
access_keys = iam_client.list_access_keys(UserName=other_user_name)
access_key_id.should_not.equal(access_keys["AccessKeyMetadata"][0]["AccessKeyId"])
assert access_key_id != access_keys["AccessKeyMetadata"][0]["AccessKeyId"]
@mock_iam
@ -1461,14 +1450,14 @@ def test_iam_cloudformation_create_role():
"StackResourceSummaries"
]
role = [res for res in resources if res["ResourceType"] == "AWS::IAM::Role"][0]
role["LogicalResourceId"].should.equal("RootRole")
assert role["LogicalResourceId"] == "RootRole"
iam_client = boto3.client("iam", region_name="us-east-1")
iam_client.list_roles()["Roles"].should.have.length_of(1)
assert len(iam_client.list_roles()["Roles"]) == 1
cf_client.delete_stack(StackName=stack_name)
iam_client.list_roles()["Roles"].should.have.length_of(0)
assert len(iam_client.list_roles()["Roles"]) == 0
@mock_iam
@ -1486,23 +1475,23 @@ def test_iam_cloudformation_create_role_and_instance_profile():
"StackResourceSummaries"
]
role = [res for res in resources if res["ResourceType"] == "AWS::IAM::Role"][0]
role["LogicalResourceId"].should.equal("RootRole")
role["PhysicalResourceId"].should.equal(role_name)
assert role["LogicalResourceId"] == "RootRole"
assert role["PhysicalResourceId"] == role_name
profile = [
res for res in resources if res["ResourceType"] == "AWS::IAM::InstanceProfile"
][0]
profile["LogicalResourceId"].should.equal("RootInstanceProfile")
profile["PhysicalResourceId"].should.contain(
stack_name
assert profile["LogicalResourceId"] == "RootInstanceProfile"
assert (
stack_name in profile["PhysicalResourceId"]
) # e.g. MyStack-RootInstanceProfile-73Y4H4ALFW3N
profile["PhysicalResourceId"].should.contain("RootInstanceProfile")
assert "RootInstanceProfile" in profile["PhysicalResourceId"]
iam_client = boto3.client("iam", region_name="us-east-1")
iam_client.list_roles()["Roles"].should.have.length_of(1)
assert len(iam_client.list_roles()["Roles"]) == 1
cf_client.delete_stack(StackName=stack_name)
iam_client.list_roles()["Roles"].should.have.length_of(0)
assert len(iam_client.list_roles()["Roles"]) == 0
@mock_autoscaling
@ -1611,14 +1600,14 @@ def test_iam_roles():
# Role name is not specified, so randomly generated - can't check exact name
if "with-path" in role["RoleName"]:
role_name_to_id["with-path"] = role["RoleId"]
role["Path"].should.equal("/my-path/")
assert role["Path"] == "/my-path/"
else:
role_name_to_id["no-path"] = role["RoleId"]
role["RoleName"].should.equal("my-role-no-path-name")
role["Path"].should.equal("/")
assert role["RoleName"] == "my-role-no-path-name"
assert role["Path"] == "/"
instance_profile_responses = iam.list_instance_profiles()["InstanceProfiles"]
instance_profile_responses.should.have.length_of(2)
assert len(instance_profile_responses) == 2
instance_profile_names = []
for instance_profile_response in instance_profile_responses:
@ -1626,26 +1615,22 @@ def test_iam_roles():
InstanceProfileName=instance_profile_response["InstanceProfileName"]
)["InstanceProfile"]
instance_profile_names.append(instance_profile["InstanceProfileName"])
instance_profile["InstanceProfileName"].should.contain("my-instance-profile")
assert "my-instance-profile" in instance_profile["InstanceProfileName"]
if "with-path" in instance_profile["InstanceProfileName"]:
instance_profile["Path"].should.equal("my-path")
instance_profile["Roles"][0]["RoleId"].should.equal(
role_name_to_id["with-path"]
assert instance_profile["Path"] == "my-path"
assert (
instance_profile["Roles"][0]["RoleId"] == role_name_to_id["with-path"]
)
else:
instance_profile["InstanceProfileName"].should.contain("no-path")
instance_profile["Roles"][0]["RoleId"].should.equal(
role_name_to_id["no-path"]
)
instance_profile["Path"].should.equal("/")
assert "no-path" in instance_profile["InstanceProfileName"]
assert instance_profile["Roles"][0]["RoleId"] == role_name_to_id["no-path"]
assert instance_profile["Path"] == "/"
autoscale = boto3.client("autoscaling", region_name="us-west-1")
launch_config = autoscale.describe_launch_configurations()["LaunchConfigurations"][
0
]
launch_config.should.have.key("IamInstanceProfile").should.contain(
"my-instance-profile-with-path"
)
assert "my-instance-profile-with-path" in launch_config["IamInstanceProfile"]
resources = cf.list_stack_resources(StackName="test_stack")[
"StackResourceSummaries"
@ -1655,8 +1640,8 @@ def test_iam_roles():
for resource in resources
if resource["ResourceType"] == "AWS::IAM::InstanceProfile"
]
{ip["PhysicalResourceId"] for ip in instance_profile_resources}.should.equal(
set(instance_profile_names)
assert {ip["PhysicalResourceId"] for ip in instance_profile_resources} == set(
instance_profile_names
)
role_resources = [
@ -1664,4 +1649,4 @@ def test_iam_roles():
for resource in resources
if resource["ResourceType"] == "AWS::IAM::Role"
]
{r["PhysicalResourceId"] for r in role_resources}.should.equal(set(role_names))
assert {r["PhysicalResourceId"] for r in role_resources} == set(role_names)

View File

@ -1,7 +1,6 @@
from datetime import datetime
import boto3
import sure # noqa # pylint: disable=unused-import
import json
import pytest
@ -32,28 +31,28 @@ def test_create_group():
with pytest.raises(ClientError) as ex:
conn.create_group(GroupName="my-group")
err = ex.value.response["Error"]
err["Code"].should.equal("Group my-group already exists")
err["Message"].should.equal(None)
assert err["Code"] == "Group my-group already exists"
assert err["Message"] is None
@mock_iam
def test_get_group():
conn = boto3.client("iam", region_name="us-east-1")
created = conn.create_group(GroupName="my-group")["Group"]
created["Path"].should.equal("/")
created["GroupName"].should.equal("my-group")
created.should.have.key("GroupId")
created["Arn"].should.equal(f"arn:aws:iam::{ACCOUNT_ID}:group/my-group")
created["CreateDate"].should.be.a(datetime)
assert created["Path"] == "/"
assert created["GroupName"] == "my-group"
assert "GroupId" in created
assert created["Arn"] == f"arn:aws:iam::{ACCOUNT_ID}:group/my-group"
assert isinstance(created["CreateDate"], datetime)
retrieved = conn.get_group(GroupName="my-group")["Group"]
retrieved.should.equal(created)
assert retrieved == created
with pytest.raises(ClientError) as ex:
conn.get_group(GroupName="not-group")
err = ex.value.response["Error"]
err["Code"].should.equal("NoSuchEntity")
err["Message"].should.equal("Group not-group not found")
assert err["Code"] == "NoSuchEntity"
assert err["Message"] == "Group not-group not found"
@mock_iam()
@ -84,7 +83,7 @@ def test_get_all_groups():
conn.create_group(GroupName="my-group1")
conn.create_group(GroupName="my-group2")
groups = conn.list_groups()["Groups"]
groups.should.have.length_of(2)
assert len(groups) == 2
@mock_iam
@ -93,8 +92,8 @@ def test_add_unknown_user_to_group():
with pytest.raises(ClientError) as ex:
conn.add_user_to_group(GroupName="my-group", UserName="my-user")
err = ex.value.response["Error"]
err["Code"].should.equal("NoSuchEntity")
err["Message"].should.equal("The user with name my-user cannot be found.")
assert err["Code"] == "NoSuchEntity"
assert err["Message"] == "The user with name my-user cannot be found."
@mock_iam
@ -104,8 +103,8 @@ def test_add_user_to_unknown_group():
with pytest.raises(ClientError) as ex:
conn.add_user_to_group(GroupName="my-group", UserName="my-user")
err = ex.value.response["Error"]
err["Code"].should.equal("NoSuchEntity")
err["Message"].should.equal("Group my-group not found")
assert err["Code"] == "NoSuchEntity"
assert err["Message"] == "Group my-group not found"
@mock_iam
@ -146,8 +145,8 @@ def test_remove_user_from_unknown_group():
with pytest.raises(ClientError) as ex:
conn.remove_user_from_group(GroupName="my-group", UserName="my-user")
err = ex.value.response["Error"]
err["Code"].should.equal("NoSuchEntity")
err["Message"].should.equal("Group my-group not found")
assert err["Code"] == "NoSuchEntity"
assert err["Message"] == "Group my-group not found"
@mock_iam
@ -158,8 +157,8 @@ def test_remove_nonattached_user_from_group():
with pytest.raises(ClientError) as ex:
conn.remove_user_from_group(GroupName="my-group", UserName="my-user")
err = ex.value.response["Error"]
err["Code"].should.equal("NoSuchEntity")
err["Message"].should.equal("User my-user not in group my-group")
assert err["Code"] == "NoSuchEntity"
assert err["Message"] == "User my-user not in group my-group"
@mock_iam
@ -180,12 +179,12 @@ def test_add_user_should_be_idempotent():
conn.add_user_to_group(GroupName="my-group", UserName="my-user")
conn.add_user_to_group(GroupName="my-group", UserName="my-user")
conn.list_groups_for_user(UserName="my-user")["Groups"].should.have.length_of(1)
assert len(conn.list_groups_for_user(UserName="my-user")["Groups"]) == 1
# Which means that if we remove one, none should be left
conn.remove_user_from_group(GroupName="my-group", UserName="my-user")
conn.list_groups_for_user(UserName="my-user")["Groups"].should.have.length_of(0)
assert len(conn.list_groups_for_user(UserName="my-user")["Groups"]) == 0
@mock_iam
@ -199,7 +198,7 @@ def test_get_groups_for_user():
conn.add_user_to_group(GroupName="my-group2", UserName="my-user")
groups = conn.list_groups_for_user(UserName="my-user")["Groups"]
groups.should.have.length_of(2)
assert len(groups) == 2
@mock_iam
@ -215,24 +214,25 @@ def test_put_group_policy():
def test_attach_group_policies():
conn = boto3.client("iam", region_name="us-east-1")
conn.create_group(GroupName="my-group")
conn.list_attached_group_policies(GroupName="my-group")[
"AttachedPolicies"
].should.be.empty
policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonElasticMapReduceforEC2Role"
conn.list_attached_group_policies(GroupName="my-group")[
"AttachedPolicies"
].should.be.empty
conn.attach_group_policy(GroupName="my-group", PolicyArn=policy_arn)
conn.list_attached_group_policies(GroupName="my-group")[
"AttachedPolicies"
].should.equal(
[{"PolicyName": "AmazonElasticMapReduceforEC2Role", "PolicyArn": policy_arn}]
assert (
conn.list_attached_group_policies(GroupName="my-group")["AttachedPolicies"]
== []
)
policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonElasticMapReduceforEC2Role"
assert (
conn.list_attached_group_policies(GroupName="my-group")["AttachedPolicies"]
== []
)
conn.attach_group_policy(GroupName="my-group", PolicyArn=policy_arn)
assert conn.list_attached_group_policies(GroupName="my-group")[
"AttachedPolicies"
] == [{"PolicyName": "AmazonElasticMapReduceforEC2Role", "PolicyArn": policy_arn}]
conn.detach_group_policy(GroupName="my-group", PolicyArn=policy_arn)
conn.list_attached_group_policies(GroupName="my-group")[
"AttachedPolicies"
].should.be.empty
assert (
conn.list_attached_group_policies(GroupName="my-group")["AttachedPolicies"]
== []
)
@mock_iam
@ -242,29 +242,29 @@ def test_get_group_policy():
with pytest.raises(ClientError) as ex:
conn.get_group_policy(GroupName="my-group", PolicyName="my-policy")
err = ex.value.response["Error"]
err["Code"].should.equal("NoSuchEntity")
err["Message"].should.equal("Policy my-policy not found")
assert err["Code"] == "NoSuchEntity"
assert err["Message"] == "Policy my-policy not found"
conn.put_group_policy(
GroupName="my-group", PolicyName="my-policy", PolicyDocument=MOCK_POLICY
)
policy = conn.get_group_policy(GroupName="my-group", PolicyName="my-policy")
policy["GroupName"].should.equal("my-group")
policy["PolicyName"].should.equal("my-policy")
policy["PolicyDocument"].should.equal(json.loads(MOCK_POLICY))
assert policy["GroupName"] == "my-group"
assert policy["PolicyName"] == "my-policy"
assert policy["PolicyDocument"] == json.loads(MOCK_POLICY)
@mock_iam()
def test_list_group_policies():
conn = boto3.client("iam", region_name="us-east-1")
conn.create_group(GroupName="my-group")
conn.list_group_policies(GroupName="my-group")["PolicyNames"].should.be.empty
assert conn.list_group_policies(GroupName="my-group")["PolicyNames"] == []
conn.put_group_policy(
GroupName="my-group", PolicyName="my-policy", PolicyDocument=MOCK_POLICY
)
conn.list_group_policies(GroupName="my-group")["PolicyNames"].should.equal(
["my-policy"]
)
assert conn.list_group_policies(GroupName="my-group")["PolicyNames"] == [
"my-policy"
]
@mock_iam
@ -275,7 +275,7 @@ def test_delete_group():
assert groups["Groups"][0]["GroupName"] == "my-group"
assert len(groups["Groups"]) == 1
conn.delete_group(GroupName="my-group")
conn.list_groups()["Groups"].should.be.empty
assert conn.list_groups()["Groups"] == []
@mock_iam
@ -283,9 +283,10 @@ def test_delete_unknown_group():
conn = boto3.client("iam", region_name="us-east-1")
with pytest.raises(ClientError) as err:
conn.delete_group(GroupName="unknown-group")
err.value.response["Error"]["Code"].should.equal("NoSuchEntity")
err.value.response["Error"]["Message"].should.equal(
"The group with name unknown-group cannot be found."
assert err.value.response["Error"]["Code"] == "NoSuchEntity"
assert (
err.value.response["Error"]["Message"]
== "The group with name unknown-group cannot be found."
)
@ -300,13 +301,13 @@ def test_update_group_name():
# The old group-name should no longer exist
with pytest.raises(ClientError) as exc:
conn.get_group(GroupName="my-group")
exc.value.response["Error"]["Code"].should.equal("NoSuchEntity")
assert exc.value.response["Error"]["Code"] == "NoSuchEntity"
result = conn.get_group(GroupName="new-group")["Group"]
result["Path"].should.equal("/")
result["GroupName"].should.equal("new-group")
result["GroupId"].should.equal(initial_group["GroupId"])
result["Arn"].should.match(":group/new-group")
assert result["Path"] == "/"
assert result["GroupName"] == "new-group"
assert result["GroupId"] == initial_group["GroupId"]
assert ":group/new-group" in result["Arn"]
@mock_iam
@ -318,7 +319,7 @@ def test_update_group_name_that_has_a_path():
# Verify the path hasn't changed
new = conn.get_group(GroupName="new-group")["Group"]
new["Path"].should.equal("/path")
assert new["Path"] == "/path"
@mock_iam
@ -332,7 +333,7 @@ def test_update_group_path():
# Verify the path has changed
new = conn.get_group(GroupName="new-group")["Group"]
new["Path"].should.equal("/new-path")
assert new["Path"] == "/new-path"
@mock_iam
@ -342,8 +343,8 @@ def test_update_group_that_does_not_exist():
with pytest.raises(ClientError) as exc:
conn.update_group(GroupName="nonexisting", NewGroupName="..")
err = exc.value.response["Error"]
err["Code"].should.equal("NoSuchEntity")
err["Message"].should.equal("The group with name nonexisting cannot be found.")
assert err["Code"] == "NoSuchEntity"
assert err["Message"] == "The group with name nonexisting cannot be found."
@mock_iam
@ -355,5 +356,5 @@ def test_update_group_with_existing_name():
with pytest.raises(ClientError) as exc:
conn.update_group(GroupName="existing1", NewGroupName="existing2")
err = exc.value.response["Error"]
err["Code"].should.equal("Conflict")
err["Message"].should.equal("Group existing2 already exists")
assert err["Code"] == "Conflict"
assert err["Message"] == "Group existing2 already exists"

View File

@ -1,5 +1,4 @@
import boto3
import sure # noqa # pylint: disable=unused-import
from botocore.exceptions import ClientError
from moto import mock_iam
@ -17,32 +16,36 @@ def test_create_open_id_connect_provider():
ThumbprintList=[], # even it is required to provide at least one thumbprint, AWS accepts an empty list
)
response["OpenIDConnectProviderArn"].should.equal(
f"arn:aws:iam::{ACCOUNT_ID}:oidc-provider/example.com"
assert (
response["OpenIDConnectProviderArn"]
== f"arn:aws:iam::{ACCOUNT_ID}:oidc-provider/example.com"
)
response = client.create_open_id_connect_provider(
Url="http://example.org", ThumbprintList=["b" * 40], ClientIDList=["b"]
)
response["OpenIDConnectProviderArn"].should.equal(
f"arn:aws:iam::{ACCOUNT_ID}:oidc-provider/example.org"
assert (
response["OpenIDConnectProviderArn"]
== f"arn:aws:iam::{ACCOUNT_ID}:oidc-provider/example.org"
)
response = client.create_open_id_connect_provider(
Url="http://example.org/oidc", ThumbprintList=[]
)
response["OpenIDConnectProviderArn"].should.equal(
f"arn:aws:iam::{ACCOUNT_ID}:oidc-provider/example.org/oidc"
assert (
response["OpenIDConnectProviderArn"]
== f"arn:aws:iam::{ACCOUNT_ID}:oidc-provider/example.org/oidc"
)
response = client.create_open_id_connect_provider(
Url="http://example.org/oidc-query?test=true", ThumbprintList=[]
)
response["OpenIDConnectProviderArn"].should.equal(
f"arn:aws:iam::{ACCOUNT_ID}:oidc-provider/example.org/oidc-query"
assert (
response["OpenIDConnectProviderArn"]
== f"arn:aws:iam::{ACCOUNT_ID}:oidc-provider/example.org/oidc-query"
)
@ -57,9 +60,9 @@ def test_create_open_id_connect_provider_with_tags():
open_id_arn = response["OpenIDConnectProviderArn"]
response = client.get_open_id_connect_provider(OpenIDConnectProviderArn=open_id_arn)
response.should.have.key("Tags").length_of(2)
response["Tags"].should.contain({"Key": "k1", "Value": "v1"})
response["Tags"].should.contain({"Key": "k2", "Value": "v2"})
assert len(response["Tags"]) == 2
assert {"Key": "k1", "Value": "v1"} in response["Tags"]
assert {"Key": "k2", "Value": "v2"} in response["Tags"]
@pytest.mark.parametrize("url", ["example.org", "example"])
@ -69,7 +72,7 @@ def test_create_open_id_connect_provider_invalid_url(url):
with pytest.raises(ClientError) as e:
client.create_open_id_connect_provider(Url=url, ThumbprintList=[])
msg = e.value.response["Error"]["Message"]
msg.should.contain("Invalid Open ID Connect Provider URL")
assert "Invalid Open ID Connect Provider URL" in msg
@mock_iam
@ -77,9 +80,12 @@ def test_create_open_id_connect_provider_errors():
client = boto3.client("iam", region_name="us-east-1")
client.create_open_id_connect_provider(Url="https://example.com", ThumbprintList=[])
client.create_open_id_connect_provider.when.called_with(
Url="https://example.com", ThumbprintList=[]
).should.throw(ClientError, "Unknown")
with pytest.raises(ClientError) as exc:
client.create_open_id_connect_provider(
Url="https://example.com", ThumbprintList=[]
)
err = exc.value.response["Error"]
assert err["Message"] == "Unknown"
@mock_iam
@ -99,7 +105,7 @@ def test_create_open_id_connect_provider_too_many_entries():
],
)
msg = e.value.response["Error"]["Message"]
msg.should.contain("Thumbprint list must contain fewer than 5 entries.")
assert "Thumbprint list must contain fewer than 5 entries." in msg
@mock_iam
@ -114,7 +120,7 @@ def test_create_open_id_connect_provider_quota_error():
ClientIDList=too_many_client_ids,
)
msg = e.value.response["Error"]["Message"]
msg.should.contain("Cannot exceed quota for ClientIdsPerOpenIdConnectProvider: 100")
assert "Cannot exceed quota for ClientIdsPerOpenIdConnectProvider: 100" in msg
@mock_iam
@ -131,15 +137,15 @@ def test_create_open_id_connect_provider_multiple_errors():
ClientIDList=[too_long_client_id],
)
msg = e.value.response["Error"]["Message"]
msg.should.contain("3 validation errors detected:")
msg.should.contain('"clientIDList" failed to satisfy constraint:')
msg.should.contain("Member must have length less than or equal to 255")
msg.should.contain("Member must have length greater than or equal to 1")
msg.should.contain('"thumbprintList" failed to satisfy constraint:')
msg.should.contain("Member must have length less than or equal to 40")
msg.should.contain("Member must have length greater than or equal to 40")
msg.should.contain('"url" failed to satisfy constraint:')
msg.should.contain("Member must have length less than or equal to 255")
assert "3 validation errors detected:" in msg
assert '"clientIDList" failed to satisfy constraint:' in msg
assert "Member must have length less than or equal to 255" in msg
assert "Member must have length greater than or equal to 1" in msg
assert '"thumbprintList" failed to satisfy constraint:' in msg
assert "Member must have length less than or equal to 40" in msg
assert "Member must have length greater than or equal to 40" in msg
assert '"url" failed to satisfy constraint:' in msg
assert "Member must have length less than or equal to 255" in msg
@mock_iam
@ -152,11 +158,10 @@ def test_delete_open_id_connect_provider():
client.delete_open_id_connect_provider(OpenIDConnectProviderArn=open_id_arn)
client.get_open_id_connect_provider.when.called_with(
OpenIDConnectProviderArn=open_id_arn
).should.throw(
ClientError, f"OpenIDConnect Provider not found for arn {open_id_arn}"
)
with pytest.raises(ClientError) as exc:
client.get_open_id_connect_provider(OpenIDConnectProviderArn=open_id_arn)
err = exc.value.response["Error"]
assert err["Message"] == f"OpenIDConnect Provider not found for arn {open_id_arn}"
# deleting a non existing provider should be successful
client.delete_open_id_connect_provider(OpenIDConnectProviderArn=open_id_arn)
@ -172,10 +177,10 @@ def test_get_open_id_connect_provider():
response = client.get_open_id_connect_provider(OpenIDConnectProviderArn=open_id_arn)
response["Url"].should.equal("example.com")
response["ThumbprintList"].should.equal(["b" * 40])
response["ClientIDList"].should.equal(["b"])
response.should.have.key("CreateDate").should.be.a(datetime)
assert response["Url"] == "example.com"
assert response["ThumbprintList"] == ["b" * 40]
assert response["ClientIDList"] == ["b"]
assert isinstance(response["CreateDate"], datetime)
@mock_iam
@ -192,10 +197,10 @@ def test_update_open_id_connect_provider():
response = client.get_open_id_connect_provider(OpenIDConnectProviderArn=open_id_arn)
response["Url"].should.equal("example.com")
response["ThumbprintList"].should.have.length_of(2)
response["ThumbprintList"].should.contain("c" * 40)
response["ThumbprintList"].should.contain("d" * 40)
assert response["Url"] == "example.com"
assert len(response["ThumbprintList"]) == 2
assert "c" * 40 in response["ThumbprintList"]
assert "d" * 40 in response["ThumbprintList"]
@mock_iam
@ -207,11 +212,10 @@ def test_get_open_id_connect_provider_errors():
open_id_arn = response["OpenIDConnectProviderArn"]
unknown_arn = open_id_arn + "-not-existing"
client.get_open_id_connect_provider.when.called_with(
OpenIDConnectProviderArn=unknown_arn
).should.throw(
ClientError, f"OpenIDConnect Provider not found for arn {unknown_arn}"
)
with pytest.raises(ClientError) as exc:
client.get_open_id_connect_provider(OpenIDConnectProviderArn=unknown_arn)
err = exc.value.response["Error"]
assert err["Message"] == f"OpenIDConnect Provider not found for arn {unknown_arn}"
@mock_iam
@ -234,9 +238,11 @@ def test_list_open_id_connect_providers():
response = client.list_open_id_connect_providers()
sorted(response["OpenIDConnectProviderList"], key=lambda i: i["Arn"]).should.equal(
[{"Arn": open_id_arn_1}, {"Arn": open_id_arn_2}, {"Arn": open_id_arn_3}]
)
assert sorted(response["OpenIDConnectProviderList"], key=lambda i: i["Arn"]) == [
{"Arn": open_id_arn_1},
{"Arn": open_id_arn_2},
{"Arn": open_id_arn_3},
]
@mock_iam
@ -252,9 +258,9 @@ def test_tag_open_id_connect_provider():
)
response = client.get_open_id_connect_provider(OpenIDConnectProviderArn=open_id_arn)
response.should.have.key("Tags").length_of(2)
response["Tags"].should.contain({"Key": "k1", "Value": "v1"})
response["Tags"].should.contain({"Key": "k2", "Value": "v2"})
assert len(response["Tags"]) == 2
assert {"Key": "k1", "Value": "v1"} in response["Tags"]
assert {"Key": "k2", "Value": "v2"} in response["Tags"]
@mock_iam
@ -273,8 +279,8 @@ def test_untag_open_id_connect_provider():
)
response = client.get_open_id_connect_provider(OpenIDConnectProviderArn=open_id_arn)
response.should.have.key("Tags").length_of(1)
response["Tags"].should.contain({"Key": "k1", "Value": "v1"})
assert len(response["Tags"]) == 1
assert {"Key": "k1", "Value": "v1"} in response["Tags"]
@mock_iam
@ -290,9 +296,9 @@ def test_list_open_id_connect_provider_tags():
response = client.list_open_id_connect_provider_tags(
OpenIDConnectProviderArn=open_id_arn
)
response.should.have.key("Tags").length_of(2)
response["Tags"].should.contain({"Key": "k1", "Value": "v1"})
response["Tags"].should.contain({"Key": "k2", "Value": "v2"})
assert len(response["Tags"]) == 2
assert {"Key": "k1", "Value": "v1"} in response["Tags"]
assert {"Key": "k2", "Value": "v2"} in response["Tags"]
@mock_iam
@ -316,14 +322,13 @@ def test_list_open_id_connect_provider_tags__paginated():
response = client.list_open_id_connect_provider_tags(
OpenIDConnectProviderArn=open_id_arn
)
response.should.have.key("Tags").length_of(100)
response.should.have.key("Marker")
assert len(response["Tags"]) == 100
response = client.list_open_id_connect_provider_tags(
OpenIDConnectProviderArn=open_id_arn, Marker=response["Marker"]
)
response.should.have.key("Tags").length_of(50)
response.shouldnt.have.key("Marker")
assert len(response["Tags"]) == 50
assert "Marker" not in response
@mock_iam
@ -339,17 +344,15 @@ def test_list_open_id_connect_provider_tags__maxitems():
response = client.list_open_id_connect_provider_tags(
OpenIDConnectProviderArn=open_id_arn, MaxItems=4
)
response.should.have.key("Tags").length_of(4)
response.should.have.key("Marker")
assert len(response["Tags"]) == 4
response = client.list_open_id_connect_provider_tags(
OpenIDConnectProviderArn=open_id_arn, Marker=response["Marker"], MaxItems=4
)
response.should.have.key("Tags").length_of(4)
response.should.have.key("Marker")
assert len(response["Tags"]) == 4
response = client.list_open_id_connect_provider_tags(
OpenIDConnectProviderArn=open_id_arn, Marker=response["Marker"]
)
response.should.have.key("Tags").length_of(2)
response.shouldnt.have.key("Marker")
assert len(response["Tags"]) == 2
assert "Marker" not in response

View File

@ -1,10 +1,8 @@
import json
import boto3
from botocore.exceptions import ClientError
import json
import pytest
import sure # noqa # pylint: disable=unused-import
from botocore.exceptions import ClientError
from moto import mock_iam
invalid_policy_document_test_cases = [
@ -1621,11 +1619,10 @@ def test_create_policy_with_invalid_policy_document(invalid_policy_document):
PolicyName="TestCreatePolicy",
PolicyDocument=json.dumps(invalid_policy_document["document"]),
)
ex.value.response["Error"]["Code"].should.equal("MalformedPolicyDocument")
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400)
ex.value.response["Error"]["Message"].should.equal(
invalid_policy_document["error_message"]
)
resp = ex.value.response
assert resp["Error"]["Code"] == "MalformedPolicyDocument"
assert resp["ResponseMetadata"]["HTTPStatusCode"] == 400
assert resp["Error"]["Message"] == invalid_policy_document["error_message"]
@pytest.mark.parametrize("valid_policy_document", valid_policy_documents)

View File

@ -1,6 +1,5 @@
import boto3
import pytest
import sure # noqa # pylint: disable=unused-import
from botocore.exceptions import ClientError
from datetime import datetime
@ -19,10 +18,10 @@ def test_get_all_server_certs():
PrivateKey="privatekey",
)
certs = conn.list_server_certificates()["ServerCertificateMetadataList"]
certs.should.have.length_of(1)
assert len(certs) == 1
cert1 = certs[0]
cert1["ServerCertificateName"].should.equal("certname")
cert1["Arn"].should.equal(f"arn:aws:iam::{ACCOUNT_ID}:server-certificate/certname")
assert cert1["ServerCertificateName"] == "certname"
assert cert1["Arn"] == f"arn:aws:iam::{ACCOUNT_ID}:server-certificate/certname"
@mock_iam
@ -32,9 +31,10 @@ def test_get_server_cert_doesnt_exist():
with pytest.raises(ClientError) as ex:
conn.get_server_certificate(ServerCertificateName="NonExistant")
err = ex.value.response["Error"]
err["Code"].should.equal("NoSuchEntity")
err["Message"].should.equal(
"The Server Certificate with name NonExistant cannot be found."
assert err["Code"] == "NoSuchEntity"
assert (
err["Message"]
== "The Server Certificate with name NonExistant cannot be found."
)
@ -50,18 +50,16 @@ def test_get_server_cert():
cert = conn.get_server_certificate(ServerCertificateName="certname")[
"ServerCertificate"
]
cert["CertificateBody"].should.equal("certbody")
cert.shouldnt.have.key("CertificateChain")
cert.shouldnt.have.key("Tags")
assert cert["CertificateBody"] == "certbody"
assert "CertificateChain" not in cert
assert "Tags" not in cert
metadata = cert["ServerCertificateMetadata"]
metadata["Path"].should.equal("/")
metadata["ServerCertificateName"].should.equal("certname")
metadata["Arn"].should.equal(
f"arn:aws:iam::{ACCOUNT_ID}:server-certificate/certname"
)
metadata.should.have.key("ServerCertificateId")
metadata["UploadDate"].should.be.a(datetime)
metadata["Expiration"].should.be.a(datetime)
assert metadata["Path"] == "/"
assert metadata["ServerCertificateName"] == "certname"
assert metadata["Arn"] == f"arn:aws:iam::{ACCOUNT_ID}:server-certificate/certname"
assert "ServerCertificateId" in metadata
assert isinstance(metadata["UploadDate"], datetime)
assert isinstance(metadata["Expiration"], datetime)
@mock_iam
@ -79,9 +77,9 @@ def test_delete_server_cert():
with pytest.raises(ClientError) as ex:
conn.get_server_certificate(ServerCertificateName="certname")
err = ex.value.response["Error"]
err["Code"].should.equal("NoSuchEntity")
err["Message"].should.equal(
"The Server Certificate with name certname cannot be found."
assert err["Code"] == "NoSuchEntity"
assert (
err["Message"] == "The Server Certificate with name certname cannot be found."
)
@ -92,7 +90,7 @@ def test_delete_unknown_server_cert():
with pytest.raises(ClientError) as ex:
conn.delete_server_certificate(ServerCertificateName="certname")
err = ex.value.response["Error"]
err["Code"].should.equal("NoSuchEntity")
err["Message"].should.equal(
"The Server Certificate with name certname cannot be found."
assert err["Code"] == "NoSuchEntity"
assert (
err["Message"] == "The Server Certificate with name certname cannot be found."
)

View File

@ -1,5 +1,4 @@
import re
import sure # noqa # pylint: disable=unused-import
import moto.server as server