|
7 | 7 | import fs |
8 | 8 | import requests |
9 | 9 | from google.api_core.exceptions import BadRequest, Conflict, NotFound |
| 10 | +from google.auth.credentials import AnonymousCredentials, Signing |
10 | 11 |
|
11 | 12 | from gcp_storage_emulator.server import create_server |
12 | 13 | from gcp_storage_emulator.settings import STORAGE_BASE, STORAGE_DIR |
13 | 14 |
|
14 | 15 |
|
| 16 | +class FakeSigningCredentials(Signing, AnonymousCredentials): |
| 17 | + def sign_bytes(self, message): |
| 18 | + return b"foobar" |
| 19 | + |
| 20 | + @property |
| 21 | + def signer_email(self): |
| 22 | + return "foobar@example.tld" |
| 23 | + |
| 24 | + @property |
| 25 | + def signer(self): |
| 26 | + pass |
| 27 | + |
| 28 | + |
15 | 29 | def _get_storage_client(http): |
16 | 30 | """Gets a python storage client""" |
17 | 31 | os.environ["STORAGE_EMULATOR_HOST"] = "http://localhost:9023" |
@@ -780,6 +794,49 @@ def test_empty_blob(self): |
780 | 794 | fetched_content = blob.download_as_bytes() |
781 | 795 | self.assertEqual(fetched_content, b"") |
782 | 796 |
|
| 797 | + def test_signed_url_download(self): |
| 798 | + content = b"The quick brown fox jumps over the lazy dog" |
| 799 | + bucket = self._client.create_bucket("testbucket") |
| 800 | + |
| 801 | + blob = bucket.blob("signed-download") |
| 802 | + blob.upload_from_string(content) |
| 803 | + |
| 804 | + url = blob.generate_signed_url( |
| 805 | + api_access_endpoint="http://localhost:9023", |
| 806 | + credentials=FakeSigningCredentials(), |
| 807 | + version="v4", |
| 808 | + expiration=datetime.timedelta(minutes=15), |
| 809 | + method="GET", |
| 810 | + ) |
| 811 | + |
| 812 | + response = requests.get(url) |
| 813 | + self.assertEqual(response.content, content) |
| 814 | + |
| 815 | + def test_signed_url_upload(self): |
| 816 | + test_text = os.path.join( |
| 817 | + os.path.dirname(os.path.abspath(__file__)), "test_text.txt" |
| 818 | + ) |
| 819 | + bucket = self._client.create_bucket("testbucket") |
| 820 | + |
| 821 | + blob = bucket.blob("signed-upload") |
| 822 | + url = blob.generate_signed_url( |
| 823 | + api_access_endpoint="http://localhost:9023", |
| 824 | + credentials=FakeSigningCredentials(), |
| 825 | + version="v4", |
| 826 | + expiration=datetime.timedelta(minutes=15), |
| 827 | + method="PUT", |
| 828 | + ) |
| 829 | + |
| 830 | + with open(test_text, "rb") as file: |
| 831 | + headers = {"Content-type": "text/plain"} |
| 832 | + response = requests.put(url, data=file, headers=headers) |
| 833 | + self.assertEqual(response.status_code, 200) |
| 834 | + |
| 835 | + blob_content = blob.download_as_bytes() |
| 836 | + file.seek(0) |
| 837 | + self.assertEqual(blob_content, file.read()) |
| 838 | + self.assertEqual(blob.content_type, "text/plain") |
| 839 | + |
783 | 840 |
|
784 | 841 | class HttpEndpointsTest(ServerBaseCase): |
785 | 842 | """Tests for the HTTP endpoints defined by server.HANDLERS.""" |
|
0 commit comments