<commit_before>#  Copyright 2008-2013 Nokia Siemens Networks Oyj
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
from __future__ import with_statement

import os
import subprocess
import tempfile

from robot.utils import ConnectionCache
from robot.version import get_version


class Process(object):
    """Robot Framework test library for running processes.
    """

    ROBOT_LIBRARY_SCOPE='GLOBAL'
    ROBOT_LIBRARY_VERSION = get_version()

    def __init__(self):
        self._started_processes = ConnectionCache()
        self._logs = dict()
        self._tempdir = tempfile.mkdtemp(suffix="processlib")

    def run_process(self, command, *args, **conf):
        active_process_index = self._started_processes.current_index
        try:
            p = self.start_new_process(command, *args, **conf)
            return self.wait_for_process(p)
        finally:
            self._started_processes.switch(active_process_index)

    def start_new_process(self, command, *args, **conf):
        config = NewProcessConfig(self._tempdir, **conf)
        p = subprocess.Popen(self._cmd(args, command, config.shell),
                             stdout=config.stdout_stream,
                             stderr=config.stderr_stream,
                             stdin=subprocess.PIPE,
                             shell=config.shell,
                             cwd=config.cwd)
        self._logs[p] = ExecutionResult(config.stdout_stream.name,
                                        config.stderr_stream.name)
        return self._started_processes.register(p, alias=config.alias)

    def _cmd(self, args, command, use_shell):
        cmd = [command] + [str(i) for i in args]
        if use_shell and args:
            cmd = subprocess.list2cmdline(cmd)
        elif use_shell:
            cmd = command
        return cmd

    def process_is_alive(self, handle=None):
        return self._process(handle).poll() is None

    def process_should_be_alive(self, handle=None):
        if not self.process_is_alive(handle):
            raise AssertionError('Process is not alive')

    def process_should_be_dead(self, handle=None):
        if self.process_is_alive(handle):
            raise AssertionError('Process is alive')

    def wait_for_process(self, handle=None):
        process = self._process(handle)
        result = self._logs[process]
        result.exit_code = process.wait()
        return result

    def terminate_process(self, handle=None, kill=False):
        process = self._process(handle)
        if kill:
            process.kill()
        else:
            process.terminate()

    def kill_all_processes(self):
        for handle in range(len(self._started_processes._connections)):
            if self.process_is_alive(handle):
                self.terminate_process(handle, kill=True)

    def get_process_id(self, handle=None):
        return self._process(handle).pid

    def input_to_process(self, msg, handle=None):
        self._process(handle).communicate(msg+'\n')

    def switch_active_process(self, handle):
        self._started_processes.switch(handle)

    def _process(self, handle):
        if handle:
            process,_ = self._started_processes.get_connection(handle)
        else:
            process = self._started_processes.current
        return process


class ExecutionResult(object):

    _stdout = _stderr = None

    def __init__(self, stdout_name, stderr_name, exit_code=None):
        self._stdout_name = stdout_name
        self._stderr_name = stderr_name
        self.exit_code = exit_code

    @property
    def stdout(self):
        if self._stdout is None:
            with open(self._stdout_name,'r') as f:
                self._stdout = f.read()
        return self._stdout

    @property
    def stderr(self):
        if self._stderr is None:
            with open(self._stderr_name,'r') as f:
                self._stderr = f.read()<commit_msg>first draft version of Process libdoc<commit_after>#  Copyright 2008-2013 Nokia Siemens Networks Oyj
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
from __future__ import with_statement

import os
import subprocess
import tempfile

from robot.utils import ConnectionCache
from robot.version import get_version


