Repository: getmoto/moto (python)

Issue:
S3_IGNORE_SUBDOMAIN_BUCKETNAME undocumented + AWS_ENDPOINT_URL gotcha
TL;DR - some additional guidance on the two gotchas that I hit in the past couple days could be added to the docs. I can try to take a stab at some language if you think that makes sense

I've been using moto for a fair bit, but lately started using the server mode for integration tests a bit more deeply.

This reproduction case is run on Ubuntu 22.04. I installed moto like this:
```
pipx install moto[server]
```

I launched the server with `moto_server` in one terminal.

In another, I ran this with aws 2.15.27

```
export AWS_ENDPOINT_URL=http://localhost:5000
aws cloudformation deploy --debug --template-file ./test1.yaml --s3-bucket test-bucket --s3-prefix test-prefix --stack-name test-stack --region us-east-1
```

using this yaml:

```
AWSTemplateFormatVersion: 2010-09-09
Description: dummy test
Resources:
    RandomSSMParameter:
        Type: AWS::SSM::Parameter
        Properties:
        Name: /my/test
        Type: String
        Value: "simple string"
```

I got the following error:

```
botocore.exceptions.ClientError: An error occurred (Unknown) when calling the CreateChangeSet operation: Unknown

An error occurred (Unknown) when calling the CreateChangeSet operation: Unknown
```

I initially noticed a NoSuchBucket which led me to https://github.com/getmoto/moto/issues/2915 where I learned about `S3_IGNORE_SUBDOMAIN_BUCKETNAME`. I restarted the server with that, which resolved NoSuchBucket error but it still failed.

After stepping thru some code and poking around at issues a bit, I retried the command with this instead: `export AWS_ENDPOINT_URL=http://localhost:5000`

That worked.

I originally used 127.0.0.1 instead of localhost as I watched https://www.youtube.com/watch?v=98SYTvNw1kw because I've been hit by localhost resolving to an ipv6 before and I figured I'd cut that out, but I can understand why dealing with the IP address can be challenging in some cases.

Anyway, I did try to review the docs carefully as I hit this issue, and in looking back over them I found that there's nothing about `S3_IGNORE_SUBDOMAIN_BUCKETNAME` https://docs.getmoto.org/en/latest/search.html?q=S3_IGNORE_SUBDOMAIN_BUCKETNAME&check_keywords=yes&area=default#

The docs over at https://docs.getmoto.org/en/latest/docs/server_mode.html do use `localhost:5000` but it might be worth pointing out that `127.0.0.1:5000` is not an adequate replacement.

Pull request:
S3: Document usecase of S3_IGNORE_SUBDOMAIN_BUCKETNAME
Fixes #7488 

Patch:
diff --git a/docs/docs/configuration/environment_variables.rst b/docs/docs/configuration/environment_variables.rst
index 2cc0382c0..fc7530b9e 100644
--- a/docs/docs/configuration/environment_variables.rst
+++ b/docs/docs/configuration/environment_variables.rst
@@ -34,6 +34,8 @@ The following is a non-exhaustive list of the environment variables that can be
 +-------------------------------+----------+-----------+-------------------------------------------------------------------------------------------------+
 | MOTO_S3_DEFAULT_MAX_KEYS      | str      |           | See :ref:`s3`.                                                                                  |
 +-------------------------------+----------+-----------+-------------------------------------------------------------------------------------------------+
+| S3_IGNORE_SUBDOMAIN_BUCKETNAME| str      |           | See :ref:`s3`.                                                                                  |
++-------------------------------+----------+-----------+-------------------------------------------------------------------------------------------------+
 | MOTO_PRETTIFY_RESPONSES       | bool     | False     | Prettify responses from Moto, making it easier to read and debug.                               |
 +-------------------------------+----------+-----------+-------------------------------------------------------------------------------------------------+
 
diff --git a/docs/docs/server_mode.rst b/docs/docs/server_mode.rst
index 3e8f1fc50..fd9c8c4ba 100644
--- a/docs/docs/server_mode.rst
+++ b/docs/docs/server_mode.rst
@@ -198,6 +198,10 @@ Other languages:
 * `Javascript`_
 
 
