简体   繁体   中英

Correct way to test a function

Is it okay to call build_admins_message in the tests to build expected result that will be used in mock assertion?

Implementation:

@slack_messages.on_pattern('(?i)^admins$')
def handle_admins_message(event, body, match):
    team_id = event['team_id']
    user_id = body['user']

    message = build_admins_message(team_id, user_id)
    Slack(team_id).send_message(user_id, **message)

Tests:

class TestAdminsMessageHandler(TestCase):
    def setUp(self):
        team = SlackTeam.objects.create(team_id='TEAMID')
        SlackUser.objects.create(team=team, user_id='USERID')

    def tearDown(self):
        SlackUser.objects.all().delete()
        SlackTeam.objects.all().delete()

    @mock.patch('slango.slack.Slack.send_message')
    def test_correct_text(self, send_message_mock):
        event = {
            'team_id': 'TEAMID',
            'event': {
                'text': 'admins',
                'user': 'USERID'
            }
        }

        handle_admins_message(event, event['event'])

        expected_message = build_admins_message('TEAMID', 'USERID')

        send_message_mock.assert_called_with('USERID', **expected_message)

Implementation of the build_admins_message :

def build_admins_message(team_id, user_id):
    user = SlackUser.retrieve(team_id, user_id)
    admins = SlackUser.objects.filter(
        is_bot_admin=True, team__team_id=team_id).order_by(
            'real_name', 'display_name')

    attachments = []
    if user.is_bot_admin:
        attachments.append(build_admin_picker())

    for admin in admins:
        attachments.append(build_admin_item(user, admin))

    attachments.append(build_admin_more())

    return {
        'text': "Here is users with admin rights:",
        'attachments': attachments
    }

This would depend on the role of build_admins_message in your program.

Since different parts of the program all need to build the message in the same way, this is probably okay. Consider whether you can make it more explicit that build_admins_message is used like this, eg with dependency injection. Make sure your helper method has its own test. (I usually see using patch as a design smell, but remember that doesn't automatically mean something is wrong!)

If instead build_admins_message existed solely as a helper function for handle_admins_message , then using it in your test violates encapsulation and ties your test to the implementation too much. In that case, I would just manually write out the expected message in my test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM