6
0
mirror of https://github.com/FirebirdSQL/firebird-qa.git synced 2025-02-02 02:40:42 +01:00

More python tests

This commit is contained in:
Pavel Císař 2021-11-16 19:44:53 +01:00
parent 8858dfd25b
commit 7822a79624
32 changed files with 2251 additions and 1322 deletions

View File

@ -9,7 +9,7 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from firebird.qa import db_factory, python_act, Action
# version: 2.5
# resources: None
@ -34,7 +34,8 @@ db_1 = db_factory(page_size=4096, sql_dialect=3, init=init_script_1)
# c.execute(cmd,['asd'])
# printData(c)
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
act_1 = python_act('db_1', substitutions=substitutions_1)
expected_stdout_1 = """O
----------
@ -42,8 +43,21 @@ asd
"""
@pytest.mark.version('>=2.5')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action, capsys):
with act_1.db.connect() as con:
c = con.cursor()
cmd = c.prepare("""execute block (i varchar(10) = ?) returns (o varchar(10))
as
begin
o = coalesce(cast(o as date), current_date);
o = i;
suspend;
end""")
c.execute(cmd, ['asd'])
act_1.print_data(c)
#
act_1.expected_stdout = expected_stdout_1
act_1.stdout = capsys.readouterr().out
assert act_1.clean_stdout == act_1.clean_expected_stdout

View File

@ -20,7 +20,8 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from difflib import unified_diff
from firebird.qa import db_factory, python_act, Action
# version: 3.0
# resources: None
@ -257,12 +258,35 @@ db_1 = db_factory(charset='UTF8', sql_dialect=3, init=init_script_1)
#
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
act_1 = python_act('db_1', substitutions=substitutions_1)
@pytest.mark.version('>=3.0')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action):
# Extract metadata
act_1.isql(switches=['-x'])
initial_meta = act_1.stdout
# Clear all
ddl_clear_all = '''
drop package pg_test;
drop function fn_test;
drop procedure sp_test;
drop table test;
drop domain dm_test;
drop collation name_coll;
drop collation nums_coll;
commit;
'''
act_1.reset()
act_1.isql(switches=[], input=ddl_clear_all)
# Recreate metadata
act_1.reset()
act_1.isql(switches=[], input=initial_meta)
# Extract metadata again
act_1.reset()
act_1.isql(switches=['-x'])
current_meta = act_1.stdout
# Compare metadata
meta_diff = '\n'.join(unified_diff(initial_meta.splitlines(), current_meta.splitlines()))
assert meta_diff == ''

View File

@ -9,7 +9,8 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from firebird.qa import db_factory, python_act, Action
from firebird.driver import DatabaseError
# version: 2.5
# resources: None
@ -52,14 +53,33 @@ db_1 = db_factory(page_size=4096, sql_dialect=3, init=init_script_1)
# print ('Execution OK')
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
expected_stdout_1 = """Execution OK
"""
act_1 = python_act('db_1', substitutions=substitutions_1)
@pytest.mark.version('>=2.5')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action):
with act_1.db.connect() as con:
c = con.cursor()
# Test fails if next raises an exception
try:
c.execute("""execute block as
declare datedoc date;
declare cod int;
declare num int;
declare name int;
declare summa int;
begin
for execute statement (
' select s.cod,s.num, s.name,sum(g.summa) from sch s
left join getschdet(s.cod,:datedoc ,:datedoc,0,0,0,0,0,0,0,0,0,0,0,1,3) g on 1=1
where s.num in (''50'',''51'') and s.udl<>''У'' and s.root=1
and not exists (select s2.cod from sch s2 where s2.prevcod=s.cod)
group by 1,2,3') (datedoc := :datedoc)
into :cod, :num, :name, :summa
do exit;
end""")
except DatabaseError as exc:
pytest.fail(f"SQL execution failed with: {str(exc)}")

View File

@ -9,7 +9,9 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
import datetime
from firebird.qa import db_factory, python_act, Action
from firebird.driver import DatabaseError
# version: 2.1.3
# resources: None
@ -33,12 +35,15 @@ db_1 = db_factory(page_size=4096, sql_dialect=3, init=init_script_1)
# MATCHING(FIELD1)""",[datetime.datetime(2011,5,1)])
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
act_1 = python_act('db_1', substitutions=substitutions_1)
@pytest.mark.version('>=2.1.3')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action):
with act_1.db.connect() as con:
c = con.cursor()
c.execute("""UPDATE OR INSERT INTO TABLE_TXT (FIELD1)
VALUES (CAST(? AS TIMESTAMP))
MATCHING(FIELD1)""", [datetime.datetime(2011,5,1)])

View File

@ -12,16 +12,15 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from pathlib import Path
from firebird.qa import db_factory, python_act, Action, temp_file
# version: 2.1.3
# resources: None
substitutions_1 = []
init_script_1 = """create table EXT1 external file '$(DATABASE_LOCATION)EXT1.TBL'
(PK INTEGER);
"""
init_script_1 = """"""
db_1 = db_factory(page_size=4096, sql_dialect=3, init=init_script_1)
@ -51,16 +50,24 @@ db_1 = db_factory(page_size=4096, sql_dialect=3, init=init_script_1)
# print("Error while removing external table file")
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
expected_stdout_1 = """PK
-----------
1
"""
act_1 = python_act('db_1', substitutions=substitutions_1)
external_table = temp_file('EXT1.TBL')
@pytest.mark.version('>=2.1.3')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action, external_table: Path):
# Create external table
act_1.isql(switches=[],
input=f"create table EXT1 external file '{str(external_table)}' (PK INTEGER); exit;")
# session A
with act_1.db.connect() as con:
c = con.cursor()
c.execute("insert into EXT1 (PK) values (1)")
con.commit()
# session B
with act_1.db.connect() as con:
c = con.cursor()
c.execute('select * from EXT1')
result = c.fetchall()
assert result == [(1, )]

View File

@ -36,6 +36,9 @@
# 40CS, build 4.0.0.955: OK, 11.219s.
# 40SS, build 4.0.0.967: OK, 12.718s.
#
# [pcisar] 16.11.2021
# This test is too complicated and fragile, and it's IMHO not worth to be implemented
#
# tracker_id: CORE-2477
# min_versions: ['2.5.0']
# versions: 2.5

View File

