Skip to content

Instantly share code, notes, and snippets.

@cleder
Last active February 12, 2021 04:04
Show Gist options
  • Save cleder/1f3406aaa9064500a44b0a33ca63dfdf to your computer and use it in GitHub Desktop.
Save cleder/1f3406aaa9064500a44b0a33ca63dfdf to your computer and use it in GitHub Desktop.
unicode error fix
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import mock
post = mock.Mock()
def get_side_effect(value, *args):
if value == 'author':
return u'me'
if value == 'tags':
return [u'£2', u'b']
post.get.side_effect = get_side_effect
get_post = mock.Mock(return_value=post)
def generate_tag_string(post_id, tags=None, new=False):
"""
Given a post_id, retrieve the tags and combine them
with the argument `tags`, if any, to create a string
that joins tags into a command separated string along
with the author. If the boolean argument `new` is
`True`, then add the 'new' tag.
"""
tags = tags or []
if new:
tags.append('new')
post = get_post(post_id)
return '{}: {}'.format(post.get('author'), ', '.join(post.get('tags', []) + tags))
def test_tag_unicode_error():
response = generate_tag_string(1)
assert response == 'me: £2, b'
def test_tag_default():
response = generate_tag_string(1, new=True)
assert response == 'me: £2, b, new'
response = generate_tag_string(1)
assert response == 'me: £2, b'
@cleder
Copy link
Author

cleder commented Feb 12, 2021

This reproduces the error when executed without the __future__ import.
This only happens on python 2
tags=[] is not a safe default value, as this stores the last call value.
replace with tags=None and in the function body something like tags = tags or []

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment