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

        content_type = self.request.headers.get('Content-Type', '')
        if content_type.startswith('application/json'):
            self.args_json = self._parse_json()
        elif content_type.startswith('application/yaml'):
            self.args_yaml = self._parse_yaml()

        self.args_query = {
            key: self.get_query_argument(key)
            for key in self.request.query_arguments}
        self.args_form = {
            key: self.get_body_argument(key)
            for key in self.request.body_arguments}

        reqargs = ReqArgs(
            ReqArgs.Path(
                args=self.path_args,
                kwargs=self.path_kwargs),
            query=self.args_query,
            form=self.args_form,
            json_=self.args_json
        )
        # standardized request arguments
        self.args = self._parse_args(reqargs)
        self.format = self.args.format
Ejemplo n.º 2
0
def test_02():
    assert str(
        ReqArgs(ReqArgs.Path(args=("gene", "1017"), kwargs={"version": "v3"}),
                query={"format": "html"})).replace(" ", "") == """
        ReqArgs(path=Path(args=('gene', '1017'), kwargs={'version': 'v3'}),
        query={'format': 'html'})
    """.replace(" ", "")[1:-1]
Ejemplo n.º 3
0
def test_05():
    args = ReqArgs(query={
        "q": "cdk2",
        "fields": "taxid"
    },
                   form={"_source": "_id"})
    locator = {"keyword": "_source", 'alias': ['fields', 'field', 'filter']}

    assert args.lookup(locator) == "taxid"
    assert args.lookup(locator, ("form", "query")) == "_id"
Ejemplo n.º 4
0
def test_06():
    args = ReqArgs(
        query={
            "q": "cdk2",
            "fields": "taxid"
        },
        json_={"fields": "ensembl"}  # THIS IS A DICT
    )
    locator = {"keyword": "_source", 'alias': ['fields', 'field', 'filter']}

    assert args.lookup(locator) == "taxid"
    assert args.lookup(locator, ("json", "query")) == "ensembl"

    args = ReqArgs(
        query={
            "q": "cdk2",
            "fields": "taxid"
        },
        json_=[{
            "fields": "ensembl"
        }]  # THIS IS A LIST
    )

    # JSON input may not be a dictionay
    # in those cases, we ignore its content
    # and should not by itself throw an error
    assert args.lookup(locator) == "taxid"
    assert args.lookup(locator, ("json", "query")) == "taxid"
Ejemplo n.º 5
0
def test_03():
    args = ReqArgs(query={
        "format": "yaml",
        "size": "1002"
    },
                   json_={
                       "q": "cdk2",
                       "scopes": ["ensembl", "entrez"],
                       "format": "json"
                   })
    assert args.lookup("scopes") == ["ensembl", "entrez"]
    assert args.lookup("format") == "yaml"
    assert args.lookup("size") == "1002"
    assert args.lookup("q") == "cdk2"
Ejemplo n.º 6
0
def test_04():
    locator = {"keyword": "_source", 'alias': ['fields', 'field', 'filter']}
    assert ReqArgs(query={
        "q": "cdk2",
        "_source": "taxid"
    }).lookup(locator) == "taxid"
    assert ReqArgs(query={
        "q": "cdk2",
        "fields": "taxid"
    }).lookup(locator) == "taxid"
    assert ReqArgs(query={
        "q": "cdk2",
        "field": "taxid"
    }).lookup(locator) == "taxid"
    assert ReqArgs(query={
        "q": "cdk2",
        "filter": "taxid"
    }).lookup(locator) == "taxid"
Ejemplo n.º 7
0
def test_02():

    reqargs = ReqArgs(
        query={
            "size": "10",
            "format": "html"
        },
        json_={
            "q": "cdk2",
            "scopes": ["ensembl", "entrez"],
            "format": "json"
        }
    )

    opt = Option({"keyword": "size", "type": int})
    assert opt.parse(reqargs) == 10

    with pytest.raises(OptionError):
        opt = Option({"keyword": "size", "type": int, "max": 3})
        opt.parse(reqargs)

    opt = Option({"keyword": "q"})
    assert opt.parse(reqargs) == "cdk2"

    opt = Option({"keyword": "q", "type": str})
    assert opt.parse(reqargs) == "cdk2"

    with pytest.raises(OptionError):
        opt = Option({"keyword": "q", "type": list})
        opt.parse(reqargs)

    opt = Option({"keyword": "q", "type": list, "strict": False})
    assert opt.parse(reqargs) == ["cdk2"]

    opt = Option({"keyword": "format", "type": str})
    assert opt.parse(reqargs) == "html"

    opt = Option({"keyword": "out_format", "alias": "format"})
    assert opt.parse(reqargs) == "html"

    opt = Option({"keyword": "format", "location": ("json", "query")})
    assert opt.parse(reqargs) == "json"

    opt = Option({"keyword": "format", "location": "json"})
    assert opt.parse(reqargs) == "json"

    with pytest.raises(OptionError):
        opt = Option({"keyword": "scopes", "type": str})
        opt.parse(reqargs)

    opt = Option({"keyword": "scopes", "type": str, "strict": False})
    assert opt.parse(reqargs) == "['ensembl', 'entrez']"

    opt = Option({"keyword": "scopes", "type": list})
    assert opt.parse(reqargs) == ["ensembl", "entrez"]
Ejemplo n.º 8
0
def test_01():
    assert str(
        ReqArgs(query={
            "format": "yaml",
            "size": "1002"
        },
                json_={
                    "q": "cdk2",
                    "scopes": ["ensembl", "entrez"],
                    "format": "json"
                })).replace(" ", "") == """
        ReqArgs(query={'format': 'yaml', 'size': '1002'},
        json={'q': 'cdk2', 'scopes': ['ensembl', 'entrez'], 'format': 'json'})
    """.replace(" ", "")[1:-1]