@ -51,12 +51,17 @@
# qmid:
import pytest
from firebird.qa import db_factory, isql_act, Action
from pathlib import Path
from firebird.qa import db_factory, python_act, Action, temp_file
# version: 3.0
# resources: None
substitutions_1 = [('SQLSTATE = 08004', 'SQLSTATE = 08001')]
substitutions_1 = [('SQLSTATE = 08004', 'SQLSTATE = 08001'),
('I/O error during.*', ''),
('-File size is less than expected', ''),
('-Error while.*', ''),
('Use CONNECT or CREATE DATABASE to specify a database', '')]
init_script_1 = """"""
@ -164,15 +169,24 @@ db_1 = db_factory(charset='UTF8', sql_dialect=3, init=init_script_1)
#
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
expected_stdout_1 = """
act_1 = python_act('db_1', substitutions=substitutions_1)
expected_stderr_1 = """
Statement failed, SQLSTATE = 08001
"""
fake_db = temp_file('tmp_2484_fake.fdb')
@pytest.mark.version('>=3.0')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action, fake_db: Path):
fake_db.write_bytes(bytes([1, 2, 3, 4, 5, 6, 0]))
act_1.expected_stdout = ''
act_1.expected_stderr = expected_stderr_1
act_1.isql(switches=['-user', act_1.db.user, '-password', act_1.db.password, str(fake_db)],
connect_db=False,
input='set heading off; select current_timestamp from rdb$database; quit;')
assert act_1.clean_stderr == act_1.clean_expected_stderr
assert act_1.clean_stdout == act_1.clean_expected_stdout

View File

@ -45,16 +45,18 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from firebird.qa import db_factory, python_act, Action
# version: 2.5
# resources: None
substitutions_1 = [('SQL_TEXT_BLOB_ID .*', ''), ('[\t ]+', ' ')]
init_script_1 = """"""
init_script_1 = """
recreate table non_ascii(stored_sql_expr varchar(255) character set win1252);
"""
db_1 = db_factory(sql_dialect=3, init=init_script_1)
db_1 = db_factory(sql_dialect=3, init=init_script_1, charset='WIN1252')
# test_script_1
#---
@ -71,9 +73,7 @@ db_1 = db_factory(sql_dialect=3, init=init_script_1)
# db_conn.close()
#
# svc = services.connect()
# FB_HOME = os.path.normpath( svc.get_home_directory() ) # 'c:
# irebird' --> 'c:
# irebird' (i.e. remove trailing backslash if needed)
# FB_HOME = os.path.normpath( svc.get_home_directory() ) # 'c:\\firebird\\' --> 'c:\\firebird' (i.e. remove trailing backslash if needed)
# svc.close()
#
# FB_CLNT = '<UNKNOWN>'
@ -207,7 +207,8 @@ db_1 = db_factory(sql_dialect=3, init=init_script_1)
#
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
act_1 = python_act('db_1', substitutions=substitutions_1)
expected_stdout_1 = """
STORED_SQL_EXPR select 'gång' as non_ascii_literal from rdb$database
@ -218,8 +219,32 @@ expected_stdout_1 = """
"""
@pytest.mark.version('>=2.5')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action):
non_ascii_query = "select 'gång' as non_ascii_literal from rdb$database"
non_ascii_query_inline = non_ascii_query.replace("'","''")
script = '''
set count on;
set blob all;
set list on;
select stored_sql_expr from non_ascii;
select
c.rdb$character_set_name as connection_charset
,s.mon$sql_text as sql_text_blob_id
from mon$attachments a
left join rdb$character_sets c on a.mon$character_set_id = c.rdb$character_set_id
left join mon$statements s on a.mon$attachment_id = s.mon$attachment_id
where
s.mon$attachment_id <> current_connection
and s.mon$sql_text containing 'non_ascii_literal'
;
'''
act_1.expected_stdout = expected_stdout_1
with act_1.db.connect(charset='WIN1252') as con:
c = con.cursor()
c.execute(f"insert into non_ascii(stored_sql_expr) values('{non_ascii_query_inline}')")
con.commit()
x = c.prepare(non_ascii_query)
act_1.isql(switches=[], input=script, charset='WIN1252')
assert act_1.clean_stdout == act_1.clean_expected_stdout

View File

@ -9,7 +9,7 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from firebird.qa import db_factory, python_act, Action
# version: 2.5
# resources: None
@ -42,12 +42,27 @@ db_1 = db_factory(page_size=4096, sql_dialect=3, init=init_script_1)
# db_conn.commit()
# db_conn.close()
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
act_1 = python_act('db_1', substitutions=substitutions_1)
@pytest.mark.version('>=2.5')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action):
sql = """CREATE OR ALTER TRIGGER DIST
ON DISCONNECT POSITION 0
AS
declare variable i integer;
begin
select mon$stat_id from mon$attachments rows 1 into :i;
end
"""
with act_1.db.connect() as con:
c = con.cursor()
c.execute(sql)
con.commit()
# The server should could be crashed at this point
with act_1.db.connect() as con:
c = con.cursor()
c.execute('DROP TRIGGER DIST')
con.commit()

View File

@ -34,7 +34,7 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from firebird.qa import db_factory, python_act, Action
# version: 2.5
# resources: None
@ -127,7 +127,8 @@ db_1 = db_factory(charset='UTF8', sql_dialect=3, init=init_script_1)
# c2utf8.close()
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
act_1 = python_act('db_1', substitutions=substitutions_1)
expected_stdout_1 = """
Attach: r2none. othr ; sql_text_hash: 98490476833044645 ; charset_name NONE
@ -137,8 +138,57 @@ expected_stdout_1 = """
"""
@pytest.mark.version('>=2.5')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action, capsys):
with act_1.db.connect(charset='UTF8') as con1_utf8, \
act_1.db.connect(charset='NONE') as con2_none, \
act_1.db.connect(charset='UTF8') as con2_utf8:
with act_1.db.connect(charset='NONE') as con1_none:
r1none = con1_none.cursor()
r1utf8 = con1_utf8.cursor()
r2none = con2_none.cursor()
r2utf8 = con2_utf8.cursor()
# In attachment with charset = NONE we start query to mon$database which includes two non-ascii characters:
# 1) Unicode Character 'LATIN SMALL LETTER A WITH ACUTE' (U+00E1)
# 2) Unicode Character 'LATIN SMALL LETTER E WITH ACUTE' (U+00E9)
r1none.execute("select '123áé456' from mon$database")
sql = '''
select
iif(s.mon$attachment_id = current_connection, 'this', 'othr') as attach
-- do NOT return SQL text of query with non-ascii characters: it can be displayed differently
-- depending on machine codepage (or OS?):
-- >>> disabled 05-feb-2018 >>> , iif(s.mon$sql_text like '%123%456%', s.mon$sql_text, '') as sql_text
-- Use HASH(sql_text) instead. Bug (in 2.1.3) still can be reproduces with hash() also:
,hash(s.mon$sql_text) as sql_text_hash
,trim(c.rdb$character_set_name) as charset_name
from mon$statements s
join mon$attachments a on s.mon$attachment_id = a.mon$attachment_id
join rdb$character_sets c on a.mon$character_set_id = c.rdb$character_set_id
where
s.mon$attachment_id != current_connection
and s.mon$sql_text NOT containing 'mon$statements'
and s.mon$sql_text NOT containing 'rdb$auth'
and a.mon$remote_protocol is not null
'''
r2none.execute(sql)
for r in r2none:
print(' '.join(('Attach: r2none.', r[0], '; sql_text_hash: ', str(r[1]), '; charset_name', r[2])))
r2utf8.execute(sql)
for r in r2utf8:
print(' '.join(('Attach: r2utf8.', r[0], '; sql_text_hash: ', str(r[1]), '; charset_name', r[2])))
r1utf8.execute("select '123áé456' from mon$database")
con2_none.commit()
con2_utf8.commit()
r2none.execute(sql)
for r in r2none:
print(' '.join(('Attach: r2none.', r[0], '; sql_text_hash: ', str(r[1]), '; charset_name', r[2])))
r2utf8.execute(sql)
for r in r2utf8:
print(' '.join(('Attach: r2utf8.', r[0], '; sql_text_hash: ', str(r[1]), '; charset_name', r[2])))
#
act_1.expected_stdout = expected_stdout_1
act_1.stdout = capsys.readouterr().out
assert act_1.clean_stdout == act_1.clean_expected_stdout

View File

@ -9,7 +9,7 @@
# qmid:
import pytest
from firebird.qa import db_factory, isql_act, Action
from firebird.qa import db_factory, python_act, Action
# version: 3.0
# resources: None
@ -55,14 +55,36 @@ db_1 = db_factory(sql_dialect=3, init=init_script_1)
#
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
expected_stdout_1 = """
act_1 = python_act('db_1', substitutions=substitutions_1)
test_script_1 = """
set list on;
select s.rdb$character_set_name as client_charset
from mon$attachments a
join rdb$character_sets s on a.mon$character_set_id = s.rdb$character_set_id
where a.mon$attachment_id=current_connection;
--set sqlda_display on;
--set planonly;
--set echo on;
select cast('A' as char character set utf8) || '.' as char1_utf8 from rdb$database;
select cast('A' as varchar(1) character set utf8) || '.' as varc1_utf8 from rdb$database;
select cast('A' as char character set ascii) || '.' char1_ascii from rdb$database;
select cast('A' as varchar(1) character set ascii) || '.' varc1_ascii from rdb$database;
"""
expected_stdout_1_a = """
CLIENT_CHARSET UTF8
CHAR1_UTF8 A.
VARC1_UTF8 A.
CHAR1_ASCII A.
VARC1_ASCII A.
"""
expected_stdout_1_b = """
CLIENT_CHARSET SJIS_0208
CHAR1_UTF8 A.
VARC1_UTF8 A.
@ -71,8 +93,18 @@ expected_stdout_1 = """
"""
@pytest.mark.version('>=3.0')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action):
act_1.expected_stdout = expected_stdout_1_a
act_1.script = test_script_1
act_1.charset = 'UTF8'
act_1.execute()
assert act_1.clean_stdout == act_1.clean_expected_stdout
act_1.reset()
act_1.expected_stdout = expected_stdout_1_b
act_1.script = test_script_1
act_1.charset = 'SJIS_0208'
act_1.execute()
assert act_1.clean_stdout == act_1.clean_expected_stdout

View File

@ -9,7 +9,7 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from firebird.qa import db_factory, python_act, Action
# version: 2.5
# resources: None
@ -35,7 +35,8 @@ db_1 = db_factory(charset='UTF8', sql_dialect=3, init=init_script_1)
# con2.close()
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
act_1 = python_act('db_1', substitutions=substitutions_1)
expected_stdout_1 = """
select mon$sql_text from mon$statements s where s.mon$sql_text containing '_dos850'
@ -43,8 +44,18 @@ expected_stdout_1 = """
"""
@pytest.mark.version('>=2.5')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action, capsys):
act_1.expected_stdout = expected_stdout_1
with act_1.db.connect() as con1:
c1 = con.cursor()
with act_1.db.connect() as con2:
c2 = con.cursor()
c1.execute("select _dos850 '123áé456' from rdb$database")
c2.execute("select mon$sql_text from mon$statements s where s.mon$sql_text containing '_dos850'")
for r in c2:
print(r[0])
act_1.stdout = capsys.readouterr().out
assert act_1.clean_stdout == act_1.clean_expected_stdout

