Пример #1
0
    def test_simple(self):
        simple_dict = {
            "schema": 1,
            "origin": {
                "description": "2D Graphics Library",
                "license": ["MPL-1.1", "LGPL-2.1"],
                "name": "cairo",
                "release": "version 1.6.4",
                "revision": "AA001122334455",
                "url": "https://www.cairographics.org/",
            },
            "bugzilla": {
                "component": "Graphics",
                "product": "Core",
            },
        }
        with mozfile.NamedTemporaryFile() as tf:
            tf.write(b"""
---
schema: 1
origin:
  name: cairo
  description: 2D Graphics Library
  url: https://www.cairographics.org/
  release: version 1.6.4
  license:
    - MPL-1.1
    - LGPL-2.1
  revision: AA001122334455
bugzilla:
  product: Core
  component: Graphics
            """.strip())
            tf.flush()
            self.assertDictEqual(
                load_moz_yaml(tf.name, require_license_file=False),
                simple_dict)

        # as above, without the --- yaml prefix
        with mozfile.NamedTemporaryFile() as tf:
            tf.write(b"""
schema: 1
origin:
  name: cairo
  description: 2D Graphics Library
  url: https://www.cairographics.org/
  release: version 1.6.4
  license:
    - MPL-1.1
    - LGPL-2.1
  revision: AA001122334455
bugzilla:
  product: Core
  component: Graphics
            """.strip())
            tf.flush()
            self.assertDictEqual(
                load_moz_yaml(tf.name, require_license_file=False),
                simple_dict)
Пример #2
0
    def test_simple(self):
        simple_dict = {
            'schema': 1,
            'origin': {
                'description': '2D Graphics Library',
                'license': ['MPL-1.1', 'LGPL-2.1'],
                'name': 'cairo',
                'release': 'version 1.6.4',
                'url': 'https://www.cairographics.org/',
            },
            'bugzilla': {
                'component': 'Graphics',
                'product': 'Core',
            },
        }
        with mozfile.NamedTemporaryFile() as tf:
            tf.write("""
---
schema: 1
origin:
  name: cairo
  description: 2D Graphics Library
  url: https://www.cairographics.org/
  release: version 1.6.4
  license:
    - MPL-1.1
    - LGPL-2.1
bugzilla:
  product: Core
  component: Graphics
            """.strip())
            tf.flush()
            self.assertDictEqual(
                load_moz_yaml(tf.name, require_license_file=False),
                simple_dict)

        # as above, without the --- yaml prefix
        with mozfile.NamedTemporaryFile() as tf:
            tf.write("""
schema: 1
origin:
  name: cairo
  description: 2D Graphics Library
  url: https://www.cairographics.org/
  release: version 1.6.4
  license:
    - MPL-1.1
    - LGPL-2.1
bugzilla:
  product: Core
  component: Graphics
            """.strip())
            tf.flush()
            self.assertDictEqual(
                load_moz_yaml(tf.name, require_license_file=False),
                simple_dict)
Пример #3
0
 def test_with_package_name(self):
     with mozfile.NamedTemporaryFile() as f:
         with zipfile.ZipFile(f.name, 'w') as z:
             self.create_apk_zipfiles(z)
             z.writestr('package-name.txt', "org.mozilla.fennec")
         v = get_version(f.name)
         self.assertEqual(v.get('package_name'), "org.mozilla.fennec")
    def test_iteration(self):
        """ensure the line iterator works"""

        # make a file and write to it
        tf = mozfile.NamedTemporaryFile()
        notes = ['doe', 'rae', 'mi']
        for note in notes:
            tf.write(b'%s\n' % note)
        tf.flush()

        # now read from it
        tf.seek(0)
        lines = [line.rstrip('\n') for line in tf.readlines()]
        self.assertEqual(lines, notes)

        # now read from it iteratively
        lines = []
        for line in tf:
            lines.append(line.strip())
        self.assertEqual(lines, [])  # because we did not seek(0)
        tf.seek(0)
        lines = []
        for line in tf:
            lines.append(line.strip())
        self.assertEqual(lines, notes)
