utils.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. # Licensed to the Software Freedom Conservancy (SFC) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The SFC licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. import json
  18. import logging
  19. import os
  20. import tempfile
  21. import zipfile
  22. from selenium.common.exceptions import NoSuchElementException
  23. LOGGER = logging.getLogger(__name__)
  24. def format_json(json_struct):
  25. return json.dumps(json_struct, indent=4)
  26. def dump_json(json_struct):
  27. return json.dumps(json_struct)
  28. def load_json(s):
  29. return json.loads(s)
  30. def handle_find_element_exception(e):
  31. if ("Unable to find" in e.response["value"]["message"] or "Unable to locate" in e.response["value"]["message"]):
  32. raise NoSuchElementException("Unable to locate element:")
  33. else:
  34. raise e
  35. def return_value_if_exists(resp):
  36. if resp and "value" in resp:
  37. return resp["value"]
  38. def get_root_parent(elem):
  39. parent = elem.parent
  40. while True:
  41. try:
  42. parent.parent
  43. parent = parent.parent
  44. except AttributeError:
  45. return parent
  46. def unzip_to_temp_dir(zip_file_name):
  47. """Unzip zipfile to a temporary directory.
  48. The directory of the unzipped files is returned if success,
  49. otherwise None is returned. """
  50. if not zip_file_name or not os.path.exists(zip_file_name):
  51. return None
  52. zf = zipfile.ZipFile(zip_file_name)
  53. if zf.testzip() is not None:
  54. return None
  55. # Unzip the files into a temporary directory
  56. LOGGER.info("Extracting zipped file: %s" % zip_file_name)
  57. tempdir = tempfile.mkdtemp()
  58. try:
  59. # Create directories that don't exist
  60. for zip_name in zf.namelist():
  61. # We have no knowledge on the os where the zipped file was
  62. # created, so we restrict to zip files with paths without
  63. # charactor "\" and "/".
  64. name = (zip_name.replace("\\", os.path.sep).
  65. replace("/", os.path.sep))
  66. dest = os.path.join(tempdir, name)
  67. if (name.endswith(os.path.sep) and not os.path.exists(dest)):
  68. os.mkdir(dest)
  69. LOGGER.debug("Directory %s created." % dest)
  70. # Copy files
  71. for zip_name in zf.namelist():
  72. # We have no knowledge on the os where the zipped file was
  73. # created, so we restrict to zip files with paths without
  74. # charactor "\" and "/".
  75. name = (zip_name.replace("\\", os.path.sep).
  76. replace("/", os.path.sep))
  77. dest = os.path.join(tempdir, name)
  78. if not (name.endswith(os.path.sep)):
  79. LOGGER.debug("Copying file %s......" % dest)
  80. outfile = open(dest, 'wb')
  81. outfile.write(zf.read(zip_name))
  82. outfile.close()
  83. LOGGER.debug("File %s copied." % dest)
  84. LOGGER.info("Unzipped file can be found at %s" % tempdir)
  85. return tempdir
  86. except IOError as err:
  87. LOGGER.error("Error in extracting webdriver.xpi: %s" % err)
  88. return None