View File

@ -9,12 +9,13 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from firebird.qa import db_factory, python_act, Action
# version: 2.5
# resources: None
substitutions_1 = []
substitutions_1 = [('[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9]', ''),
('Relation [0-9]{3,4}', 'Relation')]
init_script_1 = """set term ^;
recreate table t (id int, sss varchar(255)) ^
@ -61,12 +62,25 @@ db_1 = db_factory(page_size=4096, sql_dialect=3, init=init_script_1)
# db_conn.close()
# runProgram('gfix',['-validate','-full','-no_update','-user',user_name,'-password',user_password,dsn])
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
act_1 = python_act('db_1', substitutions=substitutions_1)
expected_stdout_1 = """
Validation started
Relation (T)
process pointer page 0 of 1
Index 1 (T_ID_DESC)
Index 2 (T_ID_ASC)
Index 3 (T_ID_SSS_DESC)
Index 4 (T_ID_SSS_ASC)
Relation (T) is ok
Validation finished
"""
@pytest.mark.version('>=2.5')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action):
act_1.expected_stdout = expected_stdout_1
with act_1.connect_server() as srv:
srv.database.validate(database=str(act_1.db.db_path))
act_1.stdout = '\n'.join(srv.readlines())
assert act_1.clean_stdout == act_1.clean_expected_stdout

View File

@ -9,7 +9,7 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from firebird.qa import db_factory, python_act, Action
# version: 2.5
# resources: None
@ -35,12 +35,16 @@ db_1 = db_factory(page_size=4096, sql_dialect=3, init=init_script_1)
# finally:
# con.close()
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
act_1 = python_act('db_1', substitutions=substitutions_1)
@pytest.mark.version('>=2.5')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action):
with act_1.db.connect(charset='CP943C') as con:
c = con.cursor()
try:
c.execute("select * from TEST_NONE")
except:
pytest.fail("Test FAILED")

View File

@ -35,7 +35,13 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
import time
import subprocess
import re
from pathlib import Path
from difflib import unified_diff
from firebird.qa import db_factory, python_act, Action, temp_file
from firebird.driver import DbWriteMode, ShutdownMode, ShutdownMethod
# version: 2.5.2
# resources: None
@ -253,15 +259,77 @@ db_1 = db_factory(sql_dialect=3, init=init_script_1)
# cleanup( [x.name for x in (f_init_log,f_work_sql,f_work_log,f_fblog_before,f_fblog_after,f_diff_txt) ] )
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
act_1 = python_act('db_1', substitutions=substitutions_1)
expected_stdout_1 = """
Expected line FOUND.
"""
work_script_1 = temp_file('work_script.sql')
@pytest.mark.version('>=2.5.2')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action, work_script_1: Path):
work_script_1.write_text('''
recreate table test(s varchar(36) unique);
insert into test(s) values('LOCKED_FOR_PAUSE');
commit;
set transaction read committed WAIT;
update test set s = s where s = 'LOCKED_FOR_PAUSE';
set term ^;
execute block as
declare n int = 150;
declare v_role varchar(31);
begin
while (n > 0) do
in autonomous transaction do
insert into test(s) values( rpad('', 36, uuid_to_char(gen_uuid()) ) )
returning :n-1 into n;
v_role = left(replace( uuid_to_char(gen_uuid()), '-', ''), 31);
begin
execute statement ('update test set s = s where s = ?') ('LOCKED_FOR_PAUSE')
on external
'localhost:' || rdb$get_context('SYSTEM', 'DB_NAME')
as user 'SYSDBA' password 'masterkey' role v_role
with autonomous transaction;
when any do
begin
end
end
end
^
set term ;^
set heading off;
select '-- shutdown me now --' from rdb$database;
''')
with act_1.connect_server() as srv:
srv.database.set_sweep_interval(database=str(act_1.db.db_path), interval=100)
srv.database.set_write_mode(database=str(act_1.db.db_path), mode=DbWriteMode.ASYNC)
p_work_sql = subprocess.Popen([act_1.vars['isql'], '-i', str(work_script_1),
'-user', act_1.db.user,
'-password', act_1.db.password, act_1.db.dsn],
stderr = subprocess.STDOUT)
time.sleep(3)
srv.database.shutdown(database=str(act_1.db.db_path), mode=ShutdownMode.FULL,
method=ShutdownMethod.FORCED, timeout=0)
p_work_sql.terminate()
srv.database.bring_online(database=str(act_1.db.db_path))
srv.info.get_log()
fblog_before = srv.readlines()
with act_1.db.connect() as con_for_sweep_start:
con_for_sweep_start.begin()
time.sleep(2)
srv.info.get_log()
fblog_after = srv.readlines()
pattern = re.compile('Sweep\\s+.*SWEEPER', re.IGNORECASE)
success = False
for line in unified_diff(fblog_before, fblog_after):
if line.startswith('+') and pattern.search(line):
success = True
assert success

View File

@ -10,7 +10,8 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from firebird.qa import db_factory, python_act, Action
from firebird.driver import DatabaseError
# version: 3.0
# resources: None
@ -55,17 +56,22 @@ db_1 = db_factory(sql_dialect=3, init=init_script_1)
# att2.close()
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
expected_stdout_1 = """
Error while preparing SQL statement:
- SQLCODE: -219
- table id 128 is not defined
"""
act_1 = python_act('db_1', substitutions=substitutions_1)
@pytest.mark.version('>=3.0')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action, capsys):
with act_1.db.connect() as att1:
cur1 = att1.cursor()
cur1.execute("recreate table test(x int)")
att1.commit()
cur1.execute("insert into test values(1)")
att1.commit()
with act_1.db.connect() as att2:
cur2 = att2.cursor()
cur2.execute("select 1 from rdb$database")
cur1.execute("drop table test")
with pytest.raises(DatabaseError, match='.*table id [0-9]+ is not defined.*'):
cur2.prepare("update test set x=-x")
att2.commit()

View File

@ -16,7 +16,7 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from firebird.qa import db_factory, python_act, Action
# version: 3.0
# resources: None
@ -212,9 +212,10 @@ db_1 = db_factory(charset='UTF8', sql_dialect=3, init=init_script_1)
#
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
expected_stdout_1 = """
act_1 = python_act('db_1', substitutions=substitutions_1)
expected_stdout_1_a = """
ID 2
CURRENT_CONNECTION_CSET NONE
SQL_TEXT
@ -236,7 +237,9 @@ expected_stdout_1 = """
Τα πάντα ήταν επιτυχής
DDL_EVENT CREATE TABLE
OBJECT_NAME T1
"""
expected_stdout_1_b = """
ID 6
CURRENT_CONNECTION_CSET UTF8
SQL_TEXT 80:0
@ -261,8 +264,34 @@ expected_stdout_1 = """
"""
@pytest.mark.version('>=3.0')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action):
sql_check = '''
delete from ddl_log;
commit;
create domain dm_name varchar(50) check (value in ('αμορτισέρ', 'κόμβο', 'σωλήνα', 'φέροντα', 'βραχίονα'));
recreate table t1 (
saller_id integer -- αναγνωριστικό εμπόρου // ID of saler
,customer_id integer -- αναγνωριστικό πελάτη // ID of customer
,product_name dm_name
);
commit;
set list on;
select id, current_connection_cset, sql_text, result_info, ddl_event, object_name
from ddl_log order by id;
commit;
drop table t1;
drop domain dm_name;
exit;
'''
#
act_1.expected_stdout = expected_stdout_1_a
act_1.isql(switches=[], charset='NONE', input=sql_check)
assert act_1.clean_stdout == act_1.clean_expected_stdout
#
act_1.reset()
act_1.expected_stdout = expected_stdout_1_b
act_1.isql(switches=[], charset='UTF8', input=sql_check)
assert act_1.clean_stdout == act_1.clean_expected_stdout