+.. warning::
+
+    Note that we use `localhost` everywhere here - 127.0.0.1 is not an adequate replacement, and may not work.
+
 Use ServerMode using the decorators
 -------------------------------------
 
diff --git a/moto/s3/exceptions.py b/moto/s3/exceptions.py
index 237096533..e17861a83 100644
--- a/moto/s3/exceptions.py
+++ b/moto/s3/exceptions.py
@@ -203,6 +203,26 @@ class IllegalLocationConstraintException(S3ClientError):
         )
 
 
+class IncompatibleLocationConstraintException(S3ClientError):
+    code = 400
+
+    def __init__(self, location: str) -> None:
+        super().__init__(
+            "IllegalLocationConstraintException",
+            f"The {location} location constraint is incompatible for the region specific endpoint this request was sent to.",
+        )
+
+
+class InvalidLocationConstraintException(S3ClientError):
+    code = 400
+
+    def __init__(self) -> None:
+        super().__init__(
+            "InvalidLocationConstraint",
+            "The specified location-constraint is not valid",
+        )
+
+
 class MalformedXML(S3ClientError):
     code = 400
 
diff --git a/moto/s3/models.py b/moto/s3/models.py
index ce7010700..b63043ebc 100644
--- a/moto/s3/models.py
+++ b/moto/s3/models.py
@@ -1686,6 +1686,20 @@ class S3Backend(BaseBackend, CloudWatchMetricProvider):
 
     If this dependency is not installed, Moto will fall-back to the CRC32-computation when computing checksums.
 
+    _-_-_-_
+
+    S3 has two endpoint styles, where the bucket name can be either part of the domain (bucket.s3.amazonaws.com) or part of the path (s3.amazonaws.com/bucket).
+
+    If you're running MotoServer on a custom host, for instance on `http://moto.service:5000`, a CreateBucket-request then becomes `http://moto.service:5000/bucketname`.
+
+    However, because Moto tries to get the bucket-name from the domain first, it will think that 'moto' is the bucket name.
+
+    You can disable this behaviour with an environment variable, so that Moto will always look at the path instead:
+
+    .. sourcecode:: bash
+
+        S3_IGNORE_SUBDOMAIN_BUCKETNAME=true
+
     """
 
     def __init__(self, region_name: str, account_id: str):
diff --git a/moto/s3/responses.py b/moto/s3/responses.py
index 90aba14eb..9e4f69399 100644
--- a/moto/s3/responses.py
+++ b/moto/s3/responses.py
@@ -32,8 +32,10 @@ from .exceptions import (
     DuplicateTagKeys,
     HeadOnDeleteMarker,
     IllegalLocationConstraintException,
+    IncompatibleLocationConstraintException,
     InvalidContentMD5,
     InvalidContinuationToken,
+    InvalidLocationConstraintException,
     InvalidMaxPartArgument,
     InvalidMaxPartNumberArgument,
     InvalidNotificationARN,
@@ -736,27 +738,15 @@ class S3Response(BaseResponse):
                 result_folders.append(key)
         return result_keys, result_folders
 
-    def _body_contains_location_constraint(self, body: bytes) -> bool:
-        if body:
-            try:
-                xmltodict.parse(body)["CreateBucketConfiguration"]["LocationConstraint"]
-                return True
-            except KeyError:
-                pass
-        return False
-
-    def _create_bucket_configuration_is_empty(self, body: bytes) -> bool:
-        if body:
-            try:
-                create_bucket_configuration = xmltodict.parse(body)[
-                    "CreateBucketConfiguration"
+    def _get_location_constraint(self) -> Optional[str]:
+        try:
+            if self.body:
+                return xmltodict.parse(self.body)["CreateBucketConfiguration"][
+                    "LocationConstraint"
                 ]
-                del create_bucket_configuration["@xmlns"]
-                if len(create_bucket_configuration) == 0:
-                    return True
-            except KeyError:
-                pass
-        return False
+        except KeyError:
+            pass
+        return None
 
     def _parse_pab_config(self) -> Dict[str, Any]:
         parsed_xml = xmltodict.parse(self.body)
@@ -885,31 +875,20 @@ class S3Response(BaseResponse):
 
         else:
             # us-east-1, the default AWS region behaves a bit differently
-            # - you should not use it as a location constraint --> it fails
-            # - querying the location constraint returns None
-            # - LocationConstraint has to be specified if outside us-east-1
-            if (
-                self.region != DEFAULT_REGION_NAME
-                and not self._body_contains_location_constraint(self.body)
-            ):
-                raise IllegalLocationConstraintException()
-            if self.body:
-                if self._create_bucket_configuration_is_empty(self.body):
-                    raise MalformedXML()
-                try:
-                    forced_region = xmltodict.parse(self.body)[
-                        "CreateBucketConfiguration"
-                    ]["LocationConstraint"]
-
-                    if forced_region == DEFAULT_REGION_NAME:
-                        raise S3ClientError(
-                            "InvalidLocationConstraint",
-                            "The specified location-constraint is not valid",
-                        )
-                    else:
-                        self.region = forced_region
-                except KeyError:
-                    pass
+            # - you should not use any location constraint
+            location_constraint = self._get_location_constraint()
+            if self.region == DEFAULT_REGION_NAME:
+                # REGION = us-east-1 - we should never receive a LocationConstraint
+                if location_constraint:
+                    raise InvalidLocationConstraintException
+            else:
+                # Non-Standard region - the LocationConstraint must be equal to the actual region the request was send to
+                if not location_constraint:
+                    raise IllegalLocationConstraintException()
+                if location_constraint != self.region:
+                    raise IncompatibleLocationConstraintException(location_constraint)
+            if self.body and not location_constraint:
+                raise MalformedXML()
 
             try:
                 new_bucket = self.backend.create_bucket(bucket_name, self.region)


Test patch:
diff --git a/tests/test_awslambda/test_lambda.py b/tests/test_awslambda/test_lambda.py
index 1490cc568..e22c99584 100644
--- a/tests/test_awslambda/test_lambda.py
+++ b/tests/test_awslambda/test_lambda.py
@@ -774,10 +774,7 @@ def test_get_function_code_signing_config(key):
 def test_get_function_by_arn():
     bucket_name = str(uuid4())
     s3_conn = boto3.client("s3", "us-east-1")
-    s3_conn.create_bucket(
-        Bucket=bucket_name,
-        CreateBucketConfiguration={"LocationConstraint": _lambda_region},
-    )
+    s3_conn.create_bucket(Bucket=bucket_name)
 
     zip_content = get_test_zip_file2()
     s3_conn.put_object(Bucket=bucket_name, Key="test.zip", Body=zip_content)
@@ -860,10 +857,7 @@ def test_delete_function():
 def test_delete_function_by_arn():
     bucket_name = str(uuid4())
     s3_conn = boto3.client("s3", "us-east-1")
-    s3_conn.create_bucket(
-        Bucket=bucket_name,
-        CreateBucketConfiguration={"LocationConstraint": _lambda_region},
-    )
+    s3_conn.create_bucket(Bucket=bucket_name)
 
     zip_content = get_test_zip_file2()
     s3_conn.put_object(Bucket=bucket_name, Key="test.zip", Body=zip_content)
diff --git a/tests/test_cloudformation/test_cloudformation_stack_integration.py b/tests/test_cloudformation/test_cloudformation_stack_integration.py
index 3b067d6dd..fa9f08a69 100644
--- a/tests/test_cloudformation/test_cloudformation_stack_integration.py
+++ b/tests/test_cloudformation/test_cloudformation_stack_integration.py
@@ -1045,7 +1045,7 @@ def test_stack_dynamodb_resources_integration():
 
 @mock_aws
 def test_create_log_group_using_fntransform():
-    s3_resource = boto3.resource("s3")
+    s3_resource = boto3.resource("s3", "us-west-2")
     s3_resource.create_bucket(
         Bucket="owi-common-cf",
         CreateBucketConfiguration={"LocationConstraint": "us-west-2"},
diff --git a/tests/test_cloudwatch/test_cloudwatch_boto3.py b/tests/test_cloudwatch/test_cloudwatch_boto3.py
index 7de4cb844..a64dc5d7e 100644
--- a/tests/test_cloudwatch/test_cloudwatch_boto3.py
+++ b/tests/test_cloudwatch/test_cloudwatch_boto3.py
@@ -1527,8 +1527,8 @@ def test_cloudwatch_return_s3_metrics():
     cloudwatch = boto3.client("cloudwatch", "eu-west-3")
 
     # given
-    s3 = boto3.resource("s3")
-    s3_client = boto3.client("s3")
+    s3 = boto3.resource("s3", "eu-west-3")
+    s3_client = boto3.client("s3", "eu-west-3")
     bucket = s3.Bucket(bucket_name)
     bucket.create(CreateBucketConfiguration={"LocationConstraint": "eu-west-3"})
     bucket.put_object(Body=b"ABCD", Key="file.txt")
diff --git a/tests/test_firehose/test_firehose_put.py b/tests/test_firehose/test_firehose_put.py
index 87f3e4385..8d58d6ce5 100644
--- a/tests/test_firehose/test_firehose_put.py
+++ b/tests/test_firehose/test_firehose_put.py
@@ -12,8 +12,6 @@ from tests.test_firehose.test_firehose_destination_types import (
     create_redshift_delivery_stream,
 )
 
-S3_LOCATION_CONSTRAINT = "us-west-1"
-
 
 @mock_aws
 def test_put_record_redshift_destination():
@@ -113,10 +111,13 @@ def test_put_record_batch_extended_s3_destination():
     # Create a S3 bucket.
     bucket_name = "firehosetestbucket"
     s3_client = boto3.client("s3", region_name=TEST_REGION)
-    s3_client.create_bucket(
-        Bucket=bucket_name,
-        CreateBucketConfiguration={"LocationConstraint": S3_LOCATION_CONSTRAINT},
-    )
+    if TEST_REGION == "us-east-1":
+        s3_client.create_bucket(Bucket=bucket_name)
+    else:
+        s3_client.create_bucket(
+            Bucket=bucket_name,
+            CreateBucketConfiguration={"LocationConstraint": TEST_REGION},
+        )
 
     stream_name = f"test_put_record_{mock_random.get_random_hex(6)}"
     client.create_delivery_stream(
diff --git a/tests/test_logs/test_integration.py b/tests/test_logs/test_integration.py
index 2d1604f04..5a079686f 100644
--- a/tests/test_logs/test_integration.py
+++ b/tests/test_logs/test_integration.py
@@ -275,10 +275,7 @@ def test_put_subscription_filter_with_firehose():
     # Create a S3 bucket.
     bucket_name = "firehosetestbucket"
     s3_client = boto3.client("s3", region_name=region_name)
-    s3_client.create_bucket(
-        Bucket=bucket_name,
-        CreateBucketConfiguration={"LocationConstraint": "us-west-1"},
-    )
+    s3_client.create_bucket(Bucket=bucket_name)
 
     # Create the Firehose delivery stream that uses that S3 bucket as
     # the destination.
diff --git a/tests/test_s3/test_s3.py b/tests/test_s3/test_s3.py
index 00f43216e..9a9f0c863 100644
--- a/tests/test_s3/test_s3.py
+++ b/tests/test_s3/test_s3.py
@@ -24,7 +24,7 @@ from moto.core.utils import utcnow
 from moto.moto_api import state_manager
 from moto.s3.models import s3_backends
 from moto.s3.responses import DEFAULT_REGION_NAME
-from tests import DEFAULT_ACCOUNT_ID
+from tests import DEFAULT_ACCOUNT_ID, aws_verified
 
 from . import s3_aws_verified
 
@@ -271,6 +271,27 @@ def test_create_existing_bucket():
     )
 
 
+@aws_verified
+@pytest.mark.aws_verified
+@pytest.mark.parametrize(
+    "constraint", ["us-east-1", "us-east-2", "eu-central-1", "us-gov-east-2"]
+)
+def test_create_bucket_with_wrong_location_constraint(constraint):
+    client = boto3.client("s3", region_name="us-west-2")
+    kwargs = {
+        "Bucket": str(uuid.uuid4()),
+        "CreateBucketConfiguration": {"LocationConstraint": constraint},
+    }
+    with pytest.raises(ClientError) as ex:
+        client.create_bucket(**kwargs)
+    err = ex.value.response["Error"]
+    assert err["Code"] == "IllegalLocationConstraintException"
+    assert (
+        err["Message"]
+        == f"The {constraint} location constraint is incompatible for the region specific endpoint this request was sent to."
+    )
+
+
 @mock_aws
 def test_create_existing_bucket_in_us_east_1():
     """Creating a bucket that already exists in us-east-1 returns the bucket.
