Completed
Push — master ( a0c806...0e659f )
by Marek
16s queued 13s
created

smoke_test.checkPlayerProgress()   D

Complexity

Conditions 12

Size

Total Lines 36
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 34
nop 0
dl 0
loc 36
rs 4.8
c 0
b 0
f 0

How to fix   Complexity   

Complexity

Complex classes like smoke_test.checkPlayerProgress() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
#!/usr/bin/env python2
2
3
#
4
#  Copyright 2001 - 2016 Ludek Smid [http://www.ospace.net/]
5
#
6
#  This file is part of Outer Space.
7
#
8
#  Outer Space is free software; you can redistribute it and/or modify
9
#  it under the terms of the GNU General Public License as published by
10
#  the Free Software Foundation; either version 2 of the License, or
11
#  (at your option) any later version.
12
#
13
#  Outer Space is distributed in the hope that it will be useful,
14
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
15
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
#  GNU General Public License for more details.
17
#
18
#  You should have received a copy of the GNU General Public License
19
#  along with Outer Space; if not, write to the Free Software
20
#  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21
#
22
23
import argparse
24
import atexit
25
import httplib
26
import json
27
import logging as log
28
import os
29
import re
30
import sys
31
32
import common as c
33
34
log.basicConfig(level=log.INFO, format='%(levelname)-7s: %(message)s')
35
36
def assertGrep(pattern, text, flags=0):
37
    if re.search(pattern, text, flags|re.MULTILINE):
38
        return True
39
    return False
40
41
def checkServerStatus():
42
    conn = httplib.HTTPConnection('localhost', '9080', timeout = 10)
43
    conn.request('GET', '/status')
44
    response = conn.getresponse()
45
    content = response.read()
46
    if response.status != 200:
47
        log.error("Server status not available")
48
        return False
49
    if not assertGrep('Outer Space Status Reports', content):
50
        log.error("Server status is malformed")
51
        log.debug(content)
52
        return False
53
    log.info('Server status is present.')
54
    return True
55
56
def checkLogs(hard=False):
57
    everything_ok = True
58
    for logfile in [c.SERVER_OUT, c.AI_OUT, c.UTILS_OUT]:
59
        with open(logfile.name) as readable_logfile:
60
            if not assertGrep('login',
61
                          readable_logfile.read(),
62
                          re.IGNORECASE):
63
                log.error('No valid content present in {0}'.format(logfile.name))
64
                everything_ok = False
65
                continue
66
        with open(logfile.name) as readable_logfile:
67
            if assertGrep('error|traceback',
68
                          readable_logfile.read(),
69
                          re.IGNORECASE):
70
                log.error('Errors present in {0}'.format(logfile.name))
71
                everything_ok = False
72
                continue
73
    if everything_ok:
74
        log.info('No error messages found in log files')
75
    elif hard:
76
        sys.exit(1)
77
78
def checkPlayerProgress():
79
    problem = False
80
    something = False
81
    with open(os.path.join(c.TEMP_DIR, 'website',
82
                           'Alpha', 'json.txt'), 'r') as stats_file:
83
        stats = json.loads(stats_file.read())
84
        buildings_counts = []
85
        for galaxy in stats:
86
            if galaxy == 'turn':
87
                something = True
88
                continue
89
            for player in stats[galaxy]['players']:
90
                player_stats = stats[galaxy]['players'][player]
91
                player_name = player_stats[0]
92
                if 'E.D.E.N.' in player_name or 'order' == player: continue
93
                elif 'Renegade' in player_name:
94
                    limit = 9
95
                elif 'Mutant' in player_name:
96
                    limit = 9
97
                else:
98
                    limit = 10
99
                buildings = int(player_stats[3])
100
                buildings_counts += [buildings]
101
                if buildings < limit:
102
                    log.error(player_stats)
103
                    problem = True
104
    if not something:
105
        log.error('No record in opened json')
106
        return False
107
    if problem:
108
        log.error('There is an issue with player progress')
109
        log.debug('Building counts: {0}'.format(buildings_counts))
110
        return False
111
    else:
112
        log.info('Player progress ok')
113
        return True
114
115
# parse command line arguments
116
parser = argparse.ArgumentParser()
117
parser.add_argument("--slow", dest = "slow", default = False,
118
    action = "store_true", help = "Switches off multiprocessing of AI")
119
parser.add_argument("--travis", dest = "travis", default = False,
120
    action = "store_true", help = "Runs limited test, suitable for Travis CI")
121
parser.add_argument("--turns", dest = "turns", default = 60,
122
    type = int, metavar = "N", help = "Process N turns on server")
123
parser.add_argument("--turn-skip", dest = "turnSkip", default = 4,
124
    type = int, metavar = "N", help = "Process N turns on server")
125
parser.add_argument("--continue", dest = "continueDir", default = None,
126
    metavar = "DIRECTORY", help = "Specify directory with previous run of smoke test. Useful for testing version migration.")
127
args = parser.parse_args()
128
129
130
c.initPaths(args.continueDir)
131
132
# test itself
133
if args.continueDir is None:
134
    # check basic sanity
135
    if not c.startServer():
136
        sys.exit(1)
137
    atexit.register(c.killServer)
138
    c.createGalaxy("Test")
139
    c.deleteGalaxy(10000) # 10000 is surely the Test galaxy
140
    c.createGalaxy("Test")
141
    c.startServerTime()
142
    c.doTurns(args.turnSkip, args.turnSkip, slow=args.slow)
143
    if not checkServerStatus():
144
        sys.exit(1)
145
    c.stopServer()
146
    checkLogs(hard=True)
147
else:
148
    # we are testing migration path - directory with outcome of previous
149
    # version is provided
150
    log.info("Running migration scenario from '{0}'".format(args.continueDir))
151
152
# check upgrade sanity
153
if not c.startServer(upgrade=True):
154
    sys.exit(1)
155
c.doTurns(args.turnSkip, args.turnSkip, slow=args.slow)
156
if not checkServerStatus():
157
    sys.exit(1)
158
c.stopServer()
159
checkLogs(hard=True)
160
161
# this block checks player progression
162
if not c.startServer():
163
    sys.exit(1)
164
c.doTurns(args.turns, args.turnSkip)
165
if not args.travis:
166
    c.makeScreenshots(os.path.join(c.TEMP_DIR, 'screens'))
167
if not checkServerStatus():
168
    sys.exit(1)
169
c.stopServer()
170
checkLogs()
171
if not checkPlayerProgress():
172
    sys.exit(1)
173
174