service_keywords.py
6.51 KB
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
# -*- coding: utf-8 -
from datetime import timedelta
from dateutil.parser import parse
from dpath.util import set as xpathset
from iso8601 import parse_date
from json import load
from jsonpath_rw import parse as parse_path
from munch import fromYAML, Munch, munchify
from robot.errors import HandlerExecutionFailed
from robot.libraries.BuiltIn import BuiltIn
from robot.output import LOGGER
from robot.output.loggerhelper import Message
# These imports are not pointless. Robot's resource and testsuite files
# can access them by simply importing library "service_keywords".
# Please ignore the warning given by Flake8 or other linter.
from .initial_data import (
auction_bid, create_fake_doc,
test_award_data, test_bid_data, test_complaint_data,
test_complaint_reply_data, test_question_answer_data,
test_question_data, test_tender_data, test_tender_data_multiple_lots
)
from .local_time import get_now, TZ
import os
def get_current_tzdate():
return get_now().strftime('%Y-%m-%d %H:%M:%S.%f')
def get_file_contents(path):
with open(path, 'r') as f:
return unicode(f.read()) or u''
def change_state(arguments):
try:
if arguments[0] == "shouldfail":
return "shouldfail"
return "pass"
except IndexError:
return "pass"
def compare_date(date1, date2):
date1 = parse(date1)
date2 = parse(date2)
if date1.tzinfo is None:
date1 = TZ.localize(date1)
if date2.tzinfo is None:
date2 = TZ.localize(date2)
delta = (date1 - date2).total_seconds()
if abs(delta) > 60:
return False
return True
def log_object_data(data, file_name=None, format="yaml"):
"""Log object data in pretty format (JSON or YAML)
Two output formats are supported: "yaml" and "json".
If a file name is specified, the output is written into that file.
If you would like to get similar output everywhere,
use the following snippet somewhere in your code
before actually using Munch. For instance,
put it into your __init__.py, or, if you use zc.buildout,
specify it in "initialization" setting of zc.recipe.egg.
from munch import Munch
Munch.__str__ = lambda self: Munch.toYAML(self, allow_unicode=True,
default_flow_style=False)
Munch.__repr__ = Munch.__str__
"""
if not isinstance(data, Munch):
data = munchify(data)
if format.lower() == 'json':
data = data.toJSON(indent=2)
else:
data = data.toYAML(allow_unicode=True, default_flow_style=False)
format = 'yaml'
LOGGER.log_message(Message(data.decode('utf-8'), "INFO"))
if file_name:
output_dir = BuiltIn().get_variable_value("${OUTPUT_DIR}")
with open(os.path.join(output_dir, file_name + '.' + format), "w") as file_obj:
file_obj.write(data)
def load_initial_data_from(file_name):
if not os.path.exists(file_name):
file_name = os.path.join(os.path.dirname(__file__), 'data/{}'.format(file_name))
with open(file_name) as file_obj:
if file_name.endswith(".json"):
return Munch.fromDict(load(file_obj))
elif file_name.endswith(".yaml"):
return fromYAML(file_obj)
def prepare_test_tender_data(period_intervals, mode):
if mode == 'single':
return munchify({'data': test_tender_data(period_intervals)})
elif mode == 'multi':
return munchify({'data': test_tender_data_multiple_lots(period_intervals)})
raise ValueError('Invalid mode for test_tender_data')
def run_keyword_and_ignore_keyword_definitions(name, *args):
"""Runs the given keyword with given arguments and returns the status as a Boolean value.
This keyword returns `True` if the keyword that is executed succeeds and
`False` if it fails. This is useful, for example, in combination with
`Run Keyword If`. If you are interested in the error message or return
value, use `Run Keyword And Ignore Error` instead.
The keyword name and arguments work as in `Run Keyword`.
Example:
| ${passed} = | `Run Keyword And Return Status` | Keyword | args |
| `Run Keyword If` | ${passed} | Another keyword |
New in Robot Framework 2.7.6.
"""
try:
status, _ = BuiltIn().run_keyword_and_ignore_error(name, *args)
except HandlerExecutionFailed:
LOGGER.log_message(Message("Keyword {} not implemented", "ERROR"))
return "FAIL", ""
return status, _
def set_tender_periods(tender):
now = get_now()
tender.data.enquiryPeriod.endDate = (now + timedelta(minutes=2)).isoformat()
tender.data.tenderPeriod.startDate = (now + timedelta(minutes=2)).isoformat()
tender.data.tenderPeriod.endDate = (now + timedelta(minutes=4)).isoformat()
return tender
def set_access_key(tender, access_token):
tender.access = munchify({"token": access_token})
return tender
def set_to_object(obj, attribute, value):
xpathset(obj, attribute.replace('.', '/'), value)
return obj
def get_from_object(obj, attribute):
"""Gets data from a dictionary using a dotted accessor-string"""
jsonpath_expr = parse_path(attribute)
return_list = [i.value for i in jsonpath_expr.find(obj)]
if return_list:
return return_list[0]
return None
def wait_to_date(date_stamp):
date = parse(date_stamp)
LOGGER.log_message(Message("date: {}".format(date.isoformat()), "INFO"))
now = get_now()
LOGGER.log_message(Message("now: {}".format(now.isoformat()), "INFO"))
wait_seconds = (date - now).total_seconds()
wait_seconds += 2
if wait_seconds < 0:
return 0
return wait_seconds
def merge_dicts(left, right):
new = {}
new.update(left)
new.update(right)
return new
# GUI Frontends common
def add_data_for_gui_frontends(tender_data):
now = get_now()
# tender_data.data.enquiryPeriod['startDate'] = (now + timedelta(minutes=2)).isoformat()
tender_data.data.enquiryPeriod['endDate'] = (now + timedelta(minutes=6)).isoformat()
tender_data.data.tenderPeriod['startDate'] = (now + timedelta(minutes=7)).isoformat()
tender_data.data.tenderPeriod['endDate'] = (now + timedelta(minutes=11)).isoformat()
return tender_data
def convert_date_to_slash_format(isodate):
iso_dt = parse_date(isodate)
date_string = iso_dt.strftime("%d/%m/%Y")
return date_string
def convert_datetime_to_dot_format(isodate):
iso_dt = parse_date(isodate)
day_string = iso_dt.strftime("%d.%m.%Y %H:%M")
return day_string
def local_path_to_file(file_name):
return os.path.join(os.path.dirname(__file__), 'documents', file_name)