Skip to content

Commit 3a7db96

Browse files
committed
regression testing: code cleanup
1 parent 752f88c commit 3a7db96

File tree

7 files changed

+627
-336
lines changed

7 files changed

+627
-336
lines changed

fence/agents/lib/fencing_pycurl.py.py

+44-19
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
__author__ = 'Ondrej Mular <[email protected]>'
2-
__all__ = ["FencingPyCurl"]
3-
41
import pycurl
52
import sys
63
import atexit
@@ -10,14 +7,17 @@
107
import logging
118
import pprint
129

10+
__all__ = ["FencingPyCurl"]
11+
1312
## do not add code here.
1413
#BEGIN_VERSION_GENERATION
1514
RELEASE_VERSION = ""
1615
REDHAT_COPYRIGHT = ""
1716
BUILD_DATE = ""
1817
#END_VERSION_GENERATION
1918

20-
class FencingPyCurl():
19+
20+
class FencingPyCurl:
2121
active = False
2222
input_file = None
2323
output_file = None
@@ -29,7 +29,10 @@ class FencingPyCurl():
2929
pycurl_obj = None
3030

3131
def __init__(self):
32-
if not FencingPyCurl.active and (FencingPyCurl.input_file or FencingPyCurl.output_file):
32+
if (
33+
not FencingPyCurl.active and
34+
(FencingPyCurl.input_file or FencingPyCurl.output_file)
35+
):
3336
FencingPyCurl.active = True
3437
logging.debug("FencingPyCurl is active now")
3538
if FencingPyCurl.active:
@@ -48,7 +51,11 @@ def __init__(self):
4851
with open(FencingPyCurl.input_file, "r") as f:
4952
FencingPyCurl.actions = json.load(f)
5053
except Exception as e:
51-
logging.debug("Reading input file (%s) failed: %s" % (FencingPyCurl.input_file, e.message))
54+
logging.debug(
55+
"Reading input file '{file}' failed: {msg}".format(
56+
file=FencingPyCurl.input_file, msg=e.message
57+
)
58+
)
5259

5360
if FencingPyCurl.output_file:
5461
logging.debug("output file detected")
@@ -68,14 +75,17 @@ def setopt(self, opt, value):
6875
return self.pycurl_obj.setopt(opt, value)
6976

7077
def perform(self):
78+
req_ind = FencingPyCurl.request_index
79+
actions = FencingPyCurl.actions
7180
if FencingPyCurl.active:
7281
if FencingPyCurl.input_file:
7382
perform_start = time.time()
74-
if self.options["request"] == FencingPyCurl.actions[FencingPyCurl.request_index]["request"]:
75-
self.options["response"] = FencingPyCurl.actions[FencingPyCurl.request_index]["response"]
83+
if self.options["request"] == actions[req_ind]["request"]:
84+
self.options["response"] = actions[req_ind]["response"]
7685
if self.write_function:
7786
self.write_function(self.options["response"]["output"])
78-
diff = FencingPyCurl.actions[FencingPyCurl.request_index]["time"]["perform_duration"] - (time.time() - perform_start)
87+
duration = actions[req_ind]["time"]["perform_duration"]
88+
diff = duration - (time.time() - perform_start)
7989
if diff > 0:
8090
logging.debug("sleeping for: %s" % str(diff))
8191
time.sleep(diff)
@@ -84,15 +94,17 @@ def perform(self):
8494
print "Request:"
8595
pprint.pprint(self.options["request"])
8696
print "Expected:"
87-
pprint.pprint(FencingPyCurl.actions[FencingPyCurl.request_index]["request"])
97+
pprint.pprint(actions[req_ind]["request"])
8898
raise Exception("Invalid request")
8999
else:
100+
response = self.options["response"]
90101
start_time = time.time()
91102
self.pycurl_obj.perform()
92-
self.options["time"]["perform_duration"] = FencingPyCurl.last_request_time - start_time
93-
self.options["response"]["output"] = self.output_buffer.getvalue()
103+
duration = FencingPyCurl.last_request_time - start_time
104+
self.options["time"]["perform_duration"] = duration
105+
response["output"] = self.output_buffer.getvalue()
94106
if self.write_function:
95-
self.write_function(self.options["response"]["output"])
107+
self.write_function(response["output"])
96108
if FencingPyCurl.output_file:
97109
FencingPyCurl.actions.append(self.options)
98110
FencingPyCurl.request_index += 1
@@ -124,31 +136,44 @@ def close(self):
124136
@staticmethod
125137
def save_log_to_file():
126138
if FencingPyCurl.output_file and FencingPyCurl.actions:
127-
logging.debug("Writing log to file: %s" % FencingPyCurl.output_file)
139+
logging.debug(
140+
"Writing log to file: {0}".format(FencingPyCurl.output_file)
141+
)
128142
try:
129143
with open(FencingPyCurl.output_file, "w") as f:
130-
json.dump(FencingPyCurl.actions, f, sort_keys=True, indent=4, separators=(',', ': '))
144+
json.dump(
145+
FencingPyCurl.actions,
146+
f,
147+
sort_keys=True,
148+
indent=4,
149+
separators=(',', ': ')
150+
)
131151
except Exception as e:
132-
logging.debug("Writing log to file (%s) failed: %s" % (FencingPyCurl.output_file, e.message))
152+
logging.debug(
153+
"Writing log to file '{file}' failed: {msg}".format(
154+
file=FencingPyCurl.output_file, msg=e.message
155+
)
156+
)
133157

