From 0520df02c13ca6dae57427fd3c7e9c76925e53e9 Mon Sep 17 00:00:00 2001 From: kbalk <7536198+kbalk@users.noreply.github.com> Date: Sun, 13 Aug 2023 16:42:50 -0400 Subject: [PATCH] Techdebt: Replace sure with regular assertions in SSM (#6645) --- tests/test_ses/test_ses_sns_boto3.py | 1 - tests/test_ssm/test_ssm_boto3.py | 1078 +++++++++-------- tests/test_ssm/test_ssm_cloudformation.py | 2 +- tests/test_ssm/test_ssm_default_amis.py | 13 +- tests/test_ssm/test_ssm_defaults.py | 21 +- tests/test_ssm/test_ssm_doc_permissions.py | 54 +- tests/test_ssm/test_ssm_docs.py | 355 +++--- tests/test_ssm/test_ssm_ec2_integration.py | 3 +- tests/test_ssm/test_ssm_ecs_images.py | 5 +- .../test_ssm/test_ssm_maintenance_windows.py | 129 +- tests/test_ssm/test_ssm_parameterstore.py | 53 +- tests/test_ssm/test_ssm_patch_baseline.py | 15 +- tests/test_ssm/test_ssm_secretsmanager.py | 44 +- tests/test_ssm/test_ssm_utils.py | 46 +- 14 files changed, 925 insertions(+), 894 deletions(-) diff --git a/tests/test_ses/test_ses_sns_boto3.py b/tests/test_ses/test_ses_sns_boto3.py index 1d9b16153..f56ef4b12 100644 --- a/tests/test_ses/test_ses_sns_boto3.py +++ b/tests/test_ses/test_ses_sns_boto3.py @@ -2,7 +2,6 @@ import json import boto3 -import sure # noqa # pylint: disable=unused-import from moto import mock_ses, mock_sns, mock_sqs from moto.ses.models import SESFeedback from moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID diff --git a/tests/test_ssm/test_ssm_boto3.py b/tests/test_ssm/test_ssm_boto3.py index 9a97573bf..8655e17be 100644 --- a/tests/test_ssm/test_ssm_boto3.py +++ b/tests/test_ssm/test_ssm_boto3.py @@ -1,11 +1,10 @@ +import datetime +import re import string +import uuid import boto3 import botocore.exceptions -import sure # noqa # pylint: disable=unused-import -import datetime -import uuid - from botocore.exceptions import ClientError import pytest @@ -24,12 +23,12 @@ def test_delete_parameter(): ) response = client.get_parameters(Names=["test"]) - len(response["Parameters"]).should.equal(1) + assert len(response["Parameters"]) == 1 client.delete_parameter(Name="test") response = client.get_parameters(Names=["test"]) - len(response["Parameters"]).should.equal(0) + assert len(response["Parameters"]) == 0 @mock_ssm @@ -38,10 +37,8 @@ def test_delete_nonexistent_parameter(): with pytest.raises(ClientError) as ex: client.delete_parameter(Name="test_noexist") - ex.value.response["Error"]["Code"].should.equal("ParameterNotFound") - ex.value.response["Error"]["Message"].should.equal( - "Parameter test_noexist not found." - ) + assert ex.value.response["Error"]["Code"] == "ParameterNotFound" + assert ex.value.response["Error"]["Message"] == "Parameter test_noexist not found." @mock_ssm @@ -53,14 +50,14 @@ def test_delete_parameters(): ) response = client.get_parameters(Names=["test"]) - len(response["Parameters"]).should.equal(1) + assert len(response["Parameters"]) == 1 result = client.delete_parameters(Names=["test", "invalid"]) - len(result["DeletedParameters"]).should.equal(1) - len(result["InvalidParameters"]).should.equal(1) + assert len(result["DeletedParameters"]) == 1 + assert len(result["InvalidParameters"]) == 1 response = client.get_parameters(Names=["test"]) - len(response["Parameters"]).should.equal(0) + assert len(response["Parameters"]) == 0 @mock_ssm @@ -101,115 +98,108 @@ def test_get_parameters_by_path(): client.put_parameter(Name="baz", Value="qux", Type="String") response = client.get_parameters_by_path(Path="/", Recursive=False) - len(response["Parameters"]).should.equal(2) - {p["Value"] for p in response["Parameters"]}.should.equal(set(["bar", "qux"])) - {p["ARN"] for p in response["Parameters"]}.should.equal( - set( - [ - f"arn:aws:ssm:us-east-1:{ACCOUNT_ID}:parameter/foo", - f"arn:aws:ssm:us-east-1:{ACCOUNT_ID}:parameter/baz", - ] - ) + assert len(response["Parameters"]) == 2 + assert {p["Value"] for p in response["Parameters"]} == set(["bar", "qux"]) + assert {p["ARN"] for p in response["Parameters"]} == set( + [ + f"arn:aws:ssm:us-east-1:{ACCOUNT_ID}:parameter/foo", + f"arn:aws:ssm:us-east-1:{ACCOUNT_ID}:parameter/baz", + ] ) - { - p["LastModifiedDate"].should.be.a(datetime.datetime) - for p in response["Parameters"] - } + for p in response["Parameters"]: + assert isinstance(p["LastModifiedDate"], datetime.datetime) response = client.get_parameters_by_path(Path="/", Recursive=True) - len(response["Parameters"]).should.equal(9) + assert len(response["Parameters"]) == 9 response = client.get_parameters_by_path(Path="/foo") - len(response["Parameters"]).should.equal(2) - {p["Value"] for p in response["Parameters"]}.should.equal(set(["value1", "value2"])) + assert len(response["Parameters"]) == 2 + assert {p["Value"] for p in response["Parameters"]} == set(["value1", "value2"]) response = client.get_parameters_by_path(Path="/bar", Recursive=False) - len(response["Parameters"]).should.equal(1) - response["Parameters"][0]["Value"].should.equal("value3") + assert len(response["Parameters"]) == 1 + assert response["Parameters"][0]["Value"] == "value3" response = client.get_parameters_by_path(Path="/bar", Recursive=True) - len(response["Parameters"]).should.equal(2) - {p["Value"] for p in response["Parameters"]}.should.equal(set(["value3", "value4"])) + assert len(response["Parameters"]) == 2 + assert {p["Value"] for p in response["Parameters"]} == set(["value3", "value4"]) response = client.get_parameters_by_path(Path="/baz") - len(response["Parameters"]).should.equal(3) + assert len(response["Parameters"]) == 3 filters = [{"Key": "Type", "Option": "Equals", "Values": ["StringList"]}] response = client.get_parameters_by_path(Path="/baz", ParameterFilters=filters) - len(response["Parameters"]).should.equal(1) - {p["Name"] for p in response["Parameters"]}.should.equal(set(["/baz/name1"])) + assert len(response["Parameters"]) == 1 + assert {p["Name"] for p in response["Parameters"]} == set(["/baz/name1"]) # note: 'Option' is optional (default: 'Equals') filters = [{"Key": "Type", "Values": ["StringList"]}] response = client.get_parameters_by_path(Path="/baz", ParameterFilters=filters) - len(response["Parameters"]).should.equal(1) - {p["Name"] for p in response["Parameters"]}.should.equal(set(["/baz/name1"])) + assert len(response["Parameters"]) == 1 + assert {p["Name"] for p in response["Parameters"]} == set(["/baz/name1"]) filters = [{"Key": "Type", "Option": "Equals", "Values": ["String"]}] response = client.get_parameters_by_path(Path="/baz", ParameterFilters=filters) - len(response["Parameters"]).should.equal(1) - {p["Name"] for p in response["Parameters"]}.should.equal(set(["/baz/name2"])) + assert len(response["Parameters"]) == 1 + assert {p["Name"] for p in response["Parameters"]} == set(["/baz/name2"]) filters = [ {"Key": "Type", "Option": "Equals", "Values": ["String", "SecureString"]} ] response = client.get_parameters_by_path(Path="/baz", ParameterFilters=filters) - len(response["Parameters"]).should.equal(2) - {p["Name"] for p in response["Parameters"]}.should.equal( - set(["/baz/name2", "/baz/pwd"]) + assert len(response["Parameters"]) == 2 + assert {p["Name"] for p in response["Parameters"]} == set( + ["/baz/name2", "/baz/pwd"] ) filters = [{"Key": "Type", "Option": "BeginsWith", "Values": ["String"]}] response = client.get_parameters_by_path(Path="/baz", ParameterFilters=filters) - len(response["Parameters"]).should.equal(2) - {p["Name"] for p in response["Parameters"]}.should.equal( - set(["/baz/name1", "/baz/name2"]) + assert len(response["Parameters"]) == 2 + assert {p["Name"] for p in response["Parameters"]} == set( + ["/baz/name1", "/baz/name2"] ) filters = [{"Key": "KeyId", "Option": "Equals", "Values": ["alias/aws/ssm"]}] response = client.get_parameters_by_path(Path="/baz", ParameterFilters=filters) - len(response["Parameters"]).should.equal(1) - {p["Name"] for p in response["Parameters"]}.should.equal(set(["/baz/pwd"])) + assert len(response["Parameters"]) == 1 + assert {p["Name"] for p in response["Parameters"]} == set(["/baz/pwd"]) response = client.get_parameters_by_path(Path="/", Recursive=True, MaxResults=4) - len(response["Parameters"]).should.equal(4) - response["NextToken"].should.equal("4") + assert len(response["Parameters"]) == 4 + assert response["NextToken"] == "4" response = client.get_parameters_by_path( Path="/", Recursive=True, MaxResults=4, NextToken=response["NextToken"] ) - len(response["Parameters"]).should.equal(4) - response["NextToken"].should.equal("8") + assert len(response["Parameters"]) == 4 + assert response["NextToken"] == "8" response = client.get_parameters_by_path( Path="/", Recursive=True, MaxResults=4, NextToken=response["NextToken"] ) - len(response["Parameters"]).should.equal(1) - response.should_not.have.key("NextToken") + assert len(response["Parameters"]) == 1 + assert "NextToken" not in response filters = [{"Key": "Name", "Values": ["error"]}] - client.get_parameters_by_path.when.called_with( - Path="/baz", ParameterFilters=filters - ).should.throw( - ClientError, + with pytest.raises(ClientError) as client_err: + client.get_parameters_by_path(Path="/baz", ParameterFilters=filters) + assert client_err.value.response["Error"]["Message"] == ( "The following filter key is not valid: Name. " - "Valid filter keys include: [Type, KeyId].", + "Valid filter keys include: [Type, KeyId]." ) filters = [{"Key": "Path", "Values": ["/error"]}] - client.get_parameters_by_path.when.called_with( - Path="/baz", ParameterFilters=filters - ).should.throw( - ClientError, + with pytest.raises(ClientError) as client_err: + client.get_parameters_by_path(Path="/baz", ParameterFilters=filters) + assert client_err.value.response["Error"]["Message"] == ( "The following filter key is not valid: Path. " - "Valid filter keys include: [Type, KeyId].", + "Valid filter keys include: [Type, KeyId]." ) filters = [{"Key": "Tier", "Values": ["Standard"]}] - client.get_parameters_by_path.when.called_with( - Path="/baz", ParameterFilters=filters - ).should.throw( - ClientError, + with pytest.raises(ClientError) as client_err: + client.get_parameters_by_path(Path="/baz", ParameterFilters=filters) + assert client_err.value.response["Error"]["Message"] == ( "The following filter key is not valid: Tier. " - "Valid filter keys include: [Type, KeyId].", + "Valid filter keys include: [Type, KeyId]." ) # Label filter in get_parameters_by_path @@ -217,8 +207,8 @@ def test_get_parameters_by_path(): filters = [{"Key": "Label", "Values": ["Label1"]}] response = client.get_parameters_by_path(Path="/foo", ParameterFilters=filters) - len(response["Parameters"]).should.equal(1) - {p["Name"] for p in response["Parameters"]}.should.equal(set(["/foo/name2"])) + assert len(response["Parameters"]) == 1 + assert {p["Name"] for p in response["Parameters"]} == set(["/foo/name2"]) @pytest.mark.parametrize("name", ["test", "my-cool-parameter"]) @@ -229,18 +219,18 @@ def test_put_parameter(name): Name=name, Description="A test parameter", Value="value", Type="String" ) - response["Version"].should.equal(1) + assert response["Version"] == 1 response = client.get_parameters(Names=[name], WithDecryption=False) - len(response["Parameters"]).should.equal(1) - response["Parameters"][0]["Name"].should.equal(name) - response["Parameters"][0]["Value"].should.equal("value") - response["Parameters"][0]["Type"].should.equal("String") - response["Parameters"][0]["Version"].should.equal(1) - response["Parameters"][0]["DataType"].should.equal("text") - response["Parameters"][0]["LastModifiedDate"].should.be.a(datetime.datetime) - response["Parameters"][0]["ARN"].should.equal( + assert len(response["Parameters"]) == 1 + assert response["Parameters"][0]["Name"] == name + assert response["Parameters"][0]["Value"] == "value" + assert response["Parameters"][0]["Type"] == "String" + assert response["Parameters"][0]["Version"] == 1 + assert response["Parameters"][0]["DataType"] == "text" + assert isinstance(response["Parameters"][0]["LastModifiedDate"], datetime.datetime) + assert response["Parameters"][0]["ARN"] == ( f"arn:aws:ssm:us-east-1:{ACCOUNT_ID}:parameter/{name}" ) initial_modification_date = response["Parameters"][0]["LastModifiedDate"] @@ -251,24 +241,23 @@ def test_put_parameter(name): ) raise RuntimeError("Should fail") except botocore.exceptions.ClientError as err: - err.operation_name.should.equal("PutParameter") - err.response["Error"]["Message"].should.equal( - "The parameter already exists. To overwrite this value, set the overwrite option in the request to true." + assert err.operation_name == "PutParameter" + assert err.response["Error"]["Message"] == ( + "The parameter already exists. To overwrite this value, set the " + "overwrite option in the request to true." ) response = client.get_parameters(Names=[name], WithDecryption=False) # without overwrite nothing change - len(response["Parameters"]).should.equal(1) - response["Parameters"][0]["Name"].should.equal(name) - response["Parameters"][0]["Value"].should.equal("value") - response["Parameters"][0]["Type"].should.equal("String") - response["Parameters"][0]["Version"].should.equal(1) - response["Parameters"][0]["DataType"].should.equal("text") - response["Parameters"][0]["LastModifiedDate"].should.equal( - initial_modification_date - ) - response["Parameters"][0]["ARN"].should.equal( + assert len(response["Parameters"]) == 1 + assert response["Parameters"][0]["Name"] == name + assert response["Parameters"][0]["Value"] == "value" + assert response["Parameters"][0]["Type"] == "String" + assert response["Parameters"][0]["Version"] == 1 + assert response["Parameters"][0]["DataType"] == "text" + assert response["Parameters"][0]["LastModifiedDate"] == initial_modification_date + assert response["Parameters"][0]["ARN"] == ( f"arn:aws:ssm:us-east-1:{ACCOUNT_ID}:parameter/{name}" ) new_data_type = "aws:ec2:image" @@ -294,22 +283,20 @@ def test_put_parameter(name): DataType=new_data_type, ) - response["Version"].should.equal(2) + assert response["Version"] == 2 response = client.get_parameters(Names=[name], WithDecryption=False) # without overwrite nothing change - len(response["Parameters"]).should.equal(1) - response["Parameters"][0]["Name"].should.equal(name) - response["Parameters"][0]["Value"].should.equal("value 3") - response["Parameters"][0]["Type"].should.equal("String") - response["Parameters"][0]["Version"].should.equal(2) - response["Parameters"][0]["DataType"].should_not.equal("text") - response["Parameters"][0]["DataType"].should.equal(new_data_type) - response["Parameters"][0]["LastModifiedDate"].should_not.equal( - initial_modification_date - ) - response["Parameters"][0]["ARN"].should.equal( + assert len(response["Parameters"]) == 1 + assert response["Parameters"][0]["Name"] == name + assert response["Parameters"][0]["Value"] == "value 3" + assert response["Parameters"][0]["Type"] == "String" + assert response["Parameters"][0]["Version"] == 2 + assert response["Parameters"][0]["DataType"] != "text" + assert response["Parameters"][0]["DataType"] == new_data_type + assert response["Parameters"][0]["LastModifiedDate"] != initial_modification_date + assert response["Parameters"][0]["ARN"] == ( f"arn:aws:ssm:us-east-1:{ACCOUNT_ID}:parameter/{name}" ) @@ -320,10 +307,10 @@ def test_put_parameter_empty_string_value(): with pytest.raises(ClientError) as e: client.put_parameter(Name="test_name", Value="", Type="String") ex = e.value - ex.operation_name.should.equal("PutParameter") - ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.response["Error"]["Code"].should.contain("ValidationException") - ex.response["Error"]["Message"].should.equal( + assert ex.operation_name == "PutParameter" + assert ex.response["ResponseMetadata"]["HTTPStatusCode"] == 400 + assert "ValidationException" in ex.response["Error"]["Code"] + assert ex.response["Error"]["Message"] == ( "1 validation error detected: " "Value '' at 'value' failed to satisfy constraint: " "Member must have length greater than or equal to 1." @@ -338,51 +325,55 @@ def test_put_parameter_invalid_names(): 'Parameter name: can\'t be prefixed with "aws" or "ssm" (case-insensitive).' ) - client.put_parameter.when.called_with( - Name="ssm_test", Value="value", Type="String" - ).should.throw(ClientError, invalid_prefix_err) + with pytest.raises(ClientError) as client_err: + client.put_parameter(Name="ssm_test", Value="value", Type="String") + assert client_err.value.response["Error"]["Message"] == invalid_prefix_err - client.put_parameter.when.called_with( - Name="SSM_TEST", Value="value", Type="String" - ).should.throw(ClientError, invalid_prefix_err) + with pytest.raises(ClientError) as client_err: + client.put_parameter(Name="SSM_TEST", Value="value", Type="String") + assert client_err.value.response["Error"]["Message"] == invalid_prefix_err - client.put_parameter.when.called_with( - Name="aws_test", Value="value", Type="String" - ).should.throw(ClientError, invalid_prefix_err) + with pytest.raises(ClientError) as client_err: + client.put_parameter(Name="aws_test", Value="value", Type="String") + assert client_err.value.response["Error"]["Message"] == invalid_prefix_err - client.put_parameter.when.called_with( - Name="AWS_TEST", Value="value", Type="String" - ).should.throw(ClientError, invalid_prefix_err) + with pytest.raises(ClientError) as client_err: + client.put_parameter(Name="AWS_TEST", Value="value", Type="String") + assert client_err.value.response["Error"]["Message"] == invalid_prefix_err ssm_path = "/ssm_test/path/to/var" - client.put_parameter.when.called_with( - Name=ssm_path, Value="value", Type="String" - ).should.throw( - ClientError, - 'Parameter name: can\'t be prefixed with "ssm" (case-insensitive). If formed as a path, it can consist of ' - "sub-paths divided by slash symbol; each sub-path can be formed as a mix of letters, numbers and the following " - "3 symbols .-_", + with pytest.raises(ClientError) as client_err: + client.put_parameter(Name=ssm_path, Value="value", Type="String") + assert client_err.value.response["Error"]["Message"] == ( + 'Parameter name: can\'t be prefixed with "ssm" (case-insensitive). ' + "If formed as a path, it can consist of sub-paths divided by slash " + "symbol; each sub-path can be formed as a mix of letters, numbers " + "and the following 3 symbols .-_" ) ssm_path = "/SSM/PATH/TO/VAR" - client.put_parameter.when.called_with( - Name=ssm_path, Value="value", Type="String" - ).should.throw( - ClientError, - 'Parameter name: can\'t be prefixed with "ssm" (case-insensitive). If formed as a path, it can consist of ' - "sub-paths divided by slash symbol; each sub-path can be formed as a mix of letters, numbers and the following " - "3 symbols .-_", + with pytest.raises(ClientError) as client_err: + client.put_parameter(Name=ssm_path, Value="value", Type="String") + assert client_err.value.response["Error"]["Message"] == ( + 'Parameter name: can\'t be prefixed with "ssm" (case-insensitive). ' + "If formed as a path, it can consist of sub-paths divided by slash " + "symbol; each sub-path can be formed as a mix of letters, numbers " + "and the following 3 symbols .-_" ) aws_path = "/aws_test/path/to/var" - client.put_parameter.when.called_with( - Name=aws_path, Value="value", Type="String" - ).should.throw(ClientError, f"No access to reserved parameter name: {aws_path}.") + with pytest.raises(ClientError) as client_err: + client.put_parameter(Name=aws_path, Value="value", Type="String") + assert client_err.value.response["Error"]["Message"] == ( + f"No access to reserved parameter name: {aws_path}." + ) aws_path = "/AWS/PATH/TO/VAR" - client.put_parameter.when.called_with( - Name=aws_path, Value="value", Type="String" - ).should.throw(ClientError, f"No access to reserved parameter name: {aws_path}.") + with pytest.raises(ClientError) as client_err: + client.put_parameter(Name=aws_path, Value="value", Type="String") + assert client_err.value.response["Error"]["Message"] == ( + f"No access to reserved parameter name: {aws_path}." + ) @mock_ssm @@ -393,7 +384,7 @@ def test_put_parameter_china(): Name="test", Description="A test parameter", Value="value", Type="String" ) - response["Version"].should.equal(1) + assert response["Version"] == 1 @mock_ssm @@ -405,10 +396,10 @@ def test_put_parameter_invalid_data_type(bad_data_type): Name="test_name", Value="some_value", Type="String", DataType=bad_data_type ) ex = e.value - ex.operation_name.should.equal("PutParameter") - ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.response["Error"]["Code"].should.contain("ValidationException") - ex.response["Error"]["Message"].should.equal( + assert ex.operation_name == "PutParameter" + assert ex.response["ResponseMetadata"]["HTTPStatusCode"] == 400 + assert "ValidationException" in ex.response["Error"]["Code"] + assert ex.response["Error"]["Message"] == ( f"The following data type is not supported: {bad_data_type}" " (Data type names are all lowercase.)" ) @@ -423,11 +414,13 @@ def test_put_parameter_invalid_type(): Name="test_name", Value="some_value", Type=bad_type, DataType="text" ) ex = e.value - ex.operation_name.should.equal("PutParameter") - ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.response["Error"]["Code"].should.contain("ValidationException") - ex.response["Error"]["Message"].should.equal( - f"1 validation error detected: Value '{bad_type}' at 'type' failed to satisfy constraint: Member must satisfy enum value set: [SecureString, StringList, String]" + assert ex.operation_name == "PutParameter" + assert ex.response["ResponseMetadata"]["HTTPStatusCode"] == 400 + assert "ValidationException" in ex.response["Error"]["Code"] + assert ex.response["Error"]["Message"] == ( + f"1 validation error detected: Value '{bad_type}' at 'type' " + "failed to satisfy constraint: Member must satisfy enum value set: " + "[SecureString, StringList, String]" ) @@ -500,12 +493,12 @@ def test_update_parameter_already_exists_error(): # Verify ex = exc.value - assert ex.operation_name.should.equal("PutParameter") - assert ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + assert ex.operation_name == "PutParameter" + assert ex.response["ResponseMetadata"]["HTTPStatusCode"] == 400 assert ex.response["Error"]["Code"] == "ParameterAlreadyExists" - assert ( - ex.response["Error"]["Message"] - == "The parameter already exists. To overwrite this value, set the overwrite option in the request to true." + assert ex.response["Error"]["Message"] == ( + "The parameter already exists. To overwrite this value, set the " + "overwrite option in the request to true." ) @@ -519,12 +512,12 @@ def test_get_parameter(): response = client.get_parameter(Name="test", WithDecryption=False) - response["Parameter"]["Name"].should.equal("test") - response["Parameter"]["Value"].should.equal("value") - response["Parameter"]["Type"].should.equal("String") - response["Parameter"]["DataType"].should.equal("text") - response["Parameter"]["LastModifiedDate"].should.be.a(datetime.datetime) - response["Parameter"]["ARN"].should.equal( + assert response["Parameter"]["Name"] == "test" + assert response["Parameter"]["Value"] == "value" + assert response["Parameter"]["Type"] == "String" + assert response["Parameter"]["DataType"] == "text" + assert isinstance(response["Parameter"]["LastModifiedDate"], datetime.datetime) + assert response["Parameter"]["ARN"] == ( f"arn:aws:ssm:us-east-1:{ACCOUNT_ID}:parameter/test" ) @@ -546,53 +539,51 @@ def test_get_parameter_with_version_and_labels(): response = client.get_parameter(Name="test-1:1", WithDecryption=False) - response["Parameter"]["Name"].should.equal("test-1") - response["Parameter"]["Value"].should.equal("value") - response["Parameter"]["Type"].should.equal("String") - response["Parameter"]["DataType"].should.equal("text") - response["Parameter"]["LastModifiedDate"].should.be.a(datetime.datetime) - response["Parameter"]["ARN"].should.equal( + assert response["Parameter"]["Name"] == "test-1" + assert response["Parameter"]["Value"] == "value" + assert response["Parameter"]["Type"] == "String" + assert response["Parameter"]["DataType"] == "text" + assert isinstance(response["Parameter"]["LastModifiedDate"], datetime.datetime) + assert response["Parameter"]["ARN"] == ( f"arn:aws:ssm:us-east-1:{ACCOUNT_ID}:parameter/test-1" ) response = client.get_parameter(Name="test-2:1", WithDecryption=False) - response["Parameter"]["Name"].should.equal("test-2") - response["Parameter"]["Value"].should.equal("value") - response["Parameter"]["Type"].should.equal("String") - response["Parameter"]["DataType"].should.equal("text") - response["Parameter"]["LastModifiedDate"].should.be.a(datetime.datetime) - response["Parameter"]["ARN"].should.equal( + assert response["Parameter"]["Name"] == "test-2" + assert response["Parameter"]["Value"] == "value" + assert response["Parameter"]["Type"] == "String" + assert response["Parameter"]["DataType"] == "text" + assert isinstance(response["Parameter"]["LastModifiedDate"], datetime.datetime) + assert response["Parameter"]["ARN"] == ( f"arn:aws:ssm:us-east-1:{ACCOUNT_ID}:parameter/test-2" ) response = client.get_parameter(Name="test-2:test-label", WithDecryption=False) - response["Parameter"]["Name"].should.equal("test-2") - response["Parameter"]["Value"].should.equal("value") - response["Parameter"]["Type"].should.equal("String") - response["Parameter"]["DataType"].should.equal("text") - response["Parameter"]["LastModifiedDate"].should.be.a(datetime.datetime) - response["Parameter"]["ARN"].should.equal( + assert response["Parameter"]["Name"] == "test-2" + assert response["Parameter"]["Value"] == "value" + assert response["Parameter"]["Type"] == "String" + assert response["Parameter"]["DataType"] == "text" + assert isinstance(response["Parameter"]["LastModifiedDate"], datetime.datetime) + assert response["Parameter"]["ARN"] == ( f"arn:aws:ssm:us-east-1:{ACCOUNT_ID}:parameter/test-2" ) with pytest.raises(ClientError) as ex: client.get_parameter(Name="test-2:2:3", WithDecryption=False) - ex.value.response["Error"]["Code"].should.equal("ParameterNotFound") - ex.value.response["Error"]["Message"].should.equal( - "Parameter test-2:2:3 not found." - ) + assert ex.value.response["Error"]["Code"] == "ParameterNotFound" + assert ex.value.response["Error"]["Message"] == ("Parameter test-2:2:3 not found.") with pytest.raises(ClientError) as ex: client.get_parameter(Name="test-2:2", WithDecryption=False) - ex.value.response["Error"]["Code"].should.equal("ParameterVersionNotFound") - ex.value.response["Error"]["Message"].should.equal( + assert ex.value.response["Error"]["Code"] == "ParameterVersionNotFound" + assert ex.value.response["Error"]["Message"] == ( "Systems Manager could not find version 2 of test-2. Verify the version and try again." ) with pytest.raises(ClientError) as ex: client.get_parameter(Name="test-3:2", WithDecryption=False) - ex.value.response["Error"]["Code"].should.equal("ParameterNotFound") - ex.value.response["Error"]["Message"].should.equal("Parameter test-3:2 not found.") + assert ex.value.response["Error"]["Code"] == "ParameterNotFound" + assert ex.value.response["Error"]["Message"] == "Parameter test-3:2 not found." @mock_ssm @@ -607,11 +598,11 @@ def test_get_parameters_errors(): with pytest.raises(ClientError) as e: client.get_parameters(Names=list(ssm_parameters.keys())) ex = e.value - ex.operation_name.should.equal("GetParameters") - ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.response["Error"]["Code"].should.contain("ValidationException") + assert ex.operation_name == "GetParameters" + assert ex.response["ResponseMetadata"]["HTTPStatusCode"] == 400 + assert "ValidationException" in ex.response["Error"]["Code"] all_keys = ", ".join(ssm_parameters.keys()) - ex.response["Error"]["Message"].should.equal( + assert ex.response["Error"]["Message"] == ( "1 validation error detected: " f"Value '[{all_keys}]' at 'names' failed to satisfy constraint: " "Member must have length less than or equal to 10." @@ -626,10 +617,8 @@ def test_get_nonexistant_parameter(): client.get_parameter(Name="test_noexist", WithDecryption=False) raise RuntimeError("Should have failed") except botocore.exceptions.ClientError as err: - err.operation_name.should.equal("GetParameter") - err.response["Error"]["Message"].should.equal( - "Parameter test_noexist not found." - ) + assert err.operation_name == "GetParameter" + assert err.response["Error"]["Message"] == "Parameter test_noexist not found." @mock_ssm @@ -647,11 +636,11 @@ def test_describe_parameters(): response = client.describe_parameters() parameters = response["Parameters"] - parameters.should.have.length_of(1) - parameters[0]["Name"].should.equal("test") - parameters[0]["Type"].should.equal("String") - parameters[0]["DataType"].should.equal("text") - parameters[0]["AllowedPattern"].should.equal(r".*") + assert len(parameters) == 1 + assert parameters[0]["Name"] == "test" + assert parameters[0]["Type"] == "String" + assert parameters[0]["DataType"] == "text" + assert parameters[0]["AllowedPattern"] == r".*" @mock_ssm @@ -662,28 +651,28 @@ def test_describe_parameters_paging(): client.put_parameter(Name=f"param-{i}", Value=f"value-{i}", Type="String") response = client.describe_parameters() - response["Parameters"].should.have.length_of(10) - response["NextToken"].should.equal("10") + assert len(response["Parameters"]) == 10 + assert response["NextToken"] == "10" response = client.describe_parameters(NextToken=response["NextToken"]) - response["Parameters"].should.have.length_of(10) - response["NextToken"].should.equal("20") + assert len(response["Parameters"]) == 10 + assert response["NextToken"] == "20" response = client.describe_parameters(NextToken=response["NextToken"]) - response["Parameters"].should.have.length_of(10) - response["NextToken"].should.equal("30") + assert len(response["Parameters"]) == 10 + assert response["NextToken"] == "30" response = client.describe_parameters(NextToken=response["NextToken"]) - response["Parameters"].should.have.length_of(10) - response["NextToken"].should.equal("40") + assert len(response["Parameters"]) == 10 + assert response["NextToken"] == "40" response = client.describe_parameters(NextToken=response["NextToken"]) - response["Parameters"].should.have.length_of(10) - response["NextToken"].should.equal("50") + assert len(response["Parameters"]) == 10 + assert response["NextToken"] == "50" response = client.describe_parameters(NextToken=response["NextToken"]) - response["Parameters"].should.have.length_of(0) - response.should_not.have.key("NextToken") + assert len(response["Parameters"]) == 0 + assert "NextToken" not in response @mock_ssm @@ -702,10 +691,10 @@ def test_describe_parameters_filter_names(): ) parameters = response["Parameters"] - parameters.should.have.length_of(1) - parameters[0]["Name"].should.equal("param-22") - parameters[0]["Type"].should.equal("String") - response.should_not.have.key("NextToken") + assert len(parameters) == 1 + assert parameters[0]["Name"] == "param-22" + assert parameters[0]["Type"] == "String" + assert "NextToken" not in response @mock_ssm @@ -724,9 +713,9 @@ def test_describe_parameters_filter_type(): ) parameters = response["Parameters"] - parameters.should.have.length_of(10) - parameters[0]["Type"].should.equal("SecureString") - response.should.have.key("NextToken").which.should.equal("10") + assert len(parameters) == 10 + assert parameters[0]["Type"] == "SecureString" + assert response["NextToken"] == "10" @mock_ssm @@ -745,10 +734,10 @@ def test_describe_parameters_filter_keyid(): ) parameters = response["Parameters"] - parameters.should.have.length_of(1) - parameters[0]["Name"].should.equal("param-10") - parameters[0]["Type"].should.equal("SecureString") - response.should_not.have.key("NextToken") + assert len(parameters) == 1 + assert parameters[0]["Name"] == "param-10" + assert parameters[0]["Type"] == "SecureString" + assert "NextToken" not in response @mock_ssm @@ -768,28 +757,28 @@ def test_describe_parameters_with_parameter_filters_keyid(): ) parameters = response["Parameters"] - parameters.should.have.length_of(1) - parameters[0]["Name"].should.equal("secure-param") - parameters[0]["Type"].should.equal("SecureString") - response.should_not.have.key("NextToken") + assert len(parameters) == 1 + assert parameters[0]["Name"] == "secure-param" + assert parameters[0]["Type"] == "SecureString" + assert "NextToken" not in response response = client.describe_parameters( ParameterFilters=[{"Key": "KeyId", "Values": ["alias/custom"]}] ) parameters = response["Parameters"] - parameters.should.have.length_of(1) - parameters[0]["Name"].should.equal("custom-secure-param") - parameters[0]["Type"].should.equal("SecureString") - response.should_not.have.key("NextToken") + assert len(parameters) == 1 + assert parameters[0]["Name"] == "custom-secure-param" + assert parameters[0]["Type"] == "SecureString" + assert "NextToken" not in response response = client.describe_parameters( ParameterFilters=[{"Key": "KeyId", "Option": "BeginsWith", "Values": ["alias"]}] ) parameters = response["Parameters"] - parameters.should.have.length_of(2) - response.should_not.have.key("NextToken") + assert len(parameters) == 2 + assert "NextToken" not in response @mock_ssm @@ -806,54 +795,54 @@ def test_describe_parameters_with_parameter_filters_name(): ) parameters = response["Parameters"] - parameters.should.have.length_of(1) - parameters[0]["Name"].should.equal("param") - parameters[0]["Type"].should.equal("String") - response.should_not.have.key("NextToken") + assert len(parameters) == 1 + assert parameters[0]["Name"] == "param" + assert parameters[0]["Type"] == "String" + assert "NextToken" not in response response = client.describe_parameters( ParameterFilters=[{"Key": "Name", "Values": ["/param"]}] ) parameters = response["Parameters"] - parameters.should.have.length_of(1) - parameters[0]["Name"].should.equal("param") - parameters[0]["Type"].should.equal("String") - response.should_not.have.key("NextToken") + assert len(parameters) == 1 + assert parameters[0]["Name"] == "param" + assert parameters[0]["Type"] == "String" + assert "NextToken" not in response response = client.describe_parameters( ParameterFilters=[{"Key": "Name", "Values": ["param-2"]}] ) parameters = response["Parameters"] - parameters.should.have.length_of(1) - parameters[0]["Name"].should.equal("/param-2") - parameters[0]["Type"].should.equal("String") - response.should_not.have.key("NextToken") + assert len(parameters) == 1 + assert parameters[0]["Name"] == "/param-2" + assert parameters[0]["Type"] == "String" + assert "NextToken" not in response response = client.describe_parameters( ParameterFilters=[{"Key": "Name", "Option": "BeginsWith", "Values": ["param"]}] ) parameters = response["Parameters"] - parameters.should.have.length_of(2) - response.should_not.have.key("NextToken") + assert len(parameters) == 2 + assert "NextToken" not in response response = client.describe_parameters( ParameterFilters=[{"Key": "Name", "Option": "Contains", "Values": ["ram"]}] ) parameters = response["Parameters"] - parameters.should.have.length_of(3) - response.should_not.have.key("NextToken") + assert len(parameters) == 3 + assert "NextToken" not in response response = client.describe_parameters( ParameterFilters=[{"Key": "Name", "Option": "Contains", "Values": ["/tan"]}] ) parameters = response["Parameters"] - parameters.should.have.length_of(2) - response.should_not.have.key("NextToken") + assert len(parameters) == 2 + assert "NextToken" not in response @mock_ssm @@ -874,40 +863,43 @@ def test_describe_parameters_with_parameter_filters_path(): ) parameters = response["Parameters"] - parameters.should.have.length_of(0) - response.should_not.have.key("NextToken") + assert len(parameters) == 0 + assert "NextToken" not in response response = client.describe_parameters( ParameterFilters=[{"Key": "Path", "Values": ["/"]}] ) parameters = response["Parameters"] - parameters.should.have.length_of(1) - parameters[0]["Name"].should.equal("foo") - parameters[0]["Type"].should.equal("String") - response.should_not.have.key("NextToken") + assert len(parameters) == 1 + assert parameters[0]["Name"] == "foo" + assert parameters[0]["Type"] == "String" + assert "NextToken" not in response response = client.describe_parameters( ParameterFilters=[{"Key": "Path", "Values": ["/", "/foo"]}] ) parameters = response["Parameters"] - parameters.should.have.length_of(3) - {parameter["Name"] for parameter in response["Parameters"]}.should.equal( - {"/foo/name1", "/foo/name2", "foo"} - ) - response.should_not.have.key("NextToken") + assert len(parameters) == 3 + assert {parameter["Name"] for parameter in response["Parameters"]} == { + "/foo/name1", + "/foo/name2", + "foo", + } + assert "NextToken" not in response response = client.describe_parameters( ParameterFilters=[{"Key": "Path", "Values": ["/foo/"]}] ) parameters = response["Parameters"] - parameters.should.have.length_of(2) - {parameter["Name"] for parameter in response["Parameters"]}.should.equal( - {"/foo/name1", "/foo/name2"} - ) - response.should_not.have.key("NextToken") + assert len(parameters) == 2 + assert {parameter["Name"] for parameter in response["Parameters"]} == { + "/foo/name1", + "/foo/name2", + } + assert "NextToken" not in response response = client.describe_parameters( ParameterFilters=[ @@ -916,26 +908,26 @@ def test_describe_parameters_with_parameter_filters_path(): ) parameters = response["Parameters"] - parameters.should.have.length_of(1) - parameters[0]["Name"].should.equal("/bar/name3/name4") - parameters[0]["Type"].should.equal("String") - response.should_not.have.key("NextToken") + assert len(parameters) == 1 + assert parameters[0]["Name"] == "/bar/name3/name4" + assert parameters[0]["Type"] == "String" + assert "NextToken" not in response response = client.describe_parameters( ParameterFilters=[{"Key": "Path", "Option": "Recursive", "Values": ["/fo"]}] ) parameters = response["Parameters"] - parameters.should.have.length_of(0) - response.should_not.have.key("NextToken") + assert len(parameters) == 0 + assert "NextToken" not in response response = client.describe_parameters( ParameterFilters=[{"Key": "Path", "Option": "Recursive", "Values": ["/"]}] ) parameters = response["Parameters"] - parameters.should.have.length_of(5) - response.should_not.have.key("NextToken") + assert len(parameters) == 5 + assert "NextToken" not in response response = client.describe_parameters( ParameterFilters=[ @@ -944,22 +936,26 @@ def test_describe_parameters_with_parameter_filters_path(): ) parameters = response["Parameters"] - parameters.should.have.length_of(4) - {parameter["Name"] for parameter in response["Parameters"]}.should.equal( - {"/foo/name1", "/foo/name2", "/bar/name3", "/bar/name3/name4"} - ) - response.should_not.have.key("NextToken") + assert len(parameters) == 4 + assert {parameter["Name"] for parameter in response["Parameters"]} == { + "/foo/name1", + "/foo/name2", + "/bar/name3", + "/bar/name3/name4", + } + assert "NextToken" not in response response = client.describe_parameters( ParameterFilters=[{"Key": "Path", "Option": "Recursive", "Values": ["/foo/"]}] ) parameters = response["Parameters"] - parameters.should.have.length_of(2) - {parameter["Name"] for parameter in response["Parameters"]}.should.equal( - {"/foo/name1", "/foo/name2"} - ) - response.should_not.have.key("NextToken") + assert len(parameters) == 2 + assert {parameter["Name"] for parameter in response["Parameters"]} == { + "/foo/name1", + "/foo/name2", + } + assert "NextToken" not in response response = client.describe_parameters( ParameterFilters=[ @@ -968,21 +964,22 @@ def test_describe_parameters_with_parameter_filters_path(): ) parameters = response["Parameters"] - parameters.should.have.length_of(1) - parameters[0]["Name"].should.equal("/bar/name3/name4") - parameters[0]["Type"].should.equal("String") - response.should_not.have.key("NextToken") + assert len(parameters) == 1 + assert parameters[0]["Name"] == "/bar/name3/name4" + assert parameters[0]["Type"] == "String" + assert "NextToken" not in response @mock_ssm def test_describe_parameters_needs_param(): client = boto3.client("ssm", region_name="us-east-1") - client.describe_parameters.when.called_with( - Filters=[{"Key": "Name", "Values": ["test"]}], - ParameterFilters=[{"Key": "Name", "Values": ["test"]}], - ).should.throw( - ClientError, - "You can use either Filters or ParameterFilters in a single request.", + with pytest.raises(ClientError) as client_err: + client.describe_parameters( + Filters=[{"Key": "Name", "Values": ["test"]}], + ParameterFilters=[{"Key": "Name", "Values": ["test"]}], + ) + assert client_err.value.response["Error"]["Message"] == ( + "You can use either Filters or ParameterFilters in a single request." ) @@ -991,7 +988,10 @@ def test_describe_parameters_needs_param(): [ ( [{"Key": "key"}], - "Member must satisfy regular expression pattern: tag:.+|Name|Type|KeyId|Path|Label|Tier", + ( + "Member must satisfy regular expression pattern: " + "tag:.+|Name|Type|KeyId|Path|Label|Tier" + ), ), ( [{"Key": "tag:" + "t" * 129}], @@ -1007,7 +1007,10 @@ def test_describe_parameters_needs_param(): ), ( [{"Key": "Name", "Values": ["t" * 1025]}], - "Member must have length less than or equal to 1024, Member must have length greater than or equal to 1", + ( + "Member must have length less than or equal to 1024, " + "Member must have length greater than or equal to 1" + ), ), ( [{"Key": "Name", "Option": "over 10 chars"}, {"Key": "key"}], @@ -1015,7 +1018,10 @@ def test_describe_parameters_needs_param(): ), ( [{"Key": "Label"}], - "The following filter key is not valid: Label. Valid filter keys include: [Path, Name, Type, KeyId, Tier]", + ( + "The following filter key is not valid: Label. Valid " + "filter keys include: [Path, Name, Type, KeyId, Tier]" + ), ), ( [{"Key": "Name"}], @@ -1026,27 +1032,45 @@ def test_describe_parameters_needs_param(): {"Key": "Name", "Values": ["test"]}, {"Key": "Name", "Values": ["test test"]}, ], - "The following filter is duplicated in the request: Name. A request can contain only one occurrence of a specific filter.", + ( + "The following filter is duplicated in the request: Name. " + "A request can contain only one occurrence of a specific filter." + ), ), ( [{"Key": "Path", "Values": ["/aws", "/ssm"]}], - 'Filters for common parameters can\'t be prefixed with "aws" or "ssm" (case-insensitive).', + ( + "Filters for common parameters can't be prefixed with " + '"aws" or "ssm" (case-insensitive).' + ), ), ( [{"Key": "Path", "Option": "Equals", "Values": ["test"]}], - "The following filter option is not valid: Equals. Valid options include: [Recursive, OneLevel]", + ( + "The following filter option is not valid: Equals. " + "Valid options include: [Recursive, OneLevel]" + ), ), ( [{"Key": "Tier", "Values": ["test"]}], - "The following filter value is not valid: test. Valid values include: [Standard, Advanced, Intelligent-Tiering]", + ( + "The following filter value is not valid: test. Valid " + "values include: [Standard, Advanced, Intelligent-Tiering]" + ), ), ( [{"Key": "Type", "Values": ["test"]}], - "The following filter value is not valid: test. Valid values include: [String, StringList, SecureString]", + ( + "The following filter value is not valid: test. Valid " + "values include: [String, StringList, SecureString]" + ), ), ( [{"Key": "Name", "Option": "option", "Values": ["test"]}], - "The following filter option is not valid: option. Valid options include: [BeginsWith, Equals].", + ( + "The following filter option is not valid: option. Valid " + "options include: [BeginsWith, Equals]." + ), ), ], ) @@ -1056,7 +1080,7 @@ def test_describe_parameters_invalid_parameter_filters(filters, error_msg): with pytest.raises(ClientError) as e: client.describe_parameters(ParameterFilters=filters) - e.value.response["Error"]["Message"].should.contain(error_msg) + assert error_msg in e.value.response["Error"]["Message"] @pytest.mark.parametrize("value", ["/###", "//", "test"]) @@ -1069,16 +1093,18 @@ def test_describe_parameters_invalid_path(value): ParameterFilters=[{"Key": "Path", "Values": [value]}] ) msg = e.value.response["Error"]["Message"] - msg.should.contain("The parameter doesn't meet the parameter name requirements") - msg.should.contain('The parameter name must begin with a forward slash "/".') - msg.should.contain('It can\'t be prefixed with "aws" or "ssm" (case-insensitive).') - msg.should.contain( - "It must use only letters, numbers, or the following symbols: . (period), - (hyphen), _ (underscore)." - ) - msg.should.contain( - 'Special characters are not allowed. All sub-paths, if specified, must use the forward slash symbol "/".' - ) - msg.should.contain("Valid example: /get/parameters2-/by1./path0_.") + assert "The parameter doesn't meet the parameter name requirements" in msg + assert 'The parameter name must begin with a forward slash "/".' in msg + assert 'It can\'t be prefixed with "aws" or "ssm" (case-insensitive).' in msg + assert ( + "It must use only letters, numbers, or the following symbols: . " + "(period), - (hyphen), _ (underscore)." + ) in msg + assert ( + "Special characters are not allowed. All sub-paths, if specified, " + 'must use the forward slash symbol "/".' + ) in msg + assert "Valid example: /get/parameters2-/by1./path0_." in msg @mock_ssm @@ -1094,15 +1120,15 @@ def test_describe_parameters_attributes(): response = client.describe_parameters() parameters = response["Parameters"] - parameters.should.have.length_of(2) + assert len(parameters) == 2 - parameters[0]["Description"].should.equal("my description") - parameters[0]["Version"].should.equal(1) - parameters[0]["LastModifiedDate"].should.be.a(datetime.date) - parameters[0]["LastModifiedUser"].should.equal("N/A") + assert parameters[0]["Description"] == "my description" + assert parameters[0]["Version"] == 1 + assert isinstance(parameters[0]["LastModifiedDate"], datetime.date) + assert parameters[0]["LastModifiedUser"] == "N/A" - parameters[1].should_not.have.key("Description") - parameters[1]["Version"].should.equal(1) + assert "Description" not in parameters[1] + assert parameters[1]["Version"] == 1 @mock_ssm @@ -1148,7 +1174,7 @@ def test_describe_parameters__multiple_tags(): {"Key": "tag:hello", "Option": "Equals", "Values": ["world"]}, ] ) - response["Parameters"].should.have.length_of(1) + assert len(response["Parameters"]) == 1 # Both params contains hello:world - ensure we also check the second tag, x=b response = client.describe_parameters( @@ -1157,19 +1183,29 @@ def test_describe_parameters__multiple_tags(): {"Key": "tag:x", "Option": "Equals", "Values": ["b"]}, ] ) - response["Parameters"].should.have.length_of(1) + assert len(response["Parameters"]) == 1 # tag begins_with should also work - client.describe_parameters( - ParameterFilters=[ - {"Key": "tag:hello", "Option": "BeginsWith", "Values": ["w"]}, - ] - )["Parameters"].should.have.length_of(2) - client.describe_parameters( - ParameterFilters=[ - {"Key": "tag:x", "Option": "BeginsWith", "Values": ["a"]}, - ] - )["Parameters"].should.have.length_of(1) + assert ( + len( + client.describe_parameters( + ParameterFilters=[ + {"Key": "tag:hello", "Option": "BeginsWith", "Values": ["w"]}, + ] + )["Parameters"] + ) + == 2 + ) + assert ( + len( + client.describe_parameters( + ParameterFilters=[ + {"Key": "tag:x", "Option": "BeginsWith", "Values": ["a"]}, + ] + )["Parameters"] + ) + == 1 + ) @mock_ssm @@ -1218,9 +1254,9 @@ def test_get_parameter_invalid(): client = client = boto3.client("ssm", region_name="us-east-1") response = client.get_parameters(Names=["invalid"], WithDecryption=False) - len(response["Parameters"]).should.equal(0) - len(response["InvalidParameters"]).should.equal(1) - response["InvalidParameters"][0].should.equal("invalid") + assert len(response["Parameters"]) == 0 + assert len(response["InvalidParameters"]) == 1 + assert response["InvalidParameters"][0] == "invalid" @mock_ssm @@ -1233,17 +1269,17 @@ def test_put_parameter_secure_default_kms(): response = client.get_parameters(Names=["test"], WithDecryption=False) - len(response["Parameters"]).should.equal(1) - response["Parameters"][0]["Name"].should.equal("test") - response["Parameters"][0]["Value"].should.equal("kms:alias/aws/ssm:value") - response["Parameters"][0]["Type"].should.equal("SecureString") + assert len(response["Parameters"]) == 1 + assert response["Parameters"][0]["Name"] == "test" + assert response["Parameters"][0]["Value"] == "kms:alias/aws/ssm:value" + assert response["Parameters"][0]["Type"] == "SecureString" response = client.get_parameters(Names=["test"], WithDecryption=True) - len(response["Parameters"]).should.equal(1) - response["Parameters"][0]["Name"].should.equal("test") - response["Parameters"][0]["Value"].should.equal("value") - response["Parameters"][0]["Type"].should.equal("SecureString") + assert len(response["Parameters"]) == 1 + assert response["Parameters"][0]["Name"] == "test" + assert response["Parameters"][0]["Value"] == "value" + assert response["Parameters"][0]["Type"] == "SecureString" @mock_ssm @@ -1260,17 +1296,17 @@ def test_put_parameter_secure_custom_kms(): response = client.get_parameters(Names=["test"], WithDecryption=False) - len(response["Parameters"]).should.equal(1) - response["Parameters"][0]["Name"].should.equal("test") - response["Parameters"][0]["Value"].should.equal("kms:foo:value") - response["Parameters"][0]["Type"].should.equal("SecureString") + assert len(response["Parameters"]) == 1 + assert response["Parameters"][0]["Name"] == "test" + assert response["Parameters"][0]["Value"] == "kms:foo:value" + assert response["Parameters"][0]["Type"] == "SecureString" response = client.get_parameters(Names=["test"], WithDecryption=True) - len(response["Parameters"]).should.equal(1) - response["Parameters"][0]["Name"].should.equal("test") - response["Parameters"][0]["Value"].should.equal("value") - response["Parameters"][0]["Type"].should.equal("SecureString") + assert len(response["Parameters"]) == 1 + assert response["Parameters"][0]["Name"] == "test" + assert response["Parameters"][0]["Value"] == "value" + assert response["Parameters"][0]["Type"] == "SecureString" @mock_ssm @@ -1292,14 +1328,14 @@ def test_get_parameter_history(): parameters_response = response["Parameters"] for index, param in enumerate(parameters_response): - param["Name"].should.equal(test_parameter_name) - param["Type"].should.equal("String") - param["Value"].should.equal(f"value-{index}") - param["Version"].should.equal(index + 1) - param["Description"].should.equal(f"A test parameter version {index}") - param["Labels"].should.equal([]) + assert param["Name"] == test_parameter_name + assert param["Type"] == "String" + assert param["Value"] == f"value-{index}" + assert param["Version"] == index + 1 + assert param["Description"] == f"A test parameter version {index}" + assert param["Labels"] == [] - len(parameters_response).should.equal(3) + assert len(parameters_response) == 3 @mock_ssm @@ -1324,19 +1360,19 @@ def test_get_parameter_history_with_secure_string(): parameters_response = response["Parameters"] for index, param in enumerate(parameters_response): - param["Name"].should.equal(test_parameter_name) - param["Type"].should.equal("SecureString") + assert param["Name"] == test_parameter_name + assert param["Type"] == "SecureString" expected_plaintext_value = f"value-{index}" if with_decryption: - param["Value"].should.equal(expected_plaintext_value) + assert param["Value"] == expected_plaintext_value else: - param["Value"].should.equal( + assert param["Value"] == ( f"kms:alias/aws/ssm:{expected_plaintext_value}" ) - param["Version"].should.equal(index + 1) - param["Description"].should.equal(f"A test parameter version {index}") + assert param["Version"] == index + 1 + assert param["Description"] == f"A test parameter version {index}" - len(parameters_response).should.equal(3) + assert len(parameters_response) == 3 @mock_ssm @@ -1354,8 +1390,8 @@ def test_label_parameter_version(): response = client.label_parameter_version( Name=test_parameter_name, Labels=["test-label"] ) - response["InvalidLabels"].should.equal([]) - response["ParameterVersion"].should.equal(1) + assert response["InvalidLabels"] == [] + assert response["ParameterVersion"] == 1 @mock_ssm @@ -1373,8 +1409,8 @@ def test_label_parameter_version_with_specific_version(): response = client.label_parameter_version( Name=test_parameter_name, ParameterVersion=1, Labels=["test-label"] ) - response["InvalidLabels"].should.equal([]) - response["ParameterVersion"].should.equal(1) + assert response["InvalidLabels"] == [] + assert response["ParameterVersion"] == 1 @mock_ssm @@ -1393,17 +1429,17 @@ def test_label_parameter_version_twice(): response = client.label_parameter_version( Name=test_parameter_name, ParameterVersion=1, Labels=test_labels ) - response["InvalidLabels"].should.equal([]) - response["ParameterVersion"].should.equal(1) + assert response["InvalidLabels"] == [] + assert response["ParameterVersion"] == 1 response = client.label_parameter_version( Name=test_parameter_name, ParameterVersion=1, Labels=test_labels ) - response["InvalidLabels"].should.equal([]) - response["ParameterVersion"].should.equal(1) + assert response["InvalidLabels"] == [] + assert response["ParameterVersion"] == 1 response = client.get_parameter_history(Name=test_parameter_name) - len(response["Parameters"]).should.equal(1) - response["Parameters"][0]["Labels"].should.equal(test_labels) + assert len(response["Parameters"]) == 1 + assert response["Parameters"][0]["Labels"] == test_labels @mock_ssm @@ -1425,27 +1461,27 @@ def test_label_parameter_moving_versions(): response = client.label_parameter_version( Name=test_parameter_name, ParameterVersion=1, Labels=test_labels ) - response["InvalidLabels"].should.equal([]) - response["ParameterVersion"].should.equal(1) + assert response["InvalidLabels"] == [] + assert response["ParameterVersion"] == 1 response = client.label_parameter_version( Name=test_parameter_name, ParameterVersion=2, Labels=test_labels ) - response["InvalidLabels"].should.equal([]) - response["ParameterVersion"].should.equal(2) + assert response["InvalidLabels"] == [] + assert response["ParameterVersion"] == 2 response = client.get_parameter_history(Name=test_parameter_name) parameters_response = response["Parameters"] for index, param in enumerate(parameters_response): - param["Name"].should.equal(test_parameter_name) - param["Type"].should.equal("String") - param["Value"].should.equal(f"value-{index}") - param["Version"].should.equal(index + 1) - param["Description"].should.equal(f"A test parameter version {index}") + assert param["Name"] == test_parameter_name + assert param["Type"] == "String" + assert param["Value"] == f"value-{index}" + assert param["Version"] == index + 1 + assert param["Description"] == f"A test parameter version {index}" labels = test_labels if param["Version"] == 2 else [] - param["Labels"].should.equal(labels) + assert param["Labels"] == labels - len(parameters_response).should.equal(3) + assert len(parameters_response) == 3 @mock_ssm @@ -1468,33 +1504,33 @@ def test_label_parameter_moving_versions_complex(): ParameterVersion=1, Labels=["test-label1", "test-label2", "test-label3"], ) - response["InvalidLabels"].should.equal([]) - response["ParameterVersion"].should.equal(1) + assert response["InvalidLabels"] == [] + assert response["ParameterVersion"] == 1 response = client.label_parameter_version( Name=test_parameter_name, ParameterVersion=2, Labels=["test-label2", "test-label3"], ) - response["InvalidLabels"].should.equal([]) - response["ParameterVersion"].should.equal(2) + assert response["InvalidLabels"] == [] + assert response["ParameterVersion"] == 2 response = client.get_parameter_history(Name=test_parameter_name) parameters_response = response["Parameters"] for index, param in enumerate(parameters_response): - param["Name"].should.equal(test_parameter_name) - param["Type"].should.equal("String") - param["Value"].should.equal(f"value-{index}") - param["Version"].should.equal(index + 1) - param["Description"].should.equal(f"A test parameter version {index}") + assert param["Name"] == test_parameter_name + assert param["Type"] == "String" + assert param["Value"] == f"value-{index}" + assert param["Version"] == index + 1 + assert param["Description"] == f"A test parameter version {index}" labels = ( ["test-label2", "test-label3"] if param["Version"] == 2 else (["test-label1"] if param["Version"] == 1 else []) ) - param["Labels"].should.equal(labels) + assert param["Labels"] == labels - len(parameters_response).should.equal(3) + assert len(parameters_response) == 3 @mock_ssm @@ -1522,13 +1558,15 @@ def test_label_parameter_version_exception_ten_labels_at_once(): Value="value", Type="String", ) - client.label_parameter_version.when.called_with( - Name="test", ParameterVersion=1, Labels=test_labels - ).should.throw( - ClientError, - "An error occurred (ParameterVersionLabelLimitExceeded) when calling the LabelParameterVersion operation: " + with pytest.raises(ClientError) as client_err: + client.label_parameter_version( + Name="test", ParameterVersion=1, Labels=test_labels + ) + assert client_err.value.response["Error"]["Message"] == ( + "An error occurred (ParameterVersionLabelLimitExceeded) when " + "calling the LabelParameterVersion operation: " "A parameter version can have maximum 10 labels." - "Move one or more labels to another version and try again.", + "Move one or more labels to another version and try again." ) @@ -1555,22 +1593,24 @@ def test_label_parameter_version_exception_ten_labels_over_multiple_calls(): "test-label5", ], ) - client.label_parameter_version.when.called_with( - Name="test", - ParameterVersion=1, - Labels=[ - "test-label6", - "test-label7", - "test-label8", - "test-label9", - "test-label10", - "test-label11", - ], - ).should.throw( - ClientError, - "An error occurred (ParameterVersionLabelLimitExceeded) when calling the LabelParameterVersion operation: " + with pytest.raises(ClientError) as client_err: + client.label_parameter_version( + Name="test", + ParameterVersion=1, + Labels=[ + "test-label6", + "test-label7", + "test-label8", + "test-label9", + "test-label10", + "test-label11", + ], + ) + assert client_err.value.response["Error"]["Message"] == ( + "An error occurred (ParameterVersionLabelLimitExceeded) when " + "calling the LabelParameterVersion operation: " "A parameter version can have maximum 10 labels." - "Move one or more labels to another version and try again.", + "Move one or more labels to another version and try again." ) @@ -1580,13 +1620,9 @@ def test_label_parameter_version_invalid_name(): test_parameter_name = "test" - client.label_parameter_version.when.called_with( - Name=test_parameter_name, Labels=["test-label"] - ).should.throw( - ClientError, - "An error occurred (ParameterNotFound) when calling the LabelParameterVersion operation: " - "Parameter test not found.", - ) + with pytest.raises(ClientError) as client_err: + client.label_parameter_version(Name=test_parameter_name, Labels=["test-label"]) + assert client_err.value.response["Error"]["Message"] == "Parameter test not found." @mock_ssm @@ -1601,13 +1637,13 @@ def test_label_parameter_version_invalid_parameter_version(): Type="String", ) - client.label_parameter_version.when.called_with( - Name=test_parameter_name, Labels=["test-label"], ParameterVersion=5 - ).should.throw( - ClientError, - "An error occurred (ParameterVersionNotFound) when calling the LabelParameterVersion operation: " + with pytest.raises(ClientError) as client_err: + client.label_parameter_version( + Name=test_parameter_name, Labels=["test-label"], ParameterVersion=5 + ) + assert client_err.value.response["Error"]["Message"] == ( "Systems Manager could not find version 5 of test. " - "Verify the version and try again.", + "Verify the version and try again." ) @@ -1625,32 +1661,34 @@ def test_label_parameter_version_invalid_label(): response = client.label_parameter_version( Name=test_parameter_name, ParameterVersion=1, Labels=["awsabc"] ) - response["InvalidLabels"].should.equal(["awsabc"]) + assert response["InvalidLabels"] == ["awsabc"] response = client.label_parameter_version( Name=test_parameter_name, ParameterVersion=1, Labels=["ssmabc"] ) - response["InvalidLabels"].should.equal(["ssmabc"]) + assert response["InvalidLabels"] == ["ssmabc"] response = client.label_parameter_version( Name=test_parameter_name, ParameterVersion=1, Labels=["9abc"] ) - response["InvalidLabels"].should.equal(["9abc"]) + assert response["InvalidLabels"] == ["9abc"] response = client.label_parameter_version( Name=test_parameter_name, ParameterVersion=1, Labels=["abc/123"] ) - response["InvalidLabels"].should.equal(["abc/123"]) + assert response["InvalidLabels"] == ["abc/123"] long_name = "a" * 101 - client.label_parameter_version.when.called_with( - Name=test_parameter_name, ParameterVersion=1, Labels=[long_name] - ).should.throw( - ClientError, + with pytest.raises(ClientError) as client_err: + client.label_parameter_version( + Name=test_parameter_name, ParameterVersion=1, Labels=[long_name] + ) + assert client_err.value.response["Error"]["Message"] == ( "1 validation error detected: " f"Value '[{long_name}]' at 'labels' failed to satisfy constraint: " "Member must satisfy constraint: " - "[Member must have length less than or equal to 100, Member must have length greater than or equal to 1]", + "[Member must have length less than or equal to 100, Member must " + "have length greater than or equal to 1]" ) @@ -1678,15 +1716,15 @@ def test_get_parameter_history_with_label(): parameters_response = response["Parameters"] for index, param in enumerate(parameters_response): - param["Name"].should.equal(test_parameter_name) - param["Type"].should.equal("String") - param["Value"].should.equal(f"value-{index}") - param["Version"].should.equal(index + 1) - param["Description"].should.equal(f"A test parameter version {index}") + assert param["Name"] == test_parameter_name + assert param["Type"] == "String" + assert param["Value"] == f"value-{index}" + assert param["Version"] == index + 1 + assert param["Description"] == f"A test parameter version {index}" labels = test_labels if param["Version"] == 1 else [] - param["Labels"].should.equal(labels) + assert param["Labels"] == labels - len(parameters_response).should.equal(3) + assert len(parameters_response) == 3 @mock_ssm @@ -1713,15 +1751,15 @@ def test_get_parameter_history_with_label_non_latest(): parameters_response = response["Parameters"] for index, param in enumerate(parameters_response): - param["Name"].should.equal(test_parameter_name) - param["Type"].should.equal("String") - param["Value"].should.equal(f"value-{index}") - param["Version"].should.equal(index + 1) - param["Description"].should.equal(f"A test parameter version {index}") + assert param["Name"] == test_parameter_name + assert param["Type"] == "String" + assert param["Value"] == f"value-{index}" + assert param["Version"] == index + 1 + assert param["Description"] == f"A test parameter version {index}" labels = test_labels if param["Version"] == 2 else [] - param["Labels"].should.equal(labels) + assert param["Labels"] == labels - len(parameters_response).should.equal(3) + assert len(parameters_response) == 3 @mock_ssm @@ -1746,15 +1784,15 @@ def test_get_parameter_history_with_label_latest_assumed(): parameters_response = response["Parameters"] for index, param in enumerate(parameters_response): - param["Name"].should.equal(test_parameter_name) - param["Type"].should.equal("String") - param["Value"].should.equal(f"value-{index}") - param["Version"].should.equal(index + 1) - param["Description"].should.equal(f"A test parameter version {index}") + assert param["Name"] == test_parameter_name + assert param["Type"] == "String" + assert param["Value"] == f"value-{index}" + assert param["Version"] == index + 1 + assert param["Description"] == f"A test parameter version {index}" labels = test_labels if param["Version"] == 3 else [] - param["Labels"].should.equal(labels) + assert param["Labels"] == labels - len(parameters_response).should.equal(3) + assert len(parameters_response) == 3 @mock_ssm @@ -1765,10 +1803,8 @@ def test_get_parameter_history_missing_parameter(): client.get_parameter_history(Name="test_noexist") raise RuntimeError("Should have failed") except botocore.exceptions.ClientError as err: - err.operation_name.should.equal("GetParameterHistory") - err.response["Error"]["Message"].should.equal( - "Parameter test_noexist not found." - ) + assert err.operation_name == "GetParameterHistory" + assert err.response["Error"]["Message"] == "Parameter test_noexist not found." @mock_ssm @@ -1793,9 +1829,9 @@ def test_add_remove_list_tags_for_resource(): response = client.list_tags_for_resource( ResourceId="test", ResourceType="Parameter" ) - len(response["TagList"]).should.equal(1) - response["TagList"][0]["Key"].should.equal("test-key") - response["TagList"][0]["Value"].should.equal("test-value") + assert len(response["TagList"]) == 1 + assert response["TagList"][0]["Key"] == "test-key" + assert response["TagList"][0]["Value"] == "test-value" client.remove_tags_from_resource( ResourceId="test", ResourceType="Parameter", TagKeys=["test-key"] @@ -1804,7 +1840,7 @@ def test_add_remove_list_tags_for_resource(): response = client.list_tags_for_resource( ResourceId="test", ResourceType="Parameter" ) - len(response["TagList"]).should.equal(0) + assert len(response["TagList"]) == 0 @mock_ssm @@ -1830,17 +1866,17 @@ def test_send_command(): ) cmd = response["Command"] - cmd["CommandId"].should_not.be(None) + assert cmd["CommandId"] is not None assert cmd["Comment"] == "some comment" - cmd["DocumentName"].should.equal(ssm_document) - cmd["Parameters"].should.equal(params) + assert cmd["DocumentName"] == ssm_document + assert cmd["Parameters"] == params - cmd["OutputS3Region"].should.equal("us-east-2") - cmd["OutputS3BucketName"].should.equal("the-bucket") - cmd["OutputS3KeyPrefix"].should.equal("pref") + assert cmd["OutputS3Region"] == "us-east-2" + assert cmd["OutputS3BucketName"] == "the-bucket" + assert cmd["OutputS3KeyPrefix"] == "pref" - cmd["ExpiresAfter"].should.be.greater_than(before) - cmd["DeliveryTimedOutCount"].should.equal(0) + assert cmd["ExpiresAfter"] > before + assert cmd["DeliveryTimedOutCount"] == 0 assert cmd["TimeoutSeconds"] == 42 assert cmd["MaxConcurrency"] == "360" @@ -1851,8 +1887,8 @@ def test_send_command(): cmd = response["Command"] - cmd["CommandId"].should_not.be(None) - cmd["DocumentName"].should.equal(ssm_document) + assert cmd["CommandId"] is not None + assert cmd["DocumentName"] == ssm_document @mock_ssm @@ -1878,8 +1914,8 @@ def test_list_commands(): response = client.list_commands(CommandId=cmd_id) cmds = response["Commands"] - len(cmds).should.equal(1) - cmds[0]["CommandId"].should.equal(cmd_id) + assert len(cmds) == 1 + assert cmds[0]["CommandId"] == cmd_id # add another command with the same instance id to test listing by # instance id @@ -1888,11 +1924,11 @@ def test_list_commands(): response = client.list_commands(InstanceId="i-123456") cmds = response["Commands"] - len(cmds).should.equal(2) + assert len(cmds) == 2 for cmd in cmds: - cmd["InstanceIds"].should.contain("i-123456") - cmd.should.have.key("DeliveryTimedOutCount").equals(0) + assert "i-123456" in cmd["InstanceIds"] + assert cmd["DeliveryTimedOutCount"] == 0 # test the error case for an invalid command id with pytest.raises(ClientError): @@ -1923,8 +1959,8 @@ def test_get_command_invocation(): CommandId=cmd_id, InstanceId=instance_id, PluginName="aws:runShellScript" ) - invocation_response["CommandId"].should.equal(cmd_id) - invocation_response["InstanceId"].should.equal(instance_id) + assert invocation_response["CommandId"] == cmd_id + assert invocation_response["InstanceId"] == instance_id # test the error case for an invalid instance id with pytest.raises(ClientError): @@ -1957,7 +1993,7 @@ def test_get_command_invocations_by_instance_tag(): instance_ids = [] for instance in resp["Instances"]: instance_ids.append(instance["InstanceId"]) - instance_ids.should.have.length_of(num_instances) + assert len(instance_ids) == num_instances command_id = ssm.send_command( DocumentName="AWS-RunShellScript", @@ -1965,11 +2001,11 @@ def test_get_command_invocations_by_instance_tag(): )["Command"]["CommandId"] resp = ssm.list_commands(CommandId=command_id) - resp["Commands"][0]["TargetCount"].should.equal(num_instances) + assert resp["Commands"][0]["TargetCount"] == num_instances for instance_id in instance_ids: resp = ssm.get_command_invocation(CommandId=command_id, InstanceId=instance_id) - resp["Status"].should.equal("Success") + assert resp["Status"] == "Success" @mock_ssm @@ -1990,11 +2026,11 @@ def test_parameter_version_limit(): item for page in page_iterator for item in page["Parameters"] ) - len(parameter_history).should.equal(PARAMETER_VERSION_LIMIT) - parameter_history[0]["Value"].should.equal("value-2") + assert len(parameter_history) == PARAMETER_VERSION_LIMIT + assert parameter_history[0]["Value"] == "value-2" latest_version_index = PARAMETER_VERSION_LIMIT - 1 latest_version_value = f"value-{PARAMETER_VERSION_LIMIT + 1}" - parameter_history[latest_version_index]["Value"].should.equal(latest_version_value) + assert parameter_history[latest_version_index]["Value"] == latest_version_value @mock_ssm @@ -2017,11 +2053,16 @@ def test_parameter_overwrite_fails_when_limit_reached_and_oldest_version_has_lab Name=parameter_name, Value="new-value", Type="String", Overwrite=True ) error = ex.value.response["Error"] - error["Code"].should.equal("ParameterMaxVersionLimitExceeded") - error["Message"].should.contain(parameter_name) - error["Message"].should.contain("Version 1") - error["Message"].should.match( - r"the oldest version, can't be deleted because it has a label associated with it. Move the label to another version of the parameter, and try again." + assert error["Code"] == "ParameterMaxVersionLimitExceeded" + assert parameter_name in error["Message"] + assert "Version 1" in error["Message"] + assert re.search( + ( + r"the oldest version, can't be deleted because it has a label " + "associated with it. Move the label to another version of the " + "parameter, and try again." + ), + error["Message"], ) @@ -2046,15 +2087,13 @@ def test_get_parameters_includes_invalid_parameter_when_requesting_invalid_versi ] ) - len(response["InvalidParameters"]).should.equal(1) - response["InvalidParameters"][0].should.equal( - f"test-param:{versions_to_create + 1}" - ) + assert len(response["InvalidParameters"]) == 1 + assert response["InvalidParameters"][0] == f"test-param:{versions_to_create + 1}" - len(response["Parameters"]).should.equal(1) - response["Parameters"][0]["Name"].should.equal("test-param") - response["Parameters"][0]["Value"].should.equal("value-4") - response["Parameters"][0]["Type"].should.equal("String") + assert len(response["Parameters"]) == 1 + assert response["Parameters"][0]["Name"] == "test-param" + assert response["Parameters"][0]["Value"] == "value-4" + assert response["Parameters"][0]["Type"] == "String" @mock_ssm @@ -2084,10 +2123,10 @@ def test_get_parameters_includes_invalid_parameter_when_requesting_invalid_label ] ) - len(response["InvalidParameters"]).should.equal(1) - response["InvalidParameters"][0].should.equal("test-param:invalid-label") + assert len(response["InvalidParameters"]) == 1 + assert response["InvalidParameters"][0] == "test-param:invalid-label" - len(response["Parameters"]).should.equal(3) + assert len(response["Parameters"]) == 3 @mock_ssm @@ -2099,7 +2138,7 @@ def test_get_parameters_should_only_return_unique_requests(): response = client.get_parameters(Names=["test-param", "test-param"]) - len(response["Parameters"]).should.equal(1) + assert len(response["Parameters"]) == 1 @mock_ssm @@ -2118,10 +2157,11 @@ def test_get_parameter_history_should_throw_exception_when_MaxResults_is_too_lar ) error = ex.value.response["Error"] - error["Code"].should.equal("ValidationException") - error["Message"].should.equal( + assert error["Code"] == "ValidationException" + assert error["Message"] == ( "1 validation error detected: " - f"Value '{PARAMETER_HISTORY_MAX_RESULTS + 1}' at 'maxResults' failed to satisfy constraint: " + f"Value '{PARAMETER_HISTORY_MAX_RESULTS + 1}' at 'maxResults' " + "failed to satisfy constraint: " "Member must have value less than or equal to 50." ) @@ -2150,7 +2190,7 @@ def test_get_parameter_history_NextTokenImplementation(): param_history.extend(response["Parameters"]) next_token = response.get("NextToken", None) - len(param_history).should.equal(100) + assert len(param_history) == 100 @mock_ssm @@ -2161,5 +2201,5 @@ def test_get_parameter_history_exception_when_requesting_invalid_parameter(): client.get_parameter_history(Name="invalid_parameter_name") error = ex.value.response["Error"] - error["Code"].should.equal("ParameterNotFound") - error["Message"].should.equal("Parameter invalid_parameter_name not found.") + assert error["Code"] == "ParameterNotFound" + assert error["Message"] == "Parameter invalid_parameter_name not found." diff --git a/tests/test_ssm/test_ssm_cloudformation.py b/tests/test_ssm/test_ssm_cloudformation.py index b1922027f..ff7e42abb 100644 --- a/tests/test_ssm/test_ssm_cloudformation.py +++ b/tests/test_ssm/test_ssm_cloudformation.py @@ -1,6 +1,6 @@ -import boto3 import json +import boto3 from moto import mock_ssm, mock_cloudformation from tests import EXAMPLE_AMI_ID diff --git a/tests/test_ssm/test_ssm_default_amis.py b/tests/test_ssm/test_ssm_default_amis.py index 252beb9d2..d64f1c79e 100644 --- a/tests/test_ssm/test_ssm_default_amis.py +++ b/tests/test_ssm/test_ssm_default_amis.py @@ -1,5 +1,4 @@ import boto3 -import sure # noqa # pylint: disable=unused-import from moto import mock_ssm @@ -12,14 +11,14 @@ def test_ssm_get_latest_ami_by_path(): client = boto3.client("ssm", region_name="us-west-1") path = "/aws/service/ami-amazon-linux-latest" params = client.get_parameters_by_path(Path=path)["Parameters"] - params.should.have.length_of(10) + assert len(params) == 10 assert all( - [p["Name"].startswith("/aws/service/ami-amazon-linux-latest") for p in params] + {p["Name"].startswith("/aws/service/ami-amazon-linux-latest") for p in params} ) - assert all([p["Type"] == "String" for p in params]) - assert all([p["DataType"] == "text" for p in params]) - assert all([p["ARN"].startswith("arn:aws:ssm:us-west-1") for p in params]) + assert all({p["Type"] == "String" for p in params}) + assert all({p["DataType"] == "text" for p in params}) + assert all({p["ARN"].startswith("arn:aws:ssm:us-west-1") for p in params}) @mock_ssm @@ -30,4 +29,4 @@ def test_ssm_latest_amis_are_different_in_regions(): client = boto3.client("ssm", region_name="eu-north-1") ami_eunorth = client.get_parameter(Name=test_ami)["Parameter"]["Value"] - ami_uswest.shouldnt.equal(ami_eunorth) + assert ami_uswest != ami_eunorth diff --git a/tests/test_ssm/test_ssm_defaults.py b/tests/test_ssm/test_ssm_defaults.py index 7b06b401c..a1eeca440 100644 --- a/tests/test_ssm/test_ssm_defaults.py +++ b/tests/test_ssm/test_ssm_defaults.py @@ -1,5 +1,4 @@ import boto3 -import sure # noqa # pylint: disable=unused-import from moto import mock_ssm from moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID @@ -12,15 +11,14 @@ def test_ssm_get_by_path(): params = client.get_parameters_by_path(Path=path)["Parameters"] pacific = [p for p in params if p["Value"] == "af-south-1"][0] - pacific["Name"].should.equal( - "/aws/service/global-infrastructure/regions/af-south-1" + assert pacific["Name"] == "/aws/service/global-infrastructure/regions/af-south-1" + assert pacific["Type"] == "String" + assert pacific["Version"] == 1 + assert pacific["ARN"] == ( + f"arn:aws:ssm:us-west-1:{ACCOUNT_ID}:parameter/aws/service" + "/global-infrastructure/regions/af-south-1" ) - pacific["Type"].should.equal("String") - pacific["Version"].should.equal(1) - pacific["ARN"].should.equal( - f"arn:aws:ssm:us-west-1:{ACCOUNT_ID}:parameter/aws/service/global-infrastructure/regions/af-south-1" - ) - pacific.should.have.key("LastModifiedDate") + assert "LastModifiedDate" in pacific @mock_ssm @@ -28,7 +26,7 @@ def test_global_infrastructure_services(): client = boto3.client("ssm", region_name="us-west-1") path = "/aws/service/global-infrastructure/services" params = client.get_parameters_by_path(Path=path)["Parameters"] - params[0]["Name"].should.equal( + assert params[0]["Name"] == ( "/aws/service/global-infrastructure/services/accessanalyzer" ) @@ -41,5 +39,4 @@ def test_ssm_region_query(): ) value = param["Parameter"]["Value"] - - value.should.equal("US West (N. California)") + assert value == "US West (N. California)" diff --git a/tests/test_ssm/test_ssm_doc_permissions.py b/tests/test_ssm/test_ssm_doc_permissions.py index e44cacd8d..af0ac18a7 100644 --- a/tests/test_ssm/test_ssm_doc_permissions.py +++ b/tests/test_ssm/test_ssm_doc_permissions.py @@ -1,8 +1,10 @@ -import boto3 -import pytest +import re import yaml +import boto3 from botocore.exceptions import ClientError +import pytest + from moto import mock_ssm from .test_ssm_docs import _get_yaml_template @@ -16,8 +18,8 @@ def test_describe_document_permissions_unknown_document(): Name="UnknownDocument", PermissionType="Share" ) err = ex.value.response["Error"] - err["Code"].should.equal("InvalidDocument") - err["Message"].should.equal("The specified document does not exist.") + assert err["Code"] == "InvalidDocument" + assert err["Message"] == "The specified document does not exist." def get_client(): @@ -41,8 +43,8 @@ def test_describe_document_permissions_initial(): res = client.describe_document_permission( Name="TestDocument", PermissionType="Share" ) - res.should.have.key("AccountIds").equal([]) - res.should.have.key("AccountSharingInfoList").equal([]) + assert res["AccountIds"] == [] + assert res["AccountSharingInfoList"] == [] @pytest.mark.parametrize( @@ -60,14 +62,14 @@ def test_modify_document_permission_add_account_id(ids): res = client.describe_document_permission( Name="TestDocument", PermissionType="Share" ) - res.should.have.key("AccountIds") - set(res["AccountIds"]).should.equal(set(ids)) - res.should.have.key("AccountSharingInfoList").length_of(len(ids)) + assert "AccountIds" in res + assert set(res["AccountIds"]) == set(ids) + assert len(res["AccountSharingInfoList"]) == len(ids) expected_account_sharing = [ {"AccountId": _id, "SharedDocumentVersion": "$DEFAULT"} for _id in ids ] - res.should.have.key("AccountSharingInfoList").equal(expected_account_sharing) + assert res["AccountSharingInfoList"] == expected_account_sharing @pytest.mark.parametrize( @@ -96,15 +98,15 @@ def test_modify_document_permission_remove_account_id(initial, to_remove): res = client.describe_document_permission( Name="TestDocument", PermissionType="Share" ) - res.should.have.key("AccountIds") - expected_new_list = set([x for x in initial if x not in to_remove]) - set(res["AccountIds"]).should.equal(expected_new_list) + assert "AccountIds" in res + expected_new_list = {x for x in initial if x not in to_remove} + assert set(res["AccountIds"]) == expected_new_list expected_account_sharing = [ {"AccountId": _id, "SharedDocumentVersion": "$DEFAULT"} for _id in expected_new_list ] - res.should.have.key("AccountSharingInfoList").equal(expected_account_sharing) + assert res["AccountSharingInfoList"] == expected_account_sharing @mock_ssm @@ -115,8 +117,8 @@ def test_fail_modify_document_permission_wrong_permission_type(): Name="TestDocument", PermissionType="WrongValue", AccountIdsToAdd=[] ) err = ex.value.response["Error"] - err["Code"].should.equal("InvalidPermissionType") - err["Message"].should.match(r"Member must satisfy enum value set: \[Share\]") + assert err["Code"] == "InvalidPermissionType" + assert re.search(r"Member must satisfy enum value set: \[Share\]", err["Message"]) @mock_ssm @@ -130,8 +132,8 @@ def test_fail_modify_document_permission_wrong_document_version(): AccountIdsToAdd=[], ) err = ex.value.response["Error"] - err["Code"].should.equal("ValidationException") - err["Message"].should.match(r"Member must satisfy regular expression pattern") + assert err["Code"] == "ValidationException" + assert re.search(r"Member must satisfy regular expression pattern", err["Message"]) @pytest.mark.parametrize( @@ -147,8 +149,8 @@ def test_fail_modify_document_permission_add_invalid_account_ids(value): Name="TestDocument", PermissionType="Share", AccountIdsToAdd=value ) err = ex.value.response["Error"] - err["Code"].should.equal("ValidationException") - err["Message"].should.match(r"Member must satisfy regular expression pattern:") + assert err["Code"] == "ValidationException" + assert re.search(r"Member must satisfy regular expression pattern:", err["Message"]) @pytest.mark.parametrize( @@ -164,8 +166,8 @@ def test_fail_modify_document_permission_remove_invalid_account_ids(value): Name="TestDocument", PermissionType="Share", AccountIdsToRemove=value ) err = ex.value.response["Error"] - err["Code"].should.equal("ValidationException") - err["Message"].should.match(r"Member must satisfy regular expression pattern:") + assert err["Code"] == "ValidationException" + assert re.search(r"Member must satisfy regular expression pattern:", err["Message"]) @mock_ssm @@ -178,8 +180,8 @@ def test_fail_modify_document_permission_add_all_and_specific(): AccountIdsToAdd=["all", "123412341234"], ) err = ex.value.response["Error"] - err["Code"].should.equal("DocumentPermissionLimit") - err["Message"].should.equal("Accounts can either be all or a group of AWS accounts") + assert err["Code"] == "DocumentPermissionLimit" + assert err["Message"] == "Accounts can either be all or a group of AWS accounts" @mock_ssm @@ -192,5 +194,5 @@ def test_fail_modify_document_permission_remove_all_and_specific(): AccountIdsToRemove=["all", "123412341234"], ) err = ex.value.response["Error"] - err["Code"].should.equal("DocumentPermissionLimit") - err["Message"].should.equal("Accounts can either be all or a group of AWS accounts") + assert err["Code"] == "DocumentPermissionLimit" + assert err["Message"] == "Accounts can either be all or a group of AWS accounts" diff --git a/tests/test_ssm/test_ssm_docs.py b/tests/test_ssm/test_ssm_docs.py index ef3058395..ba04c0d8d 100644 --- a/tests/test_ssm/test_ssm_docs.py +++ b/tests/test_ssm/test_ssm_docs.py @@ -1,19 +1,17 @@ -import boto3 -import botocore.exceptions -import sure # noqa # pylint: disable=unused-import +import copy import datetime from datetime import timezone -import json -import yaml import hashlib -import copy +import json import pkgutil +import yaml + +import boto3 +import botocore.exceptions +from botocore.exceptions import ClientError import pytest -from botocore.exceptions import ClientError - from moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID - from moto import mock_ssm @@ -32,107 +30,99 @@ def _validate_document_description( ): if expected_format == "JSON": - doc_description["Hash"].should.equal( + assert doc_description["Hash"] == ( hashlib.sha256(json.dumps(json_doc).encode("utf-8")).hexdigest() ) else: - doc_description["Hash"].should.equal( + assert doc_description["Hash"] == ( hashlib.sha256(yaml.dump(json_doc).encode("utf-8")).hexdigest() ) - doc_description["HashType"].should.equal("Sha256") - doc_description["Name"].should.equal(doc_name) - doc_description["Owner"].should.equal(ACCOUNT_ID) + assert doc_description["HashType"] == "Sha256" + assert doc_description["Name"] == doc_name + assert doc_description["Owner"] == ACCOUNT_ID difference = datetime.datetime.now(tz=timezone.utc) - doc_description["CreatedDate"] if difference.min > datetime.timedelta(minutes=1): assert False - doc_description["Status"].should.equal("Active") - doc_description["DocumentVersion"].should.equal(expected_document_version) - doc_description["Description"].should.equal(json_doc["description"]) + assert doc_description["Status"] == "Active" + assert doc_description["DocumentVersion"] == expected_document_version + assert doc_description["Description"] == json_doc["description"] doc_description["Parameters"] = sorted( doc_description["Parameters"], key=lambda doc: doc["Name"] ) - doc_description["Parameters"][0]["Name"].should.equal("Parameter1") - doc_description["Parameters"][0]["Type"].should.equal("Integer") - doc_description["Parameters"][0]["Description"].should.equal("Command Duration.") - doc_description["Parameters"][0]["DefaultValue"].should.equal("3") + assert doc_description["Parameters"][0]["Name"] == "Parameter1" + assert doc_description["Parameters"][0]["Type"] == "Integer" + assert doc_description["Parameters"][0]["Description"] == "Command Duration." + assert doc_description["Parameters"][0]["DefaultValue"] == "3" - doc_description["Parameters"][1]["Name"].should.equal("Parameter2") - doc_description["Parameters"][1]["Type"].should.equal("String") - doc_description["Parameters"][1]["DefaultValue"].should.equal("def") + assert doc_description["Parameters"][1]["Name"] == "Parameter2" + assert doc_description["Parameters"][1]["Type"] == "String" + assert doc_description["Parameters"][1]["DefaultValue"] == "def" - doc_description["Parameters"][2]["Name"].should.equal("Parameter3") - doc_description["Parameters"][2]["Type"].should.equal("Boolean") - doc_description["Parameters"][2]["Description"].should.equal("A boolean") - doc_description["Parameters"][2]["DefaultValue"].should.equal("False") + assert doc_description["Parameters"][2]["Name"] == "Parameter3" + assert doc_description["Parameters"][2]["Type"] == "Boolean" + assert doc_description["Parameters"][2]["Description"] == "A boolean" + assert doc_description["Parameters"][2]["DefaultValue"] == "False" - doc_description["Parameters"][3]["Name"].should.equal("Parameter4") - doc_description["Parameters"][3]["Type"].should.equal("StringList") - doc_description["Parameters"][3]["Description"].should.equal("A string list") - doc_description["Parameters"][3]["DefaultValue"].should.equal('["abc", "def"]') + assert doc_description["Parameters"][3]["Name"] == "Parameter4" + assert doc_description["Parameters"][3]["Type"] == "StringList" + assert doc_description["Parameters"][3]["Description"] == "A string list" + assert doc_description["Parameters"][3]["DefaultValue"] == '["abc", "def"]' - doc_description["Parameters"][4]["Name"].should.equal("Parameter5") - doc_description["Parameters"][4]["Type"].should.equal("StringMap") + assert doc_description["Parameters"][4]["Name"] == "Parameter5" + assert doc_description["Parameters"][4]["Type"] == "StringMap" - doc_description["Parameters"][5]["Name"].should.equal("Parameter6") - doc_description["Parameters"][5]["Type"].should.equal("MapList") + assert doc_description["Parameters"][5]["Name"] == "Parameter6" + assert doc_description["Parameters"][5]["Type"] == "MapList" if expected_format == "JSON": # We have to replace single quotes from the response to package it back up - json.loads(doc_description["Parameters"][4]["DefaultValue"]).should.equal( - { - "NotificationArn": "$dependency.topicArn", - "NotificationEvents": ["Failed"], - "NotificationType": "Command", - } - ) + assert json.loads(doc_description["Parameters"][4]["DefaultValue"]) == { + "NotificationArn": "$dependency.topicArn", + "NotificationEvents": ["Failed"], + "NotificationType": "Command", + } - json.loads(doc_description["Parameters"][5]["DefaultValue"]).should.equal( - [ - {"DeviceName": "/dev/sda1", "Ebs": {"VolumeSize": "50"}}, - {"DeviceName": "/dev/sdm", "Ebs": {"VolumeSize": "100"}}, - ] - ) + assert json.loads(doc_description["Parameters"][5]["DefaultValue"]) == [ + {"DeviceName": "/dev/sda1", "Ebs": {"VolumeSize": "50"}}, + {"DeviceName": "/dev/sdm", "Ebs": {"VolumeSize": "100"}}, + ] else: - yaml.safe_load(doc_description["Parameters"][4]["DefaultValue"]).should.equal( - { - "NotificationArn": "$dependency.topicArn", - "NotificationEvents": ["Failed"], - "NotificationType": "Command", - } - ) - yaml.safe_load(doc_description["Parameters"][5]["DefaultValue"]).should.equal( - [ - {"DeviceName": "/dev/sda1", "Ebs": {"VolumeSize": "50"}}, - {"DeviceName": "/dev/sdm", "Ebs": {"VolumeSize": "100"}}, - ] - ) + assert yaml.safe_load(doc_description["Parameters"][4]["DefaultValue"]) == { + "NotificationArn": "$dependency.topicArn", + "NotificationEvents": ["Failed"], + "NotificationType": "Command", + } + assert yaml.safe_load(doc_description["Parameters"][5]["DefaultValue"]) == [ + {"DeviceName": "/dev/sda1", "Ebs": {"VolumeSize": "50"}}, + {"DeviceName": "/dev/sdm", "Ebs": {"VolumeSize": "100"}}, + ] - doc_description["DocumentType"].should.equal("Command") - doc_description["SchemaVersion"].should.equal("2.2") - doc_description["LatestVersion"].should.equal(expected_latest_version) - doc_description["DefaultVersion"].should.equal(expected_default_version) - doc_description["DocumentFormat"].should.equal(expected_format) + assert doc_description["DocumentType"] == "Command" + assert doc_description["SchemaVersion"] == "2.2" + assert doc_description["LatestVersion"] == expected_latest_version + assert doc_description["DefaultVersion"] == expected_default_version + assert doc_description["DocumentFormat"] == expected_format def _get_doc_validator( response, version_name, doc_version, json_doc_content, document_format ): - response["Name"].should.equal("TestDocument3") + assert response["Name"] == "TestDocument3" if version_name: - response["VersionName"].should.equal(version_name) - response["DocumentVersion"].should.equal(doc_version) - response["Status"].should.equal("Active") + assert response["VersionName"] == version_name + assert response["DocumentVersion"] == doc_version + assert response["Status"] == "Active" if document_format == "JSON": - json.loads(response["Content"]).should.equal(json_doc_content) + assert json.loads(response["Content"]) == json_doc_content else: - yaml.safe_load(response["Content"]).should.equal(json_doc_content) - response["DocumentType"].should.equal("Command") - response["DocumentFormat"].should.equal(document_format) + assert yaml.safe_load(response["Content"]) == json_doc_content + assert response["DocumentType"] == "Command" + assert response["DocumentFormat"] == document_format @mock_ssm @@ -174,9 +164,9 @@ def test_create_document(): Tags=[{"Key": "testing", "Value": "testingValue"}], ) doc_description = response["DocumentDescription"] - doc_description["VersionName"].should.equal("Base") - doc_description["TargetType"].should.equal("/AWS::EC2::Instance") - doc_description["Tags"].should.equal([{"Key": "testing", "Value": "testingValue"}]) + assert doc_description["VersionName"] == "Base" + assert doc_description["TargetType"] == "/AWS::EC2::Instance" + assert doc_description["Tags"] == [{"Key": "testing", "Value": "testingValue"}] _validate_document_description( "TestDocument3", doc_description, json_doc, "1", "1", "1", "JSON" @@ -191,9 +181,9 @@ def test_create_document(): ) raise RuntimeError("Should fail") except botocore.exceptions.ClientError as err: - err.operation_name.should.equal("CreateDocument") - err.response["Error"]["Message"].should.equal( - "The specified document already exists." + assert err.operation_name == "CreateDocument" + assert ( + err.response["Error"]["Message"] == "The specified document already exists." ) try: @@ -205,9 +195,10 @@ def test_create_document(): ) raise RuntimeError("Should fail") except botocore.exceptions.ClientError as err: - err.operation_name.should.equal("CreateDocument") - err.response["Error"]["Message"].should.equal( - "The content for the document is not valid." + assert err.operation_name == "CreateDocument" + assert ( + err.response["Error"]["Message"] + == "The content for the document is not valid." ) del json_doc["parameters"] @@ -219,25 +210,25 @@ def test_create_document(): ) doc_description = response["DocumentDescription"] - doc_description["Hash"].should.equal( + assert doc_description["Hash"] == ( hashlib.sha256(yaml.dump(json_doc).encode("utf-8")).hexdigest() ) - doc_description["HashType"].should.equal("Sha256") - doc_description["Name"].should.equal("EmptyParamDoc") - doc_description["Owner"].should.equal(ACCOUNT_ID) + assert doc_description["HashType"] == "Sha256" + assert doc_description["Name"] == "EmptyParamDoc" + assert doc_description["Owner"] == ACCOUNT_ID difference = datetime.datetime.now(tz=timezone.utc) - doc_description["CreatedDate"] if difference.min > datetime.timedelta(minutes=1): assert False - doc_description["Status"].should.equal("Active") - doc_description["DocumentVersion"].should.equal("1") - doc_description["Description"].should.equal(json_doc["description"]) - doc_description["DocumentType"].should.equal("Command") - doc_description["SchemaVersion"].should.equal("2.2") - doc_description["LatestVersion"].should.equal("1") - doc_description["DefaultVersion"].should.equal("1") - doc_description["DocumentFormat"].should.equal("YAML") + assert doc_description["Status"] == "Active" + assert doc_description["DocumentVersion"] == "1" + assert doc_description["Description"] == json_doc["description"] + assert doc_description["DocumentType"] == "Command" + assert doc_description["SchemaVersion"] == "2.2" + assert doc_description["LatestVersion"] == "1" + assert doc_description["DefaultVersion"] == "1" + assert doc_description["DocumentFormat"] == "YAML" @mock_ssm @@ -251,9 +242,9 @@ def test_get_document(): client.get_document(Name="DNE") raise RuntimeError("Should fail") except botocore.exceptions.ClientError as err: - err.operation_name.should.equal("GetDocument") - err.response["Error"]["Message"].should.equal( - "The specified document does not exist." + assert err.operation_name == "GetDocument" + assert ( + err.response["Error"]["Message"] == "The specified document does not exist." ) client.create_document( @@ -306,18 +297,18 @@ def test_get_document(): ) raise RuntimeError("Should fail") except botocore.exceptions.ClientError as err: - err.operation_name.should.equal("GetDocument") - err.response["Error"]["Message"].should.equal( - "The specified document does not exist." + assert err.operation_name == "GetDocument" + assert ( + err.response["Error"]["Message"] == "The specified document does not exist." ) try: response = client.get_document(Name="TestDocument3", DocumentVersion="3") raise RuntimeError("Should fail") except botocore.exceptions.ClientError as err: - err.operation_name.should.equal("GetDocument") - err.response["Error"]["Message"].should.equal( - "The specified document does not exist." + assert err.operation_name == "GetDocument" + assert ( + err.response["Error"]["Message"] == "The specified document does not exist." ) # Updating default should update normal get @@ -337,9 +328,9 @@ def test_delete_document(): client.delete_document(Name="DNE") raise RuntimeError("Should fail") except botocore.exceptions.ClientError as err: - err.operation_name.should.equal("DeleteDocument") - err.response["Error"]["Message"].should.equal( - "The specified document does not exist." + assert err.operation_name == "DeleteDocument" + assert ( + err.response["Error"]["Message"] == "The specified document does not exist." ) # Test simple @@ -357,9 +348,9 @@ def test_delete_document(): client.get_document(Name="TestDocument3") raise RuntimeError("Should fail") except botocore.exceptions.ClientError as err: - err.operation_name.should.equal("GetDocument") - err.response["Error"]["Message"].should.equal( - "The specified document does not exist." + assert err.operation_name == "GetDocument" + assert ( + err.response["Error"]["Message"] == "The specified document does not exist." ) # Delete default version with other version is bad @@ -407,8 +398,8 @@ def test_delete_document(): client.delete_document(Name="TestDocument3", DocumentVersion="1") raise RuntimeError("Should fail") except botocore.exceptions.ClientError as err: - err.operation_name.should.equal("DeleteDocument") - err.response["Error"]["Message"].should.equal( + assert err.operation_name == "DeleteDocument" + assert err.response["Error"]["Message"] == ( "Default version of the document can't be deleted." ) @@ -416,8 +407,8 @@ def test_delete_document(): client.delete_document(Name="TestDocument3", VersionName="Base") raise RuntimeError("Should fail") except botocore.exceptions.ClientError as err: - err.operation_name.should.equal("DeleteDocument") - err.response["Error"]["Message"].should.equal( + assert err.operation_name == "DeleteDocument" + assert err.response["Error"]["Message"] == ( "Default version of the document can't be deleted." ) @@ -429,7 +420,7 @@ def test_delete_document(): # Check that latest version is changed response = client.describe_document(Name="TestDocument3") - response["Document"]["LatestVersion"].should.equal("4") + assert response["Document"]["LatestVersion"] == "4" client.delete_document(Name="TestDocument3", VersionName="NewBase") @@ -444,31 +435,31 @@ def test_delete_document(): client.get_document(Name="TestDocument3", DocumentVersion="1") raise RuntimeError("Should fail") except botocore.exceptions.ClientError as err: - err.operation_name.should.equal("GetDocument") - err.response["Error"]["Message"].should.equal( - "The specified document does not exist." + assert err.operation_name == "GetDocument" + assert ( + err.response["Error"]["Message"] == "The specified document does not exist." ) try: client.get_document(Name="TestDocument3", DocumentVersion="3") raise RuntimeError("Should fail") except botocore.exceptions.ClientError as err: - err.operation_name.should.equal("GetDocument") - err.response["Error"]["Message"].should.equal( - "The specified document does not exist." + assert err.operation_name == "GetDocument" + assert ( + err.response["Error"]["Message"] == "The specified document does not exist." ) try: client.get_document(Name="TestDocument3", DocumentVersion="4") raise RuntimeError("Should fail") except botocore.exceptions.ClientError as err: - err.operation_name.should.equal("GetDocument") - err.response["Error"]["Message"].should.equal( - "The specified document does not exist." + assert err.operation_name == "GetDocument" + assert ( + err.response["Error"]["Message"] == "The specified document does not exist." ) response = client.list_documents() - len(response["DocumentIdentifiers"]).should.equal(0) + assert len(response["DocumentIdentifiers"]) == 0 @mock_ssm @@ -481,9 +472,9 @@ def test_update_document_default_version(): client.update_document_default_version(Name="DNE", DocumentVersion="1") raise RuntimeError("Should fail") except botocore.exceptions.ClientError as err: - err.operation_name.should.equal("UpdateDocumentDefaultVersion") - err.response["Error"]["Message"].should.equal( - "The specified document does not exist." + assert err.operation_name == "UpdateDocumentDefaultVersion" + assert ( + err.response["Error"]["Message"] == "The specified document does not exist." ) client.create_document( @@ -511,8 +502,8 @@ def test_update_document_default_version(): response = client.update_document_default_version( Name="TestDocument", DocumentVersion="2" ) - response["Description"]["Name"].should.equal("TestDocument") - response["Description"]["DefaultVersion"].should.equal("2") + assert response["Description"]["Name"] == "TestDocument" + assert response["Description"]["DefaultVersion"] == "2" json_doc["description"] = "a new description3" @@ -526,9 +517,9 @@ def test_update_document_default_version(): response = client.update_document_default_version( Name="TestDocument", DocumentVersion="4" ) - response["Description"]["Name"].should.equal("TestDocument") - response["Description"]["DefaultVersion"].should.equal("4") - response["Description"]["DefaultVersionName"].should.equal("NewBase") + assert response["Description"]["Name"] == "TestDocument" + assert response["Description"]["DefaultVersion"] == "4" + assert response["Description"]["DefaultVersionName"] == "NewBase" @mock_ssm @@ -547,9 +538,9 @@ def test_update_document(): ) raise RuntimeError("Should fail") except botocore.exceptions.ClientError as err: - err.operation_name.should.equal("UpdateDocument") - err.response["Error"]["Message"].should.equal( - "The specified document does not exist." + assert err.operation_name == "UpdateDocument" + assert ( + err.response["Error"]["Message"] == "The specified document does not exist." ) client.create_document( @@ -569,8 +560,8 @@ def test_update_document(): ) raise RuntimeError("Should fail") except botocore.exceptions.ClientError as err: - err.operation_name.should.equal("UpdateDocument") - err.response["Error"]["Message"].should.equal( + assert err.operation_name == "UpdateDocument" + assert err.response["Error"]["Message"] == ( "The document version is not valid or does not exist." ) @@ -584,8 +575,8 @@ def test_update_document(): ) raise RuntimeError("Should fail") except botocore.exceptions.ClientError as err: - err.operation_name.should.equal("UpdateDocument") - err.response["Error"]["Message"].should.equal( + assert err.operation_name == "UpdateDocument" + assert err.response["Error"]["Message"] == ( "The content of the association document matches another " "document. Change the content of the document and try again." ) @@ -602,8 +593,8 @@ def test_update_document(): ) raise RuntimeError("Should fail") except botocore.exceptions.ClientError as err: - err.operation_name.should.equal("UpdateDocument") - err.response["Error"]["Message"].should.equal( + assert err.operation_name == "UpdateDocument" + assert err.response["Error"]["Message"] == ( "The specified version name is a duplicate." ) @@ -614,10 +605,10 @@ def test_update_document(): DocumentVersion="1", DocumentFormat="JSON", ) - response["DocumentDescription"]["Description"].should.equal("a new description") - response["DocumentDescription"]["DocumentVersion"].should.equal("2") - response["DocumentDescription"]["LatestVersion"].should.equal("2") - response["DocumentDescription"]["DefaultVersion"].should.equal("1") + assert response["DocumentDescription"]["Description"] == "a new description" + assert response["DocumentDescription"]["DocumentVersion"] == "2" + assert response["DocumentDescription"]["LatestVersion"] == "2" + assert response["DocumentDescription"]["DefaultVersion"] == "1" json_doc["description"] = "a new description2" @@ -628,11 +619,11 @@ def test_update_document(): DocumentFormat="JSON", VersionName="NewBase", ) - response["DocumentDescription"]["Description"].should.equal("a new description2") - response["DocumentDescription"]["DocumentVersion"].should.equal("3") - response["DocumentDescription"]["LatestVersion"].should.equal("3") - response["DocumentDescription"]["DefaultVersion"].should.equal("1") - response["DocumentDescription"]["VersionName"].should.equal("NewBase") + assert response["DocumentDescription"]["Description"] == "a new description2" + assert response["DocumentDescription"]["DocumentVersion"] == "3" + assert response["DocumentDescription"]["LatestVersion"] == "3" + assert response["DocumentDescription"]["DefaultVersion"] == "1" + assert response["DocumentDescription"]["VersionName"] == "NewBase" @mock_ssm @@ -645,9 +636,9 @@ def test_describe_document(): client.describe_document(Name="DNE") raise RuntimeError("Should fail") except botocore.exceptions.ClientError as err: - err.operation_name.should.equal("DescribeDocument") - err.response["Error"]["Message"].should.equal( - "The specified document does not exist." + assert err.operation_name == "DescribeDocument" + assert ( + err.response["Error"]["Message"] == "The specified document does not exist." ) client.create_document( @@ -707,29 +698,29 @@ def test_list_documents(): ) response = client.list_documents() - len(response["DocumentIdentifiers"]).should.equal(3) - response["DocumentIdentifiers"][0]["Name"].should.equal("TestDocument") - response["DocumentIdentifiers"][1]["Name"].should.equal("TestDocument2") - response["DocumentIdentifiers"][2]["Name"].should.equal("TestDocument3") - response["NextToken"].should.equal("") + assert len(response["DocumentIdentifiers"]) == 3 + assert response["DocumentIdentifiers"][0]["Name"] == "TestDocument" + assert response["DocumentIdentifiers"][1]["Name"] == "TestDocument2" + assert response["DocumentIdentifiers"][2]["Name"] == "TestDocument3" + assert response["NextToken"] == "" response = client.list_documents(MaxResults=1) - len(response["DocumentIdentifiers"]).should.equal(1) - response["DocumentIdentifiers"][0]["Name"].should.equal("TestDocument") - response["DocumentIdentifiers"][0]["DocumentVersion"].should.equal("1") - response["NextToken"].should.equal("1") + assert len(response["DocumentIdentifiers"]) == 1 + assert response["DocumentIdentifiers"][0]["Name"] == "TestDocument" + assert response["DocumentIdentifiers"][0]["DocumentVersion"] == "1" + assert response["NextToken"] == "1" response = client.list_documents(MaxResults=1, NextToken=response["NextToken"]) - len(response["DocumentIdentifiers"]).should.equal(1) - response["DocumentIdentifiers"][0]["Name"].should.equal("TestDocument2") - response["DocumentIdentifiers"][0]["DocumentVersion"].should.equal("1") - response["NextToken"].should.equal("2") + assert len(response["DocumentIdentifiers"]) == 1 + assert response["DocumentIdentifiers"][0]["Name"] == "TestDocument2" + assert response["DocumentIdentifiers"][0]["DocumentVersion"] == "1" + assert response["NextToken"] == "2" response = client.list_documents(MaxResults=1, NextToken=response["NextToken"]) - len(response["DocumentIdentifiers"]).should.equal(1) - response["DocumentIdentifiers"][0]["Name"].should.equal("TestDocument3") - response["DocumentIdentifiers"][0]["DocumentVersion"].should.equal("1") - response["NextToken"].should.equal("") + assert len(response["DocumentIdentifiers"]) == 1 + assert response["DocumentIdentifiers"][0]["Name"] == "TestDocument3" + assert response["DocumentIdentifiers"][0]["DocumentVersion"] == "1" + assert response["NextToken"] == "" # making sure no bad interactions with update json_doc["description"] = "a new description" @@ -750,24 +741,24 @@ def test_list_documents(): client.update_document_default_version(Name="TestDocument", DocumentVersion="2") response = client.list_documents() - len(response["DocumentIdentifiers"]).should.equal(3) - response["DocumentIdentifiers"][0]["Name"].should.equal("TestDocument") - response["DocumentIdentifiers"][0]["DocumentVersion"].should.equal("2") + assert len(response["DocumentIdentifiers"]) == 3 + assert response["DocumentIdentifiers"][0]["Name"] == "TestDocument" + assert response["DocumentIdentifiers"][0]["DocumentVersion"] == "2" - response["DocumentIdentifiers"][1]["Name"].should.equal("TestDocument2") - response["DocumentIdentifiers"][1]["DocumentVersion"].should.equal("1") + assert response["DocumentIdentifiers"][1]["Name"] == "TestDocument2" + assert response["DocumentIdentifiers"][1]["DocumentVersion"] == "1" - response["DocumentIdentifiers"][2]["Name"].should.equal("TestDocument3") - response["DocumentIdentifiers"][2]["DocumentVersion"].should.equal("1") - response["NextToken"].should.equal("") + assert response["DocumentIdentifiers"][2]["Name"] == "TestDocument3" + assert response["DocumentIdentifiers"][2]["DocumentVersion"] == "1" + assert response["NextToken"] == "" response = client.list_documents(Filters=[{"Key": "Owner", "Values": ["Self"]}]) - len(response["DocumentIdentifiers"]).should.equal(3) + assert len(response["DocumentIdentifiers"]) == 3 response = client.list_documents( Filters=[{"Key": "TargetType", "Values": ["/AWS::EC2::Instance"]}] ) - len(response["DocumentIdentifiers"]).should.equal(1) + assert len(response["DocumentIdentifiers"]) == 1 @mock_ssm diff --git a/tests/test_ssm/test_ssm_ec2_integration.py b/tests/test_ssm/test_ssm_ec2_integration.py index 94a34d179..c7a89c6ea 100644 --- a/tests/test_ssm/test_ssm_ec2_integration.py +++ b/tests/test_ssm/test_ssm_ec2_integration.py @@ -1,5 +1,4 @@ import boto3 -import sure # noqa # pylint: disable=unused-import from moto import mock_ec2, mock_ssm @@ -14,4 +13,4 @@ def test_ssm_get_latest_ami_by_path(): ami = ssm.get_parameter(Name=test_ami)["Parameter"]["Value"] ec2 = boto3.client("ec2", region_name="us-east-1") - ec2.describe_images(ImageIds=[ami])["Images"].should.have.length_of(1) + assert len(ec2.describe_images(ImageIds=[ami])["Images"]) == 1 diff --git a/tests/test_ssm/test_ssm_ecs_images.py b/tests/test_ssm/test_ssm_ecs_images.py index ffd7af68e..efb8fda52 100644 --- a/tests/test_ssm/test_ssm_ecs_images.py +++ b/tests/test_ssm/test_ssm_ecs_images.py @@ -1,5 +1,4 @@ import boto3 -import sure # noqa # pylint: disable=unused-import from moto import mock_ec2, mock_ssm @@ -10,10 +9,10 @@ def test_ssm_get_latest_ami_by_path(): ssm = boto3.client("ssm", region_name="us-east-1") path = "/aws/service/ecs/optimized-ami" params = ssm.get_parameters_by_path(Path=path, Recursive=True)["Parameters"] - params.should.have.length_of(10) + assert len(params) == 10 ec2 = boto3.client("ec2", region_name="us-east-1") for param in params: if "Value" in param and isinstance(param["Value"], dict): ami = param["Value"]["image_id"] - ec2.describe_images(ImageIds=[ami])["Images"].should.have.length_of(1) + assert len(ec2.describe_images(ImageIds=[ami])["Images"]) == 1 diff --git a/tests/test_ssm/test_ssm_maintenance_windows.py b/tests/test_ssm/test_ssm_maintenance_windows.py index 9d0e2ca26..ebb53bf1f 100644 --- a/tests/test_ssm/test_ssm_maintenance_windows.py +++ b/tests/test_ssm/test_ssm_maintenance_windows.py @@ -1,5 +1,4 @@ import boto3 -import sure # noqa # pylint: disable=unused-import from moto import mock_ssm @@ -9,12 +8,12 @@ def test_describe_maintenance_window(): ssm = boto3.client("ssm", region_name="us-east-1") resp = ssm.describe_maintenance_windows() - resp.should.have.key("WindowIdentities").equals([]) + assert resp["WindowIdentities"] == [] resp = ssm.describe_maintenance_windows( Filters=[{"Key": "Name", "Values": ["fake-maintenance-window-name"]}] ) - resp.should.have.key("WindowIdentities").equals([]) + assert resp["WindowIdentities"] == [] @mock_ssm @@ -28,25 +27,25 @@ def test_create_maintenance_windows_simple(): Cutoff=1, AllowUnassociatedTargets=False, ) - resp.should.have.key("WindowId") + assert "WindowId" in resp _id = resp["WindowId"] # mw-01d6bbfdf6af2c39a resp = ssm.describe_maintenance_windows() - resp.should.have.key("WindowIdentities").have.length_of(1) + assert len(resp["WindowIdentities"]) == 1 my_window = resp["WindowIdentities"][0] - my_window.should.have.key("WindowId").equal(_id) - my_window.should.have.key("Name").equal("simple-window") - my_window.should.have.key("Enabled").equal(True) - my_window.should.have.key("Duration").equal(2) - my_window.should.have.key("Cutoff").equal(1) - my_window.should.have.key("Schedule").equal("cron(15 12 * * ? *)") - # my_window.should.have.key("NextExecutionTime") - my_window.shouldnt.have.key("Description") - my_window.shouldnt.have.key("ScheduleTimezone") - my_window.shouldnt.have.key("ScheduleOffset") - my_window.shouldnt.have.key("EndDate") - my_window.shouldnt.have.key("StartDate") + assert my_window["WindowId"] == _id + assert my_window["Name"] == "simple-window" + assert my_window["Enabled"] is True + assert my_window["Duration"] == 2 + assert my_window["Cutoff"] == 1 + assert my_window["Schedule"] == "cron(15 12 * * ? *)" + # assert "NextExecutionTime" in my_window + assert "Description" not in my_window + assert "ScheduleTimezone" not in my_window + assert "ScheduleOffset" not in my_window + assert "EndDate" not in my_window + assert "StartDate" not in my_window @mock_ssm @@ -65,25 +64,25 @@ def test_create_maintenance_windows_advanced(): StartDate="2021-11-01", EndDate="2021-12-31", ) - resp.should.have.key("WindowId") + assert "WindowId" in resp _id = resp["WindowId"] # mw-01d6bbfdf6af2c39a resp = ssm.describe_maintenance_windows() - resp.should.have.key("WindowIdentities").have.length_of(1) + assert len(resp["WindowIdentities"]) == 1 my_window = resp["WindowIdentities"][0] - my_window.should.have.key("WindowId").equal(_id) - my_window.should.have.key("Name").equal("simple-window") - my_window.should.have.key("Enabled").equal(True) - my_window.should.have.key("Duration").equal(5) - my_window.should.have.key("Cutoff").equal(4) - my_window.should.have.key("Schedule").equal("cron(15 12 * * ? *)") - # my_window.should.have.key("NextExecutionTime") - my_window.should.have.key("Description").equals("French windows are just too fancy") - my_window.should.have.key("ScheduleTimezone").equals("Europe/London") - my_window.should.have.key("ScheduleOffset").equals(1) - my_window.should.have.key("StartDate").equals("2021-11-01") - my_window.should.have.key("EndDate").equals("2021-12-31") + assert my_window["WindowId"] == _id + assert my_window["Name"] == "simple-window" + assert my_window["Enabled"] is True + assert my_window["Duration"] == 5 + assert my_window["Cutoff"] == 4 + assert my_window["Schedule"] == "cron(15 12 * * ? *)" + # assert "NextExecutionTime" in my_window + assert my_window["Description"] == "French windows are just too fancy" + assert my_window["ScheduleTimezone"] == "Europe/London" + assert my_window["ScheduleOffset"] == 1 + assert my_window["StartDate"] == "2021-11-01" + assert my_window["EndDate"] == "2021-12-31" @mock_ssm @@ -97,22 +96,22 @@ def test_get_maintenance_windows(): Cutoff=1, AllowUnassociatedTargets=False, ) - resp.should.have.key("WindowId") + assert "WindowId" in resp _id = resp["WindowId"] # mw-01d6bbfdf6af2c39a my_window = ssm.get_maintenance_window(WindowId=_id) - my_window.should.have.key("WindowId").equal(_id) - my_window.should.have.key("Name").equal("my-window") - my_window.should.have.key("Enabled").equal(True) - my_window.should.have.key("Duration").equal(2) - my_window.should.have.key("Cutoff").equal(1) - my_window.should.have.key("Schedule").equal("cron(15 12 * * ? *)") - # my_window.should.have.key("NextExecutionTime") - my_window.shouldnt.have.key("Description") - my_window.shouldnt.have.key("ScheduleTimezone") - my_window.shouldnt.have.key("ScheduleOffset") - my_window.shouldnt.have.key("EndDate") - my_window.shouldnt.have.key("StartDate") + assert my_window["WindowId"] == _id + assert my_window["Name"] == "my-window" + assert my_window["Enabled"] is True + assert my_window["Duration"] == 2 + assert my_window["Cutoff"] == 1 + assert my_window["Schedule"] == "cron(15 12 * * ? *)" + # assert "NextExecutionTime" in my_window + assert "Description" not in my_window + assert "ScheduleTimezone" not in my_window + assert "ScheduleOffset" not in my_window + assert "EndDate" not in my_window + assert "StartDate" not in my_window @mock_ssm @@ -129,12 +128,12 @@ def test_describe_maintenance_windows(): ) resp = ssm.describe_maintenance_windows() - resp.should.have.key("WindowIdentities").have.length_of(4) + assert len(resp["WindowIdentities"]) == 4 resp = ssm.describe_maintenance_windows( Filters=[{"Key": "Name", "Values": ["window_0", "window_2"]}] ) - resp.should.have.key("WindowIdentities").have.length_of(2) + assert len(resp["WindowIdentities"]) == 2 @mock_ssm @@ -149,10 +148,10 @@ def test_delete_maintenance_windows(): AllowUnassociatedTargets=False, ) - ssm.delete_maintenance_window(WindowId=(resp["WindowId"])) + ssm.delete_maintenance_window(WindowId=resp["WindowId"]) resp = ssm.describe_maintenance_windows() - resp.should.have.key("WindowIdentities").equals([]) + assert resp["WindowIdentities"] == [] @mock_ssm @@ -232,17 +231,17 @@ def test_register_maintenance_window_target(): ResourceType="INSTANCE", Targets=[{"Key": "tag:Name", "Values": ["my-instance"]}], ) - resp.should.have.key("WindowTargetId") + assert "WindowTargetId" in resp _id = resp["WindowTargetId"] resp = ssm.describe_maintenance_window_targets( WindowId=window_id, ) - resp.should.have.key("Targets").should.have.length_of(1) - resp["Targets"][0].should.have.key("ResourceType").equal("INSTANCE") - resp["Targets"][0].should.have.key("WindowTargetId").equal(_id) - resp["Targets"][0]["Targets"][0].should.have.key("Key").equal("tag:Name") - resp["Targets"][0]["Targets"][0].should.have.key("Values").equal(["my-instance"]) + assert len(resp["Targets"]) == 1 + assert resp["Targets"][0]["ResourceType"] == "INSTANCE" + assert resp["Targets"][0]["WindowTargetId"] == _id + assert resp["Targets"][0]["Targets"][0]["Key"] == "tag:Name" + assert resp["Targets"][0]["Targets"][0]["Values"] == ["my-instance"] @mock_ssm @@ -273,7 +272,7 @@ def test_deregister_target_from_maintenance_window(): resp = ssm.describe_maintenance_window_targets( WindowId=window_id, ) - resp.should.have.key("Targets").should.have.length_of(0) + assert len(resp["Targets"]) == 0 @mock_ssm @@ -292,12 +291,12 @@ def test_describe_maintenance_window_with_no_task_or_targets(): resp = ssm.describe_maintenance_window_tasks( WindowId=window_id, ) - resp.should.have.key("Tasks").should.have.length_of(0) + assert len(resp["Tasks"]) == 0 resp = ssm.describe_maintenance_window_targets( WindowId=window_id, ) - resp.should.have.key("Targets").should.have.length_of(0) + assert len(resp["Targets"]) == 0 @mock_ssm @@ -329,18 +328,18 @@ def test_register_maintenance_window_task(): MaxErrors="1", ) - resp.should.have.key("WindowTaskId") + assert "WindowTaskId" in resp _id = resp["WindowTaskId"] resp = ssm.describe_maintenance_window_tasks( WindowId=window_id, ) - resp.should.have.key("Tasks").should.have.length_of(1) - resp["Tasks"][0].should.have.key("WindowTaskId").equal(_id) - resp["Tasks"][0].should.have.key("WindowId").equal(window_id) - resp["Tasks"][0].should.have.key("TaskArn").equal("AWS-RunShellScript") - resp["Tasks"][0].should.have.key("MaxConcurrency").equal("1") - resp["Tasks"][0].should.have.key("MaxErrors").equal("1") + assert len(resp["Tasks"]) == 1 + assert resp["Tasks"][0]["WindowTaskId"] == _id + assert resp["Tasks"][0]["WindowId"] == window_id + assert resp["Tasks"][0]["TaskArn"] == "AWS-RunShellScript" + assert resp["Tasks"][0]["MaxConcurrency"] == "1" + assert resp["Tasks"][0]["MaxErrors"] == "1" @mock_ssm @@ -381,4 +380,4 @@ def test_deregister_maintenance_window_task(): resp = ssm.describe_maintenance_window_tasks( WindowId=window_id, ) - resp.should.have.key("Tasks").should.have.length_of(0) + assert len(resp["Tasks"]) == 0 diff --git a/tests/test_ssm/test_ssm_parameterstore.py b/tests/test_ssm/test_ssm_parameterstore.py index 9ca1e66b6..1d0ebf01c 100644 --- a/tests/test_ssm/test_ssm_parameterstore.py +++ b/tests/test_ssm/test_ssm_parameterstore.py @@ -1,5 +1,3 @@ -import sure # noqa # pylint: disable=unused-import - from moto.ssm.models import ParameterDict @@ -7,42 +5,40 @@ def test_simple_setget(): store = ParameterDict("accnt", "region") store["/a/b/c"] = "some object" - store.get("/a/b/c").should.equal("some object") + assert store.get("/a/b/c") == "some object" def test_get_none(): store = ParameterDict("accnt", "region") - store.get(None).should.equal(None) + assert store.get(None) is None def test_get_aws_param(): store = ParameterDict("accnt", "region") p = store["/aws/service/global-infrastructure/regions/us-west-1/longName"] - p.should.have.length_of(1) - p[0].value.should.equal("US West (N. California)") + assert len(p) == 1 + assert p[0].value == "US West (N. California)" def test_iter(): store = ParameterDict("accnt", "region") store["/a/b/c"] = "some object" - "/a/b/c".should.be.within(store) - "/a/b/d".shouldnt.be.within(store) + assert "/a/b/c" in store + assert "/a/b/d" not in store def test_iter_none(): store = ParameterDict("accnt", "region") - None.shouldnt.be.within(store) + assert None not in store def test_iter_aws(): store = ParameterDict("accnt", "region") - "/aws/service/global-infrastructure/regions/us-west-1/longName".should.be.within( - store - ) + assert "/aws/service/global-infrastructure/regions/us-west-1/longName" in store def test_get_key_beginning_with(): @@ -52,20 +48,17 @@ def test_get_key_beginning_with(): store["/a/c/d"] = "some third object" begins_with_ab = list(store.get_keys_beginning_with("/a/b", recursive=False)) - begins_with_ab.should.equal(["/a/b/c"]) + assert begins_with_ab == ["/a/b/c"] begins_with_a = list(store.get_keys_beginning_with("/a", recursive=False)) - begins_with_a.should.equal([]) + assert not begins_with_a begins_with_a_recursive = list(store.get_keys_beginning_with("/a", recursive=True)) - set(begins_with_a_recursive).should.equal({"/a/b/c", "/a/c/d"}) + assert set(begins_with_a_recursive) == {"/a/b/c", "/a/c/d"} def test_get_key_beginning_with_aws(): - """ - ParameterDict should load the default parameters if we request a key starting with '/aws' - :return: - """ + """Test ParameterDict loads default params for key starting with '/aws'.""" store = ParameterDict("accnt", "region") uswest_params = set( @@ -73,22 +66,20 @@ def test_get_key_beginning_with_aws(): "/aws/service/global-infrastructure/regions/us-west-1", recursive=False ) ) - uswest_params.should.equal( - { - "/aws/service/global-infrastructure/regions/us-west-1", - "/aws/service/global-infrastructure/regions/us-west-1/domain", - "/aws/service/global-infrastructure/regions/us-west-1/geolocationCountry", - "/aws/service/global-infrastructure/regions/us-west-1/geolocationRegion", - "/aws/service/global-infrastructure/regions/us-west-1/longName", - "/aws/service/global-infrastructure/regions/us-west-1/partition", - } - ) + assert uswest_params == { + "/aws/service/global-infrastructure/regions/us-west-1", + "/aws/service/global-infrastructure/regions/us-west-1/domain", + "/aws/service/global-infrastructure/regions/us-west-1/geolocationCountry", + "/aws/service/global-infrastructure/regions/us-west-1/geolocationRegion", + "/aws/service/global-infrastructure/regions/us-west-1/longName", + "/aws/service/global-infrastructure/regions/us-west-1/partition", + } def test_ssm_parameter_from_unknown_region(): store = ParameterDict("accnt", "region") - list( + assert not list( store.get_keys_beginning_with( "/aws/service/ami-amazon-linux-latest", recursive=False ) - ).should.equal([]) + ) diff --git a/tests/test_ssm/test_ssm_patch_baseline.py b/tests/test_ssm/test_ssm_patch_baseline.py index 2e4971b87..692aac84a 100644 --- a/tests/test_ssm/test_ssm_patch_baseline.py +++ b/tests/test_ssm/test_ssm_patch_baseline.py @@ -1,5 +1,4 @@ import boto3 -import sure # noqa # pylint: disable=unused-import from moto import mock_ssm @@ -48,13 +47,13 @@ def test_create_patch_baseLine(): ], MaxResults=50, ) - response.should.have.key("BaselineIdentities").have.length_of(1) + assert len(response["BaselineIdentities"]) == 1 baseline = response["BaselineIdentities"][0] - baseline.should.have.key("BaselineId").equal(_id) - baseline.should.have.key("BaselineName").equal(baseline_name) - baseline.should.have.key("DefaultBaseline").equal(False) - baseline.should.have.key("OperatingSystem").equal("AMAZON_LINUX") - baseline.should.have.key("BaselineDescription").equal(baseline_description) + assert baseline["BaselineId"] == _id + assert baseline["BaselineName"] == baseline_name + assert baseline["DefaultBaseline"] is False + assert baseline["OperatingSystem"] == "AMAZON_LINUX" + assert baseline["BaselineDescription"] == baseline_description @mock_ssm @@ -97,4 +96,4 @@ def test_delete_patch_baseline(): ], MaxResults=50, ) - response.should.have.key("BaselineIdentities").have.length_of(0) + assert len(response["BaselineIdentities"]) == 0 diff --git a/tests/test_ssm/test_ssm_secretsmanager.py b/tests/test_ssm/test_ssm_secretsmanager.py index d8637a62c..276b8dce2 100644 --- a/tests/test_ssm/test_ssm_secretsmanager.py +++ b/tests/test_ssm/test_ssm_secretsmanager.py @@ -1,8 +1,9 @@ -import boto3 import json + +import boto3 +from botocore.exceptions import ClientError import pytest -from botocore.exceptions import ClientError from moto import mock_ssm, mock_secretsmanager @@ -22,18 +23,18 @@ def test_get_value_from_secrets_manager__by_name(): param = ssm.get_parameter( Name=f"/aws/reference/secretsmanager/{secret_name}", WithDecryption=True )["Parameter"] - param.should.have.key("Name").equals("mysecret") - param.should.have.key("Type").equals("SecureString") - param.should.have.key("Value").equals("some secret") - param.should.have.key("Version").equals(0) - param.should.have.key("SourceResult") + assert param["Name"] == "mysecret" + assert param["Type"] == "SecureString" + assert param["Value"] == "some secret" + assert param["Version"] == 0 + assert "SourceResult" in param secret = secrets_manager.describe_secret(SecretId=secret_name) source_result = json.loads(param["SourceResult"]) - source_result["ARN"].should.equal(secret["ARN"]) - source_result["Name"].should.equal(secret["Name"]) - source_result["VersionIdsToStages"].should.equal(secret["VersionIdsToStages"]) + assert source_result["ARN"] == secret["ARN"] + assert source_result["Name"] == secret["Name"] + assert source_result["VersionIdsToStages"] == secret["VersionIdsToStages"] @mock_secretsmanager @@ -44,8 +45,8 @@ def test_get_value_from_secrets_manager__without_decryption(): with pytest.raises(ClientError) as exc: ssm.get_parameter(Name="/aws/reference/secretsmanager/sth") err = exc.value.response["Error"] - err["Code"].should.equal("ValidationException") - err["Message"].should.equal( + assert err["Code"] == "ValidationException" + assert err["Message"] == ( "WithDecryption flag must be True for retrieving a Secret Manager secret." ) @@ -60,8 +61,8 @@ def test_get_value_from_secrets_manager__with_decryption_false(): Name="/aws/reference/secretsmanager/sth", WithDecryption=False ) err = exc.value.response["Error"] - err["Code"].should.equal("ValidationException") - err["Message"].should.equal( + assert err["Code"] == "ValidationException" + assert err["Message"] == ( "WithDecryption flag must be True for retrieving a Secret Manager secret." ) @@ -86,15 +87,15 @@ def test_get_value_from_secrets_manager__by_id(): # then full_name = f"/aws/reference/secretsmanager/{name}:{version_id1}" param = ssm.get_parameter(Name=full_name, WithDecryption=True)["Parameter"] - param.should.have.key("Value").equals("1st") + assert param["Value"] == "1st" full_name = f"/aws/reference/secretsmanager/{name}" param = ssm.get_parameter(Name=full_name, WithDecryption=True)["Parameter"] - param.should.have.key("Value").equals("2nd") + assert param["Value"] == "2nd" full_name = f"/aws/reference/secretsmanager/{name}:{version_id3}" param = ssm.get_parameter(Name=full_name, WithDecryption=True)["Parameter"] - param.should.have.key("Value").equals("3rd") + assert param["Value"] == "3rd" @mock_secretsmanager @@ -112,7 +113,7 @@ def test_get_value_from_secrets_manager__by_version(): # then full_name = f"/aws/reference/secretsmanager/{name}:AWSPREVIOUS" param = ssm.get_parameter(Name=full_name, WithDecryption=True)["Parameter"] - param.should.have.key("Value").equals("1st") + assert param["Value"] == "1st" @mock_secretsmanager @@ -124,7 +125,8 @@ def test_get_value_from_secrets_manager__param_does_not_exist(): Name="/aws/reference/secretsmanager/test", WithDecryption=True ) err = exc.value.response["Error"] - err["Code"].should.equal("ParameterNotFound") - err["Message"].should.equal( - "An error occurred (ParameterNotFound) when referencing Secrets Manager: Secret /aws/reference/secretsmanager/test not found." + assert err["Code"] == "ParameterNotFound" + assert err["Message"] == ( + "An error occurred (ParameterNotFound) when referencing Secrets " + "Manager: Secret /aws/reference/secretsmanager/test not found." ) diff --git a/tests/test_ssm/test_ssm_utils.py b/tests/test_ssm/test_ssm_utils.py index 040c79525..2c18cd9a9 100644 --- a/tests/test_ssm/test_ssm_utils.py +++ b/tests/test_ssm/test_ssm_utils.py @@ -1,11 +1,11 @@ -import sure # noqa # pylint: disable=unused-import - - from moto.ssm.utils import convert_to_tree, convert_to_params SOURCE_PARAMS = [ { - "ARN": "arn:aws:ssm:us-west-1::parameter/aws/service/global-infrastructure/regions/af-south-1", + "ARN": ( + "arn:aws:ssm:us-west-1::parameter/aws/service" + "/global-infrastructure/regions/af-south-1" + ), "DataType": "text", "Name": "/aws/service/global-infrastructure/regions/af-south-1", "Type": "String", @@ -13,7 +13,10 @@ SOURCE_PARAMS = [ "Version": 1, }, { - "ARN": "arn:aws:ssm:us-west-1::parameter/aws/service/global-infrastructure/regions/ap-northeast-2", + "ARN": ( + "arn:aws:ssm:us-west-1::parameter/aws/service" + "/global-infrastructure/regions/ap-northeast-2" + ), "DataType": "text", "Name": "/aws/service/global-infrastructure/regions/ap-northeast-2", "Type": "String", @@ -21,7 +24,10 @@ SOURCE_PARAMS = [ "Version": 1, }, { - "ARN": "arn:aws:ssm:us-west-1::parameter/aws/service/global-infrastructure/regions/cn-north-1", + "ARN": ( + "arn:aws:ssm:us-west-1::parameter/aws/service" + "/global-infrastructure/regions/cn-north-1" + ), "DataType": "text", "Name": "/aws/service/global-infrastructure/regions/cn-north-1", "Type": "String", @@ -29,9 +35,16 @@ SOURCE_PARAMS = [ "Version": 1, }, { - "ARN": "arn:aws:ssm:us-west-1::parameter/aws/service/global-infrastructure/regions/ap-northeast-2/services/codestar-notifications", + "ARN": ( + "arn:aws:ssm:us-west-1::parameter/aws/service" + "/global-infrastructure/regions/ap-northeast-2/services" + "/codestar-notifications" + ), "DataType": "text", - "Name": "/aws/service/global-infrastructure/regions/ap-northeast-2/services/codestar-notifications", + "Name": ( + "/aws/service/global-infrastructure/regions" + "/ap-northeast-2/services/codestar-notifications" + ), "Type": "String", "Value": "codestar-notifications", "Version": 1, @@ -73,7 +86,10 @@ CONVERTED_PARAMS = [ "Value": "ap-northeast-2", }, { - "Name": "/aws/service/global-infrastructure/regions/ap-northeast-2/services/codestar-notifications", + "Name": ( + "/aws/service/global-infrastructure/regions/ap-northeast-2" + "/services/codestar-notifications" + ), "Value": "codestar-notifications", }, ] @@ -82,20 +98,18 @@ CONVERTED_PARAMS = [ def test_convert_to_tree(): tree = convert_to_tree(SOURCE_PARAMS) - tree.should.equal(EXPECTED_TREE) + assert tree == EXPECTED_TREE def test_convert_to_params(): actual = convert_to_params(EXPECTED_TREE) - actual.should.have.length_of(len(CONVERTED_PARAMS)) + assert len(actual) == len(CONVERTED_PARAMS) for param in CONVERTED_PARAMS: - actual.should.contain(param) + assert param in actual def test_input_is_correct(): - """ - Test input should match - """ + """Test input should match.""" for src in SOURCE_PARAMS: minimized_src = {"Name": src["Name"], "Value": src["Value"]} - CONVERTED_PARAMS.should.contain(minimized_src) + assert minimized_src in CONVERTED_PARAMS