Skip to content

Commit 3bdd714

Browse files
fixing up unit tests and table edge cases
1 parent b7fd730 commit 3bdd714

File tree

7 files changed

+42
-40
lines changed

7 files changed

+42
-40
lines changed

SoftLayer/CLI/core.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
import click
1515
import requests
16+
from rich.markup import escape
1617

1718
import SoftLayer
1819
from SoftLayer.CLI.command import CommandLoader
@@ -143,9 +144,9 @@ def output_diagnostics(env, result, verbose=0, **kwargs):
143144
diagnostic_table = formatting.Table(['name', 'value'])
144145
diagnostic_table.add_row(['execution_time', '%fs' % (time.time() - START_TIME)])
145146

146-
api_call_value = []
147+
api_call_value = formatting.Table(['API Calls'], title=None, align="left")
147148
for call in env.client.transport.get_last_calls():
148-
api_call_value.append("%s::%s (%fs)" % (call.service, call.method, call.end_time - call.start_time))
149+
api_call_value.add_row(["%s::%s (%fs)" % (call.service, call.method, call.end_time - call.start_time)])
149150

150151
diagnostic_table.add_row(['api_calls', api_call_value])
151152
diagnostic_table.add_row(['version', consts.USER_AGENT])
@@ -156,13 +157,13 @@ def output_diagnostics(env, result, verbose=0, **kwargs):
156157

157158
if verbose > 1:
158159
for call in env.client.transport.get_last_calls():
159-
call_table = formatting.Table(['', '{}::{}'.format(call.service, call.method)])
160+
call_table = formatting.Table(['', '{}::{}'.format(call.service, call.method)], align="left")
160161
nice_mask = ''
161162
if call.mask is not None:
162163
nice_mask = call.mask
163-
164164
call_table.add_row(['id', call.identifier])
165-
call_table.add_row(['mask', nice_mask])
165+
# Need to escape this so Rich doesn't think the mask is a tag and hide it.
166+
call_table.add_row(['mask', escape(nice_mask)])
166167
call_table.add_row(['filter', call.filter])
167168
call_table.add_row(['limit', call.limit])
168169
call_table.add_row(['offset', call.offset])

SoftLayer/CLI/dns/zone_import.py

Lines changed: 18 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@
55
import click
66

77
import SoftLayer
8+
from SoftLayer.CLI.command import SLCommand as SLCommand
89
from SoftLayer.CLI import environment
910
from SoftLayer.CLI import exceptions
11+
from SoftLayer.CLI import formatting
1012
from SoftLayer.CLI import helpers
1113

