Passed
Pull Request — master (#652)
by
unknown
40:46 queued 23:30
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 inspect
2 1
import logging
3 1
import platform
4 1
import sys
5 1
from .query_object import QueryObject as _QueryObject
6
7
8 1
logger = logging.getLogger(__name__)
9
10
11 1
class CustomQueryObject(_QueryObject):
12 1
    def __init__(self, query, description=""):
13
        """Create a new CustomQueryObject.
14
15
        Parameters
16
        -----------
17
18
        query : function
19
            Function that defines a custom query method. The query can have any
20
            signature, but input and output of the query needs to be JSON
21
            serializable.
22
23
        description : str
24
            The description of the custom query object
25
26
        """
27 1
        super().__init__(description)
28
29 1
        self.custom_query = query
30
31 1
    def query(self, *args, **kwargs):
32
        """Query the custom defined query method using the given input.
33
34
        Parameters
35
        ----------
36
        args : list
37
            positional arguments to the query
38
39
        kwargs : dict
40
            keyword arguments to the query
41
42
        Returns
43
        -------
44
        out: object.
45
            The results depends on the implementation of the query method.
46
            Typically the return value will be whatever that function returns.
47
48
        See Also
49
        --------
50
        QueryObject
51
        """
52
        # include the dependent files in sys path so that the query can run
53
        # correctly
54
55
        try:
56
            logger.debug(
57
                "Running custom query with arguments " f"({args}, {kwargs})..."
58
            )
59
            ret = self.custom_query(*args, **kwargs)
60
        except Exception as e:
61
            logger.exception(
62
                "Exception hit when running custom query, error: " f"{str(e)}"
63
            )
64
            raise
65
66
        logger.debug(f"Received response {ret}")
67
        try:
68
            return self._make_serializable(ret)
69
        except Exception as e:
70
            logger.exception(
71
                "Cannot properly serialize custom query result, " f"error: {str(e)}"
72
            )
73
            raise
74
75 1
    def get_doc_string(self):
76
        """Get doc string from customized query"""
77 1
        default_docstring = "-- no docstring found in query function --"
78
79
        # TODO: fix docstring parsing on Windows systems
80 1
        if sys.platform == 'win32':
81
            return default_docstring
82
83 1
        ds = getattr(self.custom_query, '__doc__', None)
84 1
        return ds if ds and isinstance(ds, str) else default_docstring
85
86 1
    def get_methods(self):
87 1
        return [self.get_query_method()]
88
89 1
    def get_query_method(self):
90
        return {"method": "query"}
91