View File

@ -10,7 +10,7 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from firebird.qa import db_factory, python_act, Action
# version: 3.0
# resources: None
@ -142,24 +142,57 @@ db_1 = db_factory(sql_dialect=3, init=init_script_1)
#
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
act_1 = python_act('db_1', substitutions=substitutions_1)
expected_stdout_1 = """
DM_TEST ARRAY OF [2]
CHAR(1) CHARACTER SET ISO8859_1 Nullable
"""
expected_stderr_1_a = """
Statement failed, SQLSTATE = 42000
Dynamic SQL Error
-SQL error code = -104
-Token unknown - line 1, column 57
-[
DM_TEST ARRAY OF [2]
CHAR(1) CHARACTER SET ISO8859_1 Nullable
"""
expected_stderr_1 = """
expected_stderr_1_b = """
There is no domain DM_TEST in this database
"""
@pytest.mark.version('>=3.0')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action):
sql_ddl = ''' create domain dm_test as char(1) character set iso8859_1[1:2];
create domain dm_test as char(1)[1:2] character set iso8859_1;
commit;
show domain dm_test;
'''
act_1.expected_stderr = expected_stderr_1_a
act_1.expected_stdout = expected_stdout_1
act_1.isql(switches=[], input=sql_ddl)
assert act_1.clean_stderr == act_1.clean_expected_stderr
assert act_1.clean_stdout == act_1.clean_expected_stdout
#
act_1.reset()
act_1.isql(switches=['-x'])
xmeta = act_1.stdout
#
with act_1.db.connect() as con:
c = con.cursor()
c.execute('drop domain dm_test')
con.commit()
#
act_1.reset()
act_1.expected_stderr = expected_stderr_1_b
act_1.isql(switches=['-q'], input='show domain dm_test;')
assert act_1.clean_stderr == act_1.clean_expected_stderr
#
act_1.reset()
act_1.isql(switches=[], input=xmeta)
#
act_1.reset()
act_1.expected_stdout = expected_stdout_1
act_1.isql(switches=['-q'], input='show domain dm_test;')
assert act_1.clean_stdout == act_1.clean_expected_stdout

View File

@ -10,7 +10,7 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from firebird.qa import db_factory, python_act, Action
# version: 2.5
# resources: None
@ -85,12 +85,16 @@ db_1 = db_factory(sql_dialect=3, init=init_script_1)
# att2.close()
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
act_1 = python_act('db_1', substitutions=substitutions_1)
@pytest.mark.version('>=2.5')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action):
with act_1.db.connect() as att2:
with act_1.db.connect() as att1:
cur1 = att1.cursor()
cur2 = att2.cursor()
cur1.execute('execute procedure sp_test(0)')
cur2.execute('execute procedure sp_test(1)')
att1.commit()
cur2.execute('execute procedure sp_test(1)')

View File

@ -9,7 +9,7 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from firebird.qa import db_factory, python_act, Action
# version: 3.0
# resources: None
@ -25,12 +25,12 @@ db_1 = db_factory(page_size=4096, sql_dialect=3, init=init_script_1)
# #
# runProgram('isql',['-x',dsn,'-user',user_name,'-pass',user_password])
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
act_1 = python_act('db_1', substitutions=substitutions_1)
@pytest.mark.version('>=3.0')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action):
act_1.isql(switches=['-x'])
assert act_1.clean_stdout == act_1.clean_expected_stdout

View File

@ -25,9 +25,7 @@
# 1.2) modifying some of its attributes (password, firstname etc).
# NOTE! We do *not* run 'fbsvcmgr action_delete_user' because it does not work (at least on build 32268)
# ######################################################################################################
# COMMAND: fbsvcmgr localhost/3333:service_mgr user sysdba password masterkey action_delete_user dbname C:\\MIX
# irebird
# b30\\security3.fdb sec_username john
# COMMAND: fbsvcmgr localhost/3333:service_mgr user sysdba password masterkey action_delete_user dbname C:\\MIX\\firebird\\fb30\\security3.fdb sec_username john
# STDERR: unexpected item in service parameter block, expected isc_spb_sec_username
# (sent letter to Alex, 09-jan-2016 22:34; after getting reply about this issue test can be further changed).
# 2) run ISQL and:
@ -46,12 +44,16 @@
# qmid:
import pytest
from firebird.qa import db_factory, isql_act, Action
import string
from random import sample, choice
from firebird.qa import db_factory, python_act, Action
from firebird.driver.types import UserInfo
# version: 3.0
# resources: None
substitutions_1 = [('[ ]+', ' '), ('[\t]*', ' '), ('.* Name: .*', ' Name: <name.with.puncts>')]
substitutions_1 = [('.* name: .*', 'Name: <name.with.puncts>'),
('.*USER_NAME.*', 'USER_NAME <name.with.puncts>')]
init_script_1 = """"""
@ -301,39 +303,89 @@ db_1 = db_factory(sql_dialect=3, init=init_script_1)
#
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
act_1 = python_act('db_1', substitutions=substitutions_1)
expected_stdout_1 = """
SVC STDOUT: Try to add user with name: "<name.with.puncts>"
SVC STDOUT: Try to display user after adding.
SVC STDOUT: Login Full name uid gid adm
SVC STDOUT: <name.with.puncts> 0 0 yes
SVC STDOUT: Try to modify user: change password and some attributes.
SVC STDOUT: Try to display user after modifying.
SVC STDOUT: Login Full name uid gid adm
SVC STDOUT: <name.with.puncts> Ozzy The Terrible Osbourne 0 0 no
SVC STDOUT: All done.
SQL STDOUT: ISQL_MSG Try to add user with name: <name.with.puncts>
SQL STDOUT: ISQL_MSG Try to display user after adding.
SQL STDOUT: SEC$USER_NAME <name.with.puncts>
SQL STDOUT: SEC$FIRST_NAME <null>
SQL STDOUT: SEC$MIDDLE_NAME <null>
SQL STDOUT: SEC$LAST_NAME <null>
SQL STDOUT: SEC$ADMIN <true>
SQL STDOUT: ISQL_MSG Try to modify user: change password and some attributes.
SQL STDOUT: ISQL_MSG Try to display user after modifying.
SQL STDOUT: SEC$USER_NAME <name.with.puncts>
SQL STDOUT: SEC$FIRST_NAME John
SQL STDOUT: SEC$MIDDLE_NAME Bonzo The Beast
SQL STDOUT: SEC$LAST_NAME Bonham
SQL STDOUT: SEC$ADMIN <false>
SQL STDOUT: ISQL_MSG Try to drop user.
SQL STDOUT: ISQL_MSG All done.
ISQL_MSG Try to add user with name: <name.with.puncts>
ISQL_MSG Try to display user after adding.
SEC$USER_NAME <name.with.puncts>
SEC$FIRST_NAME <null>
SEC$MIDDLE_NAME <null>
SEC$LAST_NAME <null>
SEC$ADMIN <true>
ISQL_MSG Try to modify user: change password and some attributes.
ISQL_MSG Try to display user after modifying.
SEC$USER_NAME <name.with.puncts>
SEC$FIRST_NAME John
SEC$MIDDLE_NAME Bonzo The Beast
SEC$LAST_NAME Bonham
SEC$ADMIN <false>
ISQL_MSG Try to drop user.
ISQL_MSG All done.
"""
@pytest.mark.version('>=3.0')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action):
chars = string.punctuation
length = 28
dotted_user = ''.join(sample(chars, length)).replace('"', '.').replace("'", '.')
quoted_user = '"' + dotted_user + '"'
# Via services
with act_1.connect_server() as srv:
srv.user.add(user_name=quoted_user, password='foobarkey', admin=True)
user = srv.user.get(user_name=quoted_user)
assert user == UserInfo(user_name=dotted_user, password=None, admin=True,
first_name='', middle_name='', last_name='', user_id=0,
group_id=0)
srv.user.update(user_name=quoted_user, password='BSabbath', first_name='Ozzy',
middle_name='The Terrible', last_name='Osbourne', admin=False)
user = srv.user.get(user_name=quoted_user)
assert user == UserInfo(user_name=dotted_user, password=None, admin=False,
first_name='Ozzy', middle_name='The Terrible', last_name='Osbourne',
user_id=0, group_id=0)
srv.user.delete(user_name=quoted_user)
assert srv.user.get(user_name=quoted_user) is None
# Via ISQL
isql_txt = f'''---- {dotted_user}
set list on;
--set echo on;
create or alter view v_sec as select sec$user_name, sec$first_name, sec$middle_name, sec$last_name, sec$admin
from sec$users
where upper(sec$user_name)=upper('{dotted_user}');
commit;
select 'Try to add user with name: ' || '{dotted_user}' as isql_msg from rdb$database;
create or alter user {quoted_user} password '123' grant admin role;
commit;
select 'Try to display user after adding.' as isql_msg from rdb$database;
select * from v_sec;
commit;
select 'Try to modify user: change password and some attributes.' as isql_msg from rdb$database;
alter user {quoted_user}
password 'Zeppelin'
firstname 'John'
middlename 'Bonzo The Beast'
lastname 'Bonham'
revoke admin role
;
commit;
select 'Try to display user after modifying.' as isql_msg from rdb$database;
select * from v_sec;
commit;
select 'Try to drop user.' as isql_msg from rdb$database;
drop user {quoted_user};
commit;
select 'All done.' as isql_msg from rdb$database;
'''
act_1.expected_stdout = expected_stdout_1
act_1.isql(switches=[], input=isql_txt)
assert act_1.clean_stdout == act_1.clean_expected_stdout

View File

@ -19,12 +19,16 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
import time
import subprocess
from pathlib import Path
from difflib import unified_diff
from firebird.qa import db_factory, python_act, Action, temp_file
# version: 2.5.1
# resources: None
substitutions_1 = [('\t+', ' '), ('^((?!start|finish|expected|page|wrong).)*$', '')]
substitutions_1 = [('^((?!start|finish|expected|page|wrong).)*$', '')] # ('\t+', ' '),
init_script_1 = """"""
@ -204,16 +208,61 @@ db_1 = db_factory(sql_dialect=3, init=init_script_1)
#
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
act_1 = python_act('db_1', substitutions=substitutions_1)
expected_stdout_1 = """
Sweep is started by SYSDBA
Sweep is finished
"""
isql_script = temp_file('test-script.sql')
@pytest.mark.version('>=2.5.1')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action, isql_script: Path, capsys):
isql_script.write_text(''' set list on;
set term ^;
execute block returns (dts timestamp, sql varchar(80)) as
declare i int;
declare s varchar(256);
begin
i = 1;
while (i < 32767) do
begin
s = 'tmp' || :i;
dts = 'now';
sql = 'create global temporary table ' || :s || ' (id int);';
execute statement sql with autonomous transaction;
suspend;
dts = 'now';
sql = 'drop table ' || :s || ';';
execute statement sql with autonomous transaction;
suspend;
i = i + 1;
end
end ^
set term ;^
''')
with act_1.connect_server() as srv:
# Get content of firebird.log BEFORE test
srv.info.get_log()
log_before = srv.readlines()
p_isql = subprocess.Popen([act_1.vars['isql'], act_1.db.dsn, '-i', str(isql_script)],
stderr=subprocess.STDOUT)
time.sleep(2)
# LAUNCH SWEEP while ISQL is working
srv.database.sweep(database=str(act_1.db.db_path))
p_isql.terminate()
# Get content of firebird.log AFTER test
srv.info.get_log()
log_after = srv.readlines()
for line in unified_diff(log_before, log_after):
if line.startswith('+') and line.split('+'):
print(line.replace('+', ' '))
act_1.expected_stdout = expected_stdout_1
act_1.stdout = capsys.readouterr().out
assert act_1.clean_stdout == act_1.clean_expected_stdout

View File

@ -4,7 +4,7 @@
# title: Exception when upper casing string with lowercase y trema (code 0xFF in ISO8859_1 )
# decription:
# 02-mar-2021. Re-implemented in order to have ability to run this test on Linux.
# Ttest creates table and fills it with non-ascii characters in init_script, using charset = UTF8.
# Test creates table and fills it with non-ascii characters in init_script, using charset = UTF8.
# Then it generates .sql script for running it in separae ISQL process.
# This script makes connection to test DB using charset = ISO8859_1 and perform several queries.
# Result will be redirected to .log and .err files (they will be encoded, of course, also in ISO8859_1).
@ -14,13 +14,16 @@
# * Windows: 4.0.0.2377, 3.0.8.33420, 2.5.9.27152
# * Linux: 4.0.0.2377, 3.0.8.33415
#
# [pcisar] 16.11.2021
# This test fails as UPPER('ÿ') does not work properly
#
# tracker_id: CORE-2912
# min_versions: ['2.5.3']
# versions: 2.5.3
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from firebird.qa import db_factory, python_act, Action
# version: 2.5.3
# resources: None
@ -134,7 +137,8 @@ db_1 = db_factory(charset='ISO8859_1', sql_dialect=3, init=init_script_1)
#
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
act_1 = python_act('db_1', substitutions=substitutions_1)
expected_stdout_1 = """
AU AÿB
@ -156,8 +160,22 @@ expected_stdout_1 = """
"""
@pytest.mark.version('>=2.5.3')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action):
sql_txt = '''set names ISO8859_1;
set list on;
select upper('aÿb') au from rdb$database;
select c, upper(c) cu from test where c starting with upper('ÿ');
select c, upper(c) cu from test where c containing 'Faÿ';
select c, upper(c) cu from test where c starting with 'Faÿ';
select c, upper(c) cu from test where c like 'Faÿ%';
-- ### ACHTUNG ###
-- As of WI-V2.5.4.26857, following will FAILS if character class "alpha"
-- will be specified not in UPPER case (see note in CORE-4740 08/Apr/15 05:48 PM):
select c, upper(c) cu from test where c similar to '[[:ALPHA:]]{1,}ÿ%';
set plan on;
select c from test where upper (c collate iso8859_1) = upper('ÿ');
select c, upper(c) cu from test where upper (c collate iso8859_1) starting with upper('Faÿ');
'''
act_1.expected_stdout = expected_stdout_1
act_1.isql(switches=['-q'], charset='ISO8859_1', input=sql_txt)
assert act_1.clean_stdout == act_1.clean_expected_stdout

