From efbe77ba7cefe063ef8e87d29eb20649f852c452 Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Wed, 16 Sep 2020 20:53:01 -0700 Subject: [PATCH] Fixed bug with github-to-sqlite get and single items, refs #50 --- github_to_sqlite/cli.py | 10 +++++++++- tests/test_get.py | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/github_to_sqlite/cli.py b/github_to_sqlite/cli.py index 0194eda..992431f 100644 --- a/github_to_sqlite/cli.py +++ b/github_to_sqlite/cli.py @@ -466,9 +466,17 @@ def get(url, auth, paginate, nl): "Save repos owened by the specified (or authenticated) username or organization" token = load_token(auth) first = True + should_output_closing_brace = not nl while url: response = utils.get(url, token) items = response.json() + if isinstance(items, dict): + if nl: + click.echo(json.dumps(items)) + else: + click.echo(json.dumps(items, indent=4)) + should_output_closing_brace = False + break if first and not nl: click.echo("[") for item in items: @@ -484,7 +492,7 @@ def get(url, auth, paginate, nl): url = response.links.get("next", {}).get("url") else: url = None - if not nl: + if should_output_closing_brace: click.echo("\n]") diff --git a/tests/test_get.py b/tests/test_get.py index 1c1dddd..13fb8c9 100644 --- a/tests/test_get.py +++ b/tests/test_get.py @@ -16,6 +16,9 @@ def mocked_paginated(requests_mock): json=[{"id": 3, "title": "Item 3"}, {"id": 4, "title": "Item 4"}], headers={"link": '; rel="prev"'}, ) + requests_mock.get( + "https://api.github.com/single", json={"id": 1, "title": "Item 1"} + ) @pytest.mark.parametrize("url", ["https://api.github.com/paginated", "/paginated"]) @@ -41,6 +44,37 @@ def test_get(mocked_paginated, url): assert result.output.strip() == expected +@pytest.mark.parametrize( + "nl,expected", + [ + (True, '{"id": 1, "title": "Item 1"}'), + ( + False, + textwrap.dedent( + """ + { + "id": 1, + "title": "Item 1" + } + """ + ), + ), + ], +) +@pytest.mark.parametrize("paginate", [True, False]) +def test_get_single(mocked_paginated, nl, expected, paginate): + runner = CliRunner() + with runner.isolated_filesystem(): + args = ["get", "/single"] + if nl: + args.append("--nl") + if paginate: + args.append("--paginate") + result = runner.invoke(cli.cli, args) + assert 0 == result.exit_code + assert result.output.strip() == expected.strip() + + @pytest.mark.parametrize( "nl,expected", (