1#!/usr/bin/python
2
3import os
4import subprocess
5import logging
6
7from . import output as OutputParser
8
9NAPIPROJEKT_BASEURL_DEFAULT = 'http://napiprojekt.pl'
10
11class Runner(object):
12    testWrapper = "test_wrapper.sh"
13    testWrapperPath = os.path.join(
14            os.path.dirname(os.path.realpath(__file__)),
15            "..", "bin",
16            testWrapper)
17
18    def __init__(self,
19            napiprojektUrl = NAPIPROJEKT_BASEURL_DEFAULT,
20            bash = None):
21        self.logger = logging.getLogger()
22        self.bash = bash if bash else '/bin/bash'
23        self.napiprojektUrl = napiprojektUrl
24
25        self._prepareEnv()
26
27    def _prepareEnv(self):
28        if self.napiprojektUrl != NAPIPROJEKT_BASEURL_DEFAULT:
29            os.environ['NAPIPROJEKT_BASEURL'] = self.napiprojektUrl
30
31    def _execute(self, executable, testTraceFilePath, *args):
32
33        cmd = [ self.testWrapperPath, testTraceFilePath,
34                self.bash, executable, ] + map(str, args)
35        self.logger.info(cmd)
36        process = subprocess.Popen(
37                cmd,
38                shell = False,
39                bufsize = 1024,
40                stderr = subprocess.PIPE,
41                stdout = subprocess.PIPE)
42
43        pStdout, pStderr = process.communicate()
44        self.logger.debug('stdout: %s' % (pStdout))
45        self.logger.debug('stderr: %s' % (pStderr))
46        self.logger.info('return code: %d' % (process.returncode))
47        return pStdout, pStderr, process.returncode
48
49    def executeNapi(self, testTraceFilePath, *args):
50        output = self._execute('napi.sh', testTraceFilePath, *args)
51        return OutputParser.Parser(*output)
52
53    def executeSubotage(self, testTraceFilePath, *args):
54        output = self._execute('subotage.sh', testTraceFilePath, *args)
55        return OutputParser.Parser(*output)
56
57    def scan(self, testTraceFilePath, *args):
58        return self.executeNapi(testTraceFilePath,
59                'scan', '-v', '3', *args)
60
61    def download(self, testTraceFilePath, *args):
62        return self.executeNapi(testTraceFilePath,
63                'download', '-v', '3', *args)
64
65    def subtitles(self, testTraceFilePath, *args):
66        return self.executeNapi(testTraceFilePath,
67                'subtitles', '-v', '3', *args)
68
69    def search(self, testTraceFilePath, *args):
70        return self.executeNapi(testTraceFilePath,
71                'search', '-v', '3', *args)
72