Пример #1
0
    def _write_test(self):
        """This method is responsible for invoking ``generate_script`` that
        formulates content of testscript which is implemented in each subclass.
        Next we write content to file and apply 755 permission on script so
        it has executable permission.
        """

        # Implementation to write file generate.sh
        lines = []

        lines += self.generate_script()

        lines = "\n".join(lines)

        self.logger.info(
            f"Opening Test File for Writing: {self.metadata['testpath']}")

        write_file(self.metadata["testpath"], lines)

        self.metadata["test_content"] = lines

        self._set_execute_perm()
        # copy testpath to run_dir
        shutil.copy2(
            self.metadata["testpath"],
            os.path.join(self.run_dir,
                         os.path.basename(self.metadata["testpath"])),
        )
Пример #2
0
    def write_testresults(self, out, err):
        """This method writes test results into output and error file.

        :param out: content of output stream
        :type out: list, required
        :param err: content of error stream
        :type err: list, required
        """

        # Keep an output file
        run_output_file = os.path.join(
            self.builder.metadata.get("testroot"),
            "run",
            self.builder.metadata.get("name"),
        )
        outfile = run_output_file + ".out"
        errfile = run_output_file + ".err"

        # write output of test to .out file
        out = "".join(out)
        err = "".join(err)

        self.logger.debug(f"Writing test output to file: {outfile}")
        write_file(outfile, out)

        # write error from test to .err file
        self.logger.debug(f"Writing test error to file: {errfile}")
        write_file(errfile, err)

        self.builder.metadata["outfile"] = outfile
        self.builder.metadata["errfile"] = errfile
Пример #3
0
def test_write_file_exceptions(tmp_path):
    msg = "hi my name is Bob"
    file = os.path.join(tmp_path, "name.txt")
    print(f"Writing content: {msg} to file {file}")
    write_file(file, msg)

    # testing invalid type for file stream
    with pytest.raises(BuildTestError):
        print("Passing 'None' as input filestream to write_file")
        write_file(None, msg)

    assert is_dir(tmp_path)
    # testing if directory is passed as filepath, this is also not allowed and expected to raise error
    with pytest.raises(BuildTestError):
        print(
            f"Passing directory: {tmp_path} as input filestream to method write_file"
        )
        write_file(tmp_path, msg)

    filename = "".join(random.choice(string.ascii_letters) for i in range(10))
    path = os.path.join("/", filename)
    print(f"Can't write to path: {path} due to permissions")

    with pytest.raises(BuildTestError):
        write_file(path, msg)

    # input content must be a string, will return None upon
    with pytest.raises(BuildTestError):
        write_file(os.path.join(tmp_path, "null.txt"), ["hi"])
Пример #4
0
def test_read_file(tmp_path):
    # testing invalid type for read_file, expects of type string. Expected return is 'None'
    print("Reading file with invalid type, passing 'None'")
    with pytest.raises(BuildTestError):
        read_file(None)

    file = os.path.join(tmp_path, "hello.txt")
    print(f"Checking {file} is not a file.")
    # ensure file is not valid
    assert not is_file(file)

    print(f"Now reading an invalid file: {file}, expecting read_file to return 'None'")
    # checking invalid file should report an error
    with pytest.raises(BuildTestError):
        read_file(file)

    with tempfile.TemporaryDirectory() as tmpdir:
        fname = os.path.join(tmpdir, "permission-denied.txt")
        msg = "hello world"
        write_file(fname, msg)
        # make permission 000 so its unreadable
        os.chmod(fname, 000)
        with pytest.raises(BuildTestError):
            read_file(fname)

    print("Reading '/etc/shadow' will raise an exception BuildTestError")
    # reading /etc/shadow will raise a Permission error so we catch this exception BuildTestError
    with pytest.raises(BuildTestError):
        read_file("/etc/shadow")
Пример #5
0
def generate_tests(prefix, cmd_dict):
    create_dir(os.path.join(docgen, prefix))

    for k, v in cmd_dict.items():
        out = run(v)
        out = f"$ {v} \n" + out

        fname = os.path.join(docgen, k)
        write_file(fname, out)
        print(f"Writing File: {fname}")
Пример #6
0
def test_write_file(tmp_path):
    msg = """This is a 
    multi-line
    string"""

    file = os.path.join(tmp_path, "test_write.txt")

    print(f"Writing content to file: {file}")
    write_file(file, msg)

    print(f"Reading content from file: {file}")
    content = read_file(file)

    # ensure return type of read_file is a list
    assert isinstance(content, str)
    # split origin input by newline to create a list

    # perform a string equality between input content and result of read_file
    assert msg == content
Пример #7
0
    def write_python_script(self):
        """This method is used for writing python script when ``shell: python``
        is set. The content from ``run`` section is added into a python
        script. The file is written to run directory and we simply invoke
        python script by running ``python script.py``
        """

        python_content = self.recipe.get("run")
        script_path = "%s.py" % os.path.join(self.stage_dir, self.name)
        write_file(script_path, python_content)
        self.logger.debug(
            f"[{self.name}]: Writing python script to: {script_path}")
        shutil.copy2(script_path,
                     os.path.join(self.run_dir, os.path.basename(script_path)))
        self.logger.debug(
            f"[{self.name}]: Copying file: {script_path} to: {os.path.join(self.run_dir, os.path.basename(script_path))}"
        )

        lines = [f"python {script_path}"]
        return lines
Пример #8
0
    def setup(self):
        """This method creates directory ``var/executors/<executor-name>``
        for every executor defined in buildtest configuration and write scripts
        before_script.sh and after_script.sh if the fields ``before_script``
        and ``after_script`` are specified in executor section. This method
        is called after executors are initialized in the class **__init__**
        method.
        """

        for executor_name in self.executors.keys():
            create_dir(os.path.join(executor_root, executor_name))
            executor_settings = self.executors[executor_name]._settings

            # if before_script field defined in executor section write content to var/executors/<executor>/before_script.sh
            file = os.path.join(executor_root, executor_name,
                                "before_script.sh")
            content = executor_settings.get("before_script") or ""
            write_file(file, content)

            # after_script field defined in executor section write content to var/executors/<executor>/after_script.sh
            file = os.path.join(executor_root, executor_name,
                                "after_script.sh")
            content = executor_settings.get("after_script") or ""
            write_file(file, content)