Ejemplo n.º 1
0
    def setUp(self):

        self.cosmos1 = Cosmos()
        with self.cosmos1:

            self.places = places = API('places')

            @places.model
            class City(BaseModel):
                properties = [
                    optional(u"name", String)
                ]

            @places.model
            class Address(BaseModel):
                properties = [
                    required(u"number", Integer),
                    required(u"street", String),
                ]
                links = [
                    required(u"city", City)
                ]

        self.cosmos2 = Cosmos()
        with self.cosmos2:
            with patch.object(requests, 'get') as mock_get:
                mock_get.return_value.json = lambda: API.to_json(places)
                mock_get.return_value.status_code = 200
                self.remote_places = API.load('http://example.com/spec.json')
                self.remote_places.client_hook = WerkzeugTestClientHook(places.get_flask_app().test_client())
Ejemplo n.º 2
0
    def setUp(self):

        self.cosmos1 = Cosmos()
        with self.cosmos1:

            self.mathy = mathy = API("mathy")

            @mathy.action(accepts=Array(Integer), returns=Integer)
            def add(numbers):
                return sum(numbers)

            @mathy.action(accepts=Struct([
                required(u'numerator', Integer),
                required(u'denominator', Integer),
            ]), returns=Integer)
            def divide(numerator, denominator):
                return numerator / denominator


            self.add = add

        self.cosmos2 = Cosmos()
        with self.cosmos2:
            with patch.object(requests, 'get') as mock_get:
                mock_get.return_value.json = lambda: API.to_json(mathy)
                mock_get.return_value.status_code = 200
                self.remote_mathy = API.load('http://example.com/spec.json')
                self.remote_mathy.client_hook = WerkzeugTestClientHook(mathy.get_flask_app().test_client())
Ejemplo n.º 3
0
    def setUp(self):
        self.maxDiff = None

        self.cosmos1 = cosmos.clone()
        self.cosmos2 = Cosmos()

        with self.cosmos1:
            self.planetarium = planetarium

            self.c = self.planetarium.get_flask_app().test_client()
            app = self.planetarium.get_flask_app()
            app.debug = True
            self.d = app.test_client()

        with self.cosmos2:
            with patch.object(requests, 'get') as mock_get:
                mock_get.return_value.json = lambda: json_spec
                mock_get.return_value.status_code = 200

                self.remote_planetarium = API.load('http://example.com/spec.json')

                class Retry(Exception):
                    pass

                class Hook(SaveStackClientHookMixin, WerkzeugTestClientHook):
                    token = None

                    def build_request(self, endpoint, *args, **kwargs):
                        request = super(Hook, self).build_request(endpoint, *args, **kwargs)
                        if self.token is not None:
                            request.headers["X-Danish"] = self.token
                        return request

                    def parse_response(self, endpoint, res):
                        if res.status_code == 401:
                            raise Retry()
                        return super(Hook, self).parse_response(endpoint, res)

                    def call(self, endpoint, *args, **kwargs):
                        while True:
                            try:
                                return super(Hook, self).call(endpoint, *args, **kwargs)
                            except Retry:
                                # Find token, e.g. through OAuth
                                self.token = "poppyseed"
                                continue

                # Use the local API's HTTP client to simulate the remote API's calls
                self.remote_planetarium.client_hook = Hook(self.d)
Ejemplo n.º 4
0
    def setUp(self):

        self.cosmos = Cosmos()
        with self.cosmos:

            self.places = places = API('places')

            @places.model
            class City(BaseModel):
                properties = [
                    optional(u"name", String)
                ]

                @classmethod
                def validate(cls, datum):
                    if datum[u"name"][0].islower():
                        raise ValidationError("Name must be capitalized", datum["name"])

                def save(self):
                    if self.id is None:
                        # Create new id
                        self.id = str(len(cities))
                    cities[self.id] = self

        self.cosmos2 = Cosmos()
        with self.cosmos2:
            with patch.object(requests, 'get') as mock_get:
                mock_get.return_value.json = lambda: API.to_json(places)
                mock_get.return_value.status_code = 200
                self.remote_places = API.load('http://example.com/spec.json')
                self.remote_places.client_hook = WerkzeugTestClientHook(places.get_flask_app().test_client())

        cities = {
            "0": City(name="Toronto", id="0"),
            "1": City(name="San Francisco", id="1"),
        }
