Advertisement
yboi

Untitled

Aug 27th, 2015
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.01 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -
  3. import os
  4. from munch import munchify, Munch, fromYAML
  5. from json import load
  6. from iso8601 import parse_date
  7. from robot.output import LOGGER
  8. from robot.output.loggerhelper import Message
  9. from robot.libraries.BuiltIn import BuiltIn
  10. from robot.errors import HandlerExecutionFailed
  11. from datetime import datetime, timedelta, date
  12. from dateutil.parser import parse
  13. from dateutil.tz import tzlocal
  14. from pytz import timezone
  15. from dpath.util import set as xpathset
  16. from jsonpath_rw import parse as parse_path
  17. import time
  18. from .initial_data import (
  19. test_tender_data, test_question_data, test_question_answer_data,
  20. test_bid_data, test_award_data, test_complaint_data, test_complaint_reply_data, test_tender_data_multiple_lots,
  21. auction_bid, prom_test_tender_data, create_fake_doc
  22. )
  23. import calendar
  24.  
  25. TIMEZONE = timezone('Europe/Kiev')
  26.  
  27. def get_date():
  28. return datetime.now().isoformat()
  29.  
  30. def convert_date_to_slash_format(isodate):
  31. iso_dt=parse_date(isodate)
  32. date_string = iso_dt.strftime("%d/%m/%Y")
  33. return date_string
  34.  
  35. def convert_date_to_etender_format(isodate):
  36. iso_dt=parse_date(isodate)
  37. date_string = iso_dt.strftime("%d-%m-%Y")
  38. return date_string
  39.  
  40. def convert_time_to_etender_format(isodate):
  41. iso_dt=parse_date(isodate)
  42. time_string = iso_dt.strftime("%H:%M")
  43. return time_string
  44.  
  45. def change_state(arguments):
  46. try:
  47. if arguments[0] == "shouldfail":
  48. return "shouldfail"
  49. return "pass"
  50. except IndexError:
  51. return "pass"
  52.  
  53. def prepare_prom_test_tender_data():
  54. return munchify({'data': prom_test_tender_data()})
  55.  
  56. def compare_date(data1, data2):
  57. data1=parse(data1)
  58. data2=parse(data2)
  59. if data1.tzinfo is None:
  60. data1 = TIMEZONE.localize(data1)
  61. if data2.tzinfo is None:
  62. data2 = TIMEZONE.localize(data2)
  63.  
  64. delta = (data1-data2).total_seconds()
  65. if abs(delta) > 60:
  66. return False
  67. return True
  68.  
  69. def log_object_data(data, file_name="", format="yaml"):
  70. if not isinstance(data, Munch):
  71. data = munchify(data)
  72. if format == 'json':
  73. data = data.toJSON(indent=2)
  74. else:
  75. data = data.toYAML(allow_unicode=True, default_flow_style=False)
  76. format = 'yaml'
  77. LOGGER.log_message(Message(data, "INFO"))
  78. if file_name:
  79. output_dir = BuiltIn().get_variable_value("${OUTPUT_DIR}")
  80. with open(os.path.join(output_dir, file_name + '.' + format), "w") as file_obj:
  81. file_obj.write(data)
  82.  
  83. def convert_date_to_prom_format(isodate):
  84. iso_dt=parse_date(isodate)
  85. day_string = iso_dt.strftime("%d.%m.%Y %H:%M")
  86. return day_string
  87.  
  88. def load_initial_data_from(file_name):
  89. if not os.path.exists(file_name):
  90. file_name = os.path.join(os.path.dirname(__file__), 'data/{}'.format(file_name))
  91. with open(file_name) as file_obj:
  92. if file_name.endswith(".json"):
  93. return Munch.fromDict(load(file_obj))
  94. elif file_name.endswith(".yaml"):
  95. return fromYAML(file_obj)
  96.  
  97.  
  98. def prepare_test_tender_data(period_interval=2, mode='single'):
  99. if mode == 'single':
  100. return munchify({'data': test_tender_data(period_interval=period_interval)})
  101. elif mode == 'multi':
  102. return munchify({'data': test_tender_data_multiple_lots(period_interval=period_interval)})
  103. raise ValueError('A very specific bad thing happened')
  104.  
  105.  
  106. def run_keyword_and_ignore_keyword_definations(name, *args):
  107. """Runs the given keyword with given arguments and returns the status as a Boolean value.
  108.  
  109. This keyword returns `True` if the keyword that is executed succeeds and
  110. `False` if it fails. This is useful, for example, in combination with
  111. `Run Keyword If`. If you are interested in the error message or return
  112. value, use `Run Keyword And Ignore Error` instead.
  113.  
  114. The keyword name and arguments work as in `Run Keyword`.
  115.  
  116. Example:
  117. | ${passed} = | `Run Keyword And Return Status` | Keyword | args |
  118. | `Run Keyword If` | ${passed} | Another keyword |
  119.  
  120. New in Robot Framework 2.7.6.
  121. """
  122. try:
  123. status, _ = BuiltIn().run_keyword_and_ignore_error(name, *args)
  124. except HandlerExecutionFailed, e:
  125. LOGGER.log_message(Message("Keyword {} not implemented", "ERROR"))
  126. return "FAIL", ""
  127. return status, _
  128.  
  129.  
  130. def set_tender_periods(tender):
  131. now = datetime.now()
  132. tender.data.enquiryPeriod.endDate = (now + timedelta(minutes=2)).isoformat()
  133. tender.data.tenderPeriod.startDate = (now + timedelta(minutes=2)).isoformat()
  134. tender.data.tenderPeriod.endDate = (now + timedelta(minutes=4)).isoformat()
  135. return tender
  136.  
  137.  
  138. def set_access_key(tender, access_token):
  139. tender.access = munchify({"token": access_token})
  140. return tender
  141.  
  142.  
  143. def set_to_object(obj, attribute, value):
  144. xpathset(obj, attribute.replace('.', '/'), value)
  145. return obj
  146.  
  147.  
  148. def get_from_object(obj, attribute):
  149. """Gets data from a dictionary using a dotted accessor-string"""
  150. jsonpath_expr = parse_path(attribute)
  151. return_list = [i.value for i in jsonpath_expr.find(obj)]
  152. if return_list:
  153. return return_list[0]
  154. return None
  155.  
  156.  
  157. def wait_to_date(date_stamp):
  158. date = parse(date_stamp)
  159. LOGGER.log_message(Message("date: {}".format(date.isoformat()), "INFO"))
  160. now = datetime.now(tzlocal())
  161. LOGGER.log_message(Message("now: {}".format(now.isoformat()), "INFO"))
  162. wait_seconds = (date - now).total_seconds()
  163. wait_seconds += 2
  164. if wait_seconds < 0:
  165. return 0
  166. return wait_seconds
  167.  
  168. def newtend_date_picker_index(isodate):
  169. now = datetime.today()
  170. date_str = '01' + str(now.month) + str(now.year)
  171. first_day_of_month = datetime.strptime(date_str, "%d%m%Y")
  172. mod = first_day_of_month.isoweekday() - 2
  173. iso_dt=parse_date(isodate)
  174. last_day_of_month = calendar.monthrange(now.year, now.month)[1]
  175. #LOGGER.log_message(Message("last_day_of_month: {}".format(last_day_of_month), "INFO"))
  176. if now.day>iso_dt.day:
  177. mod = calendar.monthrange(now.year, now.month)[1] + mod
  178. return mod + iso_dt.day
  179.  
  180. def Add_time_for_GUI_FrontEnds(INITIAL_TENDER_DATA):
  181. now = datetime.now()
  182. INITIAL_TENDER_DATA.data.enquiryPeriod['startDate'] = (now + timedelta(minutes=2)).isoformat()
  183. INITIAL_TENDER_DATA.data.enquiryPeriod['endDate'] = (now + timedelta(minutes=5)).isoformat()
  184. INITIAL_TENDER_DATA.data.tenderPeriod['startDate'] = (now + timedelta(minutes=6)).isoformat()
  185. INITIAL_TENDER_DATA.data.tenderPeriod['endDate'] = (now + timedelta(minutes=7)).isoformat()
  186. return INITIAL_TENDER_DATA
  187.  
  188. def subtract_from_time_data(date_time,substr_min,substr_sec):
  189. now = datetime.strptime(date_time,"%d-%m-%Y, %H:%M")
  190. now = (now - timedelta(minutes=int(substr_min), seconds = int (substr_sec) )).isoformat()
  191. return now
  192.  
  193. def procuringEntity_name(INITIAL_TENDER_DATA):
  194. INITIAL_TENDER_DATA.data.procuringEntity['name'] = 'Повна назва невідомо чого'
  195. return INITIAL_TENDER_DATA
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement