-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathtest_004_cursor.py
More file actions
10899 lines (9067 loc) · 450 KB
/
test_004_cursor.py
File metadata and controls
10899 lines (9067 loc) · 450 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
This file contains tests for the Cursor class.
Functions:
- test_cursor: Check if the cursor is created.
- test_execute: Ensure test_cursor passed and execute a query to fetch database names and IDs.
- test_fetch_data: Ensure test_cursor passed and fetch data from a query.
- test_execute_invalid_query: Ensure test_cursor passed and check if executing an invalid query raises an exception.
Note: The cursor function is not yet implemented, so related tests are commented out.
"""
import pytest
from datetime import datetime, date, time, timedelta, timezone
import time as time_module
import decimal
from contextlib import closing
import mssql_python
import uuid
# Setup test table
TEST_TABLE = """
CREATE TABLE #pytest_all_data_types (
id INTEGER PRIMARY KEY,
bit_column BIT,
tinyint_column TINYINT,
smallint_column SMALLINT,
bigint_column BIGINT,
integer_column INTEGER,
float_column FLOAT,
wvarchar_column NVARCHAR(255),
time_column TIME,
datetime_column DATETIME,
date_column DATE,
real_column REAL
);
"""
# Test data
TEST_DATA = (
1,
1,
127,
32767,
9223372036854775807,
2147483647,
1.23456789,
"nvarchar data",
time(12, 34, 56),
datetime(2024, 5, 20, 12, 34, 56, 123000),
date(2024, 5, 20),
1.23456789
)
# Parameterized test data with different primary keys
PARAM_TEST_DATA = [
TEST_DATA,
(2, 0, 0, 0, 0, 0, 0.0, "test1", time(0, 0, 0), datetime(2024, 1, 1, 0, 0, 0), date(2024, 1, 1), 0.0),
(3, 1, 1, 1, 1, 1, 1.1, "test2", time(1, 1, 1), datetime(2024, 2, 2, 1, 1, 1), date(2024, 2, 2), 1.1),
(4, 0, 127, 32767, 9223372036854775807, 2147483647, 1.23456789, "test3", time(12, 34, 56), datetime(2024, 5, 20, 12, 34, 56, 123000), date(2024, 5, 20), 1.23456789)
]
def drop_table_if_exists(cursor, table_name):
"""Drop the table if it exists"""
try:
cursor.execute(f"DROP TABLE IF EXISTS {table_name}")
except Exception as e:
pytest.fail(f"Failed to drop table {table_name}: {e}")
def test_cursor(cursor):
"""Check if the cursor is created"""
assert cursor is not None, "Cursor should not be None"
def test_empty_string_handling(cursor, db_connection):
"""Test that empty strings are handled correctly without assertion failures"""
try:
# Create test table
drop_table_if_exists(cursor, "#pytest_empty_string")
cursor.execute("CREATE TABLE #pytest_empty_string (id INT, text_col NVARCHAR(100))")
db_connection.commit()
# Insert empty string
cursor.execute("INSERT INTO #pytest_empty_string VALUES (1, '')")
db_connection.commit()
# Fetch the empty string - this would previously cause assertion failure
cursor.execute("SELECT text_col FROM #pytest_empty_string WHERE id = 1")
row = cursor.fetchone()
assert row is not None, "Should return a row"
assert row[0] == '', "Should return empty string, not None"
# Test with fetchall to ensure batch fetch works too
cursor.execute("SELECT text_col FROM #pytest_empty_string")
rows = cursor.fetchall()
assert len(rows) == 1, "Should return 1 row"
assert rows[0][0] == '', "fetchall should also return empty string"
except Exception as e:
pytest.fail(f"Empty string handling test failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_empty_string")
db_connection.commit()
def test_empty_binary_handling(cursor, db_connection):
"""Test that empty binary data is handled correctly without assertion failures"""
try:
# Create test table
drop_table_if_exists(cursor, "#pytest_empty_binary")
cursor.execute("CREATE TABLE #pytest_empty_binary (id INT, binary_col VARBINARY(100))")
db_connection.commit()
# Insert empty binary data
cursor.execute("INSERT INTO #pytest_empty_binary VALUES (1, 0x)") # Empty binary literal
db_connection.commit()
# Fetch the empty binary - this would previously cause assertion failure
cursor.execute("SELECT binary_col FROM #pytest_empty_binary WHERE id = 1")
row = cursor.fetchone()
assert row is not None, "Should return a row"
assert row[0] == b'', "Should return empty bytes, not None"
assert isinstance(row[0], bytes), "Should return bytes type"
assert len(row[0]) == 0, "Should be zero-length bytes"
except Exception as e:
pytest.fail(f"Empty binary handling test failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_empty_binary")
db_connection.commit()
def test_mixed_empty_and_null_values(cursor, db_connection):
"""Test that empty strings/binary and NULL values are distinguished correctly"""
try:
# Create test table
drop_table_if_exists(cursor, "#pytest_empty_vs_null")
cursor.execute("""
CREATE TABLE #pytest_empty_vs_null (
id INT,
text_col NVARCHAR(100),
binary_col VARBINARY(100)
)
""")
db_connection.commit()
# Insert mix of empty and NULL values
cursor.execute("INSERT INTO #pytest_empty_vs_null VALUES (1, '', 0x)") # Empty string and binary
cursor.execute("INSERT INTO #pytest_empty_vs_null VALUES (2, NULL, NULL)") # NULL values
cursor.execute("INSERT INTO #pytest_empty_vs_null VALUES (3, 'data', 0x1234)") # Non-empty values
db_connection.commit()
# Fetch all rows
cursor.execute("SELECT id, text_col, binary_col FROM #pytest_empty_vs_null ORDER BY id")
rows = cursor.fetchall()
# Validate row 1: empty values
assert rows[0][1] == '', "Row 1 should have empty string, not None"
assert rows[0][2] == b'', "Row 1 should have empty bytes, not None"
# Validate row 2: NULL values
assert rows[1][1] is None, "Row 2 should have NULL (None) for text"
assert rows[1][2] is None, "Row 2 should have NULL (None) for binary"
# Validate row 3: non-empty values
assert rows[2][1] == 'data', "Row 3 should have non-empty string"
assert rows[2][2] == b'\x12\x34', "Row 3 should have non-empty binary"
except Exception as e:
pytest.fail(f"Empty vs NULL test failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_empty_vs_null")
db_connection.commit()
def test_empty_string_edge_cases(cursor, db_connection):
"""Test edge cases with empty strings"""
try:
# Create test table
drop_table_if_exists(cursor, "#pytest_empty_edge")
cursor.execute("CREATE TABLE #pytest_empty_edge (id INT, data NVARCHAR(MAX))")
db_connection.commit()
# Test various ways to insert empty strings
cursor.execute("INSERT INTO #pytest_empty_edge VALUES (1, '')")
cursor.execute("INSERT INTO #pytest_empty_edge VALUES (2, N'')")
cursor.execute("INSERT INTO #pytest_empty_edge VALUES (3, ?)", [''])
cursor.execute("INSERT INTO #pytest_empty_edge VALUES (4, ?)", [u''])
db_connection.commit()
# Verify all are empty strings
cursor.execute("SELECT id, data, LEN(data) as length FROM #pytest_empty_edge ORDER BY id")
rows = cursor.fetchall()
for row in rows:
assert row[1] == '', f"Row {row[0]} should have empty string"
assert row[2] == 0, f"Row {row[0]} should have length 0"
assert row[1] is not None, f"Row {row[0]} should not be None"
except Exception as e:
pytest.fail(f"Empty string edge cases test failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_empty_edge")
db_connection.commit()
def test_insert_id_column(cursor, db_connection):
"""Test inserting data into the id column"""
try:
drop_table_if_exists(cursor, "#pytest_single_column")
cursor.execute("CREATE TABLE #pytest_single_column (id INTEGER PRIMARY KEY)")
db_connection.commit()
cursor.execute("INSERT INTO #pytest_single_column (id) VALUES (?)", [1])
db_connection.commit()
cursor.execute("SELECT id FROM #pytest_single_column")
row = cursor.fetchone()
assert row[0] == 1, "ID column insertion/fetch failed"
except Exception as e:
pytest.fail(f"ID column insertion/fetch failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_single_column")
db_connection.commit()
def test_insert_bit_column(cursor, db_connection):
"""Test inserting data into the bit_column"""
try:
cursor.execute("CREATE TABLE #pytest_single_column (bit_column BIT)")
db_connection.commit()
cursor.execute("INSERT INTO #pytest_single_column (bit_column) VALUES (?)", [1])
db_connection.commit()
cursor.execute("SELECT bit_column FROM #pytest_single_column")
row = cursor.fetchone()
assert row[0] == 1, "Bit column insertion/fetch failed"
except Exception as e:
pytest.fail(f"Bit column insertion/fetch failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_single_column")
db_connection.commit()
def test_insert_nvarchar_column(cursor, db_connection):
"""Test inserting data into the nvarchar_column"""
try:
cursor.execute("CREATE TABLE #pytest_single_column (nvarchar_column NVARCHAR(255))")
db_connection.commit()
cursor.execute("INSERT INTO #pytest_single_column (nvarchar_column) VALUES (?)", ["test"])
db_connection.commit()
cursor.execute("SELECT nvarchar_column FROM #pytest_single_column")
row = cursor.fetchone()
assert row[0] == "test", "Nvarchar column insertion/fetch failed"
except Exception as e:
pytest.fail(f"Nvarchar column insertion/fetch failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_single_column")
db_connection.commit()
def test_insert_time_column(cursor, db_connection):
"""Test inserting data into the time_column"""
try:
drop_table_if_exists(cursor, "#pytest_single_column")
cursor.execute("CREATE TABLE #pytest_single_column (time_column TIME)")
db_connection.commit()
cursor.execute("INSERT INTO #pytest_single_column (time_column) VALUES (?)", [time(12, 34, 56)])
db_connection.commit()
cursor.execute("SELECT time_column FROM #pytest_single_column")
row = cursor.fetchone()
assert row[0] == time(12, 34, 56), "Time column insertion/fetch failed"
except Exception as e:
pytest.fail(f"Time column insertion/fetch failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_single_column")
db_connection.commit()
def test_insert_datetime_column(cursor, db_connection):
"""Test inserting data into the datetime_column"""
try:
drop_table_if_exists(cursor, "#pytest_single_column")
cursor.execute("CREATE TABLE #pytest_single_column (datetime_column DATETIME)")
db_connection.commit()
cursor.execute("INSERT INTO #pytest_single_column (datetime_column) VALUES (?)", [datetime(2024, 5, 20, 12, 34, 56, 123000)])
db_connection.commit()
cursor.execute("SELECT datetime_column FROM #pytest_single_column")
row = cursor.fetchone()
assert row[0] == datetime(2024, 5, 20, 12, 34, 56, 123000), "Datetime column insertion/fetch failed"
except Exception as e:
pytest.fail(f"Datetime column insertion/fetch failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_single_column")
db_connection.commit()
def test_insert_datetime2_column(cursor, db_connection):
"""Test inserting data into the datetime2_column"""
try:
drop_table_if_exists(cursor, "#pytest_single_column")
cursor.execute("CREATE TABLE #pytest_single_column (datetime2_column DATETIME2)")
db_connection.commit()
cursor.execute("INSERT INTO #pytest_single_column (datetime2_column) VALUES (?)", [datetime(2024, 5, 20, 12, 34, 56, 123456)])
db_connection.commit()
cursor.execute("SELECT datetime2_column FROM #pytest_single_column")
row = cursor.fetchone()
assert row[0] == datetime(2024, 5, 20, 12, 34, 56, 123456), "Datetime2 column insertion/fetch failed"
except Exception as e:
pytest.fail(f"Datetime2 column insertion/fetch failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_single_column")
db_connection.commit()
def test_insert_smalldatetime_column(cursor, db_connection):
"""Test inserting data into the smalldatetime_column"""
try:
drop_table_if_exists(cursor, "#pytest_single_column")
cursor.execute("CREATE TABLE #pytest_single_column (smalldatetime_column SMALLDATETIME)")
db_connection.commit()
cursor.execute("INSERT INTO #pytest_single_column (smalldatetime_column) VALUES (?)", [datetime(2024, 5, 20, 12, 34)])
db_connection.commit()
cursor.execute("SELECT smalldatetime_column FROM #pytest_single_column")
row = cursor.fetchone()
assert row[0] == datetime(2024, 5, 20, 12, 34), "Smalldatetime column insertion/fetch failed"
except Exception as e:
pytest.fail(f"Smalldatetime column insertion/fetch failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_single_column")
db_connection.commit()
def test_insert_date_column(cursor, db_connection):
"""Test inserting data into the date_column"""
try:
drop_table_if_exists(cursor, "#pytest_single_column")
cursor.execute("CREATE TABLE #pytest_single_column (date_column DATE)")
db_connection.commit()
cursor.execute("INSERT INTO #pytest_single_column (date_column) VALUES (?)", [date(2024, 5, 20)])
db_connection.commit()
cursor.execute("SELECT date_column FROM #pytest_single_column")
row = cursor.fetchone()
assert row[0] == date(2024, 5, 20), "Date column insertion/fetch failed"
except Exception as e:
pytest.fail(f"Date column insertion/fetch failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_single_column")
db_connection.commit()
def test_insert_real_column(cursor, db_connection):
"""Test inserting data into the real_column"""
try:
drop_table_if_exists(cursor, "#pytest_single_column")
cursor.execute("CREATE TABLE #pytest_single_column (real_column REAL)")
db_connection.commit()
cursor.execute("INSERT INTO #pytest_single_column (real_column) VALUES (?)", [1.23456789])
db_connection.commit()
cursor.execute("SELECT real_column FROM #pytest_single_column")
row = cursor.fetchone()
assert abs(row[0] - 1.23456789) < 1e-8, "Real column insertion/fetch failed"
except Exception as e:
pytest.fail(f"Real column insertion/fetch failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_single_column")
db_connection.commit()
def test_insert_decimal_column(cursor, db_connection):
"""Test inserting data into the decimal_column"""
try:
cursor.execute("CREATE TABLE #pytest_single_column (decimal_column DECIMAL(10, 2))")
db_connection.commit()
cursor.execute("INSERT INTO #pytest_single_column (decimal_column) VALUES (?)", [decimal.Decimal(123.45).quantize(decimal.Decimal('0.00'))])
db_connection.commit()
cursor.execute("SELECT decimal_column FROM #pytest_single_column")
row = cursor.fetchone()
assert row[0] == decimal.Decimal(123.45).quantize(decimal.Decimal('0.00')), "Decimal column insertion/fetch failed"
cursor.execute("TRUNCATE TABLE #pytest_single_column")
cursor.execute("INSERT INTO #pytest_single_column (decimal_column) VALUES (?)", [decimal.Decimal(-123.45).quantize(decimal.Decimal('0.00'))])
db_connection.commit()
cursor.execute("SELECT decimal_column FROM #pytest_single_column")
row = cursor.fetchone()
assert row[0] == decimal.Decimal(-123.45).quantize(decimal.Decimal('0.00')), "Negative Decimal insertion/fetch failed"
except Exception as e:
pytest.fail(f"Decimal column insertion/fetch failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_single_column")
db_connection.commit()
def test_insert_tinyint_column(cursor, db_connection):
"""Test inserting data into the tinyint_column"""
try:
cursor.execute("CREATE TABLE #pytest_single_column (tinyint_column TINYINT)")
db_connection.commit()
cursor.execute("INSERT INTO #pytest_single_column (tinyint_column) VALUES (?)", [127])
db_connection.commit()
cursor.execute("SELECT tinyint_column FROM #pytest_single_column")
row = cursor.fetchone()
assert row[0] == 127, "Tinyint column insertion/fetch failed"
except Exception as e:
pytest.fail(f"Tinyint column insertion/fetch failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_single_column")
db_connection.commit()
def test_insert_smallint_column(cursor, db_connection):
"""Test inserting data into the smallint_column"""
try:
cursor.execute("CREATE TABLE #pytest_single_column (smallint_column SMALLINT)")
db_connection.commit()
cursor.execute("INSERT INTO #pytest_single_column (smallint_column) VALUES (?)", [32767])
db_connection.commit()
cursor.execute("SELECT smallint_column FROM #pytest_single_column")
row = cursor.fetchone()
assert row[0] == 32767, "Smallint column insertion/fetch failed"
except Exception as e:
pytest.fail(f"Smallint column insertion/fetch failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_single_column")
db_connection.commit()
def test_insert_bigint_column(cursor, db_connection):
"""Test inserting data into the bigint_column"""
try:
cursor.execute("CREATE TABLE #pytest_single_column (bigint_column BIGINT)")
db_connection.commit()
cursor.execute("INSERT INTO #pytest_single_column (bigint_column) VALUES (?)", [9223372036854775807])
db_connection.commit()
cursor.execute("SELECT bigint_column FROM #pytest_single_column")
row = cursor.fetchone()
assert row[0] == 9223372036854775807, "Bigint column insertion/fetch failed"
except Exception as e:
pytest.fail(f"Bigint column insertion/fetch failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_single_column")
db_connection.commit()
def test_insert_integer_column(cursor, db_connection):
"""Test inserting data into the integer_column"""
try:
cursor.execute("CREATE TABLE #pytest_single_column (integer_column INTEGER)")
db_connection.commit()
cursor.execute("INSERT INTO #pytest_single_column (integer_column) VALUES (?)", [2147483647])
db_connection.commit()
cursor.execute("SELECT integer_column FROM #pytest_single_column")
row = cursor.fetchone()
assert row[0] == 2147483647, "Integer column insertion/fetch failed"
except Exception as e:
pytest.fail(f"Integer column insertion/fetch failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_single_column")
db_connection.commit()
def test_insert_float_column(cursor, db_connection):
"""Test inserting data into the float_column"""
try:
cursor.execute("CREATE TABLE #pytest_single_column (float_column FLOAT)")
db_connection.commit()
cursor.execute("INSERT INTO #pytest_single_column (float_column) VALUES (?)", [1.23456789])
db_connection.commit()
cursor.execute("SELECT float_column FROM #pytest_single_column")
row = cursor.fetchone()
assert row[0] == 1.23456789, "Float column insertion/fetch failed"
except Exception as e:
pytest.fail(f"Float column insertion/fetch failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_single_column")
db_connection.commit()
# Test that VARCHAR(n) can accomodate values of size n
def test_varchar_full_capacity(cursor, db_connection):
"""Test SQL_VARCHAR"""
try:
cursor.execute("CREATE TABLE #pytest_varchar_test (varchar_column VARCHAR(9))")
db_connection.commit()
cursor.execute("INSERT INTO #pytest_varchar_test (varchar_column) VALUES (?)", ['123456789'])
db_connection.commit()
# fetchone test
cursor.execute("SELECT varchar_column FROM #pytest_varchar_test")
row = cursor.fetchone()
assert row[0] == '123456789', "SQL_VARCHAR parsing failed for fetchone"
# fetchall test
cursor.execute("SELECT varchar_column FROM #pytest_varchar_test")
rows = cursor.fetchall()
assert rows[0] == ['123456789'], "SQL_VARCHAR parsing failed for fetchall"
except Exception as e:
pytest.fail(f"SQL_VARCHAR parsing test failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_varchar_test")
db_connection.commit()
# Test that NVARCHAR(n) can accomodate values of size n
def test_wvarchar_full_capacity(cursor, db_connection):
"""Test SQL_WVARCHAR"""
try:
cursor.execute("CREATE TABLE #pytest_wvarchar_test (wvarchar_column NVARCHAR(6))")
db_connection.commit()
cursor.execute("INSERT INTO #pytest_wvarchar_test (wvarchar_column) VALUES (?)", ['123456'])
db_connection.commit()
# fetchone test
cursor.execute("SELECT wvarchar_column FROM #pytest_wvarchar_test")
row = cursor.fetchone()
assert row[0] == '123456', "SQL_WVARCHAR parsing failed for fetchone"
# fetchall test
cursor.execute("SELECT wvarchar_column FROM #pytest_wvarchar_test")
rows = cursor.fetchall()
assert rows[0] == ['123456'], "SQL_WVARCHAR parsing failed for fetchall"
except Exception as e:
pytest.fail(f"SQL_WVARCHAR parsing test failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_wvarchar_test")
db_connection.commit()
# Test that VARBINARY(n) can accomodate values of size n
def test_varbinary_full_capacity(cursor, db_connection):
"""Test SQL_VARBINARY"""
try:
cursor.execute("CREATE TABLE #pytest_varbinary_test (varbinary_column VARBINARY(8))")
db_connection.commit()
# Try inserting binary using both bytes & bytearray
cursor.execute("INSERT INTO #pytest_varbinary_test (varbinary_column) VALUES (?)", bytearray("12345", 'utf-8'))
cursor.execute("INSERT INTO #pytest_varbinary_test (varbinary_column) VALUES (?)", bytes("12345678", 'utf-8')) # Full capacity
db_connection.commit()
expectedRows = 2
# fetchone test
cursor.execute("SELECT varbinary_column FROM #pytest_varbinary_test")
rows = []
for i in range(0, expectedRows):
rows.append(cursor.fetchone())
assert cursor.fetchone() == None, "varbinary_column is expected to have only {} rows".format(expectedRows)
assert rows[0] == [bytes("12345", 'utf-8')], "SQL_VARBINARY parsing failed for fetchone - row 0"
assert rows[1] == [bytes("12345678", 'utf-8')], "SQL_VARBINARY parsing failed for fetchone - row 1"
# fetchall test
cursor.execute("SELECT varbinary_column FROM #pytest_varbinary_test")
rows = cursor.fetchall()
assert rows[0] == [bytes("12345", 'utf-8')], "SQL_VARBINARY parsing failed for fetchall - row 0"
assert rows[1] == [bytes("12345678", 'utf-8')], "SQL_VARBINARY parsing failed for fetchall - row 1"
except Exception as e:
pytest.fail(f"SQL_VARBINARY parsing test failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_varbinary_test")
db_connection.commit()
def test_varbinary_max(cursor, db_connection):
"""Test SQL_VARBINARY with MAX length"""
try:
cursor.execute("CREATE TABLE #pytest_varbinary_test (varbinary_column VARBINARY(MAX))")
db_connection.commit()
# TODO: Uncomment this execute after adding null binary support
# cursor.execute("INSERT INTO #pytest_varbinary_test (varbinary_column) VALUES (?)", [None])
cursor.execute("INSERT INTO #pytest_varbinary_test (varbinary_column) VALUES (?), (?)", [bytearray("ABCDEF", 'utf-8'), bytes("123!@#", 'utf-8')])
db_connection.commit()
expectedRows = 2
# fetchone test
cursor.execute("SELECT varbinary_column FROM #pytest_varbinary_test")
rows = []
for i in range(0, expectedRows):
rows.append(cursor.fetchone())
assert cursor.fetchone() == None, "varbinary_column is expected to have only {} rows".format(expectedRows)
assert rows[0] == [bytearray("ABCDEF", 'utf-8')], "SQL_VARBINARY parsing failed for fetchone - row 0"
assert rows[1] == [bytes("123!@#", 'utf-8')], "SQL_VARBINARY parsing failed for fetchone - row 1"
# fetchall test
cursor.execute("SELECT varbinary_column FROM #pytest_varbinary_test")
rows = cursor.fetchall()
assert rows[0] == [bytearray("ABCDEF", 'utf-8')], "SQL_VARBINARY parsing failed for fetchall - row 0"
assert rows[1] == [bytes("123!@#", 'utf-8')], "SQL_VARBINARY parsing failed for fetchall - row 1"
except Exception as e:
pytest.fail(f"SQL_VARBINARY parsing test failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_varbinary_test")
db_connection.commit()
def test_longvarchar(cursor, db_connection):
"""Test SQL_LONGVARCHAR"""
try:
cursor.execute("CREATE TABLE #pytest_longvarchar_test (longvarchar_column TEXT)")
db_connection.commit()
cursor.execute("INSERT INTO #pytest_longvarchar_test (longvarchar_column) VALUES (?), (?)", ["ABCDEFGHI", None])
db_connection.commit()
expectedRows = 2
# fetchone test
cursor.execute("SELECT longvarchar_column FROM #pytest_longvarchar_test")
rows = []
for i in range(0, expectedRows):
rows.append(cursor.fetchone())
assert cursor.fetchone() == None, "longvarchar_column is expected to have only {} rows".format(expectedRows)
assert rows[0] == ["ABCDEFGHI"], "SQL_LONGVARCHAR parsing failed for fetchone - row 0"
assert rows[1] == [None], "SQL_LONGVARCHAR parsing failed for fetchone - row 1"
# fetchall test
cursor.execute("SELECT longvarchar_column FROM #pytest_longvarchar_test")
rows = cursor.fetchall()
assert rows[0] == ["ABCDEFGHI"], "SQL_LONGVARCHAR parsing failed for fetchall - row 0"
assert rows[1] == [None], "SQL_LONGVARCHAR parsing failed for fetchall - row 1"
except Exception as e:
pytest.fail(f"SQL_LONGVARCHAR parsing test failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_longvarchar_test")
db_connection.commit()
def test_longwvarchar(cursor, db_connection):
"""Test SQL_LONGWVARCHAR"""
try:
cursor.execute("CREATE TABLE #pytest_longwvarchar_test (longwvarchar_column NTEXT)")
db_connection.commit()
cursor.execute("INSERT INTO #pytest_longwvarchar_test (longwvarchar_column) VALUES (?), (?)", ["ABCDEFGHI", None])
db_connection.commit()
expectedRows = 2
# fetchone test
cursor.execute("SELECT longwvarchar_column FROM #pytest_longwvarchar_test")
rows = []
for i in range(0, expectedRows):
rows.append(cursor.fetchone())
assert cursor.fetchone() == None, "longwvarchar_column is expected to have only {} rows".format(expectedRows)
assert rows[0] == ["ABCDEFGHI"], "SQL_LONGWVARCHAR parsing failed for fetchone - row 0"
assert rows[1] == [None], "SQL_LONGWVARCHAR parsing failed for fetchone - row 1"
# fetchall test
cursor.execute("SELECT longwvarchar_column FROM #pytest_longwvarchar_test")
rows = cursor.fetchall()
assert rows[0] == ["ABCDEFGHI"], "SQL_LONGWVARCHAR parsing failed for fetchall - row 0"
assert rows[1] == [None], "SQL_LONGWVARCHAR parsing failed for fetchall - row 1"
except Exception as e:
pytest.fail(f"SQL_LONGWVARCHAR parsing test failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_longwvarchar_test")
db_connection.commit()
def test_longvarbinary(cursor, db_connection):
"""Test SQL_LONGVARBINARY"""
try:
cursor.execute("CREATE TABLE #pytest_longvarbinary_test (longvarbinary_column IMAGE)")
db_connection.commit()
cursor.execute("INSERT INTO #pytest_longvarbinary_test (longvarbinary_column) VALUES (?), (?)", [bytearray("ABCDEFGHI", 'utf-8'), bytes("123!@#", 'utf-8')])
db_connection.commit()
expectedRows = 2 # Only 2 rows are inserted
# fetchone test
cursor.execute("SELECT longvarbinary_column FROM #pytest_longvarbinary_test")
rows = []
for i in range(0, expectedRows):
rows.append(cursor.fetchone())
assert cursor.fetchone() == None, "longvarbinary_column is expected to have only {} rows".format(expectedRows)
assert rows[0] == [bytearray("ABCDEFGHI", 'utf-8')], "SQL_LONGVARBINARY parsing failed for fetchone - row 0"
assert rows[1] == [bytes("123!@#", 'utf-8')], "SQL_LONGVARBINARY parsing failed for fetchone - row 1"
# fetchall test
cursor.execute("SELECT longvarbinary_column FROM #pytest_longvarbinary_test")
rows = cursor.fetchall()
assert rows[0] == [bytearray("ABCDEFGHI", 'utf-8')], "SQL_LONGVARBINARY parsing failed for fetchall - row 0"
assert rows[1] == [bytes("123!@#", 'utf-8')], "SQL_LONGVARBINARY parsing failed for fetchall - row 1"
except Exception as e:
pytest.fail(f"SQL_LONGVARBINARY parsing test failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_longvarbinary_test")
db_connection.commit()
def test_create_table(cursor, db_connection):
# Drop the table if it exists
drop_table_if_exists(cursor, "#pytest_all_data_types")
# Create test table
try:
cursor.execute(TEST_TABLE)
db_connection.commit()
except Exception as e:
pytest.fail(f"Table creation failed: {e}")
def test_insert_args(cursor, db_connection):
"""Test parameterized insert using qmark parameters"""
try:
cursor.execute("""
INSERT INTO #pytest_all_data_types VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
)
""",
TEST_DATA[0],
TEST_DATA[1],
TEST_DATA[2],
TEST_DATA[3],
TEST_DATA[4],
TEST_DATA[5],
TEST_DATA[6],
TEST_DATA[7],
TEST_DATA[8],
TEST_DATA[9],
TEST_DATA[10],
TEST_DATA[11]
)
db_connection.commit()
cursor.execute("SELECT * FROM #pytest_all_data_types WHERE id = 1")
row = cursor.fetchone()
assert row[0] == TEST_DATA[0], "Insertion using args failed"
except Exception as e:
pytest.fail(f"Parameterized data insertion/fetch failed: {e}")
finally:
cursor.execute("DELETE FROM #pytest_all_data_types")
db_connection.commit()
@pytest.mark.parametrize("data", PARAM_TEST_DATA)
def test_parametrized_insert(cursor, db_connection, data):
"""Test parameterized insert using qmark parameters"""
try:
cursor.execute("""
INSERT INTO #pytest_all_data_types VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
)
""", [None if v is None else v for v in data])
db_connection.commit()
except Exception as e:
pytest.fail(f"Parameterized data insertion/fetch failed: {e}")
def test_rowcount(cursor, db_connection):
"""Test rowcount after insert operations"""
try:
cursor.execute("CREATE TABLE #pytest_test_rowcount (id INT IDENTITY(1,1) PRIMARY KEY, name NVARCHAR(100))")
db_connection.commit()
cursor.execute("INSERT INTO #pytest_test_rowcount (name) VALUES ('JohnDoe1');")
assert cursor.rowcount == 1, "Rowcount should be 1 after first insert"
cursor.execute("INSERT INTO #pytest_test_rowcount (name) VALUES ('JohnDoe2');")
assert cursor.rowcount == 1, "Rowcount should be 1 after second insert"
cursor.execute("INSERT INTO #pytest_test_rowcount (name) VALUES ('JohnDoe3');")
assert cursor.rowcount == 1, "Rowcount should be 1 after third insert"
cursor.execute("""
INSERT INTO #pytest_test_rowcount (name)
VALUES
('JohnDoe4'),
('JohnDoe5'),
('JohnDoe6');
""")
assert cursor.rowcount == 3, "Rowcount should be 3 after inserting multiple rows"
cursor.execute("SELECT * FROM #pytest_test_rowcount;")
assert cursor.rowcount == -1, "Rowcount should be -1 after a SELECT statement"
db_connection.commit()
except Exception as e:
pytest.fail(f"Rowcount test failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_test_rowcount")
db_connection.commit()
def test_rowcount_executemany(cursor, db_connection):
"""Test rowcount after executemany operations"""
try:
cursor.execute("CREATE TABLE #pytest_test_rowcount (id INT IDENTITY(1,1) PRIMARY KEY, name NVARCHAR(100))")
db_connection.commit()
data = [
('JohnDoe1',),
('JohnDoe2',),
('JohnDoe3',)
]
cursor.executemany("INSERT INTO #pytest_test_rowcount (name) VALUES (?)", data)
assert cursor.rowcount == 3, "Rowcount should be 3 after executemany insert"
cursor.execute("SELECT * FROM #pytest_test_rowcount;")
assert cursor.rowcount == -1, "Rowcount should be -1 after a SELECT statement"
db_connection.commit()
except Exception as e:
pytest.fail(f"Rowcount executemany test failed: {e}")
finally:
cursor.execute("DROP TABLE #pytest_test_rowcount")
db_connection.commit()
def test_fetchone(cursor):
"""Test fetching a single row"""
cursor.execute("SELECT * FROM #pytest_all_data_types WHERE id = 1")
row = cursor.fetchone()
assert row is not None, "No row returned"
assert len(row) == 12, "Incorrect number of columns"
def test_fetchmany(cursor):
"""Test fetching multiple rows"""
cursor.execute("SELECT * FROM #pytest_all_data_types")
rows = cursor.fetchmany(2)
assert isinstance(rows, list), "fetchmany should return a list"
assert len(rows) == 2, "Incorrect number of rows returned"
def test_fetchmany_with_arraysize(cursor, db_connection):
"""Test fetchmany with arraysize"""
cursor.arraysize = 3
cursor.execute("SELECT * FROM #pytest_all_data_types")
rows = cursor.fetchmany()
assert len(rows) == 3, "fetchmany with arraysize returned incorrect number of rows"
def test_fetchall(cursor):
"""Test fetching all rows"""
cursor.execute("SELECT * FROM #pytest_all_data_types")
rows = cursor.fetchall()
assert isinstance(rows, list), "fetchall should return a list"
assert len(rows) == len(PARAM_TEST_DATA), "Incorrect number of rows returned"
def test_execute_invalid_query(cursor):
"""Test executing an invalid query"""
with pytest.raises(Exception):
cursor.execute("SELECT * FROM invalid_table")
# def test_fetch_data_types(cursor):
# """Test data types"""
# cursor.execute("SELECT * FROM all_data_types WHERE id = 1")
# row = cursor.fetchall()[0]
# print("ROW!!!", row)
# assert row[0] == TEST_DATA[0], "Integer mismatch"
# assert row[1] == TEST_DATA[1], "Bit mismatch"
# assert row[2] == TEST_DATA[2], "Tinyint mismatch"
# assert row[3] == TEST_DATA[3], "Smallint mismatch"
# assert row[4] == TEST_DATA[4], "Bigint mismatch"
# assert row[5] == TEST_DATA[5], "Integer mismatch"
# assert round(row[6], 5) == round(TEST_DATA[6], 5), "Float mismatch"
# assert row[7] == TEST_DATA[7], "Nvarchar mismatch"
# assert row[8] == TEST_DATA[8], "Time mismatch"
# assert row[9] == TEST_DATA[9], "Datetime mismatch"
# assert row[10] == TEST_DATA[10], "Date mismatch"
# assert round(row[11], 5) == round(TEST_DATA[11], 5), "Real mismatch"
def test_arraysize(cursor):
"""Test arraysize"""
cursor.arraysize = 10
assert cursor.arraysize == 10, "Arraysize mismatch"
cursor.arraysize = 5
assert cursor.arraysize == 5, "Arraysize mismatch after change"
def test_description(cursor):
"""Test description"""
cursor.execute("SELECT * FROM #pytest_all_data_types WHERE id = 1")
desc = cursor.description
assert len(desc) == 12, "Description length mismatch"
assert desc[0][0] == "id", "Description column name mismatch"
# def test_setinputsizes(cursor):
# """Test setinputsizes"""
# sizes = [(mssql_python.ConstantsDDBC.SQL_INTEGER, 10), (mssql_python.ConstantsDDBC.SQL_VARCHAR, 255)]
# cursor.setinputsizes(sizes)
# def test_setoutputsize(cursor):
# """Test setoutputsize"""
# cursor.setoutputsize(10, mssql_python.ConstantsDDBC.SQL_INTEGER)
def test_execute_many(cursor, db_connection):
"""Test executemany"""
# Start fresh
cursor.execute("DELETE FROM #pytest_all_data_types")
db_connection.commit()
data = [(i,) for i in range(1, 12)]
cursor.executemany("INSERT INTO #pytest_all_data_types (id) VALUES (?)", data)
cursor.execute("SELECT COUNT(*) FROM #pytest_all_data_types")
count = cursor.fetchone()[0]
assert count == 11, "Executemany failed"
def test_executemany_empty_strings(cursor, db_connection):
"""Test executemany with empty strings - regression test for Unix UTF-16 conversion issue"""
try:
# Create test table for empty string testing
cursor.execute("""
CREATE TABLE #pytest_empty_batch (
id INT,
data NVARCHAR(50)
)
""")
# Clear any existing data
cursor.execute("DELETE FROM #pytest_empty_batch")
db_connection.commit()
# Test data with mix of empty strings and regular strings
test_data = [
(1, ''),
(2, 'non-empty'),
(3, ''),
(4, 'another'),
(5, '')
]
# Execute the batch insert
cursor.executemany("INSERT INTO #pytest_empty_batch VALUES (?, ?)", test_data)
db_connection.commit()
# Verify the data was inserted correctly
cursor.execute("SELECT id, data FROM #pytest_empty_batch ORDER BY id")
results = cursor.fetchall()
# Check that we got the right number of rows
assert len(results) == 5, f"Expected 5 rows, got {len(results)}"
# Check each row individually
expected = [
(1, ''),
(2, 'non-empty'),
(3, ''),
(4, 'another'),
(5, '')
]
for i, (actual, expected_row) in enumerate(zip(results, expected)):
assert actual[0] == expected_row[0], f"Row {i}: ID mismatch - expected {expected_row[0]}, got {actual[0]}"
assert actual[1] == expected_row[1], f"Row {i}: Data mismatch - expected '{expected_row[1]}', got '{actual[1]}'"
except Exception as e:
pytest.fail(f"Executemany with empty strings failed: {e}")
finally:
cursor.execute("DROP TABLE IF EXISTS #pytest_empty_batch")
db_connection.commit()
def test_executemany_empty_strings_various_types(cursor, db_connection):
"""Test executemany with empty strings in different column types"""
try:
# Create test table with different string types
cursor.execute("""
CREATE TABLE #pytest_string_types (
id INT,
varchar_col VARCHAR(50),
nvarchar_col NVARCHAR(50),
text_col TEXT,
ntext_col NTEXT
)
""")
# Clear any existing data
cursor.execute("DELETE FROM #pytest_string_types")
db_connection.commit()
# Test data with empty strings for different column types
test_data = [
(1, '', '', '', ''),
(2, 'varchar', 'nvarchar', 'text', 'ntext'),
(3, '', '', '', ''),
]
# Execute the batch insert
cursor.executemany(
"INSERT INTO #pytest_string_types VALUES (?, ?, ?, ?, ?)",
test_data
)
db_connection.commit()
# Verify the data was inserted correctly
cursor.execute("SELECT * FROM #pytest_string_types ORDER BY id")
results = cursor.fetchall()
# Check that we got the right number of rows
assert len(results) == 3, f"Expected 3 rows, got {len(results)}"
# Check each row
for i, (actual, expected_row) in enumerate(zip(results, test_data)):
for j, (actual_val, expected_val) in enumerate(zip(actual, expected_row)):
assert actual_val == expected_val, f"Row {i}, Col {j}: expected '{expected_val}', got '{actual_val}'"
except Exception as e:
pytest.fail(f"Executemany with empty strings in various types failed: {e}")
finally:
cursor.execute("DROP TABLE IF EXISTS #pytest_string_types")
db_connection.commit()
def test_executemany_unicode_and_empty_strings(cursor, db_connection):
"""Test executemany with mix of Unicode characters and empty strings"""
try:
# Create test table
cursor.execute("""
CREATE TABLE #pytest_unicode_test (
id INT,
data NVARCHAR(100)
)
""")
# Clear any existing data
cursor.execute("DELETE FROM #pytest_unicode_test")
db_connection.commit()
# Test data with Unicode and empty strings
test_data = [
(1, ''),
(2, 'Hello 😄'),
(3, ''),
(4, '中文'),
(5, ''),
(6, 'Ñice tëxt'),
(7, ''),
]
# Execute the batch insert
cursor.executemany("INSERT INTO #pytest_unicode_test VALUES (?, ?)", test_data)
db_connection.commit()
# Verify the data was inserted correctly
cursor.execute("SELECT id, data FROM #pytest_unicode_test ORDER BY id")
results = cursor.fetchall()
# Check that we got the right number of rows
assert len(results) == 7, f"Expected 7 rows, got {len(results)}"
# Check each row
for i, (actual, expected_row) in enumerate(zip(results, test_data)):
assert actual[0] == expected_row[0], f"Row {i}: ID mismatch"
assert actual[1] == expected_row[1], f"Row {i}: Data mismatch - expected '{expected_row[1]}', got '{actual[1]}'"
except Exception as e:
pytest.fail(f"Executemany with Unicode and empty strings failed: {e}")
finally:
cursor.execute("DROP TABLE IF EXISTS #pytest_unicode_test")
db_connection.commit()
def test_executemany_large_batch_with_empty_strings(cursor, db_connection):
"""Test executemany with large batch containing empty strings"""
try:
# Create test table
cursor.execute("""
CREATE TABLE #pytest_large_batch (
id INT,
data NVARCHAR(50)
)
""")
# Clear any existing data
cursor.execute("DELETE FROM #pytest_large_batch")
db_connection.commit()