Techdebt: Replace sure with regular asserts in Cognito (#6496)

This commit is contained in:
Bert Blommers 2023-07-08 20:37:50 +00:00 committed by GitHub
parent 426a8ad5ea
commit 39313ffc5b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 591 additions and 594 deletions

View File

@ -1,6 +1,5 @@
import boto3 import boto3
from unittest import mock from unittest import mock
import sure # noqa # pylint: disable=unused-import
from botocore.exceptions import ClientError from botocore.exceptions import ClientError
from datetime import datetime from datetime import datetime
import pytest import pytest
@ -23,9 +22,10 @@ def test_create_identity_pool_invalid_name(name):
IdentityPoolName=name, AllowUnauthenticatedIdentities=False IdentityPoolName=name, AllowUnauthenticatedIdentities=False
) )
err = exc.value.response["Error"] err = exc.value.response["Error"]
err["Code"].should.equal("ValidationException") assert err["Code"] == "ValidationException"
err["Message"].should.equal( assert (
f"1 validation error detected: Value '{name}' at 'identityPoolName' failed to satisfy constraint: Member must satisfy regular expression pattern: [\\w\\s+=,.@-]+" err["Message"]
== f"1 validation error detected: Value '{name}' at 'identityPoolName' failed to satisfy constraint: Member must satisfy regular expression pattern: [\\w\\s+=,.@-]+"
) )
@ -118,7 +118,7 @@ def test_update_identity_pool(key, initial_value, updated_value):
) )
first = conn.describe_identity_pool(IdentityPoolId=res["IdentityPoolId"]) first = conn.describe_identity_pool(IdentityPoolId=res["IdentityPoolId"])
first[key].should.equal(initial_value) assert first[key] == initial_value
response = conn.update_identity_pool( response = conn.update_identity_pool(
IdentityPoolId=res["IdentityPoolId"], IdentityPoolId=res["IdentityPoolId"],
@ -126,10 +126,10 @@ def test_update_identity_pool(key, initial_value, updated_value):
AllowUnauthenticatedIdentities=False, AllowUnauthenticatedIdentities=False,
**dict({key: updated_value}), **dict({key: updated_value}),
) )
response[key].should.equal(updated_value) assert response[key] == updated_value
second = conn.describe_identity_pool(IdentityPoolId=res["IdentityPoolId"]) second = conn.describe_identity_pool(IdentityPoolId=res["IdentityPoolId"])
second[key].should.equal(response[key]) assert second[key] == response[key]
@mock_cognitoidentity @mock_cognitoidentity
@ -138,17 +138,17 @@ def test_describe_identity_pool_with_invalid_id_raises_error():
with pytest.raises(ClientError) as cm: with pytest.raises(ClientError) as cm:
conn.describe_identity_pool(IdentityPoolId="us-west-2_non-existent") conn.describe_identity_pool(IdentityPoolId="us-west-2_non-existent")
cm.value.operation_name.should.equal("DescribeIdentityPool") assert cm.value.operation_name == "DescribeIdentityPool"
cm.value.response["Error"]["Code"].should.equal("ResourceNotFoundException") assert cm.value.response["Error"]["Code"] == "ResourceNotFoundException"
cm.value.response["Error"]["Message"].should.equal("us-west-2_non-existent") assert cm.value.response["Error"]["Message"] == "us-west-2_non-existent"
cm.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) assert cm.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
# testing a helper function # testing a helper function
def test_get_random_identity_id(): def test_get_random_identity_id():
identity_id = get_random_identity_id("us-west-2") identity_id = get_random_identity_id("us-west-2")
region, identity_id = identity_id.split(":") region, identity_id = identity_id.split(":")
region.should.equal("us-west-2") assert region == "us-west-2"
UUID(identity_id, version=4) # Will throw an error if it's not a valid UUID UUID(identity_id, version=4) # Will throw an error if it's not a valid UUID
@ -189,8 +189,8 @@ def test_get_credentials_for_identity():
conn = boto3.client("cognito-identity", "us-west-2") conn = boto3.client("cognito-identity", "us-west-2")
result = conn.get_credentials_for_identity(IdentityId="12345") result = conn.get_credentials_for_identity(IdentityId="12345")
result["Credentials"].get("Expiration").should.be.a(datetime) assert isinstance(result["Credentials"]["Expiration"], datetime)
result.get("IdentityId").should.equal("12345") assert result.get("IdentityId") == "12345"
@mock_cognitoidentity @mock_cognitoidentity

View File

@ -1,7 +1,5 @@
import json import json
import sure # noqa # pylint: disable=unused-import
import moto.server as server import moto.server as server
from moto import mock_cognitoidentity from moto import mock_cognitoidentity

File diff suppressed because it is too large Load Diff

View File

@ -50,7 +50,7 @@ class TestCognitoUserDeleter(TestCase):
"REFRESH_TOKEN": refresh_token, "REFRESH_TOKEN": refresh_token,
}, },
) )
exc.exception.response["Error"]["Code"].should.equal("NotAuthorizedException") assert exc.exception.response["Error"]["Code"] == "NotAuthorizedException"
@mock_cognitoidp @mock_cognitoidp
@ -84,8 +84,8 @@ class TestCognitoUserPoolDuplidateEmails(TestCase):
UserAttributes=[{"Name": "email", "Value": "user2@test.com"}], UserAttributes=[{"Name": "email", "Value": "user2@test.com"}],
) )
err = exc.value.response["Error"] err = exc.value.response["Error"]
err["Code"].should.equal("AliasExistsException") assert err["Code"] == "AliasExistsException"
err["Message"].should.equal("An account with the given email already exists.") assert err["Message"] == "An account with the given email already exists."
def test_use_existing_email__when_username_is_login(self): def test_use_existing_email__when_username_is_login(self):
# Because we cannot use the email as username, # Because we cannot use the email as username,

