Passed
Pull Request — master (#653)
by
unknown
25:49 queued 08:00
created

CustomQueryObject.get_query_method()   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 2
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nop 1
crap 1
1 1
import logging
2 1
from .query_object import QueryObject as _QueryObject
3
4
5 1
logger = logging.getLogger(__name__)
6
7
8 1
class CustomQueryObject(_QueryObject):
9 1
    def __init__(self, query, description=""):
10
        """Create a new CustomQueryObject.
11
12
        Parameters
13
        -----------
14
15
        query : function
16
            Function that defines a custom query method. The query can have any
17
            signature, but input and output of the query needs to be JSON
18
            serializable.
19
20
        description : str
21
            The description of the custom query object
22
23
        """
24 1
        super().__init__(description)
25
26 1
        self.custom_query = query
27
28 1
    def query(self, *args, **kwargs):
29
        """Query the custom defined query method using the given input.
30
31
        Parameters
32
        ----------
33
        args : list
34
            positional arguments to the query
35
36
        kwargs : dict
37
            keyword arguments to the query
38
39
        Returns
40
        -------
41
        out: object.
42
            The results depends on the implementation of the query method.
43
            Typically the return value will be whatever that function returns.
44
45
        See Also
46
        --------
47
        QueryObject
48
        """
49
        # include the dependent files in sys path so that the query can run
50
        # correctly
51
52
        try:
53
            logger.debug(
54
                "Running custom query with arguments " f"({args}, {kwargs})..."
55
            )
56
            ret = self.custom_query(*args, **kwargs)
57
        except Exception as e:
58
            logger.exception(
59
                "Exception hit when running custom query, error: " f"{str(e)}"
60
            )
61
            raise
62
63
        logger.debug(f"Received response {ret}")
64
        try:
65
            return self._make_serializable(ret)
66
        except Exception as e:
67
            logger.exception(
68
                "Cannot properly serialize custom query result, " f"error: {str(e)}"
69
            )
70
            raise
71
72 1
    def get_doc_string(self):
73
        """Get doc string from customized query"""
74 1
        return str(self.custom_query.__doc__ or "-- no docstring found in query function --")
75
76 1
    def get_methods(self):
77 1
        return [self.get_query_method()]
78
79 1
    def get_query_method(self):
80
        return {"method": "query"}
81