Skip to content

Instantly share code, notes, and snippets.

@santiagobasulto
Created April 20, 2015 13:11
Show Gist options
  • Save santiagobasulto/62e21b1cede780c9eb43 to your computer and use it in GitHub Desktop.
Save santiagobasulto/62e21b1cede780c9eb43 to your computer and use it in GitHub Desktop.
import re
import unittest
FORMAT = {
"b": lambda r: r["brand"],
"m": lambda r: r["model"],
"y": lambda r: str(r["year"])[2:],
"Y": lambda r: r["year"],
"%": lambda r: "%"
}
__format = format
def format_result(result, format):
"""
Format values according to a certain format specification:
%b = Brand
%m = Model
%y = Year (YY)
%Y = Year (YYYY)
"""
return re.compile("%(.)").sub(lambda m: FORMAT[m.group(1)](result), format)
class FormatResultTestCase(unittest.TestCase):
def setUp(self):
self.result = {
'brand': 'Ford',
'model': 'Fiesta',
'year': '1996'
}
def test_format_result_case_1(self):
"""Should format it ok with characters surrounding format"""
self.assertEqual(
format_result(self.result, "(%b) - %m"),
"(Ford) - Fiesta"
)
def test_format_result_case_2(self):
"""Should format ok without chars surrounding"""
self.assertEqual(
format_result(self.result, "%b - %m"),
"Ford - Fiesta"
)
def test_format_result_case_3(self):
"""Should format ok other random chars"""
self.assertEqual(
format_result(self.result, "Brand: %b - Model: %m"),
"Brand: Ford - Model: Fiesta"
)
def test_format_result_surrounded_with_quotes(self):
"""Should format ok if a format is quoted"""
self.assertEqual(
format_result(self.result, "Brand: '%b' - Model: '%m'"),
"Brand: 'Ford' - Model: 'Fiesta'"
)
def test_format_with_full_year(self):
"""Should format ok with YYYY year"""
self.assertEqual(
format_result(self.result, "Brand: %b - Model: %m - Year: %Y"),
"Brand: Ford - Model: Fiesta - Year: 1996"
)
def test_format_with_two_digits_year(self):
"""Should format ok with YY year"""
self.assertEqual(
format_result(self.result, "Brand: %b - Model: %m - Year: %y"),
"Brand: Ford - Model: Fiesta - Year: 96"
)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment