Completed
Pull Request — master (#192)
by Marek
01:39
created

smoke_test.checkPlayerProgress()   C

Complexity

Conditions 10

Size

Total Lines 30
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 29
nop 0
dl 0
loc 30
rs 5.9999
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
                buildings = int(player_stats[3])
94
                buildings_counts += [buildings]
95
                if buildings < 10:
96
                    log.error(player_stats)
97
                    problem = True
98
    if not something:
99
        log.error('No record in opened json')
100
        return False
101
    if problem:
102
        log.error('There is an issue with player progress')
103
        log.debug('Building counts: {0}'.format(buildings_counts))
104
        return False
105
    else:
106
        log.info('Player progress ok')
107
        return True
108
109
# parse command line arguments
110
parser = argparse.ArgumentParser()
111
parser.add_argument("--slow", dest = "slow", default = False,
112
    action = "store_true", help = "Switches off multiprocessing of AI")
113
parser.add_argument("--travis", dest = "travis", default = False,
114
    action = "store_true", help = "Runs limited test, suitable for Travis CI")
115
parser.add_argument("--turns", dest = "turns", default = 60,
116
    type = int, metavar = "N", help = "Process N turns on server")
117
parser.add_argument("--turn-skip", dest = "turnSkip", default = 4,
118
    type = int, metavar = "N", help = "Process N turns on server")
119
args = parser.parse_args()
120
121
122
c.initPaths()
123
124
# test itself
125
# check basic sanity
126
if not c.startServer():
127
    sys.exit(1)
128
atexit.register(c.killServer)
129
c.createGalaxy("Test")
130
c.startServerTime()
131
c.doTurns(args.turnSkip, args.turnSkip, slow=args.slow)
132
if not checkServerStatus():
133
    sys.exit(1)
134
c.stopServer()
135
checkLogs(hard=True)
136
137
# check upgrade sanity
138
if not c.startServer(upgrade=True):
139
    sys.exit(1)
140
c.doTurns(args.turnSkip, args.turnSkip, slow=args.slow)
141
if not checkServerStatus():
142
    sys.exit(1)
143
c.stopServer()
144
checkLogs(hard=True)
145
146
# this block checks player progression
147
if not c.startServer():
148
    sys.exit(1)
149
c.doTurns(args.turns, args.turnSkip)
150
if not args.travis:
151
    c.makeScreenshots(os.path.join(c.TEMP_DIR, 'screens'))
152
if not checkServerStatus():
153
    sys.exit(1)
154
c.stopServer()
155
if not checkPlayerProgress():
156
    sys.exit(1)
157
checkLogs(hard=True)
158
159