2929import psycopg2 .extensions
3030from psycopg2 .extensions import b
3131
32+
3233class QuotingTestCase (ConnectingTestCase ):
3334 r"""Checks the correct quoting of strings and binary objects.
3435
@@ -51,7 +52,7 @@ def test_string(self):
5152 data = """some data with \t chars
5253 to escape into, 'quotes' and \\ a backslash too.
5354 """
54- data += "" .join (map (chr , range (1 ,127 )))
55+ data += "" .join (map (chr , range (1 , 127 )))
5556
5657 curs = self .conn .cursor ()
5758 curs .execute ("SELECT %s;" , (data ,))
@@ -90,13 +91,13 @@ def test_unicode(self):
9091 if server_encoding != "UTF8" :
9192 return self .skipTest (
9293 "Unicode test skipped since server encoding is %s"
93- % server_encoding )
94+ % server_encoding )
9495
9596 data = u"""some data with \t chars
9697 to escape into, 'quotes', \u20ac euro sign and \\ a backslash too.
9798 """
98- data += u"" .join (map (unichr , [ u for u in range (1 ,65536 )
99- if not 0xD800 <= u <= 0xDFFF ])) # surrogate area
99+ data += u"" .join (map (unichr , [u for u in range (1 , 65536 )
100+ if not 0xD800 <= u <= 0xDFFF ])) # surrogate area
100101 self .conn .set_client_encoding ('UNICODE' )
101102
102103 psycopg2 .extensions .register_type (psycopg2 .extensions .UNICODE , self .conn )
@@ -183,9 +184,45 @@ def test_unicode_ident(self):
183184 self .assertEqual (quote_ident (snowman , self .conn ), quoted )
184185
185186
187+ class TestStringAdapter (ConnectingTestCase ):
188+ def test_encoding_default (self ):
189+ from psycopg2 .extensions import adapt
190+ a = adapt ("hello" )
191+ self .assertEqual (a .encoding , 'latin1' )
192+ self .assertEqual (a .getquoted (), "'hello'" )
193+
194+ egrave = u'\xe8 '
195+ self .assertEqual (adapt (egrave ).getquoted (), "'\xe8 '" )
196+
197+ def test_encoding_error (self ):
198+ from psycopg2 .extensions import adapt
199+ snowman = u"\u2603 "
200+ a = adapt (snowman )
201+ self .assertRaises (UnicodeEncodeError , a .getquoted )
202+
203+ def test_set_encoding (self ):
204+ from psycopg2 .extensions import adapt
205+ snowman = u"\u2603 "
206+ a = adapt (snowman )
207+ a .encoding = 'utf8'
208+ self .assertEqual (a .encoding , 'utf8' )
209+ self .assertEqual (a .getquoted (), "'\xe2 \x98 \x83 '" )
210+
211+ def test_connection_wins_anyway (self ):
212+ from psycopg2 .extensions import adapt
213+ snowman = u"\u2603 "
214+ a = adapt (snowman )
215+ a .encoding = 'latin9'
216+
217+ self .conn .set_client_encoding ('utf8' )
218+ a .prepare (self .conn )
219+
220+ self .assertEqual (a .encoding , 'utf_8' )
221+ self .assertEqual (a .getquoted (), "'\xe2 \x98 \x83 '" )
222+
223+
186224def test_suite ():
187225 return unittest .TestLoader ().loadTestsFromName (__name__ )
188226
189227if __name__ == "__main__" :
190228 unittest .main ()
191-
0 commit comments