Advertisement
yboi

Untitled

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