class Process(object):
    """Robot Framework test library for running processes.

    This library utilizes Python's
    [http://docs.python.org/2.7/library/subprocess.html#subprocess.Popen|Subprocess API and its Popen class].

    The library has following main usages:

    - Starting a processes, and managing their handles, stdouts and stderrs
    - Stopping processes started by this library
    - Switching between processes
    - Checking process status.

    == Table of contents ==

    - `Arguments`
    - `Example`
    - `Active process`
    - `ExecutionResult`

    = Arguments =
    `Run Process` and `Start New Process` keywords can be given several named
    arguments, which are listed below. Default values in the parenthesis.

     - `cwd` specifies if program's directory is used as cwd  (`False`)
     - `shell` specifies if shell is used for program execution (`False`)
     - `stdout` is a file handle for standard output
     - `stderr` is a file handle for standard error
     - `stdin` is a file handle for standard input
     - `alias` is a name for the process (`None`).

    = Example =
    The following example demonstrates library's main usages as stated above.

    | *** Settings *** |  |  |  |  |
    | Library | Process |  |  |  |
    |  |  |  |  |  |
    | *** Test Cases *** |  |  |  |  |
    | Example |  |  |  |  |
    | ${handle1}= | `Start New Process` | /path/command.sh    | shell=True  | cwd=/path |
    | ${handle2}= | `Start New Process` | ${CURDIR}${/}mytool   | shell=True |   |
    | ${result1}=  | `Wait For Process` | ${handle1} |    |  |
    |  | `Terminate Process` | ${handle1} |    |   |
    | ${is_alive}= | `Process Is Alive` | ${handle2} |    |   |
    |  | Should Be True | ${is_alive} |    |   |
    |  | [Teardown] | `Kill All Processes` |    |   |

    = Active process =
    Many of the library keywords have `handle` as optional argument. This means
    that if argument `handle` is NOT given, then current active process is used.

    = ExecutionResult =
    This object contains information about the process execution.

    Included information is:

    - `stdout` standard output file handle
    - `stderr` standard error file handle
    - `exit_code` from the process, `None` during execution.
    """

    ROBOT_LIBRARY_SCOPE='GLOBAL'
    ROBOT_LIBRARY_VERSION = get_version()

    def __init__(self):
        self._started_processes = ConnectionCache()
        self._logs = dict()
        self._tempdir = tempfile.mkdtemp(suffix="processlib")

    def run_process(self, command, *args, **conf):
        """This keyword runs a process and waits for it to finish.
        """
        active_process_index = self._started_processes.current_index
        try:
            p = self.start_new_process(command, *args, **conf)
            return self.wait_for_process(p)
        finally:
            self._started_processes.switch(active_process_index)

    def start_new_process(self, command, *args, **conf):
        """This keyword starts a new process with given `args` and `conf`.

        Returns process index on success.
        """
        config = NewProcessConfig(self._tempdir, **conf)
        p = subprocess.Popen(self._cmd(args, command, config.shell),
                             stdout=config.stdout_stream,
                             stderr=config.stderr_stream,
                             stdin=subprocess.PIPE,
                             shell=config.shell,
                             cwd=config.cwd)
        self._logs[p] = ExecutionResult(config.stdout_stream.name,
                                        config.stderr_stream.name)
        return self._started_processes.register(p, alias=config.alias)

    def _cmd(self, args, command, use_shell):
        cmd = [command] + [str(i) for i in args]
        if use_shell and args:
            cmd = subprocess.list2cmdline(cmd)
        elif use_shell:
            cmd = command
        return cmd

    def process_is_alive(self, handle=None):
        """Returns a running status of process with `handle`. Argument `handle`
        is optional, if `None` then the current process is used.

        Return value is either `True` or `False`
        """
        return self._process(handle).poll() is None

    def process_should_be_alive(self, handle=None):
        """Assertion keyword, which expects that process with `handle` is alive.
        Argument `handle` is optional, if `None` then the current process is used.

        Check is done using `Process Is Alive` keyword.

        Raises an error if process is dead.
        """
        if not self.process_is_alive(handle):
            raise AssertionError('Process is not alive')

    def process_should_be_dead(self, handle=None):
        """Assertion keyword, which expects that process with `handle` is dead.
        Argument `handle` is optional, if left then the current process is used.

        Check is done using `Process Is Alive` keyword.

        Raises an error if process is alive.
        """
        if self.process_is_alive(handle):
            raise AssertionError('Process is alive')

    def wait_for_process(self, handle=None):
        """This waits for process with `handle` to complete its execution.
        Argument `handle` is optional, if left then the current process is used.

        Returns an `ExecutionResult` object.
        """
        process = self._process(handle)
        result = self._logs[process]
        result.exit_code = process.wait()
        return result

    def terminate_process(self, handle=None, kill=False):
        """This keyword terminates process using either `Subprocess` `kill()`
        or `terminate()`, which can be selected using `kill` argument.

        Returns a running status of process with `handle`. Argument `handle`
        is optional, if `None` then the current process is used.
        """
        process = self._process(handle)
        if kill:
            process.kill()
        else:
            process.terminate()

    def kill_all_processes(self):
        """This keyword terminates all processes started by the library.
        """
        for handle in range(len(self._started_processes._connections)):
            if self.process_is_alive(handle):
                self.terminate_process(handle, kill=True)

    def get_process_id(self, handle=None):
        """Returns a process ID of process with `handle`.

        Argument `handle` is optional, if `None` then the current process is used.

        Return value is a integer value.
        """
        return self._process(handle).pid

    def input_to_process(self, msg, handle=None):
        """This keyword can be used to communicate with the process with `handle`.

        Argument `handle` is optional, if `None` then the current process is used.
        """
        self._process(handle).communicate(msg+'\n')

    def switch_active_process(self, handle):
        """This keyword switches active process into process with `handle`.
        """
        self._started_processes.switch(handle)

    def _process(self, handle):
        if handle:
            process,_ = self._started_processes.get_connection(handle)
        else:
            process = self._started_processes.current
        return process


class ExecutionResult(object):

    _stdout = _stderr = None

    def __init__(self, stdout_name, stderr_name, exit_code=None):
        self._stdout_name = stdout_name
        self._stderr_name = stderr_name
        self.exit_code = exit_code

    @property
    def stdout(self):
        if self._stdout is None:
            with open(self._stdout_name,'r') as f:
                self._stdout = f.read()
        return self._stdout

    @property
    def stderr(self):
        if self._stderr is None:
            with open(self._stderr_name,'r') as f:
                self._stderr = f.read()
{'fraction_non_alphanumeric': 0.09077017114914425, 'fraction_numerical': 0.002597799511002445, 'mean_word_length': 2.4590380549682873, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7564716', 'n_tokens_mistral': 3676, 'n_tokens_neox': 3538, 'n_words': 1121}