Esempio n. 1
0
def client():
    client = TestClient(app)
    yield client
Esempio n. 2
0
def test_websocket():
    client = TestClient(app)
    with client.websocket_connect("/ws") as websocket:
        data = websocket.receive_json()
        assert data == {"msg": "Hello WebSocket"}
def test_reset_account_password_with_hash(db):
    # Create an account, set a reset hash, create a new client without tokens, get new tokens from
    # the reset hash link, update password, check old password does not work and new does with
    # the basic auth api.
    account = valid_account.copy()
    account['oauth'] = None
    response = client.post(f'api/accounts/', json=account).json()
    uuid = response['uuid']

    # notification for valid username
    resp = client.post(f'api/notifications/',
                       json={
                           "username": "******",
                           "notification_type": "password_reset"
                       })

    settings = client.get(f'api/account_settings/{uuid}').json()
    print(settings)
    # Can't get hash from email
    reset_hash = settings['password_reset_hash']

    # get a new client to remove existing cookies
    new_client = TestClient(app)
    resp = new_client.get(f'api/account_settings/{uuid}')
    assert resp.status_code > 400
    resp = new_client.get(f'api/settings_from_hash')
    assert resp.status_code > 400

    resp = new_client.patch(f'api/accounts/{uuid}',
                            json={'password': '******'})
    assert resp.status_code == 401

    resp = new_client.get(f'api/settings_from_hash?pw_reset_hash={reset_hash}')
    assert resp.status_code < 400, resp.json()

    resp = new_client.patch(f'api/accounts/{uuid}',
                            json={'password': '******'})
    assert resp.status_code < 400

    new_client = TestClient(app)
    resp = new_client.post(f'api/auth/basic',
                           json={
                               'email': '*****@*****.**',
                               'password': '******'
                           })
    assert resp.status_code > 400
    resp = new_client.post(f'api/auth/basic',
                           json={
                               'email': '*****@*****.**',
                               'password': '******'
                           })
    assert resp.status_code < 400

    resp = client.delete(f'api/accounts/{uuid}')
    assert resp.status_code < 400
Esempio n. 4
0
def test_param():
    with TestClient(app) as client:
        response = client.get("/params/seed")
        assert response.status_code == HTTPStatus.OK
        assert response.request.method == "GET"
        assert isinstance(response.json()["data"]["params"]["seed"], int)
Esempio n. 5
0
class TestServer(unittest.TestCase):

    def __init__(self, *args, **kwargs):
        super(TestServer, self).__init__(*args, **kwargs)
        self.client = TestClient(app)
        self.ohlc_loader = OHLCLoader()
        self.from_ts = 1603622100  # Sunday, 25. October 2020 10:35:00
        self.from_ts_in_millis = self.from_ts * 1000
        # Binance' maximum of 1000 bars would end at 1603682040000 => Monday, 26. October 2020 03:14:00
        self.to_ts = 1603708513  # Monday, 26. October 2020 10:35:13
        self.symbol = "BTC/USDT"
        self.tf = '1m'

    def test_read_main(self):
        response = self.client.get("/")
        assert response.status_code == 200
        assert response.json() == {"message": "Hello World"}

    def test_calc_minutes(self):
        from_ts = 1603622100  # Sunday, 25. October 2020 10:35:00
        # +1000 min = 1603682040000 last candle
        # Binance' maximum of 1000 bars would end at 1603682040000 => Monday, 26. October 2020 03:14:00
        to_ts = 1603708513  # Monday, 26. October 2020 10:35:13

        tdelta_in_minutes = self.ohlc_loader.get_delta_in_decimal_minutes(from_ts * 1000, to_ts * 1000)
        assert tdelta_in_minutes == pytest.approx(1440.21666, abs=0.001)
        print(tdelta_in_minutes)

    def test_get_ohlc_iteration_count(self):

        iteration_count = self.ohlc_loader.get_iteration_count(self.from_ts * 1000, self.to_ts * 1000)

        assert iteration_count == 1

    def test_get_ohlcv_from_limit_iterations(self):
        iteration_count = 1
        ohlc_list = self.ohlc_loader.get_ohlcv_from_limit_iterations(self.from_ts, iteration_count, '1m', self.symbol)
        remaining_ohlc = self.ohlc_loader.get_remaining_ohlc(ohlc_list[-1][0] + (1000 * 60), self.to_ts * 1000, self.tf, self.symbol)
        ohlc_last_ts = remaining_ohlc[-1][0]

        assert ohlc_last_ts == 1603708500000, \
            "The timestamp of the last candle is Monday, 26. October 2020 10:35:00." \
            "It is the the same minute as the to_ts."

        ohlc_list = self.ohlc_loader.get_ohlcv_from_limit_iterations(self.from_ts, 2, self.tf, self.symbol)

        assert ohlc_list[0][0] == self.from_ts_in_millis, "The from_ts is inclusive"

        assert ohlc_list[self.ohlc_loader.get_limit() - 1][0] == 1603682040000  # Monday, 26. October 2020 03:14:00

        assert ohlc_list[self.ohlc_loader.get_limit()][0] == (1603682040000 + (60 * 1000)), \
            "The start of the second iteration is a minute after the end of the first iteration"

        assert ohlc_list[(self.ohlc_loader.get_limit() * 2) - 1][0] == (
                    1603682040000 + (60 * 1000) * self.ohlc_loader.get_limit()), \
            "The end of the second iteration is the start of the second iteration plus 60 seconds * the limit"

        assert len(ohlc_list) == (2 * self.ohlc_loader.get_limit())

    def test_get_ohlc_over_candle_limit(self):
        ohlc_list = self.ohlc_loader.get_ohlc(self.from_ts, self.to_ts, self.tf, self.symbol)
        minute_delta = math.ceil(self.ohlc_loader.get_delta_in_decimal_minutes(self.from_ts * 1000, self.to_ts * 1000))

        assert len(ohlc_list) == minute_delta

    def test_get_ohlc_sub_candle_limit(self):
        from_ts=1605883816
        to_ts  =1605889815
        ohlc_list = self.ohlc_loader.get_ohlc(from_ts, to_ts, self.tf, self.symbol)
        minute_delta = math.ceil(self.ohlc_loader.get_delta_in_decimal_minutes(from_ts * 1000, to_ts * 1000))
        assert len(ohlc_list) == minute_delta