@@ -934,11 +955,9 @@ def test_put_chunked_with_v4_signature_in_body():
 
 @mock_aws
 def test_s3_object_in_private_bucket():
-    s3_resource = boto3.resource("s3")
+    s3_resource = boto3.resource("s3", "us-east-1")
     bucket = s3_resource.Bucket("test-bucket")
-    bucket.create(
-        ACL="private", CreateBucketConfiguration={"LocationConstraint": "us-west-1"}
-    )
+    bucket.create(ACL="private")
     bucket.put_object(ACL="private", Body=b"ABCD", Key="file.txt")
 
     s3_anonymous = boto3.resource("s3")
@@ -1580,7 +1599,8 @@ def test_bucket_create():
     )
 
 
-@mock_aws
+@aws_verified
+@pytest.mark.aws_verified
 def test_bucket_create_force_us_east_1():
     s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
     with pytest.raises(ClientError) as exc:
@@ -1589,6 +1609,10 @@ def test_bucket_create_force_us_east_1():
             CreateBucketConfiguration={"LocationConstraint": DEFAULT_REGION_NAME},
         )
     assert exc.value.response["Error"]["Code"] == "InvalidLocationConstraint"
+    assert (
+        exc.value.response["Error"]["Message"]
+        == "The specified location-constraint is not valid"
+    )
 
 
 @mock_aws