1214
RECORD_REGEX = re.compile(r"""^((?P<domain>(([\w-]+|\*)(\.)?)*|\@)?\s+
@@ -17,9 +19,8 @@
1719
RECORD_FMT = "type={type}, record={record}, data={data}, ttl={ttl}"
1820

1921

20-
@click.command(cls=SoftLayer.CLI.command.SLCommand, )
21-
@click.argument('zonefile',
22-
type=click.Path(exists=True, readable=True, resolve_path=True))
22+
@click.command(cls=SLCommand)
23+
@click.argument('zonefile', type=click.Path(exists=True, readable=True, resolve_path=True))
2324
@click.option('--dry-run', is_flag=True, help="Don't actually create records")
2425
@environment.pass_env
2526
def cli(env, zonefile, dry_run):
@@ -31,12 +32,12 @@ def cli(env, zonefile, dry_run):
3132

3233
zone, records, bad_lines = parse_zone_details(zone_contents)
3334

34-
env.out("Parsed: zone=%s" % zone)
35+
click.secho("Parsed: zone=%s" % zone)
3536
for record in records:
36-
env.out("Parsed: %s" % RECORD_FMT.format(**record))
37+
click.secho("Parsed: %s" % RECORD_FMT.format(**record), fg="green")
3738

3839
for line in bad_lines:
39-
env.out("Unparsed: %s" % line)
40+
click.secho("Unparsed: %s" % line, fg="yellow")
4041

4142
if dry_run:
4243
return
@@ -47,25 +48,19 @@ def cli(env, zonefile, dry_run):
4748
name='zone')
4849
except exceptions.CLIAbort:
4950
zone_id = manager.create_zone(zone)['id']
50-
env.out(click.style("Created: %s" % zone, fg='green'))
51+
click.secho(click.style("Created: %s" % zone, fg='green'))
5152

5253
# Attempt to create each record
5354
for record in records:
5455
try:
55-
manager.create_record(zone_id,
56-
record['record'],
57-
record['type'],
58-
record['data'],
59-
record['ttl'])
60-
61-
env.out(click.style("Created: %s" % RECORD_FMT.format(**record),
62-
fg='green'))
56+
manager.create_record(zone_id, record['record'], record['type'], record['data'], record['ttl'])
57+
58+
click.secho(click.style("Created: %s" % RECORD_FMT.format(**record), fg='green'))
6359
except SoftLayer.SoftLayerAPIError as ex:
64-
env.out(click.style("Failed: %s" % RECORD_FMT.format(**record),
65-
fg='red'))
66-
env.out(click.style(str(ex), fg='red'))
60+
click.secho(click.style("Failed: %s" % RECORD_FMT.format(**record), fg='red'))
61+
click.secho(click.style(str(ex), fg='red'))
6762

68-
env.out(click.style("Finished", fg='green'))
63+
click.secho(click.style("Finished", fg='green'))
6964

7065

7166
def parse_zone_details(zone_contents):
@@ -75,7 +70,10 @@ def parse_zone_details(zone_contents):
7570
zone_lines = [line.strip() for line in zone_contents.split('\n')]
7671

7772
zone_search = re.search(r'^\$ORIGIN (?P<zone>.*)\.', zone_lines[0])
78-
zone = zone_search.group('zone')
73+
if zone_search:
74+
zone = zone_search.group('zone')
75+
else:
76+
raise exceptions.ArgumentError("Invalid Zone File")
7977

8078
for line in zone_lines[1:]:
8179
record_search = re.search(RECORD_REGEX, line)

SoftLayer/CLI/environment.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,13 +53,14 @@ def out(self, output):
5353
# If we want to print a list of tables, Rich doens't handle that well.
5454
if isinstance(output, list):
5555
for line in output:
56-
self.console.print(line)
56+
self.console.print(line, overflow='ignore')
5757
else:
58-
self.console.print(output)
58+
self.console.print(output, overflow='ignore')
5959

6060
def err(self, output, newline=True):
6161
"""Outputs an error string to the console (stderr)."""
62-
click.echo(output, nl=newline, err=True)
62+
error_console = Console(stderr=True)
63+
error_console.print(output)
6364

6465
def fmt(self, output, fmt=None):
6566
"""Format output based on current the environment format."""

SoftLayer/CLI/formatting.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -93,17 +93,15 @@ def b_to_gb(_bytes):
9393
9494
:param int _bytes: number of bytes
9595
"""
96-
return FormattedItem(_bytes,
97-
"%.2fG" % (float(_bytes) / 1024 / 1024 / 1024))
96+
return FormattedItem(_bytes, "%.2fG" % (float(_bytes) / 1024 / 1024 / 1024))
9897

9998

10099
def gb(gigabytes): # pylint: disable=C0103
101100
"""Converts number of gigabytes to a FormattedItem in gigabytes.
102101
103102
:param int gigabytes: number of gigabytes
104103
"""
105-
return FormattedItem(int(float(gigabytes)) * 1024,
106-
"%dG" % int(float(gigabytes)))
104+
return FormattedItem(int(float(gigabytes)) * 1024, "%dG" % int(float(gigabytes)))
107105

108106

109107
def blank():
@@ -233,7 +231,7 @@ class Table(object):
233231
:param list columns: a list of column names
234232
"""
235233

236-
def __init__(self, columns, title=None):
234+
def __init__(self, columns, title=None, align={}):
237235
duplicated_cols = [col for col, count
238236
in collections.Counter(columns).items()
239237
if count > 1]
@@ -243,7 +241,7 @@ def __init__(self, columns, title=None):
243241

244242
self.columns = columns
245243
self.rows = []
246-
self.align = {}
244+
self.align = align
247245
self.sortby = None
248246
self.title = title
249247

SoftLayer/transports.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -430,7 +430,7 @@ def print_reproduceable(self, request):
430430
431431
:param request request: Request object
432432
"""
433-
command = "curl -u $SL_USER:$SL_APIKEY -X {method} -H {headers} {data} '{uri}'"
433+
command = "curl -u $SL_USER:$SL_APIKEY -X {method} -H {headers} [red]{data}[/red] [yellow]'{uri}'[/yellow]"
434434

435435
method = REST_SPECIAL_METHODS.get(request.method)
436436

tests/CLI/modules/call_api_tests.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ def test_python_output(self):
9595
'--output-python'])
9696
print("OUTPUT: \n{}".format(result.exception))
9797
self.assert_no_fail(result)
98-
98+
9999
self.assertIsNotNone(result.output, """import SoftLayer
100100
101101
client = SoftLayer.create_client_from_env()
@@ -293,7 +293,6 @@ def test_filter_with_filter(self):
293293
self.assertIsInstance(result.exception, exceptions.CLIAbort)
294294

295295
def test_json_filter(self):
296-
pass
297296
result = self.run_command(['call-api', 'Account', 'getObject', '--json-filter={"test":"something"}'])
298297
self.assert_no_fail(result)
299298
self.assert_called_with('SoftLayer_Account', 'getObject', filter={"test": "something"})
@@ -315,3 +314,9 @@ def test_call_api_orderBy(self):
315314
'value': ['DESC']}]},
316315
'typeId': {'operation': 1}}
317316
})
317+
def test_very_verbose(self):
318+
result = self.run_command(['call-api', '-vvv', 'Account', 'getObject'])
319+
self.assert_no_fail(result)
320+
self.assert_called_with('SoftLayer_Account', 'getObject')
321+
print(result.output)
322+
self.assertEqual(result.output, "soething")

tests/CLI/modules/file_tests.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -88,12 +88,11 @@ def test_volume_list_reduced_notes_format_output_table(self, list_mock):
8888
{'notes': note_mock}
8989
]
9090
expected_table = formatting.Table(['notes'])
91-
expected_table.add_row([expected_reduced_note])
92-
expected_output = formatting.format_output(expected_table) + '\n'
9391
result = self.run_command(['--format', 'table', 'file', 'volume-list', '--columns', 'notes'])
9492

9593
self.assert_no_fail(result)
96-
self.assertEqual(expected_output, result.output)
94+
self.assertIn(expected_reduced_note, result.output)
95+
self.assertNotIn(note_mock, result.output)
9796

9897
@mock.patch('SoftLayer.FileStorageManager.list_file_volumes')
9998
def test_volume_count(self, list_mock):

0 commit comments

Comments
 (0)