Esempio n. 6
0
# -*- coding: utf-8 -*-
import unittest
import unittest.mock as mock

from fastapi.testclient import TestClient

from projects.api.main import app
from projects.database import session_scope

import tests.util as util

app.dependency_overrides[session_scope] = util.override_session_scope
TEST_CLIENT = TestClient(app)


class TestMonitoringFigures(unittest.TestCase):
    maxDiff = None

    def setUp(self):
        """
        Sets up the test before running it.
        """
        util.create_mocks()

    def tearDown(self):
        """
        Deconstructs the test after running it.
        """
        util.delete_mocks()

    def test_list_figures_project_not_found(self):
Esempio n. 7
0
def client() -> Generator:
    with TestClient(app) as c:
        yield c
Esempio n. 8
0
def test_get_deck_public_snapshot(client: TestClient, snapshot1):
    """Public snapshots must return the snapshot"""
    response = client.get(f"/v2/decks/{snapshot1.id}")
    assert response.status_code == status.HTTP_200_OK
    assert response.json()["deck"]["id"] == snapshot1.id
Esempio n. 9
0
def test_get_deck(client: TestClient, deck1, snapshot1):
    """By default, the latest public snapshot is returned"""
    response = client.get(f"/v2/decks/{deck1.id}")
    assert response.status_code == status.HTTP_200_OK
    assert response.json()["deck"]["id"] == snapshot1.id
Esempio n. 10
0
def test_get_deck_private_snapshot(client: TestClient, session: db.Session, user1):
    """Unauthenticated users must not be able to access private snapshots"""
    deck = create_deck_for_user(session, user1)
    snapshot = create_snapshot_for_deck(session, user1, deck)
    response = client.get(f"/v2/decks/{snapshot.id}")
    assert response.status_code == status.HTTP_403_FORBIDDEN
Esempio n. 11
0
def test_get_deck_private_saved(client: TestClient, deck1):
    """Unauthenticated users must not be able to access private decks via show_saved"""
    response = client.get(f"/v2/decks/{deck1.id}", params={"show_saved": True})
    assert response.status_code == status.HTTP_403_FORBIDDEN
Esempio n. 12
0
def test_get_private_share_published_snapshot(client: TestClient, snapshot1):
    """Direct share UUIDs must allow access to public snapshots"""
    response = client.get(f"/v2/decks/shared/{snapshot1.direct_share_uuid}")
    assert response.status_code == status.HTTP_200_OK
    assert response.json()["id"] == snapshot1.id