Пример #5
0
def run_linter(python, paths, config, **lintargs):
    binary = find_executable(python)
    if not binary:
        # If we're in automation, this is fatal. Otherwise, the warning in the
        # setup method was already printed.
        if 'MOZ_AUTOMATION' in os.environ:
            return 1
        return []

    files = expand_exclusions(paths, config, lintargs['root'])

    with mozfile.NamedTemporaryFile(mode='w') as fh:
        fh.write('\n'.join(files))
        fh.flush()

        cmd = [binary, os.path.join(here, 'check_compat.py'), fh.name]

        proc = PyCompatProcess(config, cmd)
        proc.run()
        try:
            proc.wait()
        except KeyboardInterrupt:
            proc.kill()

    return results
Пример #6
0
    def get_memory_total(self, timeout=None):
        """Returns the total memory available with units.

        :param timeout: optional integer specifying the maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :returns: memory total with units.
        :raises: * ADBTimeoutError
                 * ADBError
        """
        meminfo = {}
        with mozfile.NamedTemporaryFile() as tf:
            self.pull('/proc/meminfo', tf.name, timeout=timeout)
            try:
                with open(tf.name) as tf2:
                    for line in tf2.read().splitlines():
                        key, value = line.split(':')
                        meminfo[key] = value.strip()
            except Exception as e:
                raise ADBError(
                    traceback.format_exception_only(type(e), e)[0].strip())
        return meminfo['MemTotal']
Пример #7
0
def test_prefs_write():
    """test that the Preferences.write() method correctly serializes preferences"""

    _prefs = {
        "browser.startup.homepage": "http://planet.mozilla.org",
        "zoom.minPercent": 30,
        "zoom.maxPercent": 300,
    }

    # make a Preferences manager with the testing preferences
    preferences = Preferences(_prefs)

    # write them to a temporary location
    path = None
    read_prefs = None
    try:
        with mozfile.NamedTemporaryFile(suffix=".js", delete=False,
                                        mode="w+t") as f:
            path = f.name
            preferences.write(f, _prefs)

        # read them back and ensure we get what we put in
        read_prefs = dict(Preferences.read_prefs(path))

    finally:
        # cleanup
        if path and os.path.exists(path):
            os.remove(path)

    assert read_prefs == _prefs
Пример #8
0
 def test_basic(self):
     with mozfile.NamedTemporaryFile() as f:
         with zipfile.ZipFile(f.name, 'w') as z:
             self.create_apk_zipfiles(z)
         v = get_version(f.name)
         self.assertEqual(v.get('application_changeset'), self.application_changeset)
         self.assertEqual(v.get('platform_changeset'), self.platform_changeset)
Пример #9
0
def run_linter(python, paths, config, **lintargs):
    log = lintargs["log"]
    binary = find_executable(python)
    if not binary:
        # If we're in automation, this is fatal. Otherwise, the warning in the
        # setup method was already printed.
        if "MOZ_AUTOMATION" in os.environ:
            return 1
        return []

    files = expand_exclusions(paths, config, lintargs["root"])

    with mozfile.NamedTemporaryFile(mode="w") as fh:
        fh.write("\n".join(files))
        fh.flush()

        cmd = [binary, os.path.join(here, "check_compat.py"), fh.name]
        log.debug("Command: {}".format(" ".join(cmd)))

        proc = PyCompatProcess(config, cmd)
        proc.run()
        try:
            proc.wait()
        except KeyboardInterrupt:
            proc.kill()

    return results