View File

@ -40,7 +40,8 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from threading import Thread
from firebird.qa import db_factory, python_act, Action
# version: 2.5
# resources: None
@ -237,15 +238,65 @@ db_1 = db_factory(sql_dialect=3, init=init_script_1)
#
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
act_1 = python_act('db_1', substitutions=substitutions_1)
expected_stdout_1 = """
1 records fetched
"""
@pytest.mark.version('>=2.5')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
test_script_1 = """
set list on;
-- statistics for this statement SHOULD appear in trace log:
select 1 k1 from rdb$database;
commit;
-- statistics for this statement should NOT appear in trace log:
select 2 k2 from rdb$types rows 2 /* no_trace*/;
-- statistics for this statement should NOT appear in trace log:
select 3 no_trace from rdb$types rows 3;
-- statistics for this statement should NOT appear in trace log:
set term ^;
execute block returns(k4 int) as
begin
for select 4 from rdb$types rows 4 into k4 do suspend;
end -- no_trace
^
set term ;^
"""
def trace_session(act: Action):
cfg30 = ['# Trace config, format for 3.0. Generated auto, do not edit!',
f'database=%[\\\\/]{act.db.db_path.name}',
'{',
' enabled = true',
' #include_filter',
' exclude_filter = %no_trace%',
' log_connections = true',
' log_transactions = true',
' log_statement_finish = true',
' print_plan = true',
' print_perf = true',
' time_threshold = 0',
'}']
with act.connect_server() as srv:
srv.trace.start(config='\n'.join(cfg30))
for line in srv:
print(line)
@pytest.mark.version('>=3.0')
def test_1(act_1: Action, capsys):
trace_thread = Thread(target=trace_session, args=[act_1])
trace_thread.start()
act_1.isql(switches=['-n'], input=test_script_1)
with act_1.connect_server() as srv:
for session in list(srv.trace.sessions.keys()):
srv.trace.stop(session_id=session)
trace_thread.join(1.0)
if trace_thread.is_alive():
pytest.fail('Trace thread still alive')
act_1.expected_stdout = expected_stdout_1
act_1.stdout = capsys.readouterr().out
assert act_1.clean_stdout == act_1.clean_expected_stdout

