Example #1
0
    async def test_sub_domain_working_with_non_hosts_based(self):
        b1 = Blueprint(hosts=["test.vibora.io"])
        b2 = Blueprint()

        @b1.route("/")
        async def home():
            return Response(b"123")

        @b2.route("/test")
        async def home2():
            return Response(b"123")

        self.app.add_blueprint(b1)
        self.app.add_blueprint(b2)
        async with self.app.test_client() as client:
            response = await client.request("/",
                                            headers={"Host": "test.vibora.io"})
            self.assertEqual(response.status_code, 200)
            response = await client.request(
                "/", headers={"Host": "test2.vibora.io"})
            self.assertEqual(response.status_code, 404)
            response = await client.request(
                "/test", headers={"Host": "anything.should.work"})
            self.assertEqual(response.status_code, 200)
            response = await client.request(
                "/test2", headers={"Host": "anything.should.404"})
            self.assertEqual(response.status_code, 404)
Example #2
0
    async def test_sub_domain_working_with_non_hosts_based(self):
        b1 = Blueprint(hosts=['test.vibora.io'])
        b2 = Blueprint()

        @b1.route('/')
        async def home():
            return Response(b'123')

        @b2.route('/test')
        async def home():
            return Response(b'123')

        self.app.add_blueprint(b1)
        self.app.add_blueprint(b2)
        with self.app.test_client() as client:
            response = await client.request('/',
                                            headers={'Host': 'test.vibora.io'})
            self.assertEqual(response.status_code, 200)
            response = await client.request(
                '/', headers={'Host': 'test2.vibora.io'})
            self.assertEqual(response.status_code, 404)
            response = await client.request(
                '/test', headers={'Host': 'anything.should.work'})
            self.assertEqual(response.status_code, 200)
            response = await client.request(
                '/test2', headers={'Host': 'anything.should.404'})
            self.assertEqual(response.status_code, 404)
Example #3
0
    async def test_simple_add_nested_blueprints(self):
        b1 = Blueprint()
        b2 = Blueprint()

        @b2.route('/123')
        async def home():
            return Response(b'123')

        b1.add_blueprint(b2)
        self.app.add_blueprint(b1)
        async with self.app.test_client() as client:
            response = await client.request('/123')
            self.assertEqual(response.content, b'123')
Example #4
0
    async def test_simple_add_nested_blueprints_with_prefixes(self):
        b1 = Blueprint()
        b2 = Blueprint()

        @b2.route("/123")
        async def home():
            return Response(b"123")

        b1.add_blueprint(b2, prefixes={"a": "/a", "b": "/b"})
        self.app.add_blueprint(b1, prefixes={"a": "/a", "b": "/b"})
        async with self.app.test_client() as client:
            response = await client.request("/a/a/123")
            self.assertEqual(response.content, b"123")
            response = await self.app.test_client().request("/b/b/123")
            self.assertEqual(response.content, b"123")
Example #5
0
    async def test_simple_add_nested_blueprints_with_prefixes(self):
        b1 = Blueprint()
        b2 = Blueprint()

        @b2.route('/123')
        async def home():
            return Response(b'123')

        b1.add_blueprint(b2, prefixes={'a': '/a', 'b': '/b'})
        self.app.add_blueprint(b1, prefixes={'a': '/a', 'b': '/b'})
        async with self.app.test_client() as client:
            response = await client.request('/a/a/123')
            self.assertEqual(response.content, b'123')
            response = await self.app.test_client().request('/b/b/123')
            self.assertEqual(response.content, b'123')
Example #6
0
    async def test_blueprint_exception_propagation(self):
        b1 = Blueprint()

        class ExceptionA(Exception):
            pass

        class ExceptionB(ExceptionA):
            pass

        class ExceptionC(ExceptionB):
            pass

        @b1.route("/")
        async def handle_errors():
            raise ExceptionC("Vibora ;)")

        @self.app.handle(ExceptionA)
        async def handle_errors2():
            return Response(b"Wrong!", status_code=500)

        @self.app.handle(ExceptionB)
        async def handle_errors3():
            return Response(b"Correct!", status_code=500)

        self.app.add_blueprint(b1, prefixes={"": ""})

        response = await self.app.test_client().request("/")
        self.assertEqual(response.status_code, 500)
        self.assertEqual(response.content, b"Correct!")
Example #7
0
    async def test_after_response_sent_called_from_blueprint(self):

        b1 = Blueprint()

        class Mock:
            def __init__(self):
                self.test = 'test'

        @b1.route('/')
        async def home(request: Request):
            try:
                request.app.components.get(Mock)
                return Response(b'Second')
            except Exception as error:
                return Response(str(error).encode(), status_code=500)

        @b1.handle(Events.AFTER_RESPONSE_SENT)
        async def after_response_sent(app: Vibora):
            try:
                app.components.add(Mock())
            except ValueError:
                pass

        self.app.add_blueprint(b1, prefixes={'v1': '/v1'})

        async with self.app.test_client() as client:
            response = await client.get('/v1')
            self.assertEqual(response.status_code, 500)
            await asyncio.sleep(0)
            response = await client.get('/v1')
            self.assertEqual(response.status_code, 200)