Пример #10
0
def dumpScreen(utilityPath):
    """dumps a screenshot of the entire screen to a directory specified by
  the MOZ_UPLOAD_DIR environment variable"""
    import mozfile

    # Need to figure out which OS-dependent tool to use
    if mozinfo.isUnix:
        utility = [os.path.join(utilityPath, "screentopng")]
    elif mozinfo.isMac:
        utility = ['/usr/sbin/screencapture', '-C', '-x', '-t', 'png']
    elif mozinfo.isWin:
        utility = [os.path.join(utilityPath, "screenshot.exe")]

    # Get dir where to write the screenshot file
    parent_dir = os.environ.get('MOZ_UPLOAD_DIR', None)
    if not parent_dir:
        log.info('Failed to retrieve MOZ_UPLOAD_DIR env var')
        return

    # Run the capture
    try:
        with mozfile.NamedTemporaryFile(suffix='.png',
                                        prefix='mozilla-test-fail-screenshot_',
                                        dir=parent_dir,
                                        delete=False) as f:
            returncode = subprocess.call(utility + [f.name])
    except OSError, err:
        log.info("Failed to start %s for screenshot: %s", utility[0],
                 err.strerror)
        return
Пример #11
0
 def test_json(self):
     with mozfile.NamedTemporaryFile() as tf:
         tf.write('{"origin": {"release": "version 1.6.4", "url": "https://w'
                  'ww.cairographics.org/", "description": "2D Graphics Libra'
                  'ry", "license": ["MPL-1.1", "LGPL-2.1"], "name": "cairo"}'
                  ', "bugzilla": {"product": "Core", "component": "Graphics"'
                  '}, "schema": 1}')
         tf.flush()
         load_moz_yaml(tf.name, require_license_file=False)
Пример #12
0
def test_json_datatypes():
    # minPercent is at 30.1 to test if non-integer data raises an exception
    json = """{"zoom.minPercent": 30.1, "zoom.maxPercent": 300}"""

    with mozfile.NamedTemporaryFile(suffix=".json") as f:
        f.write(json.encode())
        f.flush()

        with pytest.raises(PreferencesReadError):
            Preferences.read_json(f._path)
Пример #13
0
 def test_pull_file(self):
     data = 'foobar'
     with mozfile.NamedTemporaryFile() as tf:
         with open(tf.name, 'w') as tf2:
             tf2.write(data)
         filename = tf.name.rpartition(os.path.sep)[-1]
         remote_path = self.device.storage_path
         self.device.file_manager.push_file(tf.name, remote_path)
         self.assertEqual(
             self.device.file_manager.pull_file(
                 posixpath.join(remote_path, filename)), data)
Пример #14
0
 def test_utf8str_write(self):
     with mozfile.NamedTemporaryFile() as logfile:
         _fmt = formatters.TbplFormatter()
         _handler = handlers.StreamHandler(logfile, _fmt)
         self.logger.add_handler(_handler)
         self.logger.suite_start([])
         self.logger.info("☺")
         with open(logfile.name) as f:
             data = f.readlines()
             self.assertEquals(data[-1], "☺\n")
         self.logger.suite_end()
Пример #15
0
 def test_utf8str_write(self):
     with mozfile.NamedTemporaryFile() as logfile:
         _fmt = formatters.TbplFormatter()
         _handler = handlers.StreamHandler(logfile, _fmt)
         self.logger.add_handler(_handler)
         self.logger.suite_start([])
         self.logger.info("☺")
         logfile.seek(0)
         data = logfile.readlines()[-1].strip()
         self.assertEquals(data, "☺")
         self.logger.suite_end()
Пример #16
0
def test_json(compare_generated):
    _prefs = {"browser.startup.homepage": "http://planet.mozilla.org/"}
    json = '{"browser.startup.homepage": "http://planet.mozilla.org/"}'

    # just repr it...could use the json module but we don't need it here
    with mozfile.NamedTemporaryFile(suffix=".json") as f:
        f.write(json.encode())
        f.flush()

        commandline = ["--preferences", f.name]
        compare_generated(_prefs, commandline)
    def test_delete(self):
        """ensure ``delete=True/False`` works as expected"""

        # make a deleteable file; ensure it gets cleaned up
        path = None
        with mozfile.NamedTemporaryFile(delete=True) as tf:
            path = tf.name
        self.assertTrue(isinstance(path, six.string_types))
        self.assertFalse(os.path.exists(path))

        # it is also deleted when __del__ is called
        # here we will do so explicitly
        tf = mozfile.NamedTemporaryFile(delete=True)
        path = tf.name
        self.assertTrue(os.path.exists(path))
        del tf
        self.assertFalse(os.path.exists(path))

        # Now the same thing but we won't delete the file
        path = None
        try:
            with mozfile.NamedTemporaryFile(delete=False) as tf:
                path = tf.name
            self.assertTrue(os.path.exists(path))
        finally:
            if path and os.path.exists(path):
                os.remove(path)

        path = None
        try:
            tf = mozfile.NamedTemporaryFile(delete=False)
            path = tf.name
            self.assertTrue(os.path.exists(path))
            del tf
            self.assertTrue(os.path.exists(path))
        finally:
            if path and os.path.exists(path):
                os.remove(path)
