Skip to content

Commit c98431a

Browse files
committed
mock s3 test
1 parent 621906a commit c98431a

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

tests/unit/test_mock_s3.py

+88
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import os
2+
import s3fs
3+
import pathlib
4+
from tempfile import NamedTemporaryFile
5+
import logging
6+
import boto3
7+
import moto
8+
import pyfive
9+
import pytest
10+
from botocore.exceptions import ClientError
11+
12+
13+
def file_upload(upload_file_bucket, file_name, file_path):
14+
if os.path.exists(file_path):
15+
with open(file_path, 'r') as f:
16+
xml = f.read()
17+
else:
18+
logging.error("File '%s' does not exist." % file_path)
19+
tools.exit_gracefully(botocore.log)
20+
try:
21+
conn = boto3.session.Session()
22+
s3 = conn.resource('s3')
23+
object = s3.Object(upload_file_bucket, file_name)
24+
result = object.put(Body=xml)
25+
res = result.get('ResponseMetadata')
26+
if res.get('HTTPStatusCode') == 200:
27+
logging.info('File Uploaded Successfully')
28+
else:
29+
logging.info('File Not Uploaded Successfully')
30+
return res
31+
except ClientError as e:
32+
logging.error(e)
33+
34+
35+
def file_load(bucket, file_name):
36+
conn = boto3.session.Session()
37+
s3 = conn.resource('s3')
38+
object = s3.Object(bucket, file_name)
39+
result = object.get(Range="0=2")
40+
print("S3 Test mock file:", result)
41+
42+
ds = pyfive.File(result)
43+
return ds
44+
45+
46+
@pytest.fixture(scope='session')
47+
def aws_credentials():
48+
"""Mocked AWS Credentials for moto."""
49+
os.environ['AWS_ACCESS_KEY_ID'] = 'testing'
50+
os.environ['AWS_SECRET_ACCESS_KEY'] = 'testing'
51+
os.environ['AWS_SECURITY_TOKEN'] = 'testing'
52+
os.environ['AWS_SESSION_TOKEN'] = 'testing'
53+
os.environ['AWS_DEFAULT_REGION'] = 'us-east-1'
54+
55+
try:
56+
tmp = NamedTemporaryFile(delete=False)
57+
# you many need to change 'aws_prof_dev_qa' to be your profile name
58+
tmp.write(b"""[aws_prof_dev_qa]
59+
aws_access_key_id = testing
60+
aws_secret_access_key = testing""")
61+
tmp.close()
62+
os.environ['AWS_SHARED_CREDENTIALS_FILE'] = str(tmp.name)
63+
yield
64+
finally:
65+
os.unlink(tmp.name)
66+
67+
68+
@pytest.fixture(scope='function')
69+
def empty_bucket(aws_credentials):
70+
moto_fake = moto.mock_aws()
71+
try:
72+
moto_fake.start()
73+
conn = boto3.resource('s3')
74+
conn.create_bucket(Bucket="MY_BUCKET")
75+
yield conn
76+
finally:
77+
moto_fake.stop()
78+
79+
80+
def test_file_upload(empty_bucket):
81+
with NamedTemporaryFile() as tmp:
82+
tmp.write(b'Hi')
83+
file_name = pathlib.Path(tmp.name).name
84+
85+
result = file_upload("MY_BUCKET", file_name, tmp.name)
86+
result2 = file_load("MY_BUCKET", file_name)
87+
88+
assert result.get('HTTPStatusCode') == 200

0 commit comments

Comments
 (0)