コード例 #1
0
def test_execute_with_called_process_error(
    capsys, docker_container, return_code, tmp_path
):
    tmp_file = os.path.join(tmp_path, "CalledProcessError.sh")
    # "This is stdout" to stdout, "This is stderr" to stderr
    script = f"""#!/bin/bash
echo "This is stdout"
>&2 echo "This is stderr"
{"exit 1" if return_code else ""}
"""
    write_file(tmp_file, script)
    if return_code:
        with pytest.raises(CalledProcessError):
            for line in Client.execute(
                docker_container[1], f"/bin/sh {tmp_file}", stream=True
            ):
                print(line, "")
    else:
        for line in Client.execute(
            docker_container[1], f"/bin/sh {tmp_file}", stream=True
        ):
            print(line, "")
    captured = capsys.readouterr()
    assert "stdout" in captured.out
    if return_code:
        assert "stderr" in captured.err
    else:
        assert "stderr" not in captured.err
コード例 #2
0
ファイル: test_utils.py プロジェクト: al3x609/singularity-cli
    def test_write_read_files(self):
        '''test_write_read_files will test the functions write_file and read_file
        '''
        print("Testing utils.write_file...")
        from spython.utils import write_file
        import json
        tmpfile = tempfile.mkstemp()[1]
        os.remove(tmpfile)
        write_file(tmpfile, "hello!")
        self.assertTrue(os.path.exists(tmpfile))

        print("Testing utils.read_file...")
        from spython.utils import read_file
        content = read_file(tmpfile)[0]
        self.assertEqual("hello!", content)

        from spython.utils import write_json
        print("Testing utils.write_json...")
        print("...Case 1: Providing bad json")
        bad_json = {"Wakkawakkawakka'}": [{True}, "2", 3]}
        tmpfile = tempfile.mkstemp()[1]
        os.remove(tmpfile)
        with self.assertRaises(TypeError) as cm:
            write_json(bad_json, tmpfile)

        print("...Case 2: Providing good json")
        good_json = {"Wakkawakkawakka": [True, "2", 3]}
        tmpfile = tempfile.mkstemp()[1]
        os.remove(tmpfile)
        write_json(good_json, tmpfile)
        with open(tmpfile, 'r') as filey:
            content = json.loads(filey.read())
        self.assertTrue(isinstance(content, dict))
        self.assertTrue("Wakkawakkawakka" in content)
コード例 #3
0
def test_write_read_files(tmp_path):
    """test_write_read_files will test the functions write_file and read_file"""
    print("Testing utils.write_file...")
    from spython.utils import write_file

    tmpfile = str(tmp_path / "written_file.txt")
    assert not os.path.exists(tmpfile)
    write_file(tmpfile, "hello!")
    assert os.path.exists(tmpfile)

    print("Testing utils.read_file...")
    from spython.utils import read_file

    content = read_file(tmpfile)[0]
    assert content == "hello!"
コード例 #4
0
    def write(self, output_file=None, force=False):
        '''convert a recipe to a specified format, and write to file, meaning
           we use the loaded recipe to write to an output file.
           If the output file is not specified, a temporary file is used.

           Parameters
           ==========
           output_file: the file to save to, not required (estimates default)
           force: if True, if file exists, over-write existing file

        '''
        if output_file is None:
            output_file = self._get_conversion_outfile()

        # Cut out early if file exists and we aren't overwriting
        if os.path.exists(output_file) and not force:
            bot.exit('%s exists, and force is False.' % output_file)

        # Do the conversion if function is provided by subclass
        if hasattr(self, 'convert'):
            converted = self.convert()
            bot.info('Saving to %s' % output_file)
            write_file(output_file, converted)
コード例 #5
0
ファイル: recipe.py プロジェクト: al3x609/singularity-cli
    def save(self,
             output_file=None,
             convert_to=None,
             runscript="/bin/bash",
             force=False):
        '''save will convert a recipe to a specified format (defaults to the
           opposite of the recipe type originally loaded, (e.g., docker-->
           singularity and singularity-->docker) and write to an output file,
           if specified. If not specified, a temporary file is used.

           Parameters
           ==========
           output_file: the file to save to, not required (estimates default)
           convert_to: can be manually forced (docker or singularity)
           runscript: default runscript (entrypoint) to use
           force: if True, override discovery from Dockerfile

        '''

        converted = self.convert(convert_to, runscript, force)
        if output_file is None:
            output_file = self._get_conversion_outfile(convert_to=None)
        bot.info('Saving to %s' % output_file)
        write_file(output_file, converted)
コード例 #6
0
ファイル: recipe.py プロジェクト: cceyda/singularity-cli
def main(args, options, parser):
    """This function serves as a wrapper around the DockerParser,
    SingularityParser, DockerWriter, and SingularityParser converters.
    We can either save to file if args.outfile is defined, or print
    to the console if not.
    """
    # We need something to work with
    if not args.files:
        parser.print_help()
        sys.exit(1)

    # Get the user specified input and output files
    outfile = None
    if len(args.files) > 1:
        outfile = args.files[1]

    # First try to get writer and parser, if not defined will return None
    writer = get_writer(args.writer)
    parser = get_parser(args.parser)

    # If the user wants to auto-detect the type
    if args.parser == "auto":
        if "dockerfile" in args.files[0].lower():
            parser = get_parser("docker")
        elif "singularity" in args.files[0].lower():
            parser = get_parser("singularity")

    # If the parser still isn't defined, no go.
    if parser is None:
        bot.exit(
            "Please provide a Dockerfile or Singularity recipe, or define the --parser type."
        )

    # If the writer needs auto-detect
    if args.writer == "auto":
        if parser.name == "docker":
            writer = get_writer("singularity")
        else:
            writer = get_writer("docker")

    # If the writer still isn't defined, no go
    if writer is None:
        bot.exit("Please define the --writer type.")

    # Initialize the chosen parser
    recipeParser = parser(args.files[0])

    # By default, discover entrypoint / cmd from Dockerfile
    entrypoint = "/bin/bash"
    force = False

    if args.entrypoint is not None:
        entrypoint = args.entrypoint

        # This is only done if the user intended to print json here
        recipeParser.entrypoint = args.entrypoint
        recipeParser.cmd = None
        force = True

    if args.json:

        if outfile is not None:
            if not os.path.exists(outfile):
                if force:
                    write_json(outfile, recipeParser.recipe.json())
                else:
                    bot.exit("%s exists, set --force to overwrite." % outfile)
        else:
            print(json.dumps(recipeParser.recipe.json(), indent=4))

    else:

        # Do the conversion
        recipeWriter = writer(recipeParser.recipe)
        result = recipeWriter.convert(runscript=entrypoint, force=force)

        # If the user specifies an output file, save to it
        if outfile is not None:
            write_file(outfile, result)

        # Otherwise, convert and print to screen
        else:
            print(result)