Пример #18
0
 def test_basic(self):
     with mozfile.NamedTemporaryFile() as f:
         with zipfile.ZipFile(f.name, 'w') as z:
             z.writestr(
                 'application.ini',
                 """[App]\nSourceStamp=%s\n""" % self.application_changeset)
             z.writestr(
                 'platform.ini',
                 """[Build]\nSourceStamp=%s\n""" % self.platform_changeset)
             z.writestr('AndroidManifest.xml', '')
         v = get_version(f.name)
         self.assertEqual(v.get('application_changeset'),
                          self.application_changeset)
         self.assertEqual(v.get('platform_changeset'),
                          self.platform_changeset)
Пример #19
0
    def fetch_and_unpack(self, revision):
        """Fetch and unpack upstream source"""
        url = self.source_host.upstream_snapshot(revision)
        self.log(
            logging.INFO,
            "vendor",
            {"revision_url": url},
            "Fetching code archive from {revision_url}",
        )

        prefix = self.manifest["origin"]["name"] + "-" + revision
        with mozfile.NamedTemporaryFile() as tmptarfile:
            req = requests.get(url, stream=True)
            for data in req.iter_content(4096):
                tmptarfile.write(data)
            tmptarfile.seek(0)

            tar = tarfile.open(tmptarfile.name)

            if any([
                    name for name in tar.getnames()
                    if name.startswith("/") or ".." in name
            ]):
                raise Exception("Tar archive contains non-local paths,"
                                "e.g. '%s'" % bad_paths[0])

            vendor_dir = self.manifest["vendoring"]["vendor-directory"]
            self.log(logging.INFO, "rm_vendor_dir", {},
                     "rm -rf %s" % vendor_dir)
            mozfile.remove(vendor_dir)

            self.log(
                logging.INFO,
                "vendor",
                {"vendor_dir": vendor_dir},
                "Unpacking upstream files from {vendor_dir}.",
            )
            tar.extractall(vendor_dir)

            has_prefix = all(
                map(lambda name: name.startswith(prefix), tar.getnames()))
            tar.close()

            # GitLab puts everything properly down a directory; move it up.
            if has_prefix:
                tardir = mozpath.join(vendor_dir, prefix)
                mozfile.copy_contents(tardir, vendor_dir)
                mozfile.remove(tardir)
    def test_named_temporary_file(self):
        """ Ensure the fix for re-opening a NamedTemporaryFile works

            Refer to https://bugzilla.mozilla.org/show_bug.cgi?id=818777
            and https://bugzilla.mozilla.org/show_bug.cgi?id=821362
        """

        test_string = b"A simple test"
        with mozfile.NamedTemporaryFile() as temp:
            # Test we can write to file
            temp.write(test_string)
            # Forced flush, so that we can read later
            temp.flush()

            # Test we can open the file again on all platforms
            self.assertEqual(open(temp.name).read(), test_string)
Пример #21
0
def _download_log(url):
    r = requests.get(url, stream=True)
    if r.status_code == 401:
        if hasattr(config, 'auth'):
            auth = (config.auth['user'], config.auth['password'])
            r = requests.get(url, stream=True, auth=auth)
        else:
            logger.error("The url '{}' requires authentication!".format(url))
    r.raise_for_status()

    with mozfile.NamedTemporaryFile(prefix='structured-catalog',
                                    delete=False) as tf:
        for chunk in r.iter_content(1024):
            tf.write(chunk)
        path = tf.name
    return path
