Skip to content
Merged
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
25 changes: 24 additions & 1 deletion sopel/irc/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,30 @@ def get_cnames(domain):


def safe(string):
"""Remove newlines from a string."""
"""Remove newlines from a string.

:param str string: input text to process
:return: the string without newlines
:rtype: str
:raises TypeError: when ``string`` is ``None``

This function removes newlines from a string and always returns a unicode
string (as in ``str`` on Python 3 and ``unicode`` on Python 2), but doesn't
strip or alter it in any other way::

>>> safe('some text\\r\\n')
'some text'

This is useful to ensure a string can be used in a IRC message.

.. versionchanged:: 7.1

This function now raises a :exc:`TypeError` instead of an unpredictable
behaviour when given ``None``.

"""
if string is None:
raise TypeError('safe function requires a string, not NoneType')
if sys.version_info.major >= 3 and isinstance(string, bytes):
string = string.decode("utf8")
elif sys.version_info.major < 3:
Expand Down
44 changes: 44 additions & 0 deletions test/irc/test_irc_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# coding=utf-8
"""Tests for core ``sopel.irc.utils``"""
from __future__ import absolute_import, division, print_function, unicode_literals

import pytest

from sopel.irc import utils


def test_safe():
text = 'some text'
assert utils.safe(text + '\r\n') == text
assert utils.safe(text + '\n') == text
assert utils.safe(text + '\r') == text
assert utils.safe('\r\n' + text) == text
assert utils.safe('\n' + text) == text
assert utils.safe('\r' + text) == text
assert utils.safe('some \r\ntext') == text
assert utils.safe('some \ntext') == text
assert utils.safe('some \rtext') == text


def test_safe_empty():
text = ''
assert utils.safe(text) == text


def test_safe_null():
with pytest.raises(TypeError):
utils.safe(None)


def test_safe_bytes():
text = b'some text'
assert utils.safe(text) == text.decode('utf-8')
assert utils.safe(text + b'\r\n') == text.decode('utf-8')
assert utils.safe(text + b'\n') == text.decode('utf-8')
assert utils.safe(text + b'\r') == text.decode('utf-8')
assert utils.safe(b'\r\n' + text) == text.decode('utf-8')
assert utils.safe(b'\n' + text) == text.decode('utf-8')
assert utils.safe(b'\r' + text) == text.decode('utf-8')
assert utils.safe(b'some \r\ntext') == text.decode('utf-8')
assert utils.safe(b'some \ntext') == text.decode('utf-8')
assert utils.safe(b'some \rtext') == text.decode('utf-8')