Esempio n. 13
0
def test_get_private_share_deck(client: TestClient, private_deck1):
    """Direct share UUIDs must allow access to the exact deck or snapshot"""
    response = client.get(f"/v2/decks/shared/{private_deck1.direct_share_uuid}")
    assert response.status_code == status.HTTP_200_OK
    assert response.json()["id"] == private_deck1.id
Esempio n. 14
0
 def setUp(self):
     self.app = CustomFastAPI()
     self.client = TestClient(self.app)
 def setUp(self):
     app = create_app_imperative()
     self.client = TestClient(app)
Esempio n. 16
0
def test_list_snapshots_deleted_deck(client: TestClient, session: db.Session, deck1):
    """Not found error thrown when viewing a deleted deck"""
    deck1.is_deleted = True
    session.commit()
    response = client.get(f"/v2/decks/{deck1.id}/snapshots")
    assert response.status_code == status.HTTP_404_NOT_FOUND
Esempio n. 17
0
def test_farm_terms_oauth_scope(client: TestClient):
    r = client.get(f"{settings.API_V1_STR}/farms/terms")
    assert r.status_code == 401
Esempio n. 18
0
def test_list_snapshots_snapshot_id(client: TestClient, snapshot1):
    """Not found error thrown when viewing a snapshot instead of a source deck"""
    response = client.get(f"/v2/decks/{snapshot1.id}/snapshots")
    assert response.status_code == status.HTTP_404_NOT_FOUND
    def setUpClass(cls):
        """Setup common to all tests in this class"""

        cls.client = TestClient(fastapi_app.app)
        log.info('Completed initialization for FastAPI based  REST API tests')
Esempio n. 20
0
def test_validate_service(client: TestClient, data: dict, service_name: str) -> None:
    response = client.post(f"{settings.API_V1_STR}/service/validate", json=data)
    assert response.status_code == requests.codes["ok"]
    validation = response.json()
    assert validation
    assert validation.get("name") == service_name
Esempio n. 21
0
def rest_client(mongodb):
    return TestClient(app)
from fastapi.testclient import TestClient
from forest_lite.server import main, config
from forest_lite.server.lib.config import Config
import pytest

client = TestClient(main.app)


def use_settings(props):
    """Override get_settings runtime dependency"""
    settings = Config(**props)
    main.app.dependency_overrides[config.get_settings] = lambda: settings


def test_get_viewport():
    """HTTP GET endpoint to set map boundaries"""
    # Fake config
    use_settings({"datasets": []})

    # System under test
    response = client.get("/api")
    url = response.json()["links"]["viewport"]
    response = client.get(url)
    actual = response.json()

    # Assertions
    expected = {"longitude": [-180, 180], "latitude": [-85, 85]}
    assert expected == actual
Esempio n. 23
0
def test_filtered_performance():
    with TestClient(app) as client:
        response = client.get("/performance?filter=overall")
        assert response.status_code == HTTPStatus.OK
        assert response.request.method == "GET"
        assert isinstance(response.json()["data"]["performance"]["overall"], dict)
Esempio n. 24
0
def client(app: FastAPI) -> TestClient:
    return TestClient(app)
Esempio n. 25
0
def test_read_main():
    client = TestClient(app)
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"msg": "Hello World"}
Esempio n. 26
0
def test_e2e():
    app = make_app()
    client = TestClient(app)
    url = ""
    e2e(httpclient=client, url=url)
Esempio n. 27
0
def anon_client():
    """A test client with no authorization."""
    return TestClient(app)
Esempio n. 28
0
def client():
    with TestClient(app) as client:
        yield client
Esempio n. 29
0
import pytest
from fastapi.testclient import TestClient

from docs_src.body_fields.tutorial001 import app

client = TestClient(app)

openapi_schema = {
    "openapi": "3.0.2",
    "info": {
        "title": "FastAPI",
        "version": "0.1.0"
    },
    "paths": {
        "/items/{item_id}": {
            "put": {
                "responses": {
                    "200": {
                        "description": "Successful Response",
                        "content": {
                            "application/json": {
                                "schema": {}
                            }
                        },
                    },
                    "422": {
                        "description": "Validation Error",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref":
Esempio n. 30
0
def test_view_inexistent_dataframe_in_database():
    from mlmonitoring.server.main import app
    client = TestClient(app)
    response = client.get("/view/inexistent_table")
    assert response.status_code == 500