Skip to content

Commit

Permalink
Merge pull request #434 from pymssql/425-sproc-binary-types
Browse files Browse the repository at this point in the history
update expected types for binary sproc args for py2 & py3 compatibility.

Fixes #425
  • Loading branch information
ramiro committed Jun 22, 2016
2 parents f8daf2a + 881e8ed commit 7409a2a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/_mssql.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -971,8 +971,10 @@ cdef class MSSQLConnection:
return 0

if dbtype[0] in (SQLBINARY, SQLVARBINARY, SQLIMAGE):
if type(value) is not str:
raise TypeError('value can only be str')
if PY_MAJOR_VERSION == 3 and type(value) not in (bytes, bytearray):
raise TypeError('value can only be bytes or bytearray')
elif PY_MAJOR_VERSION == 2 and type(value) not in (str, bytearray):
raise TypeError('value can only be str or bytearray')

binValue = <BYTE *>PyMem_Malloc(len(value))
memcpy(binValue, <char *>value, len(value))
Expand Down
24 changes: 24 additions & 0 deletions tests/test_sprocs.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
VARIABLE_TYPES = (
('Char', 4),
('VarChar', 4),
('VarBinary', 4),
('Text', None) # Leave this one in the last position in case it fails (see https://code.google.com/p/pymssql/issues/detail?id=113#c2)
)

Expand Down Expand Up @@ -428,6 +429,29 @@ def testVarChar(self):
proc.execute()
eq_(input, proc.parameters['@ovarchar'])

def testVarBinary(self):
def check_conversion(input, output_type):
proc = self.mssql.init_procedure('pymssqlTestVarBinary')
proc.bind(input, _mssql.SQLVARBINARY, '@ivarbinary')
proc.bind(None, _mssql.SQLVARBINARY, '@ovarbinary', output=True)
proc.execute()
eq_(input, proc.parameters['@ovarbinary'])
eq_(output_type, type(proc.parameters['@ovarbinary']))

if sys.version_info[0] == 3:
check_conversion(bytes(b'\xDE\xAD\xBE\xEF'), bytes)
check_conversion(bytearray(b'\xDE\xAD\xBE\xEF'), bytes)
with pytest.raises(TypeError) as exc_info:
check_conversion('FOO', bytes)
assert 'value can only be bytes or bytearray' == str(exc_info.value)
else:
check_conversion(b'\xDE\xAD\xBE\xEF', str)
check_conversion(bytes(b'\xDE\xAD\xBE\xEF'), str)
check_conversion(bytearray(b'\xDE\xAD\xBE\xEF'), str)
with pytest.raises(TypeError) as exc_info:
check_conversion(unicode('Foo'), str)
assert 'value can only be str or bytearray' == str(exc_info.value)


class TestFloatTypeConversion(unittest.TestCase):
def setUp(self):
Expand Down

0 comments on commit 7409a2a

Please sign in to comment.