@@ -2696,11 +2720,8 @@ def test_can_suspend_bucket_acceleration():
 @mock_aws
 def test_suspending_acceleration_on_not_configured_bucket_does_nothing():
     bucket_name = "some_bucket"
-    s3_client = boto3.client("s3")
-    s3_client.create_bucket(
-        Bucket=bucket_name,
-        CreateBucketConfiguration={"LocationConstraint": "us-west-1"},
-    )
+    s3_client = boto3.client("s3", DEFAULT_REGION_NAME)
+    s3_client.create_bucket(Bucket=bucket_name)
     resp = s3_client.put_bucket_accelerate_configuration(
         Bucket=bucket_name, AccelerateConfiguration={"Status": "Suspended"}
     )
diff --git a/tests/test_s3/test_s3_acl.py b/tests/test_s3/test_s3_acl.py
index 9dd998c12..2b4f65a6f 100644
--- a/tests/test_s3/test_s3_acl.py
+++ b/tests/test_s3/test_s3_acl.py
@@ -81,11 +81,9 @@ def test_acl_switching_nonexistent_key():
 
 @mock_aws
 def test_s3_object_in_public_bucket():
-    s3_resource = boto3.resource("s3")
+    s3_resource = boto3.resource("s3", DEFAULT_REGION_NAME)
     bucket = s3_resource.Bucket("test-bucket")
-    bucket.create(
-        ACL="public-read", CreateBucketConfiguration={"LocationConstraint": "us-west-1"}
-    )
+    bucket.create(ACL="public-read")
     bucket.put_object(Body=b"ABCD", Key="file.txt")
 
     s3_anonymous = boto3.resource("s3")
@@ -107,11 +105,9 @@ def test_s3_object_in_public_bucket():
 
 @mock_aws
 def test_s3_object_in_public_bucket_using_multiple_presigned_urls():
-    s3_resource = boto3.resource("s3")
+    s3_resource = boto3.resource("s3", DEFAULT_REGION_NAME)
     bucket = s3_resource.Bucket("test-bucket")
-    bucket.create(
-        ACL="public-read", CreateBucketConfiguration={"LocationConstraint": "us-west-1"}
-    )
+    bucket.create(ACL="public-read")
     bucket.put_object(Body=b"ABCD", Key="file.txt")
 
     params = {"Bucket": "test-bucket", "Key": "file.txt"}
