Exemplo n.º 1
0
 def test_source_from_url_certificate(self):
     """ When the manifest is sourced from a url, the source should be the url. """
     with patch("sprinter.lib.cleaned_request") as cleaned_request:
         mock = Mock(spec=Response)
         mock.text = old_manifest
         cleaned_request.return_value = mock
         TEST_URI = "https://testme.com/test.cfg"
         load_manifest(TEST_URI, verify_certificate=False)
         cleaned_request.assert_called_with("get", TEST_URI, verify=False)
Exemplo n.º 2
0
 def test_source_from_url_certificate(self):
     """ When the manifest is sourced from a url, the source should be the url. """
     with patch('sprinter.lib.cleaned_request') as cleaned_request:
         mock = Mock(spec=Response)
         mock.text = old_manifest
         cleaned_request.return_value = mock
         TEST_URI = "https://testme.com/test.cfg"
         load_manifest(TEST_URI, verify_certificate=False)
         cleaned_request.assert_called_with('get', TEST_URI, verify=False)
Exemplo n.º 3
0
 def test_source_from_url(self):
     """ When the manifest is sourced from a url, the source should be the url. """
     TEST_URI = "http://testme.com/test.cfg"
     httpretty.register_uri(httpretty.GET, TEST_URI,
                            body=http_manifest)
     m = load_manifest(TEST_URI)
     assert m.source() == TEST_URI
Exemplo n.º 4
0
 def test_get_context_dict_escaped_character(self):
     """ Test getting a config dict with escaping filter will properly escape a character"""
     manifest = load_manifest(StringIO(manifest_escaped_parameters))
     context_dict = manifest.get_context_dict()
     assert "section:escapeme|escaped" in context_dict
     tools.eq_(context_dict["section:escapeme|escaped"],
               "\!\@\#\$\%\^\&\*\(\)\\\"\\'\~\`\/\?\<\>")
Exemplo n.º 5
0
 def test_write(self):
     """ Test the write command """
     temp_file = tempfile.mkstemp()[1]
     try:
         with open(temp_file, 'w+') as fh:
             self.new_manifest.write(fh)
         tools.eq_(self.new_manifest, load_manifest(temp_file))
     finally:
         os.unlink(temp_file)
Exemplo n.º 6
0
 def test_write(self):
     """ Test the write command """
     temp_file = tempfile.mkstemp()[1]
     try:
         with open(temp_file, "w+") as fh:
             self.new_manifest.write(fh)
         tools.eq_(self.new_manifest, load_manifest(temp_file))
     finally:
         os.unlink(temp_file)
Exemplo n.º 7
0
    def test_load_manifest_no_inheritance(self):
        """ load_manifest should not load ancestors with inherit=False """
        temp_directory = tempfile.mkdtemp()
        parent_file_path = os.path.join(temp_directory, "parent.cfg")
        child_file_path = os.path.join(temp_directory, "child.cfg")
        with open(parent_file_path, "w") as fh:
            fh.write(parent_manifest)

        with open(child_file_path, "w") as fh:
            fh.write(child_manifest.format(parent_file_path))

        manifest = load_manifest(child_file_path, do_inherit=False)

        assert not manifest.has_option("config", "namespace")
Exemplo n.º 8
0
    def test_load_manifest_no_inheritance(self):
        """ load_manifest should not load ancestors with inherit=False """
        temp_directory = tempfile.mkdtemp()
        parent_file_path = os.path.join(temp_directory, 'parent.cfg')
        child_file_path = os.path.join(temp_directory, 'child.cfg')
        with open(parent_file_path, 'w') as fh:
            fh.write(parent_manifest)

        with open(child_file_path, 'w') as fh:
            fh.write(child_manifest.format(parent_file_path))

        manifest = load_manifest(child_file_path, do_inherit=False)

        assert not manifest.has_option('config', 'namespace')
