Skip to content

Commit a573c08

Browse files
committed
ref(*): clean up Go and Python code for make test-style
1 parent df47b06 commit a573c08

10 files changed

Lines changed: 87 additions & 69 deletions

File tree

client/deis.py

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,7 @@ def readable_datetime(datetime_str):
318318
else:
319319
return "{}{}ago".format(hour_str, min_str)
320320
# if it happened yesterday, say "yesterday at 3:23 pm"
321-
yesterday = now + relativedelta.relativedelta(days= -1)
321+
yesterday = now + relativedelta.relativedelta(days=-1)
322322
if delta.days <= 2 and dt.day == yesterday.day:
323323
return dt.strftime("Yesterday at %X")
324324
# otherwise return locale-specific date/time format
@@ -1033,12 +1033,13 @@ def clusters_update(self, args):
10331033
if k == 'auth' and args.get('--auth') is not None:
10341034
auth_path = os.path.expanduser(args['--auth'])
10351035
if not os.path.exists(auth_path):
1036-
print('Path to authentication credentials does not exist: {}'.format(auth_path))
1036+
print(
1037+
"Path to authentication credentials does not exist: {}".format(auth_path))
10371038
sys.exit(1)
10381039
with open(auth_path) as f:
10391040
data = f.read()
10401041
body.update({'auth': base64.b64encode(data)})
1041-
else :
1042+
else:
10421043
v = args.get(arg)
10431044
if v:
10441045
body.update({k: v})
@@ -1176,7 +1177,8 @@ def config_unset(self, args):
11761177
try:
11771178
progress = TextProgress()
11781179
progress.start()
1179-
response = self._dispatch('post', "/api/apps/{}/config".format(app), json.dumps(body))
1180+
response = self._dispatch(
1181+
'post', "/api/apps/{}/config".format(app), json.dumps(body))
11801182
finally:
11811183
progress.cancel()
11821184
progress.join()
@@ -1230,10 +1232,8 @@ def config_pull(self, args):
12301232
if response.status_code == requests.codes.ok: # @UndefinedVariable
12311233
config = json.loads(response.json()['values'])
12321234
for k, v in config.items():
1233-
if interactive:
1234-
confirm = raw_input('overwrite {} with {}? (y/N) '.format(k, v))
1235-
if confirm == 'y':
1236-
env_dict[k] = v
1235+
if interactive and raw_input("overwrite {} with {}? (y/N) ".format(k, v)) == 'y':
1236+
env_dict[k] = v
12371237
if k in env_dict and not overwrite:
12381238
continue
12391239
env_dict[k] = v
@@ -1284,7 +1284,8 @@ def domains_add(self, args):
12841284
try:
12851285
progress = TextProgress()
12861286
progress.start()
1287-
response = self._dispatch('post', "/api/apps/{app}/domains".format(app=app), json.dumps(body))
1287+
response = self._dispatch(
1288+
'post', "/api/apps/{app}/domains".format(app=app), json.dumps(body))
12881289
finally:
12891290
progress.cancel()
12901291
progress.join()
@@ -1316,7 +1317,8 @@ def domains_remove(self, args):
13161317
try:
13171318
progress = TextProgress()
13181319
progress.start()
1319-
response = self._dispatch('delete', "/api/apps/{app}/domains/{domain}".format(**locals()))
1320+
response = self._dispatch(
1321+
'delete', "/api/apps/{app}/domains/{domain}".format(**locals()))
13201322
finally:
13211323
progress.cancel()
13221324
progress.join()

controller/api/models.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ def deploy(self, release, initial=False):
186186
elif release.build.dockerfile and not release.build.procfile:
187187
self.structure = {'cmd': 1}
188188
# if a procfile exists without a web entry, assume docker workflow
189-
elif release.build.procfile and not 'web' in release.build.procfile:
189+
elif release.build.procfile and 'web' not in release.build.procfile:
190190
self.structure = {'cmd': 1}
191191
# default to heroku workflow
192192
else:
@@ -206,7 +206,7 @@ def scale(self, **kwargs): # noqa
206206
for container_type in requested_containers.keys():
207207
if container_type == 'cmd':
208208
continue # allow docker cmd types in case we don't have the image source
209-
if not container_type in available_process_types:
209+
if container_type not in available_process_types:
210210
raise EnvironmentError(
211211
'Container type {} does not exist in application'.format(container_type))
212212
msg = 'Containers scaled ' + ' '.join(

controller/scheduler/coreos.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@
1111
if not os.path.exists(ROOT_DIR):
1212
os.mkdir(ROOT_DIR)
1313

14-
MATCH = re.compile('(?P<app>[a-z0-9-]+)_?(?P<version>v[0-9]+)?\.?(?P<c_type>[a-z]+)?.(?P<c_num>[0-9]+)')
14+
MATCH = re.compile(
15+
'(?P<app>[a-z0-9-]+)_?(?P<version>v[0-9]+)?\.?(?P<c_type>[a-z]+)?.(?P<c_num>[0-9]+)')
16+
1517

1618
class FleetClient(object):
1719

@@ -76,15 +78,15 @@ def _create_container(self, name, image, command, template, env, **kwargs):
7678
# prepare memory limit for the container type
7779
mem = kwargs.get('memory', {}).get(l['c_type'], None)
7880
if mem:
79-
l.update({'memory': '-m {}'.format(mem.lower())})
81+
l.update({'memory': '-m {}'.format(mem.lower())})
8082
else:
81-
l.update({'memory': ''})
83+
l.update({'memory': ''})
8284
# prepare memory limit for the container type
8385
cpu = kwargs.get('cpu', {}).get(l['c_type'], None)
8486
if cpu:
85-
l.update({'cpu': '-c {}'.format(cpu)})
87+
l.update({'cpu': '-c {}'.format(cpu)})
8688
else:
87-
l.update({'cpu': ''})
89+
l.update({'cpu': ''})
8890
env.update({'FLEETW_UNIT': name + '.service'})
8991
# construct unit from template
9092
unit = template.format(**l)
@@ -148,7 +150,7 @@ def _wait_for_announcer(self, name, env):
148150
# we bump to 20 minutes here to match the timeout on the router and in the app unit files
149151
for _ in range(1200):
150152
status = subprocess.check_output(
151-
"fleetctl.sh list-units --no-legend --fields unit,sub | grep {name}-announce.service | awk '{{print $2}}'".format(**locals()),
153+
"fleetctl.sh list-units --no-legend --fields unit,sub | grep {name}-announce.service | awk '{{print $2}}'".format(**locals()), # noqa
152154
shell=True, env=env).strip('\n')
153155
if status == 'running':
154156
break
@@ -246,7 +248,7 @@ def attach(self, name):
246248
ExecStart=/bin/sh -c "IMAGE=$(etcdctl get /deis/registry/host 2>&1):$(etcdctl get /deis/registry/port 2>&1)/{image}; port=$(docker inspect -f '{{{{range $k, $v := .ContainerConfig.ExposedPorts }}}}{{{{$k}}}}{{{{end}}}}' $IMAGE | cut -d/ -f1) ; docker run --name {name} {memory} {cpu} -P -e PORT=$port $IMAGE {command}"
247249
ExecStop=/usr/bin/docker rm -f {name}
248250
TimeoutStartSec=20m
249-
"""
251+
""" # noqa
250252

251253
# TODO revisit the "not getting a port" issue after we upgrade to Docker 1.1.0
252254
ANNOUNCE_TEMPLATE = """
@@ -263,7 +265,7 @@ def attach(self, name):
263265
264266
[X-Fleet]
265267
X-ConditionMachineOf={name}.service
266-
"""
268+
""" # noqa
267269

268270
LOG_TEMPLATE = """
269271
[Unit]
@@ -277,4 +279,4 @@ def attach(self, name):
277279
278280
[X-Fleet]
279281
X-ConditionMachineOf={name}.service
280-
"""
282+
""" # noqa

logger/syslog/filehandler.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ func (h *FileHandler) checkErr(err error) bool {
8989
return true
9090
}
9191

92-
// See BaseHandler.Handle
92+
// Handle queues and dispatches a message. See BaseHandler.Handle
9393
func (h *FileHandler) Handle(m *Message) *Message {
9494
return h.bh.Handle(m)
9595
}

logger/syslog/message.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@ import (
66
"time"
77
)
88

9-
// Struct Message defines an RFC 3164 syslog message.
9+
// Message defines an RFC 3164 syslog message.
1010
type Message struct {
11-
Time time.Time // time the message was logged
12-
Source net.Addr // source address of the log message
11+
Time time.Time // time the message was logged
12+
Source net.Addr // source address of the log message
1313
Facility // facility tag (see type Facility)
1414
Severity // severity tag (see type Severity)
1515
Timestamp time.Time // optional

logger/syslog/message_test.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,45 +10,45 @@ func TestMessageNetSrc(t *testing.T) {
1010
tcpAddress, err := net.ResolveTCPAddr("tcp", "localhost:1234")
1111

1212
if err != nil {
13-
t.Errorf("could not resolve TCP address")
13+
t.Error("could not resolve TCP address")
1414
}
1515

1616
m := &Message{time.Now(), tcpAddress, 0, 0, time.Now(), "", "", "", "", ""}
1717
if m.NetSrc() != "127.0.0.1" {
18-
t.Errorf("expected 127.0.0.1, got ", m.NetSrc())
18+
t.Errorf("expected 127.0.0.1, got %s", m.NetSrc())
1919
}
2020

2121
udpAddress, err := net.ResolveUDPAddr("udp", "localhost:1234")
2222

2323
if err != nil {
24-
t.Errorf("could not resolve UDP address")
24+
t.Error("could not resolve UDP address")
2525
}
2626

2727
m.Source = udpAddress
2828
if m.NetSrc() != "127.0.0.1" {
29-
t.Errorf("expected 127.0.0.1, got ", m.NetSrc())
29+
t.Errorf("expected 127.0.0.1, got %s", m.NetSrc())
3030
}
3131

3232
unixAddress, err := net.ResolveUnixAddr("unix", "/tmp/str")
3333

3434
if err != nil {
35-
t.Errorf("could not resolve unix address")
35+
t.Error("could not resolve unix address")
3636
}
3737

3838
m.Source = unixAddress
3939
if m.NetSrc() != "/tmp/str" {
40-
t.Errorf("expected /tmp/str, got ", m.NetSrc())
40+
t.Errorf("expected /tmp/str, got %s", m.NetSrc())
4141
}
4242

4343
unknownAddress, err := net.ResolveIPAddr("ip4", "localhost")
4444

4545
if err != nil {
46-
t.Errorf("could not resolve unknown address")
46+
t.Error("could not resolve unknown address")
4747
}
4848

4949
m.Source = unknownAddress
5050
if m.NetSrc() != "127.0.0.1" {
51-
t.Errorf("expected 127.0.0.1, got ", m.NetSrc())
51+
t.Errorf("expected 127.0.0.1, got %s", m.NetSrc())
5252
}
5353
}
5454

logger/syslog/priority.go

Lines changed: 42 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,34 @@
11
package syslog
22

3+
// Facility represents a message source as defined by RFC 3164.
34
type Facility byte
45

56
// The following is a list of Facilities as defined by RFC 3164.
67
const (
7-
Kern Facility = iota // kernel messages
8-
User // user-level messages
9-
Mail // mail system
10-
Daemon // system daemons
11-
Auth // security/authorization messages
12-
Syslog // messages internal to syslogd
13-
Lpr // line printer subsystem
14-
News // newtork news subsystem
15-
Uucp // UUCP subsystem
16-
Cron // cron messages
17-
Authpriv // security/authorization messages
18-
System0 // historically FTP daemon
19-
System1 // historically NTP subsystem
20-
System2 // historically log audit
21-
System3 // historically log alert
22-
System4 // historically clock daemon, some operating systems use this for cron
23-
Local0 // local use 0
24-
Local1 // local use 1
25-
Local2 // local use 2
26-
Local3 // local use 3
27-
Local4 // local use 4
28-
Local5 // local use 5
29-
Local6 // local use 6
30-
Local7 // local use 7
8+
Kern Facility = iota // kernel messages
9+
User // user-level messages
10+
Mail // mail system
11+
Daemon // system daemons
12+
Auth // security/authorization messages
13+
Syslog // messages internal to syslogd
14+
Lpr // line printer subsystem
15+
News // newtork news subsystem
16+
Uucp // UUCP subsystem
17+
Cron // cron messages
18+
Authpriv // security/authorization messages
19+
System0 // historically FTP daemon
20+
System1 // historically NTP subsystem
21+
System2 // historically log audit
22+
System3 // historically log alert
23+
System4 // historically clock daemon, some operating systems use this for cron
24+
Local0 // local use 0
25+
Local1 // local use 1
26+
Local2 // local use 2
27+
Local3 // local use 3
28+
Local4 // local use 4
29+
Local5 // local use 5
30+
Local6 // local use 6
31+
Local7 // local use 7
3132
)
3233

3334
var facToStr = [...]string{
@@ -66,17 +67,26 @@ func (f Facility) String() string {
6667
return facToStr[f]
6768
}
6869

70+
// Severity represents a level of messsage importance.
6971
type Severity byte
7072

7173
const (
72-
Emerg Severity = iota // Emergency: system is unusable
73-
Alert // immediate action required
74-
Crit // critical conditions
75-
Err // error conditions
76-
Warning // warning conditions
77-
Notice // normal but significant condition
78-
Info // information message
79-
Debug // debug-level message
74+
// Emerg - system is unusable
75+
Emerg Severity = iota
76+
// Alert - immediate action required
77+
Alert
78+
// Crit - critical conditions
79+
Crit
80+
// Err - error conditions
81+
Err
82+
// Warning - warning conditions
83+
Warning
84+
// Notice - normal but significant condition
85+
Notice
86+
// Info - information message
87+
Info
88+
// Debug - debug-level message
89+
Debug
8090
)
8191

8292
var sevToStr = [...]string{

logger/syslog/server.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,15 @@ import (
1313
"unicode"
1414
)
1515

16-
// Struct Server is the wrapper for a syslog server.
16+
// Server is the wrapper for a syslog server.
1717
type Server struct {
1818
conns []net.PacketConn
1919
handlers []Handler
2020
shutdown bool
2121
l FatalLogger
2222
}
2323

24-
// NewServer creates an idle server
24+
// NewServer creates an idle server.
2525
func NewServer() *Server {
2626
return &Server{l: log.New(os.Stderr, "", log.LstdFlags)}
2727
}

tests/etcdutils/etcdutils.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"github.com/deis/deis/tests/utils"
1212
)
1313

14+
// EtcdHandle is used to set keys and values in a test etcd instance.
1415
type EtcdHandle struct {
1516
Dirs []string
1617
Keys []string
@@ -24,6 +25,7 @@ func getetcdClient(port string) *etcd.Client {
2425
return c
2526
}
2627

28+
// InitetcdValues configures a test etcd instance.
2729
func InitetcdValues(setdir, setkeys []string, port string) *EtcdHandle {
2830
cli := getetcdClient(port)
2931
controllerHandle := new(EtcdHandle)
@@ -34,6 +36,7 @@ func InitetcdValues(setdir, setkeys []string, port string) *EtcdHandle {
3436
return controllerHandle
3537
}
3638

39+
// SetEtcdValues sets an array of values into a test etcd instance.
3740
func SetEtcdValues(t *testing.T, keys []string, values []string, c *etcd.Client) {
3841
for i, key := range keys {
3942
_, err := c.Set(key, values[i], 0)
@@ -43,6 +46,7 @@ func SetEtcdValues(t *testing.T, keys []string, values []string, c *etcd.Client)
4346
}
4447
}
4548

49+
// Publishvalues sets canonical etcd values into a test etcd instance.
4650
func Publishvalues(t *testing.T, ecli *EtcdHandle) {
4751
fmt.Println("--- Publish etcd keys and values")
4852
for _, dir := range ecli.Dirs {

tests/utils/itutils.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -152,9 +152,9 @@ func CheckList(
152152
if strings.Contains(stdout.String(), contain) == notflag {
153153
if notflag {
154154
t.Fatalf(
155-
"Didn't expect '%s' in command output:\n%s", contain, stdout)
155+
"Didn't expect '%s' in command output:\n%v", contain, stdout)
156156
}
157-
t.Fatalf("Expected '%s' in command output:\n%s", contain, stdout)
157+
t.Fatalf("Expected '%s' in command output:\n%v", contain, stdout)
158158
}
159159
}
160160

0 commit comments

Comments
 (0)