~andrewjbeach/juju-ci-tools/make-local-patcher

« back to all changes in this revision

Viewing changes to gotesttarfile.py

  • Committer: Aaron Bentley
  • Date: 2014-02-24 17:18:29 UTC
  • mto: This revision was merged to the branch mainline in revision 252.
  • Revision ID: aaron.bentley@canonical.com-20140224171829-sz644yhoygu7m9dm
Use tags to identify and shut down instances.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/python
2
 
from __future__ import print_function
3
 
 
4
 
from argparse import ArgumentParser
5
 
import shutil
6
 
import os
7
 
import subprocess
8
 
import sys
9
 
import tarfile
10
 
import tempfile
11
 
import traceback
12
 
 
13
 
from utility import (
14
 
    print_now,
15
 
    temp_dir,
16
 
)
17
 
 
18
 
 
19
 
class WorkingDirectory:
20
 
    """Context manager for changing the current working directory"""
21
 
    def __init__(self, working_path):
22
 
        self.working_path = working_path
23
 
 
24
 
    def __enter__(self):
25
 
        self.savedPath = os.getcwd()
26
 
        os.chdir(self.working_path)
27
 
 
28
 
    def __exit__(self, etype, value, traceback):
29
 
        os.chdir(self.savedPath)
30
 
 
31
 
 
32
 
def run(command, **kwargs):
33
 
    """Run a command returning exit status."""
34
 
    proc = subprocess.Popen(command, **kwargs)
35
 
    proc.communicate()
36
 
    return proc.returncode
37
 
 
38
 
 
39
 
def untar_gopath(tarfile_path, gopath, delete=False, verbose=False):
40
 
    """Untar the tarfile to the gopath."""
41
 
    with temp_dir() as tmp_dir:
42
 
        with tarfile.open(name=tarfile_path, mode='r:gz') as tar:
43
 
            tar.extractall(path=tmp_dir)
44
 
        if verbose:
45
 
            print_now('Extracted the Juju source.')
46
 
        dir_name = os.path.basename(tarfile_path).replace('.tar.gz', '')
47
 
        dir_path = os.path.join(tmp_dir, dir_name)
48
 
        shutil.move(dir_path, gopath)
49
 
        if verbose:
50
 
            print_now('Moved %s to %s' % (dir_name, gopath))
51
 
    if delete:
52
 
        os.unlink(tarfile_path)
53
 
        if verbose:
54
 
            print_now('Deleted %s' % tarfile_path)
55
 
 
56
 
 
57
 
def murder_mongo():
58
 
    """Kill off any lingering mongod processess."""
59
 
    if sys.platform == 'win32':
60
 
        return run(["taskkill.exe", "/F", "/FI", "imagename eq mongod.exe"])
61
 
    return run(["sudo", "killall", "-SIGABRT", "mongod"])
62
 
 
63
 
 
64
 
def go_test_package(package, go_cmd, gopath, verbose=False):
65
 
    """Run the package unit tests."""
66
 
    # Set GOPATH and GOARCH to ensure the go command tests extracted
67
 
    # tarfile using the arch the win-agent is compiled with. The
68
 
    # default go env might be 386 used to create a win client.
69
 
    env = dict(os.environ)
70
 
    env['GOPATH'] = gopath
71
 
    env['GOARCH'] = 'amd64'
72
 
    build_cmd = [go_cmd, 'test', '-i', './...']
73
 
    test_cmd = [go_cmd, 'test', '-timeout=1200s', './...']
74
 
    if sys.platform == 'win32':
75
 
        # Ensure OpenSSH is never in the path for win tests.
76
 
        sane_path = [p for p in env['PATH'].split(';') if 'OpenSSH' not in p]
77
 
        env['PATH'] = ';'.join(sane_path)
78
 
        if verbose:
79
 
            print_now('Setting environ Path to:')
80
 
            print_now(env['PATH'])
81
 
        # GZ 2015-04-21: Short-term hack to work around case-insensitive issues
82
 
        env['Path'] = env.pop('PATH')
83
 
        tempdir = tempfile.mkdtemp(prefix="tmp-juju-test", dir=gopath)
84
 
        env['TMP'] = env['TEMP'] = tempdir
85
 
        if verbose:
86
 
            print_now('Setting environ TMP and TEMP to:')
87
 
            print_now(env['TEMP'])
88
 
        build_cmd = ['powershell.exe', '-Command'] + build_cmd
89
 
        test_cmd = ['powershell.exe', '-Command'] + test_cmd
90
 
    package_dir = os.path.join(gopath, 'src', package.replace('/', os.sep))
91
 
    with WorkingDirectory(package_dir):
92
 
        if verbose:
93
 
            print_now('Building test dependencies')
94
 
        returncode = run(build_cmd, env=env)
95
 
        if returncode != 0:
96
 
            return returncode
97
 
        if verbose:
98
 
            print_now('Running unit tests in %s' % package)
99
 
        returncode = run(test_cmd, env=env)
100
 
        if verbose:
101
 
            if returncode == 0:
102
 
                print_now('SUCCESS')
103
 
            else:
104
 
                print_now('FAIL')
105
 
            print_now("Killing any lingering mongo processes...")
106
 
        murder_mongo()
107
 
    return returncode
108
 
 
109
 
# suppress nosetests
110
 
go_test_package.__test__ = False
111
 
 
112
 
 
113
 
def parse_args(args=None):
114
 
    """Return parsed args for this program."""
115
 
    parser = ArgumentParser("Run go test against the content of a tarfile.")
116
 
    parser.add_argument(
117
 
        '-v', '--verbose', action='store_true', default=False,
118
 
        help='Increase verbosity.')
119
 
    parser.add_argument(
120
 
        '-g', '--go', default='go', help='The go comand.')
121
 
    parser.add_argument(
122
 
        '-p', '--package', default='github.com/juju/juju',
123
 
        help='The package to test.')
124
 
    parser.add_argument(
125
 
        '-r', '--remove-tarfile', action='store_true', default=False,
126
 
        help='Remove the tarfile after extraction.')
127
 
    parser.add_argument(
128
 
        'tarfile', help='The path to the gopath tarfile.')
129
 
    return parser.parse_args(args)
130
 
 
131
 
 
132
 
def main(argv=None):
133
 
    """Run go test against the content of a tarfile."""
134
 
    returncode = 0
135
 
    args = parse_args(argv)
136
 
    tarfile_path = args.tarfile
137
 
    tarfile_name = os.path.basename(tarfile_path)
138
 
    version = tarfile_name.split('_')[-1].replace('.tar.gz', '')
139
 
    try:
140
 
        if args.verbose:
141
 
            print_now('Testing juju %s from %s' % (version, tarfile_name))
142
 
        with temp_dir() as workspace:
143
 
            gopath = os.path.join(workspace, 'gogo')
144
 
            untar_gopath(
145
 
                tarfile_path, gopath, delete=args.remove_tarfile,
146
 
                verbose=args.verbose)
147
 
            returncode = go_test_package(
148
 
                args.package, args.go, gopath, verbose=args.verbose)
149
 
    except Exception as e:
150
 
        print_now(str(e))
151
 
        print_now(traceback.print_exc())
152
 
        return 3
153
 
    return returncode
154
 
 
155
 
 
156
 
if __name__ == '__main__':
157
 
    sys.exit(main())