View File

@ -16,7 +16,9 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from threading import Thread
from difflib import unified_diff
from firebird.qa import db_factory, python_act, Action
# version: 2.5.1
# resources: None
@ -389,12 +391,153 @@ db_1 = db_factory(sql_dialect=3, init=init_script_1)
#
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
act_1 = python_act('db_1', substitutions=substitutions_1)
test_script_1 = """
set list on;
select '*Лев Николаевич Толстой *
*Анна Каренина *
/Мне отмщение, и аз воздам/
*ЧАСТЬ ПЕРВАЯ*
*I *
Все счастливые семьи похожи друг на друга, каждая несчастливая
семья несчастлива по-своему.
Все смешалось в доме Облонских. Жена узнала, что муж был в связи
с бывшею в их доме француженкою-гувернанткой, и объявила мужу, что
не может жить с ним в одном доме. Положение это продолжалось уже
третий день и мучительно чувствовалось и самими супругами, и всеми
членами семьи, и домочадцами. Все члены семьи и домочадцы
чувствовали, что нет смысла в их сожительстве и что на каждом
постоялом дворе случайно сошедшиеся люди более связаны между собой,
чем они, члены семьи и домочадцы Облонских. Жена не выходила из
своих комнат, мужа третий день не было дома. Дети бегали по всему
дому, как потерянные; англичанка поссорилась с экономкой и написала
записку приятельнице, прося приискать ей новое место; повар ушел еще
вчера со двора, во время обеда; черная кухарка и кучер просили расчета.
На третий день после ссоры князь Степан Аркадьич Облонский --
Стива, как его звали в свете, -- в обычный час, то есть в восемь
часов утра, проснулся не в спальне жены, а в своем кабинете, на
сафьянном диване... Он повернул свое полное, выхоленное тело на
пружинах дивана, как бы желая опять заснуть надолго, с другой
стороны крепко обнял подушку и прижался к ней щекой; но вдруг
вскочил, сел на диван и открыл глаза.
"Да, да, как это было? -- думал он, вспоминая сон. -- Да, как это
было? Да! Алабин давал обед в Дармштадте; нет, не в Дармштадте, а
что-то американское. Да, но там Дармштадт был в Америке. Да, Алабин
давал обед на стеклянных столах, да, -- и столы пели: Il mio tesoro,
и не Il mio tesoro, а что-то лучше, и какие-то маленькие графинчики,
и они же женщины", -- вспоминал он.
Глаза Степана Аркадьича весело заблестели, и он задумался,
улыбаясь. "Да, хорошо было, очень хорошо. Много еще там было
отличного, да не скажешь словами и мыслями даже наяву не выразишь".
И, заметив полосу света, пробившуюся сбоку одной из суконных стор,
он весело скинул ноги с дивана, отыскал ими шитые женой (подарок ко
дню рождения в прошлом году), обделанные в золотистый сафьян туфли и
по старой, девятилетней привычке, не вставая, потянулся рукой к тому
месту, где в спальне у него висел халат. И тут он вспомнил вдруг,
как и почему он спит не в спальне жены, а в кабинете; улыбка исчезла
с его лица, он сморщил лоб.
"Ах, ах, ах! Ааа!.." -- замычал он, вспоминая все, что было. И
его воображению представились опять все подробности ссоры с женою,
вся безвыходность его положения и мучительнее всего собственная вина
его.
"Да! она не простит и не может простить. И всего ужаснее то, что
виной всему я, виной я, а не виноват. В этом-то вся драма, -- думал
он. -- Ах, ах, ах!" -- приговаривал он с отчаянием, вспоминая самые
тяжелые для себя впечатления из этой ссоры.
Неприятнее всего была та первая минута, когда он, вернувшись из
театра, веселый и довольный, с огромною грушей для жены в руке, не
нашел жены в гостиной; к удивлению, не нашел ее и в кабинете и,
наконец, увидал ее в спальне с несчастною, открывшею все, запиской в
руке.
Она, эта вечно озабоченная, и хлопотливая, и недалекая, какою он
считал ее, Долли, неподвижно сидела с запиской в руке и с выражением
ужаса, отчаяния и гнева смотрела на него.
-- Что это? это? -- спрашивала она, указывая на записку.
И при этом воспоминании, как это часто бывает, мучала Степана
Аркадьича не столько самое событие, сколько то, как он ответил на
эти слова жены.
С ним случилось в эту минуту то, что случается с людьми, когда
они неожиданно уличены в чем-нибудь слишком постыдном. Он не сумел
приготовить свое лицо к тому положению, в которое он становился
перед женой после открытия его вины. Вместо того чтоб оскорбиться,
отрекаться, оправдываться, просить прощения, оставаться даже
равнодушным -- все было бы лучше того, что он сделал! -- его лицо
совершенно невольно ("рефлексы головного мозга", -- подумал Степан
Аркадьич, который любил физиологию), совершенно невольно вдруг
улыбнулось привычною, доброю и потому глупою улыбкой.
Эту глупую улыбку он не мог простить себе. Увидав эту улыбку,
Долли вздрогнула, как от физической боли, разразилась, со
свойственною ей горячностью, потоком жестоких слов и выбежала из
комнаты. С тех пор она не хотела видеть мужа.
"Всему виной эта глупая улыбка", -- думал Степан Аркадьич.
"Но что же делать? что делать?" -- с отчаянием говорил он себе и
не находил ответа.
' from rdb$database;
"""
def trace_session(act: Action):
cfg30 = ['# Trace config, format for 3.0. Generated auto, do not edit!',
f'database=%[\\\\/]{act.db.db_path.name}',
'{',
' enabled = true',
' include_filter = %(SELECT|INSERT|UPDATE|DELETE)%',
' exclude_filter = %no_trace%',
' log_connections = true',
' log_transactions = true',
' log_statement_prepare = true',
' log_statement_free = true',
' log_statement_start = true',
' log_statement_finish = true',
' log_trigger_start = true',
' log_trigger_finish = true',
' log_context = true',
' print_plan = true',
' print_perf = true',
' time_threshold = 0',
' max_sql_length = 5000',
' max_blr_length = 500',
' max_dyn_length = 500',
' max_arg_length = 80',
' max_arg_count = 30',
'}',
'services {',
' enabled = false',
' log_services = false',
' log_service_query = false',
'}']
with act.connect_server() as srv:
srv.encoding = 'utf8'
srv.trace.start(config='\n'.join(cfg30))
for line in srv:
pass # we are not interested in trace output
@pytest.mark.version('>=2.5.1')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action):
# Get content of firebird.log BEFORE test
with act_1.connect_server() as srv:
srv.info.get_log()
log_before = srv.readlines()
trace_thread = Thread(target=trace_session, args=[act_1])
trace_thread.start()
# RUN QUERY WITH NON-ASCII CHARACTERS
act_1.isql(switches=['-n', '-q'], input=test_script_1)
with act_1.connect_server() as srv:
for session in list(srv.trace.sessions.keys()):
srv.trace.stop(session_id=session)
trace_thread.join(1.0)
if trace_thread.is_alive():
pytest.fail('Trace thread still alive')
# Get content of firebird.log AFTER test
with act_1.connect_server() as srv:
srv.info.get_log()
log_after = srv.readlines()
assert '\n'.join(unified_diff(log_before, log_after)) == ''