Exemplo n.º 9
0
    def test_load_manifest_inheritance(self):
        """
        With a parent, a child manifest should load it's parent manifest,
        with child values overriding parent values
        """
        temp_directory = tempfile.mkdtemp()
        parent_file_path = os.path.join(temp_directory, 'parent.cfg')
        child_file_path = os.path.join(temp_directory, 'child.cfg')
        with open(parent_file_path, 'w') as fh:
            fh.write(parent_manifest)

        with open(child_file_path, 'w') as fh:
            fh.write(child_manifest.format(parent_file_path))

        manifest = load_manifest(child_file_path)

        assert manifest.get('config', 'namespace') == 'inheritance', "Value not present in child should be pulled from parent!"

        assert manifest.get('parent_section', 'parent') == 'not me', "child value should override parent value!"
Exemplo n.º 10
0
    def test_load_manifest_inheritance(self):
        """
        With a parent, a child manifest should load it's parent manifest,
        with child values overriding parent values
        """
        temp_directory = tempfile.mkdtemp()
        parent_file_path = os.path.join(temp_directory, "parent.cfg")
        child_file_path = os.path.join(temp_directory, "child.cfg")
        with open(parent_file_path, "w") as fh:
            fh.write(parent_manifest)

        with open(child_file_path, "w") as fh:
            fh.write(child_manifest.format(parent_file_path))

        manifest = load_manifest(child_file_path)

        assert (
            manifest.get("config", "namespace") == "inheritance"
        ), "Value not present in child should be pulled from parent!"

        assert manifest.get("parent_section", "parent") == "not me", "child value should override parent value!"
Exemplo n.º 11
0
 def setup(self):
     self.old_manifest = load_manifest(StringIO(old_manifest))
     self.new_manifest = load_manifest(StringIO(new_manifest))
Exemplo n.º 12
0
 def setup(self):
     self.old_manifest = load_manifest(StringIO(old_manifest))
     self.new_manifest = load_manifest(StringIO(new_manifest))
Exemplo n.º 13
0
 def test_incorrect_dependency(self):
     """ Test whether an incorrect dependency tree returns an error. """
     load_manifest(StringIO(manifest_incorrect_dependency))
Exemplo n.º 14
0
 def test_invalid_manifest_filepath(self):
     """ The manifest should throw an exception on an invalid manifest path """
     load_manifest("./ehiiehaiehnatheita")
Exemplo n.º 15
0
 def test_equality(self):
     """ Manifest object should be equal to itself """
     tools.eq_(self.old_manifest, load_manifest(StringIO(old_manifest)))
Exemplo n.º 16
0
 def test_get_context_dict_escaped_character(self):
     """ Test getting a config dict with escaping filter will properly escape a character"""
     manifest = load_manifest(StringIO(manifest_escaped_parameters))
     context_dict = manifest.get_context_dict()
     assert "section:escapeme|escaped" in context_dict
     tools.eq_(context_dict["section:escapeme|escaped"], "\!\@\#\$\%\^\&\*\(\)\\\"\\'\~\`\/\?\<\>")
Exemplo n.º 17
0
 def test_equality(self):
     """ Manifest object should be equal to itself """
     tools.eq_(self.old_manifest, load_manifest(StringIO(old_manifest)))
Exemplo n.º 18
0
 def test_incorrect_dependency(self):
     """ Test whether an incorrect dependency tree returns an error. """
     load_manifest(StringIO(manifest_incorrect_dependency))
Exemplo n.º 19
0
 def test_invalid_manifest_filepath(self):
     """ The manifest should throw an exception on an invalid manifest path """
     load_manifest("./ehiiehaiehnatheita")
