logger.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import io
  2. import os
  3. from pathlib import Path
  4. import json
  5. import uuid
  6. import shutil
  7. from attr import asdict
  8. from allure_commons import hookimpl
  9. INDENT = 4
  10. class AllureFileLogger:
  11. def __init__(self, report_dir, clean=False):
  12. self._report_dir = Path(report_dir).absolute()
  13. if self._report_dir.is_dir() and clean:
  14. shutil.rmtree(self._report_dir)
  15. self._report_dir.mkdir(parents=True, exist_ok=True)
  16. def _report_item(self, item):
  17. indent = INDENT if os.environ.get("ALLURE_INDENT_OUTPUT") else None
  18. filename = item.file_pattern.format(prefix=uuid.uuid4())
  19. data = asdict(item, filter=lambda _, v: v or v is False)
  20. with io.open(self._report_dir / filename, 'w', encoding='utf8') as json_file:
  21. json.dump(data, json_file, indent=indent, ensure_ascii=False)
  22. @hookimpl
  23. def report_result(self, result):
  24. self._report_item(result)
  25. @hookimpl
  26. def report_container(self, container):
  27. self._report_item(container)
  28. @hookimpl
  29. def report_attached_file(self, source, file_name):
  30. destination = self._report_dir / file_name
  31. shutil.copy2(source, destination)
  32. @hookimpl
  33. def report_attached_data(self, body, file_name):
  34. destination = self._report_dir / file_name
  35. with open(destination, 'wb') as attached_file:
  36. if isinstance(body, str):
  37. attached_file.write(body.encode('utf-8'))
  38. else:
  39. attached_file.write(body)
  40. class AllureMemoryLogger:
  41. def __init__(self):
  42. self.test_cases = []
  43. self.test_containers = []
  44. self.attachments = {}
  45. @hookimpl
  46. def report_result(self, result):
  47. data = asdict(result, filter=lambda _, v: v or v is False)
  48. self.test_cases.append(data)
  49. @hookimpl
  50. def report_container(self, container):
  51. data = asdict(container, filter=lambda _, v: v or v is False)
  52. self.test_containers.append(data)
  53. @hookimpl
  54. def report_attached_file(self, source, file_name):
  55. self.attachments[file_name] = source
  56. @hookimpl
  57. def report_attached_data(self, body, file_name):
  58. self.attachments[file_name] = body