Skip to content

Commit

Permalink
Merge pull request #137 from supabase-community/move-subclients-tests…
Browse files Browse the repository at this point in the history
…-to-subclients

tests: move subclients tests to subclients
  • Loading branch information
dreinon authored Feb 3, 2022
2 parents 2cd8826 + ea00e58 commit 1d5aa55
Show file tree
Hide file tree
Showing 10 changed files with 169 additions and 119 deletions.
1 change: 0 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ jobs:
test:
name: Test / OS ${{ matrix.os }} / Python ${{ matrix.python-version }}
strategy:
max-parallel: 1
matrix:
os: [ubuntu-latest]
python-version: [3.7, 3.8, 3.9, '3.10']
Expand Down
10 changes: 4 additions & 6 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,12 @@ install_poetry:
curl -sSL https://install.python-poetry.org | python -
poetry install

tests: install tests_only tests_pre_commit

tests_pre_commit:
poetry run pre-commit run --all-files

run_tests: tests

tests_only:
export SUPABASE_TEST_KEY="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiIsImlhdCI6MTYzNTAwODQ4NywiZXhwIjoxOTUwNTg0NDg3fQ.l8IgkO7TQokGSc9OJoobXIVXsOXkilXl4Ak6SCX5qI8" &&\
export SUPABASE_TEST_URL="https://ibrydvrsxoapzgtnhpso.supabase.co" &&\
poetry run pytest --cov=./ --cov-report=xml --cov-report=html -vv

tests: install tests_only tests_pre_commit

run_tests: tests
17 changes: 16 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ isort = "^5.9.3"
pytest-cov = "^3.0.0"
commitizen = "^2.20.3"
python-semantic-release = "^7.24.0"
python-dotenv = "^0.19.2"

[tool.semantic_release]
version_variable = "supabase/__init__.py:__version__"
Expand Down
2 changes: 1 addition & 1 deletion supabase/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
from supabase.client import Client, create_client
from supabase.lib.auth_client import SupabaseAuthClient
from supabase.lib.realtime_client import SupabaseRealtimeClient
from supabase.lib.storage_client import SupabaseStorageClient
from supabase.lib.storage_client import StorageFileAPI, SupabaseStorageClient
16 changes: 8 additions & 8 deletions supabase/lib/storage/storage_bucket_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ class StorageBucketAPI:
"""This class abstracts access to the endpoint to the Get, List, Empty, and Delete operations on a bucket"""

def __init__(
self, url: str, headers: dict[str, str], is_async: bool = False
self, url: str, headers: Dict[str, str], is_async: bool = False
) -> None:
self.url = url
self.headers = headers
Expand All @@ -64,7 +64,7 @@ def _request(
self,
method: _RequestMethod,
url: str,
json: Optional[dict[Any, Any]] = None,
json: Optional[Dict[Any, Any]] = None,
response_class: Optional[Type] = None,
) -> Any:
if self._is_async:
Expand All @@ -76,7 +76,7 @@ def _sync_request(
self,
method: _RequestMethod,
url: str,
json: Optional[dict[Any, Any]] = None,
json: Optional[Dict[Any, Any]] = None,
response_class: Optional[Type] = None,
) -> ResponseType:
if isinstance(self._client, AsyncClient): # only to appease the type checker
Expand All @@ -102,7 +102,7 @@ async def _async_request(
self,
method: _RequestMethod,
url: str,
json: Optional[dict[Any, Any]] = None,
json: Optional[Dict[Any, Any]] = None,
response_class: Optional[Type] = None,
) -> ResponseType:
if isinstance(self._client, Client): # only to appease the type checker
Expand All @@ -124,7 +124,7 @@ async def _async_request(
else:
return response_class(**response_data)

def list_buckets(self) -> Union[list[Bucket], Awaitable[list[Bucket]], None]:
def list_buckets(self) -> Union[List[Bucket], Awaitable[List[Bucket]], None]:
"""Retrieves the details of all storage buckets within an existing product."""
return self._request("GET", f"{self.url}/bucket", response_class=Bucket)

Expand All @@ -140,7 +140,7 @@ def get_bucket(self, id: str) -> Union[Bucket, Awaitable[Bucket], None]:

def create_bucket(
self, id: str, name: str = None, public: bool = False
) -> Union[dict[str, str], Awaitable[dict[str, str]]]:
) -> Union[Dict[str, str], Awaitable[Dict[str, str]]]:
"""Creates a new storage bucket.
Parameters
Expand All @@ -158,7 +158,7 @@ def create_bucket(
json={"id": id, "name": name or id, "public": public},
)

def empty_bucket(self, id: str) -> Union[dict[str, str], Awaitable[dict[str, str]]]:
def empty_bucket(self, id: str) -> Union[Dict[str, str], Awaitable[Dict[str, str]]]:
"""Removes all objects inside a single bucket.
Parameters
Expand All @@ -170,7 +170,7 @@ def empty_bucket(self, id: str) -> Union[dict[str, str], Awaitable[dict[str, str

def delete_bucket(
self, id: str
) -> Union[dict[str, str], Awaitable[dict[str, str]]]:
) -> Union[Dict[str, str], Awaitable[Dict[str, str]]]:
"""Deletes an existing bucket. Note that you cannot delete buckets with existing objects inside. You must first
`empty()` the bucket.
Expand Down
5 changes: 5 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,15 @@
import os

import pytest
from dotenv import load_dotenv

from supabase import Client, create_client


def pytest_configure(config) -> None:
load_dotenv(dotenv_path="tests/tests.env")


@pytest.fixture(scope="session")
def supabase() -> Client:
url = os.environ.get("SUPABASE_TEST_URL")
Expand Down
103 changes: 1 addition & 102 deletions tests/test_client.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,8 @@
from __future__ import annotations

import random
import string
from typing import TYPE_CHECKING, Any, Union
from typing import Any

import pytest
from gotrue import Session, User

if TYPE_CHECKING:
from supabase import Client


def _random_string(length: int = 10) -> str:
"""Generate random string."""
return "".join(random.choices(string.ascii_uppercase + string.digits, k=length))


def _assert_authenticated_user(data: Union[Session, User, str, None]) -> None:
"""Raise assertion error if user is not logged in correctly."""
assert data is not None
assert isinstance(data, Session)
assert data.user is not None
assert data.user.aud == "authenticated"


@pytest.mark.xfail(
Expand All @@ -34,85 +15,3 @@ def test_incorrect_values_dont_instanciate_client(url: Any, key: Any) -> None:
from supabase import Client, create_client

_: Client = create_client(url, key)


@pytest.mark.skip(reason="TO FIX: Session does not terminate with test included.")
def test_client_auth(supabase: Client) -> None:
"""Ensure we can create an auth user, and login with it."""
# Create a random user login email and password.
random_email = f"{_random_string(10)}@supamail.com"
random_password = _random_string(20)
# Sign up (and sign in).
user = supabase.auth.sign_up(
email=random_email,
password=random_password,
phone=None,
)
_assert_authenticated_user(user)
# Sign out.
supabase.auth.sign_out()
assert supabase.auth.user() is None
assert supabase.auth.session() is None
# Sign in (explicitly this time).
user = supabase.auth.sign_in(email=random_email, password=random_password)
_assert_authenticated_user(user)


def test_client_select(supabase: Client) -> None:
"""Ensure we can select data from a table."""
# TODO(fedden): Add this set back in (and expand on it) when postgrest and
# realtime libs are working.
data, _ = supabase.table("countries").select("*").execute()
# Assert we pulled real data.
assert data


def test_client_insert(supabase: Client) -> None:
"""Ensure we can select data from a table."""
data, _ = supabase.table("countries").select("*").execute()
# Assert we pulled real data.
previous_length = len(data)
new_row = {
"name": "test name",
"iso2": "test iso2",
"iso3": "test iso3",
"local_name": "test local name",
"continent": None,
}
result, _ = supabase.table("countries").insert(new_row).execute()
# Check returned result for insert was valid.
assert result
data, _ = supabase.table("countries").select("*").execute()
current_length = len(data)
# Ensure we've added a row remotely.
assert current_length == previous_length + 1


@pytest.mark.skip(reason="missing permissions on test instance")
def test_client_upload_file(supabase: Client) -> None:
"""Ensure we can upload files to a bucket"""

TEST_BUCKET_NAME = "atestbucket"

storage = supabase.storage()
storage_file = storage.StorageFileAPI(TEST_BUCKET_NAME)

filename = "test.jpeg"
filepath = f"tests/{filename}"
mimetype = "image/jpeg"
options = {"contentType": mimetype}

storage_file.upload(filename, filepath, options)
files = storage_file.list()
assert files

image_info = None
for item in files:
if item.get("name") == filename:
image_info = item
break

assert image_info is not None
assert image_info.get("metadata", {}).get("mimetype") == mimetype

storage_file.remove([filename])
Loading

0 comments on commit 1d5aa55

Please sign in to comment.