Пример #22
0
 def pullFile(self, remoteFile, offset=None, length=None):
     # TODO: add debug flags and allow for printing stdout
     with mozfile.NamedTemporaryFile() as tf:
         self._runPull(remoteFile, tf.name)
         # we need to reopen the file to get the written contents
         with open(tf.name) as tf2:
             # ADB pull does not support offset and length, but we can
             # instead read only the requested portion of the local file
             if offset is not None and length is not None:
                 tf2.seek(offset)
                 return tf2.read(length)
             elif offset is not None:
                 tf2.seek(offset)
                 return tf2.read()
             else:
                 return tf2.read()
Пример #23
0
 def process_test_vectors(self, test_vectors):
     index = 0
     for vector in test_vectors:
         print("Testing index", index)
         expected, yaml = vector
         with mozfile.NamedTemporaryFile() as tf:
             tf.write(yaml)
             tf.flush()
             if expected == "exception":
                 with self.assertRaises(MozYamlVerifyError):
                     load_moz_yaml(tf.name, require_license_file=False)
             else:
                 self.assertDictEqual(
                     load_moz_yaml(tf.name, require_license_file=False), expected
                 )
         index += 1
Пример #24
0
    def test_logger_defaults(self):
        """Tests the default logging format and behavior."""

        default_logger = mozlog.getLogger('default.logger')
        self.assertEqual(default_logger.name, 'default.logger')
        self.assertEqual(len(default_logger.handlers), 1)
        self.assertTrue(isinstance(default_logger.handlers[0],
                                   mozlog.StreamHandler))

        f = mozfile.NamedTemporaryFile()
        list_logger = mozlog.getLogger('file.logger',
                                       handler=mozlog.FileHandler(f.name))
        self.assertEqual(len(list_logger.handlers), 1)
        self.assertTrue(isinstance(list_logger.handlers[0],
                                   mozlog.FileHandler))
        f.close()

        self.assertRaises(ValueError, mozlog.getLogger,
                          'file.logger', handler=ListHandler())
def run_linter(python, paths, config, **lintargs):
    binary = find_executable(python)
    if not binary:
        # If we're in automation, this is fatal. Otherwise, the warning in the
        # setup method was already printed.
        if 'MOZ_AUTOMATION' in os.environ:
            return 1
        return []

    root = lintargs['root']
    pattern = "**/*.py"
    exclude = [mozpath.join(root, e) for e in lintargs.get('exclude', [])]
    files = []
    for path in paths:
        path = mozpath.normsep(path)
        if os.path.isfile(path):
            files.append(path)
            continue

        ignore = [
            e[len(path):].lstrip('/') for e in exclude
            if mozpath.commonprefix((path, e)) == path
        ]
        finder = FileFinder(path, ignore=ignore)
        files.extend([os.path.join(path, p) for p, f in finder.find(pattern)])

    with mozfile.NamedTemporaryFile(mode='w') as fh:
        fh.write('\n'.join(files))
        fh.flush()

        cmd = [binary, os.path.join(here, 'check_compat.py'), fh.name]

        proc = PyCompatProcess(config, cmd)
        proc.run()
        try:
            proc.wait()
        except KeyboardInterrupt:
            proc.kill()

    return results
Пример #26
0
    def get_battery_percentage(self, timeout=None):
        """Returns the battery charge as a percentage.

        :param timeout: optional integer specifying the maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :returns: battery charge as a percentage.
        :raises: * ADBTimeoutError
                 * ADBError
        """
        with mozfile.NamedTemporaryFile() as tf:
            self.pull('/sys/class/power_supply/battery/capacity',
                      tf.name,
                      timeout=timeout)
            try:
                with open(tf.name) as tf2:
                    return tf2.read().splitlines()[0]
            except Exception as e:
                raise ADBError(
                    traceback.format_exception_only(type(e), e)[0].strip())