Exemplo n.º 20
0
def parse_args(argv, Environment=Environment):
    options = docopt(
        __doc__,
        argv=argv,
        version=pkg_resources.get_distribution('sprinter').version)
    logging_level = logging.DEBUG if options['--verbose'] else logging.INFO
    # start processing commands
    env = Environment(logging_level=logging_level,
                      ignore_errors=options['--ignore-errors'])
    try:
        if options['install']:
            target = options['<environment_source>']

            def handle_install_shutdown(signal, frame):
                if env.phase == PHASE.INSTALL:
                    print("Removing install...")
                    env.directory.remove()
                    env.clear_all()
                signal_handler(signal, frame)

            signal.signal(signal.SIGINT, handle_install_shutdown)
            if options['--username'] or options['--auth']:
                options = get_credentials(options, parse_domain(target))
                target = manifest.load_manifest(
                    target,
                    username=options['<username>'],
                    password=options['<password>'],
                    verify_certificate=(
                        not options['--allow-bad-certificate']))
            else:
                target = manifest.load_manifest(
                    target,
                    verify_certificate=(
                        not options['--allow-bad-certificate']))
            env.target = target
            if options['--namespace']:
                env.namespace = options['--namespace']
            if options['--local']:
                env.do_inject_environment_config = False
                env.custom_directory_root = os.path.abspath(
                    os.path.expanduser(options['--local']))
            env.install()

        elif options['update']:
            target = options['<environment_name>']
            env.directory = Directory(os.path.join(env.root, target),
                                      shell_util_path=env.shell_util_path)
            env.source = manifest.load_manifest(env.directory.manifest_path,
                                                do_inherit=False)
            use_auth = options['--username'] or options['--auth']
            if use_auth:
                options = get_credentials(options, target)
            env.target = manifest.load_manifest(
                env.source.source(),
                username=options['<username>'] if use_auth else None,
                password=options['<password>'] if use_auth else None,
                verify_certificate=(not options['--allow-bad-certificate']))
            env.update(reconfigure=options['--reconfigure'])

        elif options["remove"]:
            env.directory = Directory(os.path.join(
                env.root, options['<environment_name>']),
                                      shell_util_path=env.shell_util_path)
            env.source = manifest.load_manifest(
                env.directory.manifest_path,
                namespace=options['<environment_name>'],
                do_inherit=False)
            env.remove()

        elif options['deactivate']:
            env.directory = Directory(os.path.join(
                env.root, options['<environment_name>']),
                                      shell_util_path=env.shell_util_path)
            env.source = manifest.load_manifest(
                env.directory.manifest_path,
                namespace=options['<environment_name>'],
                do_inherit=False)
            env.deactivate()

        elif options['activate']:
            env.directory = Directory(os.path.join(
                env.root, options['<environment_name>']),
                                      shell_util_path=env.shell_util_path)
            env.source = manifest.load_manifest(
                env.directory.manifest_path,
                namespace=options['<environment_name>'],
                do_inherit=False)
            env.activate()

        elif options['list']:
            for _env in os.listdir(env.root):
                if _env != ".global":
                    print(_env)

        elif options['validate']:
            if options['--username'] or options['--auth']:
                options = get_credentials(options, parse_domain(target))
                target = manifest.load_manifest(
                    options['<environment_source>'],
                    username=options['<username>'],
                    password=options['<password>'],
                    verify_certificate=(
                        not options['--allow-bad-certificate']))
            env.target = options['<environment_source>']
            env.validate()
            if not env.error_occured:
                print("No errors! Manifest is valid!")
            else:
                "Manifest is invalid! Please see errors above."
        elif options['globals']:
            if options['--reconfigure']:
                configure_config(env.global_config, reconfigure=True)
                write_config(env.global_config, env.global_config_path)
            else:
                print_global_config(env.global_config)
    except BadCredentialsException:
        e = sys.exc_info()[1]
        raise e
    except ManifestException:
        e = sys.exc_info()[1]
        env.log_error(str(e))
        env.logger.info("Error occured when attempting to load manifest!")
        env.logger.info("Writing debug output to /tmp/sprinter.log")
        env.write_debug_log("/tmp/sprinter.log")
    except Exception:
        e = sys.exc_info()[1]
        env.log_error(str(e))
        env.logger.info("""
=====================================================================
the sprinter action failed! Writing debug output to /tmp/sprinter.log
        """)
        env.write_debug_log("/tmp/sprinter.log")
        if env.message_failure():
            env.logger.info(env.message_failure())
        env.logger.info("""
=====================================================================
        """.strip())
        raise