Example #8
0
    async def test_blueprint_exception_propagation(self):
        b1 = Blueprint()

        class ExceptionA(Exception):
            pass

        class ExceptionB(ExceptionA):
            pass

        class ExceptionC(ExceptionB):
            pass

        @b1.route('/')
        async def handle_errors():
            raise ExceptionC('Vibora ;)')

        @self.app.handle(ExceptionA)
        async def handle_errors():
            return Response(b'Wrong!', status_code=500)

        @self.app.handle(ExceptionB)
        async def handle_errors():
            return Response(b'Correct!', status_code=500)

        self.app.add_blueprint(b1, prefixes={'': ''})

        response = await self.app.test_client().request('/')
        self.assertEqual(response.status_code, 500)
        self.assertEqual(response.content, b'Correct!')
Example #9
0
    def _make_json_api(self):
        print('\nInitializing JsonApi routes:')
        from .apis.jsonapi import JsonApi

        self.json_api = Blueprint()
        for route in JsonApi(self.app).endpoints:
            self._add_route(self.json_api, route)
        self.vibora.add_blueprint(self.json_api)
Example #10
0
    def _make_gui(self):
        print('\nInitializing Web frontend:')
        from .gui import Gui

        self.web = Blueprint()
        for route in Gui(self.app).pages:
            self._add_route(self.web, route)
        self.vibora.add_blueprint(self.web)
Example #11
0
    async def test_simple_add_blueprint_with_prefix_expects_added(self):
        b1 = Blueprint()

        @b1.route("/")
        async def home():
            return Response(b"123")

        self.app.add_blueprint(b1, prefixes={"home": "/home"})
        async with self.app.test_client() as client:
            response = await client.request("/home/")
            self.assertEqual(response.content, b"123")
Example #12
0
    async def test_prefix_with_dynamic_route(self):
        app = Vibora()
        bp = Blueprint()

        @bp.route("/<name>")
        async def home(name: str):
            return JsonResponse({"name": name})

        app.add_blueprint(bp, prefixes={"test": "/test"})
        response = await app.test_client().request("/test/test")
        self.assertEqual(response.json(), {"name": "test"})
Example #13
0
    async def test_add_blueprint_with_one_prefix(self):
        data, app = {"hello": "world"}, Vibora()
        bp = Blueprint()

        @bp.route("/")
        async def home():
            return JsonResponse(data)

        app.add_blueprint(bp, prefixes={"test": "/test"})
        response = await app.test_client().request("/test")
        self.assertEqual(response.json(), data)
Example #14
0
    async def test_different_sub_domain_expects_404(self):
        b1 = Blueprint(hosts=['test.vibora.io'])

        @b1.route('/')
        async def home():
            return Response(b'123')

        self.app.add_blueprint(b1)
        with self.app.test_client() as client:
            response = await client.request('/', headers={'Host': 'test2.vibora.io'})
            self.assertEqual(response.status_code, 404)
Example #15
0
    async def test_exact_match_sub_domain_expects_match(self):
        b1 = Blueprint(hosts=['test.vibora.io'])

        @b1.route('/')
        async def home():
            return Response(b'123')

        self.app.add_blueprint(b1)
        with self.app.test_client() as client:
            response = await client.request('/', headers={'Host': 'test.vibora.io'})
            self.assertEqual(response.content, b'123')
Example #16
0
 def _make_blueprint(self, bp_name: str, bp: MiyagiBlueprint):
     # Make a blueprint
     vibora_bp = Blueprint()
     # Make it accessible in self
     setattr(self, bp_name, vibora_bp)
     # get all the routes in the given MiyagiBlueprint
     for route in bp(self.app).endpoints:
         # Register the route in the new blueprint
         self._add_route(vibora_bp, route)
     # Register the Blueprint in the Vibora App
     self.vibora.add_blueprint(vibora_bp)
Example #17
0
    async def test_simple_add_blueprint_with_prefix_expects_added(self):
        b1 = Blueprint()

        @b1.route('/')
        async def home():
            return Response(b'123')

        self.app.add_blueprint(b1, prefixes={'home': '/home'})
        async with self.app.test_client() as client:
            response = await client.request('/home/')
            self.assertEqual(response.content, b'123')
Example #18
0
    async def test_add_blueprint_with_one_prefix(self):
        data, app = {'hello': 'world'}, Vibora()
        bp = Blueprint()

        @bp.route('/')
        async def home():
            return JsonResponse(data)

        app.add_blueprint(bp, prefixes={'test': '/test'})
        response = await app.test_client().request('/test')
        self.assertEqual(response.json(), data)
Example #19
0
    async def test_simple_sub_domain_expects_match(self):
        b1 = Blueprint(hosts=['.*'])

        @b1.route('/')
        async def home():
            return Response(b'123')

        self.app.add_blueprint(b1)
        with self.app.test_client() as client:
            response = await client.request('/')
            self.assertEqual(response.content, b'123')
Example #20
0
    async def test_multiple_exceptions_at_a_single_handle(self):
        b1 = Blueprint()
        b2 = Blueprint()

        class ExceptionA(Exception):
            pass

        @b2.route("/")
        async def handle_errors():
            raise ExceptionA("Vibora ;)")

        @self.app.handle((IOError, ExceptionA))
        async def handle_errors2():
            return Response(b"Correct!", status_code=500)

        b1.add_blueprint(b2, prefixes={"": ""})
        self.app.add_blueprint(b1, prefixes={"": ""})

        response = await self.app.test_client().request("/")
        self.assertEqual(response.status_code, 500)
        self.assertEqual(response.content, b"Correct!")
Example #21
0
    async def test_exact_match_sub_domain_expects_match(self):
        b1 = Blueprint(hosts=["test.vibora.io"])

        @b1.route("/")
        async def home():
            return Response(b"123")

        self.app.add_blueprint(b1)
        async with self.app.test_client() as client:
            response = await client.request("/",
                                            headers={"Host": "test.vibora.io"})
            self.assertEqual(response.content, b"123")
Example #22
0
    async def test_different_sub_domain_expects_404(self):
        b1 = Blueprint(hosts=["test.vibora.io"])

        @b1.route("/")
        async def home():
            return Response(b"123")

        self.app.add_blueprint(b1)
        async with self.app.test_client() as client:
            response = await client.request(
                "/", headers={"Host": "test2.vibora.io"})
            self.assertEqual(response.status_code, 404)
Example #23
0
    async def test_before_response_called_from_blueprint(self):

        b1 = Blueprint()

        class Mock:
            def __init__(self):
                self.test = 'test'

        @b1.handle(Events.BEFORE_SERVER_START)
        async def after_response_sent(app: Vibora):
            try:
                app.components.add(Mock())
            except ValueError:
                pass

        @b1.route('/')
        async def home(mock: Mock):
            return Response(mock.test.encode())

        self.app.add_blueprint(b1, prefixes={'v1': '/v1'})

        async with self.app.test_client() as client:
            response = await client.get('/v1')
            self.assertEqual(response.status_code, 200)
Example #24
0
from enum import Enum
from vibora.blueprints import Blueprint
from vibora.responses import JsonResponse

from backend.config import Config

api = Blueprint()


class CruddyHeaders(Enum):
    JSON: object = {'content-type': 'application/json'}
    HTML: object = {'content-type': 'html'}


class CruddyCodes(Enum):
    SUCCESS: int = 200


@api.route('/', methods=['GET'])
async def home(config: Config):
    welcome_msg = f'Welcome to {config.app_name}'
    return JsonResponse(content={'msg': welcome_msg},
                        status_code=CruddyCodes.SUCCESS.value,
                        headers=CruddyHeaders.JSON.value)


@api.route('/<something>', methods=['POST'])
async def store_something(something):
    return JsonResponse(
        content={
            'obj': {},  # TODO Connect to DataService
Example #25
0
 def _add_route(self, blueprint: Blueprint, route: MiyagiRoute):
     print(
         f'Adding route: {self.vibora.url_scheme}://{self.app.config.host}:{self.app.config.port}{route.uri}'
     )
     blueprint.route(route.uri, methods=route.methods)(route.handler)
Example #26
0
from vibora.responses import JsonResponse
from vibora.blueprints import Blueprint

v2 = Blueprint()


@v2.route('/')
def home():
    return JsonResponse({'a': 2})


@v2.route('/exception')
def exception():
    raise IOError('oi')


@v2.handle(Exception)
def handle_exception():
    return JsonResponse({'msg': 'Exception catched correctly on v2.'})
Example #27
0
import json
import re
from vibora.responses import JsonResponse
from vibora.blueprints import Blueprint
from vibora import Request
from .dao import save, retrieve, delete

user_api = Blueprint()


@user_api.route('/user')
async def get():
    users = retrieve()
    return JsonResponse(users, status_code=200)


@user_api.route('/user', methods=['POST'])
async def create(request: Request):
    body = await request.stream.read()
    user = json.loads(body)
    save(user)
    return JsonResponse(user, status_code=201)


@user_api.route('/user/<user_id>', methods=['DELETE'])
async def remove(user_id: int):
    delete(user_id)
    return JsonResponse({}, status_code=204)
Example #28
0
from vibora.blueprints import Blueprint
from vibora.responses import JsonResponse

from Miyagi.config import Config

frontend = Blueprint()


@frontend.route("/test", methods=['GET'])
async def home(config: Config):
    print(config)
    return JsonResponse({'1': 2})
Example #29
0
from vibora.responses import JsonResponse
from vibora.blueprints import Blueprint

v1 = Blueprint()


@v1.route('/')
def home():
    return JsonResponse({'hello': 'world'})


@v1.route('/exception')
def exception():
    raise Exception('oi')


@v1.handle(IOError)
def handle_exception():
    return JsonResponse({'msg': 'Exception caught correctly.'})