134158

135159
def get_and_remove_arg(arg, has_value=True):
136-
logging.debug("Getting arg: %s (has_value: %s)" % (arg, str(has_value)))
160+
logging.debug("Getting arg: '{0}'".format(arg))
137161
if not has_value:
138162
if arg in sys.argv:
139163
sys.argv.remove(arg)
140-
logging.debug("%s: True" % arg)
164+
logging.debug(arg + ": True")
141165
return True
142166
if arg in sys.argv:
143167
index = sys.argv.index(arg)
144168
sys.argv.remove(arg)
145169
if len(sys.argv) > index:
146170
value = sys.argv[index]
147171
sys.argv.remove(value)
148-
logging.debug("%s: %s" % (arg, value))
172+
logging.debug("{arg}: {val}".format(arg=arg, val=value))
149173
return value
150174
return None
151175

176+
152177
FencingPyCurl.input_file = get_and_remove_arg("--fencing_pycurl-log-in")
153178
FencingPyCurl.output_file = get_and_remove_arg("--fencing_pycurl-log-out")
154179

tests/actions.d/sleep.cfg

-2
This file was deleted.

tests/actions.d/status.cfg

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
name = "Simple Status"
2-
actions = [ { "command" : "status", "return_code" : "^[02]$" }, { "command" : "sleep(1)", "return_code" : "^0$" } ]
2+
actions = [ { "command" : "status", "return_code" : "^[02]$" }]

tests/binmitm.py

+70-41
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,20 @@
11
#!/usr/bin/python
22

3-
__author__ = 'Ondrej Mular <[email protected]>'
4-
53
import sys
64
import os
75
import subprocess
86
import logging
97
import json
108
import time
119

