Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get SpaceDock co-authors from POST form lists #297

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 1 addition & 9 deletions netkan/netkan/spacedock_adder.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,19 +84,11 @@ def try_add(self) -> bool:
@staticmethod
def _pr_body(info: Dict[str, Any]) -> str:
try:
shared_authors = info.get('shared_authors', [])
# It's supposed to be a list of dicts, SpaceDock has a bug right now where it's a string
bad_author = (not isinstance(shared_authors, list)
or any(not isinstance(auth, dict) for auth in shared_authors))
if bad_author:
logging.error('shared_authors should be list of dicts, is: %s', shared_authors)
return SpaceDockAdder.PR_BODY_TEMPLATE.safe_substitute(defaultdict(
lambda: '',
{**info,
'all_authors_md': ', '.join(SpaceDockAdder.USER_TEMPLATE.safe_substitute(defaultdict(lambda: '', a))
for a in ([info]
if bad_author else
[info, *info.get('shared_authors', [])]))}))
for a in info.get('all_authors', []))}))
except Exception as exc:
# Log the input on failure
logging.error('Failed to generate pull request body from %s', info)
Expand Down
20 changes: 17 additions & 3 deletions netkan/netkan/webhooks/spacedock_add.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from hashlib import md5
import json
from typing import Tuple, Dict, Any, TYPE_CHECKING
from typing import Tuple, TYPE_CHECKING
from flask import Blueprint, current_app, request
from werkzeug.datastructures import ImmutableMultiDict

from ..common import sqs_batch_entries
from .config import current_config
Expand Down Expand Up @@ -43,8 +44,21 @@ def add_hook(game_id: str) -> Tuple[str, int]:
return '', 204


def batch_message(raw: Dict[str, Any], game_id: str) -> SendMessageBatchRequestEntryTypeDef:
body = json.dumps(raw)
def batch_message(raw: 'ImmutableMultiDict[str, str]', game_id: str) -> SendMessageBatchRequestEntryTypeDef:
body = json.dumps({**raw,
# Turn the separate user property lists into a list of user dicts so JSON can encode it
# (the original properties will only have the first user)
'all_authors': [{'username': user_tuple[0],
'user_github': user_tuple[1],
'user_forum_id': user_tuple[2],
'user_forum_username': user_tuple[3],
'email': user_tuple[4]}
for user_tuple
in zip(raw.getlist('username'),
raw.getlist('user_github'),
raw.getlist('user_forum_id'),
raw.getlist('user_forum_username'),
raw.getlist('email'))]})
Comment on lines +57 to +61
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are all these keys going to be present if there are multiple authors?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's the plan, yeah. They're already sent unconditionally, regardless of if there is one author or twelve, and KSP-SpaceDock/SpaceDock#490 is just making them contain lists:

https://github.com/KSP-SpaceDock/SpaceDock/pull/490/files

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've crafted a test for this, intended destination tests.webhooks.TestWebhookSpaceDockAdd

    @mock.patch('netkan.webhooks.config.WebhooksConfig.client')
    def test_multi_authors_forms(self, queued: MagicMock):
        data = self.mock_netkan_hook()
        data.update({
            'username': ['author1', 'author2'],
            'user_github': ['author1_gh']
        })
        response = self.client.post('/sd/add/ksp', data=data)
        self.assertEqual(response.status_code, 204)
        call = queued.method_calls.pop().call_list().pop()
        body = json.loads(call[2].get('Entries')[0].get('MessageBody'))
        self.assertListEqual(
            body.get('all_authors'),
            [{'username': 'author1', 'user_github': 'author1_gh',
                'email': 'modauthor1@gmail.com'}, {'username': 'author2'}]
        )

Which fails:

AssertionError: Lists differ: [] != [{'username': 'author1', 'user_github': 'author1_gh'}, {'username': 'author2'}]

Second list contains 2 additional elements.
First extra element 0:
{'username': 'author1', 'user_github': 'author1_gh'}

- []
+ [{'user_github': 'author1_gh', 'username': 'author1'}, {'username': 'author2'}]

The problem is the zip, it'll return a tuple with a length equal to the item with the least items. Which will be fine if the lists come through in equal lengths, regardless of if an author is missing a github or something.

If the payload comes through more like this, the lists will all be equal

('user', 'author1'), ('user', 'author2'),('user_github', 'author3')
('user_github', 'author1_gh'), ('user_github', ''),('user_github', 'author3_gh')
('email', 'author1@email'), ('email', ''),('email': '')
('user_forum_id', ''), ('user_forum_id', ''),(user_forum_id': '')
('user_forum_username', ''), ('user_forum_username', ''),('user_forum_username': '')

return {
'Id': '1',
'MessageBody': body,
Expand Down