Ejemplo n.º 5
0
 def test_to_json(self):
     places = self.places
     with self.cosmos:
         self.assertEqual(API.to_json(places), {
             u'name': u'places',
             u'actions': { u'map': {}, u'order': [] },
             u"models": {
                 u"map": {
                     u"Address": {
                         u"data_schema": {
                             u'type': u"Struct",
                             u"param": {
                                 u"map": {
                                     u"number": {
                                         u"required": True,
                                         u"schema": {u"type": u"Integer"}
                                     },
                                     u"street": {
                                         u"required": True,
                                         u"schema": {u"type": u"String"}
                                     },
                                     u"city": {
                                         u"required": False,
                                         u"schema": {u"type": u"String"}
                                     }
                                 },
                                 u"order": [u"number", u"street", u"city"]
                             }
                         },
                         u"links": { u"map": {}, u"order": [] },
                         u"query_fields": { u"map": {}, u"order": [] }
                     }
                 },
                 u"order": [u"Address"]
             }
         })
        # Remove jobs which will be triggered
        for token, _ in urls:
            del monitoring_items[token]

        # make requests
        for token, url in urls:

            try:
                r = requests.get(url)
                print(token, r.url, r.status_code)
            except Exception as e:
                print e


# Name your API
api = API("detect_disconnect")

manager = Manager()
monitoring_items = manager.dict()


# Decorate your function with the parameter type and return type
@api.action(accepts=Struct([
    required("token", String),
    required("timeout", Integer),
    required("url", String)
]))
def monitor(token, timeout, url):
    """
  If this endpoint is not called with identical token + url within
  timeout seconds, a GET request will be made to supplied url.
Ejemplo n.º 7
0
from time import sleep

from cosmic.api import API
from cosmic.http import Server
from cosmic.types import *
from cosmic.models import BaseModel
from cosmic.exceptions import NotFound

words = API('words')


@words.action(accepts=String, returns=String)
def pluralize(word):
    if word.endswith('y'):
        return word[:-1] + 'ies'
    else:
        return word + 's'


@words.model
class Word(BaseModel):
    methods = ['get_by_id']
    properties = [
        required(u"letters", String)
    ]
    @classmethod
    def get_by_id(cls, id):
        if id == "0":
            return {"letters": "hello"}
        else:
            raise NotFound
Ejemplo n.º 8
0
                u"self": {u"href": u"/Sphere/1"},
                u"revolves_around": {u"href": u"/Sphere/0"},
            }
        },
        {
            u"name": u"Moon",
            u"_links": {
                u"self": {u"href": u"/Sphere/2"},
                u"revolves_around": {u"href": u"/Sphere/1"},
            }
        }
    ]
}


planetarium = API("planetarium")


class SHook(ServerHook):

    def parse_request(self, endpoint, request, **url_args):
        if not endpoint.never_authenticate:
            if request.headers.get('X-Danish', None) != "poppyseed":
                abort(401)
        return super(SHook, self).parse_request(endpoint, request, **url_args)

planetarium.server_hook = SHook()


@planetarium.model
class Sphere(DBModel):
Ejemplo n.º 9
0
from cosmic.tools import normalize_schema
from cosmic.api import API


# Define name of the API
api = API.create('cosmic_hello_world')

# Set of people
people = set()


@api.action(
    accepts=normalize_schema({"type": "string"}),
    returns=normalize_schema({"type": "string"})
)
def remember_me(name):
  """Remember names upto 10 people.
  """
  if name not in people:
    # Too many people to remember!
    if len(people) >= 10:
      people.pop()
    # Add new person
    people.add(name)
    return "Hello, %s! I'll remember you." % name
  else:
    return "Welcome back, %s." % name


@api.action(
    returns=normalize_schema({
Ejemplo n.º 10
0
#!/usr/bin/python
from cosmic.api import API

client = API.load("http://127.0.0.1:5000/spec.json")
print client.actions.query("tyop")
Ejemplo n.º 11
0
 def test_schema(self):
     API.from_json(API.to_json(self.cookbook))
Ejemplo n.º 12
0
 def test_serialize(self):
     self.assertEqual(API.to_json(self.cookbook), cookbook_spec)
        # Remove jobs which will be triggered
        for token, _ in urls:
            del monitoring_items[token]

        # make requests
        for token, url in urls:

            try:
                r = requests.get(url)
                print (token, r.url, r.status_code)
            except Exception as e:
                print e

# Name your API
api = API("detect_disconnect")

manager = Manager()
monitoring_items = manager.dict()

# Decorate your function with the parameter type and return type
@api.action(
  accepts=Struct([
        required("token", String),
        required("timeout", Integer),
        required("url", String)
    ])
)
def monitor(token, timeout, url):
  """
  If this endpoint is not called with identical token + url within
Ejemplo n.º 14
0
            u"temperature": 3000.0,
        },
        "1": {
            u"name": u"Earth",
            u"temperature": 30.0,
            u"revolves_around": "0",
        },
        "2": {
            u"name": u"Moon",
            u"temperature": -50.0,
            u"revolves_around": "1",
        },
    }
}

planetarium = API("planetarium")


class PlanetariumServer(Server):
    def parse_request(self, endpoint, request, **url_args):
        if request.headers.get('X-Danish', None) != "poppyseed":
            raise HTTPError(401, "Unauthorized")
        return super(PlanetariumServer, self).parse_request(endpoint, request, **url_args)


planetarium_server = PlanetariumServer(planetarium)


@planetarium.model
class Sphere(DBModel):
    table_name = 'Sphere'