GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 7d41d1...923e60 )
by Flávio
8s
created

WebserviceBase.call()   B

Complexity

Conditions 4

Size

Total Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4.3731

Importance

Changes 5
Bugs 0 Features 0
Metric Value
c 5
b 0
f 0
dl 0
loc 32
ccs 10
cts 14
cp 0.7143
rs 8.5806
cc 4
crap 4.3731
1
# -*- coding: utf-8 -*-
0 ignored issues
show
Coding Style introduced by
This module should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2
# #############################################################################
3
#
4
# The MIT License (MIT)
5
#
6
# Copyright (c) 2016 Trocafone
7
#
8
# Permission is hereby granted, free of charge, to any person obtaining a copy
9
# of this software and associated documentation files (the "Software"), to deal
10
# in the Software without restriction, including without limitation the rights
11
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
# copies of the Software, and to permit persons to whom the Software is
13
# furnished to do so, subject to the following conditions:
14
#
15
# The above copyright notice and this permission notice shall be included in
16
# all copies or substantial portions of the Software.
17
#
18
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
# SOFTWARE.
25
#
26
###############################################################################
27
28 1
from zeep import Client
29 1
from zeep.transports import Transport
30 1
from voluptuous import Invalid, MultipleInvalid
31 1
import certifi
32 1
import logging.config
33
34
35 1
class WebserviceError(Exception):
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
36 1
    pass
37
38
39 1
class WebserviceBase():
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
introduced by
Old-style class defined.
Loading history...
Complexity introduced by
This abstract class seems to be used only once.

Abstract classes which are used only once can usually be inlined into the class which already uses this abstract class.

Loading history...
40
41 1
    def __init__(self, env, id_correios, password,
0 ignored issues
show
best-practice introduced by
Too many arguments (6/5)
Loading history...
42
                 cert=False, log_config=None):
43
        ''' Webservice initialization.
44
45
        Depending on the env get a different wsdl definition.
46
        New Correios SIGEP uses HTTPAuth to do requests.
47
48
        Args:
49
            env (str): Environment used to get the wsdl
50
            id_correios (str): IdCorreios given by correios website
51
            password (str): password vinculated to the IdCorreios
52
            log_config (dict): Dictionary configurations of logging
53
        '''
54
55
        ''' Untrusted ssl certificate for homolog envs see more at:
56
57
        https://www.ssllabs.com/ssltest/analyze.html?d=apphom.correios.com.br
58
        '''
0 ignored issues
show
Unused Code introduced by
This string statement has no effect and could be removed.
Loading history...
59 1
        if cert is False:
60 1
            verify = False
61
        else:
62
            verify = certifi.where()
63
64 1
        if log_config is not None and isinstance(log_config, dict):
65
            """ Example config from zeep documentation:
66
67
            {
68
                'version': 1,
69
                'formatters': {
70
                    'verbose': {
71
                        'format': '%(name)s: %(message)s'
72
                    }
73
                },
74
                'handlers': {
75
                    'console': {
76
                        'level': 'DEBUG',
77
                        'class': 'logging.StreamHandler',
78
                        'formatter': 'verbose',
79
                    },
80
                },
81
                'loggers': {
82
                    'zeep.transports': {
83
                        'level': 'DEBUG',
84
                        'propagate': True,
85
                        'handlers': ['console'],
86
                    },
87
                }
88
            }
89
            """
0 ignored issues
show
Unused Code introduced by
This string statement has no effect and could be removed.
Loading history...
90
            logging.config.dictConfig(log_config)
91
92 1
        t = Transport(
0 ignored issues
show
Coding Style Naming introduced by
The name t does not conform to the variable naming conventions ([a-z_][a-z0-9_]{2,30}$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
93
            verify=verify,
94
            http_auth=(id_correios, password)
95
        )
96 1
        self.client = Client(wsdl=self.get_env(env), transport=t)
97
98 1
    def get_env(self, env):
99
        """ Get WSDL Url.
100
101
        Must be implemented in order to return the correct WSDL.
102
103
        Args:
104
            env (str): Environment used to get the wsdl
105
106
        Returns:
107
            str: WSDL Url of the corresponding environment
108
        """
109 1
        raise NotImplementedError()
110
111 1
    def call(self, method, request):
112
        ''' Call the webservice method with the validated request content
113
114
        Args:
115
            method (str): Name of the method available at the webservice
116
            request (RequestObject): Object containing all the info needed
117
118
        Returns:
119
            dict: Result of the service call
120
        '''
121 1
        service_method = getattr(self.client.service, method, None)
122
123 1
        req_type = 'Request' + method[0].upper() + method[1:]
124 1
        req_instance = request.__class__.__name__
125
126 1
        if req_type != req_instance:
127 1
            raise WebserviceError(
128
                'Request must be an instance of {0}, given {1}'.format(
129
                    req_type,
130
                    req_instance
131
                 )
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation.
)
|^ |
Loading history...
132
            )
133
134 1
        import sys
135 1
        if sys.version_info <= (3, 0):
136
            reload(sys)
137
            sys.setdefaultencoding('utf-8')
0 ignored issues
show
Bug introduced by
The Module sys does not seem to have a member named setdefaultencoding.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
138
139 1
        try:
140 1
            return service_method(**request)
0 ignored issues
show
Coding Style introduced by
Usage of * or ** arguments should usually be done with care.

Generally, there is nothing wrong with usage of * or ** arguments. For readability of the code base, we suggest to not over-use these language constructs though.

For more information, we can recommend this blog post from Ned Batchelder including its comments which also touches this aspect.

Loading history...
141
        except ValueError as e:
142
            raise WebserviceError(e)
143
144
145 1
class EntityBase(dict):
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
146
147 1
    def __init__(self, **kargs):
148 1
        super(EntityBase, self).__init__(kargs)
149 1
        self.validate()
150
151 1
        try:
152 1
            raise getattr(self, 'error')
153 1
        except AttributeError:
154 1
            pass
155 1
        except Invalid as e:
156 1
            raise MultipleInvalid([e])
157
158 1
    def get_schema(self):
159
        """ Returns validation schema
160
161
        Returns:
162
            voluptous.Schema: Schema with validation rules
163
        """
164
        raise NotImplementedError("Every entitiy needs validation against a " +
165
                                  "Schema.")
166
167 1
    def validate(self):
168
        """ Validates content against schema
169
170
        In case of failure an error is kept inside the entity object,
171
        to be displayed by the client user if needed.
172
173
        Returns:
174
            bool: Validation result
175
        """
176 1
        schema = self.get_schema()
177 1
        try:
178 1
            super(EntityBase, self).__init__(schema(self))
179 1
            return True
180 1
        except Exception as e:
0 ignored issues
show
Best Practice introduced by
Catching very general exceptions such as Exception is usually not recommended.

Generally, you would want to handle very specific errors in the exception handler. This ensure that you do not hide other types of errors which should be fixed.

So, unless you specifically plan to handle any error, consider adding a more specific exception.

Loading history...
181 1
            self.error = e
182
            return False
183