View File

@ -33,12 +33,15 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from firebird.qa import db_factory, isql_act, Action, python_act
from firebird.driver import TPB, TraAccessMode, Isolation
# version: 3.0
# resources: None
substitutions_1 = [('record not found for user:.*', ''), ('-concurrent transaction number is.*', '-concurrent transaction number is'), ('-At block line: [\\d]+, col: [\\d]+', '-At block line')]
substitutions_1 = [('record not found for user:.*', ''),
('-concurrent transaction number is.*', '-concurrent transaction number is'),
('-At block line: [\\d]+, col: [\\d]+', '-At block line')]
init_script_1 = """"""
@ -156,6 +159,7 @@ act_1 = isql_act('db_1', test_script_1, substitutions=substitutions_1)
expected_stdout_1 = """
ID 1
"""
expected_stderr_1 = """
Statement failed, SQLSTATE = HY000
record not found for user: TMP$2988
@ -190,7 +194,8 @@ def test_1(act_1: Action):
# version: 4.0
# resources: None
substitutions_2 = [('^((?!concurrent transaction number is).)*$', ''), ('[\\-]{0,1}concurrent transaction number is [0-9]+', 'concurrent transaction number is')]
substitutions_2 = [('^((?!concurrent transaction number is).)*$', ''),
('[\\-]{0,1}concurrent transaction number is [0-9]+', 'concurrent transaction number is')]
init_script_2 = """
create table test(id int, x int, constraint test_pk primary key(id) using index test_pk);
@ -282,16 +287,63 @@ db_2 = db_factory(sql_dialect=3, init=init_script_2)
#
#
#---
#act_2 = python_act('db_2', test_script_2, substitutions=substitutions_2)
act_2 = python_act('db_2', substitutions=substitutions_2)
expected_stdout_2 = """
- concurrent transaction number is 13
- concurrent transaction number is 13
concurrent transaction number is 13
concurrent transaction number is 13
"""
@pytest.mark.version('>=4.0')
@pytest.mark.xfail
def test_2(db_2):
pytest.fail("Test not IMPLEMENTED")
def test_2(act_2: Action, capsys):
with act_2.db.connect() as con:
tx1 = con.transaction_manager()
tx1.begin()
cur1 = tx1.cursor()
cur1.execute('update test set x = ? where id = ?', (222, 1))
# **INSTEAD** of ticket case-1:
# set transaction read committed no record_version lock timeout N;
# -- we start Tx with lock_timeout using custom TPB and try just to **update** record which is locked now
# (but NOT 'SELECT ...'! It is useless with default value of confign parameter ReadConsistency = 1).
# Message about concurrent transaction (which holds lock) in any case must appear in exception text.
# NB: NO_rec_version is USELESS in default FB 4.0 config!
custom_tpb = TPB(access_mode=TraAccessMode.WRITE,
isolation=Isolation.READ_COMMITTED_RECORD_VERSION,
lock_timeout=1)
tx2 = con.transaction_manager(default_tpb=custom_tpb.get_buffer())
tx2.begin()
cur2 = tx2.cursor()
try:
cur2.execute('update test set x = ? where id = ?', (333, 1))
except Exception as e:
print('Exception in cur2:')
print('-' * 30)
for x in e.args:
print(x)
print('-' * 30)
finally:
tx2.commit()
# This is for ticket case-2:
# set transaction read committed lock timeout N;
# select * from test with lock;
custom_tpb.isolation = Isolation.CONCURRENCY
tx3 = con.transaction_manager(default_tpb=custom_tpb.get_buffer())
tx3.begin()
cur3 = tx3.cursor()
try:
cur3.execute('select x from test where id = ? with lock', (1,))
for r in cur3:
print(r[0])
except Exception as e:
print('Exception in cur3:')
print('-' * 30)
for x in e.args:
print(x)
print('-' * 30)
finally:
tx3.commit()
tx1.commit()
act_2.expected_stdout = expected_stdout_2
act_2.stdout = capsys.readouterr().out
assert act_2.clean_stdout == act_2.clean_expected_stdout

View File

@ -20,12 +20,14 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from threading import Thread
from firebird.qa import db_factory, python_act, Action
# version: 2.5
# resources: None
substitutions_1 = [('^((?!ERROR|ELEMENT|SYSDBA:NONE).)*$', ''), ('.*SYSDBA:NONE', 'SYSDBA:NONE'), ('TCPV.*', 'TCP')]
substitutions_1 = [('^((?!ERROR|ELEMENT|SYSDBA:NONE).)*$', ''),
('.*SYSDBA:NONE', 'SYSDBA:NONE'), ('TCPV.*', 'TCP')]
init_script_1 = """"""
@ -176,7 +178,8 @@ db_1 = db_factory(sql_dialect=3, init=init_script_1)
#
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
act_1 = python_act('db_1', substitutions=substitutions_1)
expected_stdout_1 = """
SYSDBA:NONE, UTF8, TCP
@ -185,9 +188,34 @@ expected_stdout_1 = """
SYSDBA:NONE, ISO88591, TCP
"""
@pytest.mark.version('>=2.5')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def trace_session(act: Action):
cfg30 = ['# Trace config, format for 3.0. Generated auto, do not edit!',
f'database=%[\\\\/]{act.db.db_path.name}',
'{',
' enabled = true',
' log_connections = true',
' time_threshold = 0',
'}']
with act.connect_server() as srv:
srv.trace.start(config='\n'.join(cfg30))
for line in srv:
print(line.upper())
@pytest.mark.version('>=3.0')
def test_1(act_1: Action, capsys):
trace_thread = Thread(target=trace_session, args=[act_1])
trace_thread.start()
# make two connections with different charset
with act_1.db.connect(charset='utf8'):
pass
with act_1.db.connect(charset='iso8859_1'):
pass
with act_1.connect_server() as srv:
for session in list(srv.trace.sessions.keys()):
srv.trace.stop(session_id=session)
trace_thread.join(1.0)
if trace_thread.is_alive():
pytest.fail('Trace thread still alive')
act_1.expected_stdout = expected_stdout_1
act_1.stdout = capsys.readouterr().out
assert act_1.clean_stdout == act_1.clean_expected_stdout

View File

@ -13,7 +13,7 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from firebird.qa import db_factory, python_act, Action
# version: 2.5.6
# resources: None
@ -55,7 +55,8 @@ db_1 = db_factory(sql_dialect=3, init=init_script_1)
# printData(cur2)
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
act_1 = python_act('db_1', substitutions=substitutions_1)
expected_stdout_1 = """
A B C
@ -63,8 +64,24 @@ expected_stdout_1 = """
"""
@pytest.mark.version('>=2.5.6')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action, capsys):
with act_1.db.connect() as att1, act_1.db.connect() as att2:
trn1 = att1.transaction_manager()
cur1 = trn1.cursor()
cur1.execute("create table t(a int, b int, c int)") # att_12, tra_4
cur1.execute("create view v as select a,b from t")
trn1.commit()
cur1.execute("insert into t values(1,2,3)") # att_12, tra_5
cur1.execute("select * from v")
trn1.commit()
trn2 = att2.transaction_manager()
cur2 = trn2.cursor()
cur2.execute("select * from v") # att_13, tra_7
trn2.commit()
cur1.execute("alter view v as select a, b, c from t") # att-12, tra_8
trn1.commit()
cur2.execute("select * from v") # att_13, tra_9
act_1.print_data(cur2)
act_1.expected_stdout = expected_stdout_1
act_1.stdout = capsys.readouterr().out
assert act_1.clean_stdout == act_1.clean_expected_stdout