12-
INPUT_FILE = os.environ["BINMITM_INPUT"] if "BINMITM_INPUT" in os.environ else None
13-
OUTPUT_FILE = os.environ["BINMITM_OUTPUT"] if "BINMITM_OUTPUT" in os.environ else None
14-
COUNTER_FILE = os.environ["BINMITM_COUNTER_FILE"] if "BINMITM_COUNTER_FILE" in os.environ else ".binmitm_counter"
15-
ENV_VARS = os.environ["BINMITM_ENV"].split(",") if "BINMITM_ENV" in os.environ else []
10+
INPUT_FILE = os.environ["BINMITM_INPUT"]\
11+
if "BINMITM_INPUT" in os.environ else None
12+
OUTPUT_FILE = os.environ["BINMITM_OUTPUT"]\
13+
if "BINMITM_OUTPUT" in os.environ else None
14+
COUNTER_FILE = os.environ["BINMITM_COUNTER_FILE"]\
15+
if "BINMITM_COUNTER_FILE" in os.environ else ".binmitm_counter"
16+
ENV_VARS = os.environ["BINMITM_ENV"].split(",")\
17+
if "BINMITM_ENV" in os.environ else []
1618
IGNORE_TIMING = "BINMITM_IGNORE_TIMING" in os.environ
1719
DEBUG = "BINMITM_DEBUG" in os.environ
1820

@@ -22,18 +24,24 @@ def log_debug(msg):
2224
logging.error(msg)
2325

2426

25-
def exit(ret):
27+
def _exit(ret):
2628
if COUNTER_FILE and os.path.isfile(COUNTER_FILE):
2729
try:
2830
os.remove(COUNTER_FILE)
2931
except Exception as e:
30-
log_debug("Unable to delete counter file (%s): %s" % (COUNTER_FILE, e.message))
32+
log_debug("Unable to delete counter file ({0}): {1}".format(
33+
COUNTER_FILE, e.message
34+
))
3135
try:
3236
with open(COUNTER_FILE, "w") as f:
3337
f.write("0\n")
34-
log_debug("0 written into counter file (%s)" % COUNTER_FILE)
38+
log_debug(
39+
"0 written into counter file ({0})".format(COUNTER_FILE)
40+
)
3541
except Exception as e:
36-
log_debug("Unable to write 0 to counter file (%s): %s" % (COUNTER_FILE, e.message))
42+
log_debug("Unable to write 0 to counter file ({0}): {1}".format(
43+
COUNTER_FILE, e.message
44+
))
3745
sys.exit(ret)
3846

3947

@@ -45,41 +53,52 @@ def get_count(max_count):
4553
count = int(f.readline().strip())
4654
f.seek(0)
4755
f.truncate()
48-
f.write("%d\n" % ((count+1)%max_count))
56+
f.write("{0}\n".format((count+1) % max_count))
4957
except Exception as e:
50-
log_debug("Unable to read/write from/to '%s': %s" % (COUNTER_FILE, e.message))
58+
log_debug("Unable to read/write from/to '{0}': {1}".format(
59+
COUNTER_FILE, e.message
60+
))
5161
else:
5262
if max_count != 1:
5363
try:
5464
with open(COUNTER_FILE, "w") as f:
5565
f.write("1\n")
5666
except Exception as e:
57-
log_debug("Unable to write to '%s': %s" % (COUNTER_FILE, e.message))
67+
log_debug("Unable to write to '{0}': {1}".format(
68+
COUNTER_FILE, e.message
69+
))
5870
return count
5971

6072

6173
def record(argv):
6274
output = OUTPUT_FILE and not INPUT_FILE
6375
env = os.environ.copy()
6476

65-
cur_output = {}
66-
cur_output["request"] = {}
67-
cur_output["response"] = {}
68-
cur_output["time"] = {}
69-
cur_output["request"]["argv"] = argv
70-
cur_output["request"]["env"] = {}
77+
cur_output = {
78+
"request": {
79+
"argv": argv,
80+
"env": {}
81+
},
82+
"response": {},
83+
"time": {}
84+
}
7185

7286
for e in ENV_VARS:
7387
if e in env:
7488
cur_output["request"]["env"][e] = env[e]
7589

7690
proc_start_time = time.time()
91+
process = None
7792

7893
try:
79-
process = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
94+
process = subprocess.Popen(
95+
argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env
96+
)
8097
except OSError as e:
81-
log_debug("Unable to run command '%s': %s" % (" ".join(argv), e.message))
82-
exit(127)
98+
log_debug("Unable to run command '{0}': {1}".format(
99+
" ".join(argv), e.message
100+
))
101+
_exit(127)
83102

84103
status = process.wait()
85104
cur_output["time"]["perform_duration"] = time.time() - proc_start_time
@@ -104,7 +123,10 @@ def record(argv):
104123
try:
105124
output_values = json.load(f)
106125
except:
107-
log_debug("Parsing output file '%s' failed. It is considered as empty." % OUTPUT_FILE)
126+
log_debug(
127+
"Parsing output file '{0}' failed. It is "
128+
"considered as empty.".format(OUTPUT_FILE)
129+
)
108130

109131
output_values.append(cur_output)
110132
f.truncate()
@@ -113,11 +135,10 @@ def record(argv):
113135
else:
114136
with open(OUTPUT_FILE, "w") as f:
115137
json.dump([cur_output], f, indent=4)
116-
except ValueError as e:
117-
log_debug("Unable to parse output file: %s" % e.message)
118-
except IOError as e:
119-
log_debug("Unable to open output file '%s': %s" % (OUTPUT_FILE, e.message))
120-
138+
except (IOError, ValueError) as e:
139+
log_debug("Unable to store data to file '{0}': {1}".format(
140+
OUTPUT_FILE, e.message
141+
))
121142
sys.exit(status)
122143

123144

@@ -129,45 +150,54 @@ def replay(argv):
129150
try:
130151
with open(INPUT_FILE) as f:
131152
input_values = json.load(f)
132-
except ValueError as e:
133-
log_debug("Unable to parse input file: %s" % e.message)
134-
except IOError as e:
135-
log_debug("Unable to open input file '%s': %s" % (INPUT_FILE, e.message))
153+
except (ValueError, IOError) as e:
154+
log_debug("Unable to parse input file '{0}': {1}".format(
155+
OUTPUT_FILE, e.message
156+
))
136157

137158
if not input_values:
138159
log_debug("Empty input")
139-
exit(127)
160+
_exit(127)
140161

141162
input_number = get_count(len(input_values))
142163
if input_number >= len(input_values):
143164
log_debug("Unable to get current input")
144-
exit(127)
165+
_exit(127)
145166

146167
cur_input = input_values[input_number]
147168
if cur_input["request"]["argv"] != argv:
148-
log_debug("Expected different command (Expected: '%s', Given: '%s')" % (" ".join(cur_input["request"]["argv"]), " ".join(argv)))
149-
exit(127)
169+
log_debug(
170+
"Expected different command (Expected: '{0}', Given: '{1}')".format(
171+
" ".join(cur_input["request"]["argv"]),
172+
" ".join(argv)
173+
)
174+
)
175+
_exit(127)
150176

151177
env.update(cur_input["request"]["env"])
152178
sys.stderr.write(cur_input["response"]["stderr"])
153179
sys.stdout.write(cur_input["response"]["stdout"])
154180

155181
if not IGNORE_TIMING:
156-
time_left = cur_input["time"]["perform_duration"] - (time.time() - start_time)
182+
time_left = cur_input["time"]["perform_duration"] - (
183+
time.time() - start_time
184+
)
157185

158186
if time_left > 0:
159-
log_debug("Sleeping for %f s" % time_left)
187+
log_debug("Sleeping for {0} s".format(time_left))
160188
time.sleep(time_left)
161189
else:
162-
log_debug("Uooops! We are runnig %f s longer." % abs(time_left))
190+
log_debug("Uooops! We are running {0} s longer.".format(
191+
abs(time_left)
192+
))
163193

164194
sys.exit(cur_input["response"]["return_code"])
165195

166196

167197
def main(argv):
168198
if not argv:
169199
print "No command to run"
170-
exit(127)
200+
_exit(127)
171201
if INPUT_FILE:
172202
replay(argv)
173203
else:
@@ -176,4 +206,3 @@ def main(argv):
176206

177207
if __name__ == "__main__":
178208
main(sys.argv[1:])
179-

0 commit comments

Comments
 (0)