-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
252 lines (206 loc) · 7.76 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import getopt
import logging
import logging.config
import pkgutil
import yaml
from endpoints import *
class APIValidator(object):
"""
This class is responsible for loading initial setup.
It loads the configurations required for the validation
It lists all the rules (or requests) to validate and manages the execution
All the rules which will be validated should extend RequestValidator class
"""
__CONFIG_BASE_PATH = 'config/'
"""
str: Base path to the configuration files.
It holds the base path to the location of the folder which contains
all the configuration files. This directory should at least container
one main configuration file which is main.conf
"""
__logger = None
"""
Object: logger instance
Holds the logger instance valid throughout the application
"""
__configuration = {}
"""
dict: Dictionary of application configuration
Holds all the configurations for the application which can be used to define the application
it contains configuration of request, response, header, logger etc
"""
def __init__(self):
"""
Initializes the APIValidator instance
loads the default configuration defined in `main.conf`
initializes the logger configuration if exist else creates a basic logger
initializes header configurations in exist
"""
self.__configuration = self.load_configuration('main.conf')
if not self.__configuration:
print('Failed to load initial configuration')
exit()
self.initialize_logger()
"""
logger is been initialized based on the configuration provided
if the configuration is not provided in main.conf basic logger is configured
"""
self.initialize_configuration('headers')
"""
Initialize the header configuration for the current request
this header configuration will be common accross all the request
"""
def load_configuration(self, _file_):
"""
This will load the configuration specified by the file passed
If the path exist then only the configuration is returned
Configuration file should be in YAML format
The configuration file should be located in the base path specified
Args:
_file_: configuration file name to load.
Returns:
dict: Dictionary format of configuration.
"""
if os.path.exists(self.__CONFIG_BASE_PATH + _file_):
with open(self.__CONFIG_BASE_PATH + _file_, 'rt') as conf:
return yaml.safe_load(conf.read())
return {}
def initialize_configuration(self, key):
"""
The key will be with respect to the initial configuration file `main.py`
Configuration is loaded only if the given key has a reference to configuration file
If the key has a configuration in form of dictionary then by default its loaded from base confif
Args:
key: key of configuration which has to be loaded.
"""
if key not in self.__configuration:
"""
No operation to perform if key is not present
"""
return {}
elif type(self.__configuration[key]) == str:
"""
Load configuration from file if the reference to a file is given
"""
self.__configuration[key] = self.load_configuration(
self.__configuration[key]
)
elif type(self.__configuration[key]) != dict:
"""
Configuration is invalid if its other then dictrinary format
"""
print('invalid format for '+ key)
exit()
def initialize_logger(self):
"""
This method will initialize the loggers based on the configuration specified in .conf file
in case of absence of the configuration, it loads teh basic logger configuration
"""
self.initialize_advance_logger()
"""
Initializes the logger based on the configuration if configuration is specified
"""
if not self.__logger:
"""
Loads the basic logger configuration in case of logger configurations not found
"""
self.initialize_basic_logger()
def initialize_basic_logger(self):
"""
This will be called when logger configuration is not found
this method will initialize the logger with the basic configuration
"""
logging.basicConfig(level=logging.DEBUG)
self.__logger = logging.getLogger(__name__)
def initialize_advance_logger(self):
"""
Logger is initialized based on the configuration specified
in case of missing configuration the logger will not be initialized
"""
if 'logger' not in self.__configuration:
return
config = self.initialize_configuration('logger')
"""
Configuration is loaded from the file specified
"""
if config:
"""
If configuration is found, then logger is configured
"""
logging.config.dictConfig(config)
self.__logger = logging.getLogger(__name__)
def usage(self):
"""
Prints info about usage
"""
print('python3 main.py [options]')
exit()
def add_argumet_filter(self, scripts):
"""
Options are evaluated and based on which the updated list of tests are generated
-r option will add the argument mentioned in the running list
-x will eliminate the test from the running list
Args:
scripts (list): list of test to run by default
Returns:
updated running list of tests
"""
try:
opts, _ = getopt.getopt(sys.argv[1:], "r:x:", ["run=", "exclude="])
except getopt.GetoptError as err:
print(err)
self.usage()
new_list = []
for opt, arg in opts:
if opt in ('-h', '--help'):
self.usage()
elif opt in ('-r', '--run'):
new_list.append(arg)
elif opt in ('-x', '--exclude'):
scripts.remove(arg)
if new_list:
return new_list
else:
return scripts
def get_test_list(self):
"""
Gives the list of test script to run
The priority of section is as below:
- This will default consider all the list
- The list is taken from the configuration
- command line options are evaluated
-r will run only that test
-x will exclude the test from running config
Returns:
list: list of tests to run
"""
self.initialize_configuration('tests')
if 'tests' in self.__configuration:
scripts = self.__configuration['tests']
else:
scripts = [name for _, name, _ in pkgutil.iter_modules(['endpoints'])]
return self.add_argumet_filter(scripts)
def execute(self):
"""
Executes the rules from the list given and validated for the required content
"""
test_list = self.get_test_list()
if not test_list:
print('No test scripts found')
exit()
for test in test_list:
try:
getattr(globals()[test], test)(self.__configuration, logging).run()
except KeyError:
print('Nothing like `'+ test + '` found in endpoints.')
if __name__ == '__main__':
"""
Executes the validator if this file is executed
Executes only when this file is been executed
If this file in included the below code wont execute
"""
APIValidator().execute()