Пример #27
0
 def setUp(self):
     self.profile_dir = tempfile.mkdtemp()
     self.locations_file = mozfile.NamedTemporaryFile()
     self.locations_file.write(self.locations)
     self.locations_file.flush()
Пример #28
0
 def _prepare_mozlog(self, url):
     with mozfile.NamedTemporaryFile(prefix='ti', delete=False) as f:
         f.write(self._download(url))
         return f.name
Пример #29
0
 def setUp(self):
     self.logfile = mozfile.NamedTemporaryFile()
Пример #30
0
    def test_updatebot(self):
        test_vectors = [
            (
                {
                    "schema": 1,
                    "origin": {
                        "description": "2D Graphics Library",
                        "license": ["MPL-1.1", "LGPL-2.1"],
                        "name": "cairo",
                        "release": "version 1.6.4",
                        "revision": "AA001122334455",
                        "url": "https://www.cairographics.org/",
                    },
                    "bugzilla": {
                        "component": "Graphics",
                        "product": "Core",
                    },
                    "updatebot": {
                        "maintainer-phab": "tjr",
                        "maintainer-bz": "*****@*****.**",
                    },
                },
                b"""
---
schema: 1
origin:
  name: cairo
  description: 2D Graphics Library
  url: https://www.cairographics.org/
  release: version 1.6.4
  license:
    - MPL-1.1
    - LGPL-2.1
  revision: AA001122334455
bugzilla:
  product: Core
  component: Graphics
updatebot:
  maintainer-phab: tjr
  maintainer-bz: [email protected]
            """.strip(),
            ),
            # -------------------------------------------------
            (
                {
                    "schema": 1,
                    "origin": {
                        "description": "2D Graphics Library",
                        "license": ["MPL-1.1", "LGPL-2.1"],
                        "name": "cairo",
                        "release": "version 1.6.4",
                        "revision": "AA001122334455",
                        "url": "https://www.cairographics.org/",
                    },
                    "bugzilla": {
                        "component": "Graphics",
                        "product": "Core",
                    },
                    "vendoring": {
                        "url": "https://example.com",
                        "source-hosting": "gitlab",
                    },
                    "updatebot": {
                        "maintainer-phab": "tjr",
                        "maintainer-bz": "*****@*****.**",
                        "tasks": [{
                            "type": "commit-alert"
                        }],
                    },
                },
                b"""
---
schema: 1
origin:
  name: cairo
  description: 2D Graphics Library
  url: https://www.cairographics.org/
  release: version 1.6.4
  license:
    - MPL-1.1
    - LGPL-2.1
  revision: AA001122334455
vendoring:
  url: https://example.com
  source-hosting: gitlab
bugzilla:
  product: Core
  component: Graphics
updatebot:
  maintainer-phab: tjr
  maintainer-bz: [email protected]
  tasks:
    - type: commit-alert
            """.strip(),
            ),
            # -------------------------------------------------
            (
                {
                    "schema": 1,
                    "origin": {
                        "description": "2D Graphics Library",
                        "license": ["MPL-1.1", "LGPL-2.1"],
                        "name": "cairo",
                        "release": "version 1.6.4",
                        "revision": "AA001122334455",
                        "url": "https://www.cairographics.org/",
                    },
                    "bugzilla": {
                        "component": "Graphics",
                        "product": "Core",
                    },
                    "vendoring": {
                        "url": "https://example.com",
                        "source-hosting": "gitlab",
                    },
                    "updatebot": {
                        "maintainer-phab":
                        "tjr",
                        "maintainer-bz":
                        "*****@*****.**",
                        "tasks": [
                            {
                                "type": "commit-alert"
                            },
                            {
                                "type": "vendoring",
                                "branch": "foo",
                                "enabled": False,
                                "cc": ["*****@*****.**"],
                                "needinfo": ["*****@*****.**"],
                            },
                        ],
                    },
                },
                b"""
---
schema: 1
origin:
  name: cairo
  description: 2D Graphics Library
  url: https://www.cairographics.org/
  release: version 1.6.4
  license:
    - MPL-1.1
    - LGPL-2.1
  revision: AA001122334455
vendoring:
  url: https://example.com
  source-hosting: gitlab
bugzilla:
  product: Core
  component: Graphics
updatebot:
  maintainer-phab: tjr
  maintainer-bz: [email protected]
  tasks:
    - type: commit-alert
    - type: vendoring
      enabled: False
      branch: foo
      cc: ["*****@*****.**"]
      needinfo: ["*****@*****.**"]
            """.strip(),
            ),
            # -------------------------------------------------
            (
                {
                    "schema": 1,
                    "origin": {
                        "description": "2D Graphics Library",
                        "license": ["MPL-1.1", "LGPL-2.1"],
                        "name": "cairo",
                        "release": "version 1.6.4",
                        "revision": "AA001122334455",
                        "url": "https://www.cairographics.org/",
                    },
                    "bugzilla": {
                        "component": "Graphics",
                        "product": "Core",
                    },
                    "vendoring": {
                        "url": "https://example.com",
                        "source-hosting": "gitlab",
                    },
                    "updatebot": {
                        "maintainer-phab":
                        "tjr",
                        "maintainer-bz":
                        "*****@*****.**",
                        "tasks": [
                            {
                                "type": "vendoring",
                                "branch": "foo",
                                "enabled": False,
                                "cc": ["*****@*****.**", "*****@*****.**"],
                                "needinfo": ["*****@*****.**", "*****@*****.**"],
                            },
                            {
                                "type": "commit-alert",
                                "filter": "none",
                                "source-extensions": [".c", ".cpp"],
                            },
                        ],
                    },
                },
                b"""
---
schema: 1
origin:
  name: cairo
  description: 2D Graphics Library
  url: https://www.cairographics.org/
  release: version 1.6.4
  license:
    - MPL-1.1
    - LGPL-2.1
  revision: AA001122334455
vendoring:
  url: https://example.com
  source-hosting: gitlab
bugzilla:
  product: Core
  component: Graphics
updatebot:
  maintainer-phab: tjr
  maintainer-bz: [email protected]
  tasks:
    - type: vendoring
      enabled: False
      branch: foo
      cc:
        - [email protected]
        - [email protected]
      needinfo:
        - [email protected]
        - [email protected]
    - type: commit-alert
      filter: none
      source-extensions:
        - .c
        - .cpp
            """.strip(),
            ),
            # -------------------------------------------------
            (
                "exception",
                b"""
---
schema: 1
origin:
  name: cairo
  description: 2D Graphics Library
  url: https://www.cairographics.org/
  release: version 1.6.4
  license:
    - MPL-1.1
    - LGPL-2.1
  revision: AA001122334455
bugzilla:
  product: Core
  component: Graphics
updatebot:
  maintainer-phab: tjr
  maintainer-bz: [email protected]
  tasks:
    - type: vendoring
      enabled: False
      branch: foo
      cc:
        - [email protected]
        - [email protected]
    - type: commit-alert
      filter: none
      source-extensions:
        - .c
        - .cpp
            """.strip(),
            ),
            # -------------------------------------------------
            (
                "exception",
                b"""
---
schema: 1
origin:
  name: cairo
  description: 2D Graphics Library
  url: https://www.cairographics.org/
  release: version 1.6.4
  license:
    - MPL-1.1
    - LGPL-2.1
bugzilla:
  product: Core
  component: Graphics
vendoring:
  url: https://example.com
  source-hosting: gitlab
updatebot:
  maintainer-phab: tjr
  maintainer-bz: [email protected]
  tasks:
    - type: vendoring
      enabled: False
      branch: foo
      cc:
        - [email protected]
        - [email protected]
    - type: commit-alert
      filter: none
      source-extensions:
        - .c
        - .cpp
            """.strip(),
            ),
            # -------------------------------------------------
            (
                "exception",
                b"""
---
schema: 1
origin:
  name: cairo
  description: 2D Graphics Library
  url: https://www.cairographics.org/
  release: version 1.6.4
  license:
    - MPL-1.1
    - LGPL-2.1
  revision: AA001122334455
vendoring:
  url: https://example.com
  source-hosting: gitlab
bugzilla:
  product: Core
  component: Graphics
updatebot:
  maintainer-phab: tjr
  maintainer-bz: [email protected]
  tasks:
    - type: vendoring
      filter: none
            """.strip(),
            ),
            # -------------------------------------------------
            (
                "exception",
                b"""
---
schema: 1
origin:
  name: cairo
  description: 2D Graphics Library
  url: https://www.cairographics.org/
  release: version 1.6.4
  license:
    - MPL-1.1
    - LGPL-2.1
  revision: AA001122334455
vendoring:
  url: https://example.com
  source-hosting: gitlab
bugzilla:
  product: Core
  component: Graphics
updatebot:
  maintainer-phab: tjr
  maintainer-bz: [email protected]
  tasks:
    - type: foo
            """.strip(),
            ),
            # -------------------------------------------------
            (
                "exception",
                b"""
---
schema: 1
origin:
  name: cairo
  description: 2D Graphics Library
  url: https://www.cairographics.org/
  release: version 1.6.4
  license:
    - MPL-1.1
    - LGPL-2.1
  revision: AA001122334455
vendoring:
  url: https://example.com
  source-hosting: gitlab
bugzilla:
  product: Core
  component: Graphics
updatebot:
  maintainer-phab: tjr
  maintainer-bz: [email protected]
  tasks:
    - type: vendoring
      source-extensions:
        - .c
        - .cpp
            """.strip(),
            ),
            # -------------------------------------------------
            (
                "exception",
                b"""
---
schema: 1
origin:
  name: cairo
  description: 2D Graphics Library
  url: https://www.cairographics.org/
  release: version 1.6.4
  license:
    - MPL-1.1
    - LGPL-2.1
  revision: AA001122334455
vendoring:
  url: https://example.com
  source-hosting: gitlab
bugzilla:
  product: Core
  component: Graphics
updatebot:
  maintainer-phab: tjr
  maintainer-bz: [email protected]
  tasks:
    - type: commit-alert
      filter: hogwash
            """.strip(),
            ),
            (
                "exception",
                b"""
---
schema: 1
origin:
  name: cairo
  description: 2D Graphics Library
  url: https://www.cairographics.org/
  release: version 1.6.4
  license:
    - MPL-1.1
    - LGPL-2.1
  revision: AA001122334455
bugzilla:
  product: Core
  component: Graphics
vendoring:
  url: https://example.com
  source-hosting: gitlab
updatebot:
  maintainer-phab: tjr
  maintainer-bz: [email protected]
  tasks:
    - type: vendoring
      enabled: False
      branch: foo
      cc:
        - [email protected]
        - [email protected]
    - type: commit-alert
    - type: commit-alert
      filter: none
      source-extensions:
        - .c
        - .cpp""".strip(),
            ),
            (
                "exception",
                b"""
---
schema: 1
origin:
  name: cairo
  description: 2D Graphics Library
  url: https://www.cairographics.org/
  release: version 1.6.4
  license:
    - MPL-1.1
    - LGPL-2.1
  revision: AA001122334455
bugzilla:
  product: Core
  component: Graphics
vendoring:
  url: https://example.com
  source-hosting: gitlab
updatebot:
  maintainer-phab: tjr
  maintainer-bz: [email protected]
  tasks:
    - type: vendoring
      enabled: False
      branch: foo
      cc:
        - [email protected]
        - [email protected]
    - type: vendoring
    - type: commit-alert
      filter: none
      source-extensions:
        - .c
        - .cpp""".strip(),
            ),
        ]

        indx = 0
        for vector in test_vectors:
            print("Testing index", indx)
            expected, yaml = vector
            with mozfile.NamedTemporaryFile() as tf:
                tf.write(yaml)
                tf.flush()
                if expected == "exception":
                    with self.assertRaises(MozYamlVerifyError):
                        load_moz_yaml(tf.name, require_license_file=False)
                else:
                    self.assertDictEqual(
                        load_moz_yaml(tf.name, require_license_file=False),
                        expected)
            indx += 1