Ejemplo n.º 9
0
def test_03():

    reqargs = ReqArgs(form={
        "ids": "cdk,cdk2",
        "scopes": "symbol",
        "size": 10
    })

    opt = Option({"keyword": "scopes", "type": list})
    assert opt.parse(reqargs) == ["symbol"]

    opt = Option({"keyword": "ids", "type": list})
    assert opt.parse(reqargs) == ["cdk", "cdk2"]

    opt = Option({"keyword": "size", "type": int})
    assert opt.parse(reqargs) == 10
Ejemplo n.º 10
0
def test_01():
    reqargs = (
        ReqArgs.Path(
            args=("gene", "1017"),
            kwargs={
                "host": "mygene.info",
                "version": "v3"}),
        {
            "size": "10",
            "dotfield": "true",
            "format": "json"
        }
    )

    opt = Option({"keyword": "doc_type", "path": 0})
    assert opt.parse(reqargs) == "gene"

    opt = Option({"keyword": "gene_id", "type": int, "path": 1})
    assert opt.parse(reqargs) == 1017

    opt = Option({"keyword": "host", "path": "host"})
    assert opt.parse(reqargs) == "mygene.info"

    opt = Option({"keyword": "host", "path": 100})
    assert opt.parse(reqargs) is None

    opt = Option({"keyword": "size", "type": int})
    assert opt.parse(reqargs) == 10

    opt = Option({"keyword": "dotfield", "type": bool, "default": False})
    assert opt.parse(reqargs) is True

    opt = Option({"keyword": "from", "type": int, "default": 0})
    assert opt.parse(reqargs) == 0

    opt = Option({"keyword": "userquery", "type": str})
    assert opt.parse(reqargs) is None
Ejemplo n.º 11
0
 def get_new_calling_signature(self):
     return self.method, ReqArgs(*self.reqargs)
Ejemplo n.º 12
0
def test_02():
    args = ReqArgs(ReqArgs.Path(args=("gene", "1017"),
                                kwargs={
                                    "host": "mygene.info",
                                    "version": "v3",
                                }),
                   query={"format": "json"},
                   form={"format": "html"})
    assert args.lookup({"keyword": "biothing_type", "path": 0}) == "gene"
    assert args.lookup({"keyword": "_id", "path": 1}) == "1017"
    assert args.lookup({"keyword": "unknown", "path": 2}) is None
    assert args.lookup({"keyword": "host", "path": "host"}) == "mygene.info"
    assert args.lookup({"keyword": "version", "path": "version"}) == "v3"
    assert args.lookup({"keyword": "unknown", "path": "unknown"}) is None
    assert args.lookup("format") == "json"
    assert args.lookup("format", "form") == "html"
    assert args.lookup("format", ("form", "query")) == "html"
Ejemplo n.º 13
0
def test_01():
    args = ReqArgs(query={"format": "json"}, form={"q": "1017"})
    assert args.lookup("format") == "json"
    assert args.lookup("q") == "1017"
Ejemplo n.º 14
0
    def prepare(self):
        """
        Extract body and url query parameters into functional groups.
        Typify predefined user inputs patterns here. Rules:

            * Inputs are combined and then separated into functional catagories.
            * Duplicated query or body arguments will overwrite the previous value.

        Extend to add more customizations.
        """
        content_type = self.request.headers.get('Content-Type', '')

        if content_type.startswith('application/json'):
            if not self.request.body:
                raise HTTPError(
                    400,
                    reason=('Empty body is not a valid JSON. '
                            'Remove the content-type header, or '
                            'provide an empty object in the body.'))
            try:
                # pylint: disable=attribute-defined-outside-init
                self.args_json = json_decode(self.request.body)
            except json.JSONDecodeError:
                raise HTTPError(400, reason='Invalid JSON body.')

        elif content_type.startswith('application/yaml'):
            try:
                self.args_yaml = yaml.load(self.request.body,
                                           Loader=yaml.SafeLoader)
            except (yaml.scanner.ScannerError, yaml.parser.ParserError) as err:
                raise HTTPError(400, reason='Invalid YAML body.')

        # pylint: disable=attribute-defined-outside-init
        self.args_query = {
            key: self.get_query_argument(key)
            for key in self.request.query_arguments
        }
        # pylint: disable=attribute-defined-outside-init
        self.args_form = {
            key: self.get_body_argument(key)
            for key in self.request.body_arguments
        }

        regargs = ReqArgs(ReqArgs.Path(args=self.path_args,
                                       kwargs=self.path_kwargs),
                          query=self.args_query,
                          form=self.args_form,
                          json_=self.args_json)

        # per request logging should not be combined in one message
        # it's possible to encounter OptionError during parsing
        self.logger.debug("%s %s\n%s", self.request.method, self.request.uri,
                          regargs)

        if self.name:
            optionset = self.web_settings.optionsets.get(self.name)
            try:
                # pylint: disable=attribute-defined-outside-init
                self.args = optionset.parse(self.request.method, regargs)
            except OptionError as err:
                raise BadRequest(**err.info)

            self.logger.debug("↓ (%s)\n%s", self.name,
                              pformat(self.args, width=150))
Ejemplo n.º 15
0
def test_03():
    assert str(ReqArgs(ReqArgs.Path())) == """
        ReqArgs()
    """.replace(" ", "")[1:-1]