Exemplo n.º 21
0
def parse_args(argv, Environment=Environment):
    options = docopt(__doc__, argv=argv, version= pkg_resources.get_distribution('sprinter').version)
    logging_level = logging.DEBUG if options['--verbose'] else logging.INFO
    # start processing commands
    env = Environment(logging_level=logging_level, ignore_errors=options['--ignore-errors'])
    try:
        if options['install']:
            target = options['<environment_source>']

            def handle_install_shutdown(signal, frame):
                if env.phase == PHASE.INSTALL:
                    print("Removing install...")
                    env.directory.remove()
                    env.clear_all()
                signal_handler(signal, frame)
            signal.signal(signal.SIGINT, handle_install_shutdown)
            if options['--username'] or options['--auth']:
                options = get_credentials(options, parse_domain(target))
                target = manifest.load_manifest(
                    target,
                    username=options['<username>'],
                    password=options['<password>'],
                    verify_certificate=(not options['--allow-bad-certificate'])
                )
            else:
                target = manifest.load_manifest(
                    target,
                    verify_certificate=(not options['--allow-bad-certificate'])
                )
            env.target = target
            if options['--namespace']:
                env.namespace = options['--namespace']
            if options['--local']:
                env.do_inject_environment_config = False
                env.custom_directory_root = os.path.abspath(os.path.expanduser(options['--local']))
            env.install()

        elif options['update']:
            target = options['<environment_name>']
            env.directory = Directory(os.path.join(env.root, target),
                                      shell_util_path=env.shell_util_path)
            env.source = manifest.load_manifest(
                env.directory.manifest_path, do_inherit=False
            )
            use_auth = options['--username'] or options['--auth']
            if use_auth:
                options = get_credentials(options, target)
            env.target = manifest.load_manifest(
                env.source.source(),
                username=options['<username>'] if use_auth else None,
                password=options['<password>'] if use_auth else None,
                verify_certificate=(not options['--allow-bad-certificate'])
            )
            env.update(reconfigure=options['--reconfigure'])

        elif options["remove"]:
            env.directory = Directory(os.path.join(env.root, options['<environment_name>']),
                                      shell_util_path=env.shell_util_path)
            env.source = manifest.load_manifest(
                env.directory.manifest_path,
                namespace=options['<environment_name>'],
                do_inherit=False
            )
            env.remove()

        elif options['deactivate']:
            env.directory = Directory(os.path.join(env.root, options['<environment_name>']),
                                      shell_util_path=env.shell_util_path)
            env.source = manifest.load_manifest(
                env.directory.manifest_path,
                namespace=options['<environment_name>'],
                do_inherit=False
            )
            env.deactivate()

        elif options['activate']:
            env.directory = Directory(os.path.join(env.root, options['<environment_name>']),
                                      shell_util_path=env.shell_util_path)
            env.source = manifest.load_manifest(
                env.directory.manifest_path,
                namespace=options['<environment_name>'],
                do_inherit=False
            )
            env.activate()

        elif options['list']:
            for _env in os.listdir(env.root):
                if _env != ".global":
                    print(_env)

        elif options['validate']:
            if options['--username'] or options['--auth']:
                options = get_credentials(options, parse_domain(target))
                target = manifest.load_manifest(
                    options['<environment_source>'],
                    username=options['<username>'],
                    password=options['<password>'],
                    verify_certificate=(not options['--allow-bad-certificate'])
                )
            env.target = options['<environment_source>']
            env.validate()
            if not env.error_occured:
                print("No errors! Manifest is valid!")
            else:
                "Manifest is invalid! Please see errors above."
        elif options['globals']:
            if options['--reconfigure']:
                configure_config(env.global_config, reconfigure=True)
                write_config(env.global_config, env.global_config_path)
            else:
                print_global_config(env.global_config)
    except BadCredentialsException:
        e = sys.exc_info()[1]
        raise e
    except ManifestException:
        e = sys.exc_info()[1]
        env.log_error(str(e))
        env.logger.info("Error occured when attempting to load manifest!")
        env.logger.info("Writing debug output to /tmp/sprinter.log")
        env.write_debug_log("/tmp/sprinter.log")
    except Exception:
        e = sys.exc_info()[1]
        env.log_error(str(e))
        env.logger.info("""
=====================================================================
the sprinter action failed! Writing debug output to /tmp/sprinter.log
        """)
        env.write_debug_log("/tmp/sprinter.log")
        if env.message_failure():
            env.logger.info(env.message_failure())
        env.logger.info("""
=====================================================================
        """.strip())
        raise