View File

@ -18,7 +18,7 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from firebird.qa import db_factory, python_act, Action
# version: 2.5.1
# resources: None
@ -86,15 +86,21 @@ db_1 = db_factory(sql_dialect=3, init=init_script_1)
#
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
act_1 = python_act('db_1', substitutions=substitutions_1)
expected_stdout_1 = """
{'loop': 3}
"""
@pytest.mark.version('>=2.5.1')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
@pytest.mark.version('>=3.0')
def test_1(act_1: Action, capsys):
act_1.expected_stdout = expected_stdout_1
with act_1.db.connect() as con:
c = con.cursor()
with con.event_collector(['loop']) as events:
c.execute('execute procedure sp_test(3)')
con.commit()
print(events.wait(10))
act_1.stdout = capsys.readouterr().out
assert act_1.clean_stdout == act_1.clean_expected_stdout

View File

@ -39,7 +39,8 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from pathlib import Path
from firebird.qa import db_factory, python_act, Action, temp_file
# version: 2.5
# resources: None
@ -197,7 +198,90 @@ db_1 = db_factory(charset='WIN1257', sql_dialect=3, init=init_script_1)
#
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
act_1 = python_act('db_1', substitutions=substitutions_1)
test_script_1 = """
set bail on;
set names win1257;
create collation coll_1257_ci_ai
for win1257 from win1257_lv
no pad case insensitive accent sensitive;
commit;
create table test1257 (
letter varchar(2) collate coll_1257_ci_ai,
sort_index smallint
);
commit;
-- ### ONCE AGAIN ###
-- 1) for checking this under ISQL following must be encoded in WIN1257
-- 2) for running under fbt_run utility following must be encoded in UTF8.
insert into test1257 values ('Iz', 18);
insert into test1257 values ('Īb', 19);
insert into test1257 values ('Īz', 20);
insert into test1257 values ('Ķz', 24);
insert into test1257 values ('Ēz', 12);
insert into test1257 values ('Gb', 13);
insert into test1257 values ('Ģz', 16);
insert into test1257 values ('Ib', 17);
insert into test1257 values ('Gz', 14);
insert into test1257 values ('Ģb', 15);
insert into test1257 values ('Ņb', 31);
insert into test1257 values ('Ņz', 32);
insert into test1257 values ('Cb', 5);
insert into test1257 values ('Ūb', 39);
insert into test1257 values ('Ūz', 40);
insert into test1257 values ('Zb', 41);
insert into test1257 values ('Eb', 9);
insert into test1257 values ('Ez', 10);
insert into test1257 values ('Ēb', 11);
insert into test1257 values ('Ub', 37);
insert into test1257 values ('Uz', 38);
insert into test1257 values ('Lz', 26);
insert into test1257 values ('Ļb', 27);
insert into test1257 values ('Ļz', 28);
insert into test1257 values ('Kb', 21);
insert into test1257 values ('Kz', 22);
insert into test1257 values ('Šz', 36);
insert into test1257 values ('Lb', 25);
insert into test1257 values ('Cz', 6);
insert into test1257 values ('Čb', 7);
insert into test1257 values ('Čz', 8);
insert into test1257 values ('Sb', 33);
insert into test1257 values ('Sz', 34);
insert into test1257 values ('Šb', 35);
insert into test1257 values ('Nb', 29);
insert into test1257 values ('Nz', 30);
insert into test1257 values ('Ķb', 23);
insert into test1257 values ('Zz', 42);
insert into test1257 values ('Žb', 43);
insert into test1257 values ('Žz', 44);
insert into test1257 values ('Ab', 1);
insert into test1257 values ('Az', 2);
insert into test1257 values ('Āb', 3);
insert into test1257 values ('Āz', 4);
commit;
set heading off;
select *
from test1257 tls
order by tls.letter collate coll_1257_ci_ai;
"""
expected_stdout_1 = """
Ab 1
@ -246,9 +330,13 @@ expected_stdout_1 = """
Žz 44
"""
script_file = temp_file('test-script.sql')
@pytest.mark.version('>=2.5')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action, script_file: Path):
script_file.write_text(test_script_1, encoding='cp1257')
act_1.expected_stdout = expected_stdout_1
act_1.isql(switches=[], input_file=script_file, charset='WIN1257')
assert act_1.clean_stdout == act_1.clean_expected_stdout

View File

@ -33,7 +33,10 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from threading import Thread, Barrier
from io import BytesIO
from firebird.qa import db_factory, python_act, Action, temp_file
from firebird.driver import SrvStatFlag
# version: 2.5
# resources: None
@ -254,18 +257,51 @@ db_1 = db_factory(sql_dialect=3, init=init_script_1)
#
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
act_1 = python_act('db_1', substitutions=substitutions_1)
expected_stdout_1 = """
EXCLUDE_FILTER = "DATABASE STATS"
"DATABASE PROPERTIES"
"DATABASE STATS"
"BACKUP DATABASE"
"RESTORE DATABASE"
"""
@pytest.mark.version('>=2.5')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def trace_session(act: Action, barrier: Barrier):
cfg30 = ['services',
'{',
' enabled = true',
' log_services = true',
' exclude_filter = "Database Stats"',
'}']
with act.connect_server() as srv:
srv.trace.start(config='\n'.join(cfg30))
barrier.wait()
for line in srv:
print(line.upper())
temp_file_1 = temp_file('test-file')
@pytest.mark.version('>=3.0')
def test_1(act_1: Action, capsys, temp_file_1):
b = Barrier(2)
trace_thread = Thread(target=trace_session, args=[act_1, b])
trace_thread.start()
with act_1.connect_server() as srv:
# Make some service requests
b.wait()
srv.database.set_sweep_interval(database=str(act_1.db.db_path), interval=1234321)
srv.database.get_statistics(database=str(act_1.db.db_path), flags=SrvStatFlag.HDR_PAGES)
srv.wait()
srv.database.backup(database=str(act_1.db.db_path), backup=str(temp_file_1))
srv.wait()
#
for session in list(srv.trace.sessions.keys()):
srv.trace.stop(session_id=session)
trace_thread.join(2.0)
if trace_thread.is_alive():
pytest.fail('Trace thread still alive')
act_1.expected_stdout = expected_stdout_1
act_1.stdout = capsys.readouterr().out
assert act_1.clean_stdout == act_1.clean_expected_stdout

View File

@ -27,7 +27,8 @@
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
from difflib import unified_diff
from firebird.qa import db_factory, python_act, Action
# version: 2.5.1
# resources: None
@ -157,12 +158,22 @@ db_1 = db_factory(sql_dialect=3, init=init_script_1)
#
#
#---
#act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1)
act_1 = python_act('db_1', substitutions=substitutions_1)
@pytest.mark.version('>=2.5.1')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
def test_1(act_1: Action):
with act_1.connect_server() as srv:
srv.info.get_log()
log_before = srv.readlines()
with act_1.db.connect() as con1, act_1.db.connect() as con2:
c1 = con1.cursor()
c1.execute("create table test(id int primary key)")
con1.commit()
#
c2 = con2.cursor()
c2.execute('drop table test')
con2.commit()
srv.info.get_log()
log_after = srv.readlines()
assert list(unified_diff(log_before, log_after)) == []