@@ -128,11 +124,9 @@ def test_s3_object_in_public_bucket_using_multiple_presigned_urls():
 
 @mock_aws
 def test_s3_object_in_private_bucket():
-    s3_resource = boto3.resource("s3")
+    s3_resource = boto3.resource("s3", DEFAULT_REGION_NAME)
     bucket = s3_resource.Bucket("test-bucket")
-    bucket.create(
-        ACL="private", CreateBucketConfiguration={"LocationConstraint": "us-west-1"}
-    )
+    bucket.create(ACL="private")
     bucket.put_object(ACL="private", Body=b"ABCD", Key="file.txt")
 
     s3_anonymous = boto3.resource("s3")
diff --git a/tests/test_s3/test_s3_copyobject.py b/tests/test_s3/test_s3_copyobject.py
index 08ea47521..a75f18cc4 100644
--- a/tests/test_s3/test_s3_copyobject.py
+++ b/tests/test_s3/test_s3_copyobject.py
@@ -392,12 +392,8 @@ def test_copy_object_with_versioning(bucket_name=None):
 def test_copy_object_from_unversioned_to_versioned_bucket():
     client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
 
-    client.create_bucket(
-        Bucket="src", CreateBucketConfiguration={"LocationConstraint": "eu-west-1"}
-    )
-    client.create_bucket(
-        Bucket="dest", CreateBucketConfiguration={"LocationConstraint": "eu-west-1"}
-    )
+    client.create_bucket(Bucket="src")
+    client.create_bucket(Bucket="dest")
     client.put_bucket_versioning(
         Bucket="dest", VersioningConfiguration={"Status": "Enabled"}
     )
@@ -459,9 +455,7 @@ def test_copy_object_with_kms_encryption():
     kms_client = boto3.client("kms", region_name=DEFAULT_REGION_NAME)
     kms_key = kms_client.create_key()["KeyMetadata"]["KeyId"]
 
-    client.create_bucket(
-        Bucket="blah", CreateBucketConfiguration={"LocationConstraint": "eu-west-1"}
-    )
+    client.create_bucket(Bucket="blah")
 
     client.put_object(Bucket="blah", Key="test1", Body=b"test1")
 
diff --git a/tests/test_s3/test_s3_lifecycle.py b/tests/test_s3/test_s3_lifecycle.py
index b43789139..569c7c74f 100644
--- a/tests/test_s3/test_s3_lifecycle.py
+++ b/tests/test_s3/test_s3_lifecycle.py
@@ -5,14 +5,13 @@ import pytest
 from botocore.exceptions import ClientError
 
 from moto import mock_aws
+from moto.s3.responses import DEFAULT_REGION_NAME
 
 
 @mock_aws
 def test_lifecycle_with_filters():
-    client = boto3.client("s3")
-    client.create_bucket(
-        Bucket="bucket", CreateBucketConfiguration={"LocationConstraint": "us-west-1"}
-    )
+    client = boto3.client("s3", DEFAULT_REGION_NAME)
+    client.create_bucket(Bucket="bucket")
 
     # Create a lifecycle rule with a Filter (no tags):
     lfc = {
@@ -223,10 +222,8 @@ def test_lifecycle_with_filters():
 
 @mock_aws
 def test_lifecycle_with_eodm():
-    client = boto3.client("s3")
-    client.create_bucket(
-        Bucket="bucket", CreateBucketConfiguration={"LocationConstraint": "us-west-1"}
-    )
+    client = boto3.client("s3", DEFAULT_REGION_NAME)
+    client.create_bucket(Bucket="bucket")
 
     lfc = {
         "Rules": [
@@ -273,10 +270,8 @@ def test_lifecycle_with_eodm():
 
 @mock_aws
 def test_lifecycle_with_nve():
-    client = boto3.client("s3")
-    client.create_bucket(
-        Bucket="bucket", CreateBucketConfiguration={"LocationConstraint": "us-west-1"}
-    )
+    client = boto3.client("s3", DEFAULT_REGION_NAME)
+    client.create_bucket(Bucket="bucket")
 
     lfc = {
         "Rules": [
@@ -309,10 +304,8 @@ def test_lifecycle_with_nve():
 
 @mock_aws
 def test_lifecycle_with_nvt():
-    client = boto3.client("s3")
-    client.create_bucket(
-        Bucket="bucket", CreateBucketConfiguration={"LocationConstraint": "us-west-1"}
-    )
+    client = boto3.client("s3", DEFAULT_REGION_NAME)
+    client.create_bucket(Bucket="bucket")
 
     lfc = {
         "Rules": [
@@ -377,10 +370,8 @@ def test_lifecycle_with_nvt():
 
 @mock_aws
 def test_lifecycle_with_multiple_nvt():
-    client = boto3.client("s3")
-    client.create_bucket(
-        Bucket="bucket", CreateBucketConfiguration={"LocationConstraint": "us-west-1"}
-    )
+    client = boto3.client("s3", DEFAULT_REGION_NAME)
+    client.create_bucket(Bucket="bucket")
 
     lfc = {
         "Rules": [
@@ -412,10 +403,8 @@ def test_lifecycle_with_multiple_nvt():
 
 @mock_aws
 def test_lifecycle_with_multiple_transitions():
-    client = boto3.client("s3")
-    client.create_bucket(
-        Bucket="bucket", CreateBucketConfiguration={"LocationConstraint": "us-west-1"}
-    )
+    client = boto3.client("s3", DEFAULT_REGION_NAME)
+    client.create_bucket(Bucket="bucket")
 
     lfc = {
         "Rules": [
@@ -447,10 +436,8 @@ def test_lifecycle_with_multiple_transitions():
 
 @mock_aws
 def test_lifecycle_with_aimu():
-    client = boto3.client("s3")
-    client.create_bucket(
-        Bucket="bucket", CreateBucketConfiguration={"LocationConstraint": "us-west-1"}
-    )
+    client = boto3.client("s3", DEFAULT_REGION_NAME)
+    client.create_bucket(Bucket="bucket")
 
     lfc = {
         "Rules": [
diff --git a/tests/test_s3/test_s3_logging.py b/tests/test_s3/test_s3_logging.py
index d0a4c39d9..a728f3547 100644
--- a/tests/test_s3/test_s3_logging.py
+++ b/tests/test_s3/test_s3_logging.py
@@ -19,13 +19,14 @@ from tests.test_s3 import empty_bucket, s3_aws_verified
 @mock_aws
 def test_put_bucket_logging():
     s3_client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
+    wrong_region_client = boto3.client("s3", region_name="us-west-2")
     bucket_name = "mybucket"
     log_bucket = "logbucket"
     wrong_region_bucket = "wrongregionlogbucket"
     s3_client.create_bucket(Bucket=bucket_name)
     # Adding the ACL for log-delivery later...
     s3_client.create_bucket(Bucket=log_bucket)
-    s3_client.create_bucket(
+    wrong_region_client.create_bucket(
         Bucket=wrong_region_bucket,
         CreateBucketConfiguration={"LocationConstraint": "us-west-2"},
     )
diff --git a/tests/test_s3/test_s3_storageclass.py b/tests/test_s3/test_s3_storageclass.py
index f2c202373..f40c97ee6 100644
--- a/tests/test_s3/test_s3_storageclass.py
+++ b/tests/test_s3/test_s3_storageclass.py
@@ -3,11 +3,12 @@ import pytest
 from botocore.exceptions import ClientError
 
 from moto import mock_aws
+from moto.s3.responses import DEFAULT_REGION_NAME
 
 
 @mock_aws
 def test_s3_storage_class_standard():
-    s3_client = boto3.client("s3", region_name="us-east-1")
+    s3_client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
     s3_client.create_bucket(Bucket="Bucket")
 
     # add an object to the bucket with standard storage
@@ -21,10 +22,8 @@ def test_s3_storage_class_standard():
 
 @mock_aws
 def test_s3_storage_class_infrequent_access():
-    s3_client = boto3.client("s3")
-    s3_client.create_bucket(
-        Bucket="Bucket", CreateBucketConfiguration={"LocationConstraint": "us-west-2"}
-    )
+    s3_client = boto3.client("s3", DEFAULT_REGION_NAME)
+    s3_client.create_bucket(Bucket="Bucket")
 
     # add an object to the bucket with standard storage
 
@@ -42,11 +41,9 @@ def test_s3_storage_class_infrequent_access():
 
 @mock_aws
 def test_s3_storage_class_intelligent_tiering():
-    s3_client = boto3.client("s3")
+    s3_client = boto3.client("s3", DEFAULT_REGION_NAME)
 
-    s3_client.create_bucket(
-        Bucket="Bucket", CreateBucketConfiguration={"LocationConstraint": "us-east-2"}
-    )
+    s3_client.create_bucket(Bucket="Bucket")
     s3_client.put_object(
         Bucket="Bucket",
         Key="my_key_infrequent",
@@ -118,10 +115,8 @@ def test_s3_invalid_copied_storage_class():
 
 @mock_aws
 def test_s3_invalid_storage_class():
-    s3_client = boto3.client("s3")
-    s3_client.create_bucket(
-        Bucket="Bucket", CreateBucketConfiguration={"LocationConstraint": "us-west-1"}
-    )
+    s3_client = boto3.client("s3", DEFAULT_REGION_NAME)
+    s3_client.create_bucket(Bucket="Bucket")
 
     # Try to add an object with an invalid storage class
     with pytest.raises(ClientError) as err:
@@ -138,10 +133,8 @@ def test_s3_invalid_storage_class():
 
 @mock_aws
 def test_s3_default_storage_class():
-    s3_client = boto3.client("s3")
-    s3_client.create_bucket(
-        Bucket="Bucket", CreateBucketConfiguration={"LocationConstraint": "us-west-1"}
-    )
+    s3_client = boto3.client("s3", DEFAULT_REGION_NAME)
+    s3_client.create_bucket(Bucket="Bucket")
 
     s3_client.put_object(Bucket="Bucket", Key="First_Object", Body="Body")
 
@@ -153,10 +146,8 @@ def test_s3_default_storage_class():
 
 @mock_aws
 def test_s3_copy_object_error_for_glacier_storage_class_not_restored():
-    s3_client = boto3.client("s3")
-    s3_client.create_bucket(
-        Bucket="Bucket", CreateBucketConfiguration={"LocationConstraint": "us-west-1"}
-    )
+    s3_client = boto3.client("s3", DEFAULT_REGION_NAME)
+    s3_client.create_bucket(Bucket="Bucket")
 
     s3_client.put_object(
         Bucket="Bucket", Key="First_Object", Body="Body", StorageClass="GLACIER"
@@ -174,10 +165,8 @@ def test_s3_copy_object_error_for_glacier_storage_class_not_restored():
 
 @mock_aws
 def test_s3_copy_object_error_for_deep_archive_storage_class_not_restored():
-    s3_client = boto3.client("s3")
-    s3_client.create_bucket(
-        Bucket="Bucket", CreateBucketConfiguration={"LocationConstraint": "us-west-1"}
-    )
+    s3_client = boto3.client("s3", DEFAULT_REGION_NAME)
+    s3_client.create_bucket(Bucket="Bucket")
 
     s3_client.put_object(
         Bucket="Bucket", Key="First_Object", Body="Body", StorageClass="DEEP_ARCHIVE"
diff --git a/tests/test_sagemaker/test_sagemaker_pipeline.py b/tests/test_sagemaker/test_sagemaker_pipeline.py
index 30adf5540..862dc629e 100644
--- a/tests/test_sagemaker/test_sagemaker_pipeline.py
+++ b/tests/test_sagemaker/test_sagemaker_pipeline.py
@@ -26,7 +26,7 @@ TEST_REGION_NAME = "us-west-1"
 
 @contextmanager
 def setup_s3_pipeline_definition(bucket_name, object_key, pipeline_definition):
-    client = boto3.client("s3")
+    client = boto3.client("s3", TEST_REGION_NAME)
     client.create_bucket(
         Bucket=bucket_name,
         CreateBucketConfiguration={"LocationConstraint": TEST_REGION_NAME},