View File

@ -2,7 +2,6 @@ import os
import boto3 import boto3
import uuid import uuid
import sure # noqa # pylint: disable=unused-import
import pytest import pytest
import requests import requests
@ -37,7 +36,7 @@ class TestCreateUserPoolWithPredeterminedID(TestCase):
resp = requests.get( resp = requests.get(
"http://localhost:5000/moto-api/recorder/download-recording" "http://localhost:5000/moto-api/recorder/download-recording"
) )
resp.status_code.should.equal(200) assert resp.status_code == 200
return resp.content.decode("utf-8") return resp.content.decode("utf-8")
else: else:
return recorder.download_recording() return recorder.download_recording()
@ -107,8 +106,8 @@ class TestCreateUserPoolWithPredeterminedID(TestCase):
with pytest.raises(ClientError) as exc: with pytest.raises(ClientError) as exc:
self.client.describe_user_pool(UserPoolId=self.pool_id) self.client.describe_user_pool(UserPoolId=self.pool_id)
err = exc.value.response["Error"] err = exc.value.response["Error"]
err["Code"].should.equal("ResourceNotFoundException") assert err["Code"] == "ResourceNotFoundException"
# It is created - just with a different ID # It is created - just with a different ID
all_pools = self.client.list_user_pools(MaxResults=5)["UserPools"] all_pools = self.client.list_user_pools(MaxResults=5)["UserPools"]
all_pools.should.have.length_of(1) assert len(all_pools) == 1

View File

@ -44,7 +44,7 @@ def test_sign_up_user_without_authentication():
"Authorization": "AWS4-HMAC-SHA256 Credential=abcd/20010101/us-east-2/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=...", "Authorization": "AWS4-HMAC-SHA256 Credential=abcd/20010101/us-east-2/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=...",
}, },
) )
json.loads(res.data)["UserPoolClients"].should.have.length_of(1) assert len(json.loads(res.data)["UserPoolClients"]) == 1
# Sign Up User # Sign Up User
data = {"ClientId": client_id, "Username": "test@gmail.com", "Password": "P2$Sword"} data = {"ClientId": client_id, "Username": "test@gmail.com", "Password": "P2$Sword"}
@ -53,8 +53,8 @@ def test_sign_up_user_without_authentication():
data=json.dumps(data), data=json.dumps(data),
headers={"X-Amz-Target": "AWSCognitoIdentityProviderService.SignUp"}, headers={"X-Amz-Target": "AWSCognitoIdentityProviderService.SignUp"},
) )
res.status_code.should.equal(200) assert res.status_code == 200
json.loads(res.data).should.have.key("UserConfirmed").equals(False) assert json.loads(res.data)["UserConfirmed"] is False
# Confirm Sign Up User # Confirm Sign Up User
data = { data = {
@ -79,7 +79,7 @@ def test_sign_up_user_without_authentication():
data=json.dumps(data), data=json.dumps(data),
headers={"X-Amz-Target": "AWSCognitoIdentityProviderService.InitiateAuth"}, headers={"X-Amz-Target": "AWSCognitoIdentityProviderService.InitiateAuth"},
) )
res.status_code.should.equal(200) assert res.status_code == 200
access_token = json.loads(res.data)["AuthenticationResult"]["AccessToken"] access_token = json.loads(res.data)["AuthenticationResult"]["AccessToken"]
# Get User # Get User
@ -89,11 +89,11 @@ def test_sign_up_user_without_authentication():
data=json.dumps(data), data=json.dumps(data),
headers={"X-Amz-Target": "AWSCognitoIdentityProviderService.GetUser"}, headers={"X-Amz-Target": "AWSCognitoIdentityProviderService.GetUser"},
) )
res.status_code.should.equal(200) assert res.status_code == 200
data = json.loads(res.data) data = json.loads(res.data)
data.should.have.key("UserPoolId").equals(user_pool_id) assert data["UserPoolId"] == user_pool_id
data.should.have.key("Username").equals("test@gmail.com") assert data["Username"] == "test@gmail.com"
data.should.have.key("UserStatus").equals("CONFIRMED") assert data["UserStatus"] == "CONFIRMED"
def test_admin_create_user_without_authentication(): def test_admin_create_user_without_authentication():
@ -142,7 +142,7 @@ def test_admin_create_user_without_authentication():
"Authorization": "AWS4-HMAC-SHA256 Credential=abcd/20010101/us-east-2/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=...", "Authorization": "AWS4-HMAC-SHA256 Credential=abcd/20010101/us-east-2/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=...",
}, },
) )
res.status_code.should.equal(200) assert res.status_code == 200
# Initiate Auth # Initiate Auth
data = { data = {
@ -174,9 +174,9 @@ def test_admin_create_user_without_authentication():
"X-Amz-Target": "AWSCognitoIdentityProviderService.RespondToAuthChallenge" "X-Amz-Target": "AWSCognitoIdentityProviderService.RespondToAuthChallenge"
}, },
) )
res.status_code.should.equal(200) assert res.status_code == 200
response = json.loads(res.data) response = json.loads(res.data)
response.should.have.key("AuthenticationResult") assert "AuthenticationResult" in response
response["AuthenticationResult"].should.have.key("IdToken") assert "IdToken" in response["AuthenticationResult"]
response["AuthenticationResult"].should.have.key("AccessToken") assert "AccessToken" in response["AuthenticationResult"]