def test_idb2call_with_uid_pwd(mocker, database_callproc): ibm_db = mocker.patch('itoolkit.db2.idb2call.ibm_db', create=True) connect = mocker.patch('itoolkit.db2.idb2call.connect', create=True) class MockConn(object): pass ibm_db.IBM_DBConnection = MockConn connect.return_value = database_callproc user = '******' password = '******' transport = iDB2Call(user, password) tk = iToolKit() out = transport.call(tk) assert isinstance(out, (bytes, str)) kwargs = dict(database='*LOCAL', user=user, password=password) connect.assert_called_once_with(**kwargs) cursor = database_callproc.cursor() cursor.callproc.assert_called_once() cursor.__iter__.assert_called_once()
def run_cl_command(job_number, job_user, job_name): itool = iToolKit() itool.add(iCmd('test', 'CRTLIB wytest')) # itransport = DatabaseTransport(conn) itransport = DirectTransport() itool.call(itransport) # output rtvjoba = itool.dict_out('rtvjoba') print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%') print(rtvjoba) if 'error' in rtvjoba: print(rtvjoba['error']) exit() elif 'row' in rtvjoba: rtvjoba_vals = rtvjoba['row'] for item_dict in rtvjoba_vals: for key in item_dict: print(item_dict[key]) print('hahahahahahhahahahahhaah') # print('value:' + rtvjoba) # print('USRLIBL = ' + rtvjoba_vals['USRLIBL']) # print('SYSLIBL = ' + rtvjoba_vals['SYSLIBL']) # print('CCSID = ' + rtvjoba_vals['CCSID']) # print('OUTQ = ' + rtvjoba_vals['OUTQ']) else: print('ERRORRRRRRRRRRRRRRRRRRR') print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
def itoolkit_run_sql(sql): conn = dbi.connect() db_itransport = DatabaseTransport(conn) itool = iToolKit() itool.add(iSqlQuery('query', sql, {'error': 'on'})) itool.add(iSqlFetch('fetch')) itool.add(iSqlFree('free')) itool.call(db_itransport) command_output = itool.dict_out('fetch') rc = IBMi_COMMAND_RC_UNEXPECTED out = '' err = '' if 'error' in command_output: command_error = command_output['error'] if 'joblog' in command_error: rc = IBMi_COMMAND_RC_ERROR err = command_error['joblog'] else: # should not be here, must xmlservice has internal error rc = IBMi_COMMAND_RC_ITOOLKIT_NO_KEY_JOBLOG err = "iToolKit result dict does not have key 'joblog', the output is %s" % command_output else: rc = IBMi_COMMAND_RC_SUCCESS out = command_output['row'] return rc, out, err
def itoolkit_run_rtv_command(self, command, args_dict): '''IBM i XMLSERVICE call *CMD with REXX''' itool = iToolKit(iparm=0, iret=0, ids=1, irow=0) itransport = DatabaseTransport(self.conn) args = ' ' for (k, v) in args_dict.items(): parm = '(?) ' if v == 'number': parm = '(?N) ' args = args + k + parm itool.add(iCmd('rtv_command', command + args)) itool.call(itransport) rtv_command = itool.dict_out('rtv_command') ibmi_util.log_debug("rtv_command " + str(rtv_command), sys._getframe().f_code.co_name) if 'error' in rtv_command: rc = ibmi_util.IBMi_COMMAND_RC_ERROR out_dict = dict() error = str(rtv_command) else: # remove the key 'success' and its value, just left the result del rtv_command['success'] rc = ibmi_util.IBMi_COMMAND_RC_SUCCESS out_dict = rtv_command error = '' return rc, out_dict, error
def remove_pending_joblog(conn, job_name, user_name, job_number): itransport = DatabaseTransport(conn) itool = iToolKit() itool.add( iPgm('qwtrmvjl', 'QWTRMVJL').addParm( iDS('RJLS0100_t', { 'len': 'rhrlen' }).addData(iData('length', '10i0', '44')).addData( iData('day_since', '10i0', '0')).addData( iData('job_name', '10A', job_name)).addData( iData('user_name', '10A', user_name)).addData( iData('job_number', '6A', job_number)).addData( iData('job_log_output', '10A', '*ALL'))). addParm(iData('fmtnam', '8A', 'RJLS0100')).addParm( iDS('ERRC0100_t', { 'len': 'errlen' }).addData(iData('errRet', '10i0', '')).addData( iData('errAvl', '10i0', '')).addData( iData('errExp', '7A', '', {'setlen': 'errlen'})).addData( iData('errRsv', '1A', '')))) itool.call(itransport) qwtrmvjl = itool.dict_out('qwtrmvjl') if 'success' in qwtrmvjl: return 0, qwtrmvjl['success'] else: return -1, qwtrmvjl['error']
def itoolkit_run_sql(conn, sql): out_list = [] rc = '' try: itransport = DatabaseTransport(conn) itool = iToolKit() itool.add(iSqlQuery('query', sql, {'error': 'on'})) itool.add(iSqlFetch('fetch')) itool.add(iSqlFree('free')) itool.call(itransport) command_output = itool.dict_out('fetch') out = '' if 'error' not in command_output: rc = IBMi_COMMAND_RC_SUCCESS out = command_output['row'] if isinstance(out, dict): out_list.append(out) elif isinstance(out, list): out_list = out else: command_error = command_output['error'] if 'joblog' in command_error: rc = IBMi_COMMAND_RC_ERROR else: # should not be here, must xmlservice has internal error rc = IBMi_COMMAND_RC_ITOOLKIT_NO_KEY_JOBLOG if 'Row not found' in command_error: rc = 0 # treat as success but also indicate the Row not found message in stderr except Exception as e_db_connect: raise Exception(str(e_db_connect)) return rc, interpret_return_code(rc), out_list
def itoolkit_rum_command(conn, command): try: itransport = DatabaseTransport(conn) itool = iToolKit() itool.add(iCmd('command', command, {'error': 'on'})) itool.call(itransport) rc = '' out = '' command_output = itool.dict_out('command') if 'success' in command_output: rc = IBMi_COMMAND_RC_SUCCESS out = command_output['success'] elif 'error' in command_output: command_error = command_output['error'] if 'joblog' in command_error: rc = IBMi_COMMAND_RC_ERROR else: # should not be here, must xmlservice has internal error rc = IBMi_COMMAND_RC_ITOOLKIT_NO_KEY_JOBLOG else: # should not be here, must xmlservice has internal error rc = IBMi_COMMAND_RC_ITOOLKIT_NO_KEY_ERROR except Exception as e_disconnect: raise Exception(e_disconnect) return rc, interpret_return_code(rc), out
def test_pgm(transport): """Test calling ZZCALL https://bitbucket.org/inext/xmlservice-rpg/src/master/test.rpg/zzcall.rpgle """ transport.set_out("""<?xml version="1.0" ?> <xmlservice> <pgm error="fast" lib="XMLSERVICE" name="ZZCALL" var="zzcall"> <parm io="both" var="p1"> <data type="1a" var="INCHARA">C</data> </parm> <parm io="both" var="p2"> <data type="1a" var="INCHARB">D</data> </parm> <parm io="both" var="p3"> <data type="7p4" var="INDEC1">321.1234</data> </parm> <parm io="both" var="p4"> <data type="12p2" var="INDEC2">1234567890.12</data> </parm> <parm io="both" var="p5"> <ds var="INDS1"> <data type="1a" var="DSCHARA">E</data> <data type="1a" var="DSCHARB">F</data> <data type="7p4" var="DSDEC1">333.3330</data> <data type="12p2" var="DSDEC2">4444444444.44</data> </ds> </parm> <success>+++ success XMLSERVICE ZZCALL </success> </pgm> </xmlservice> """) tk = iToolKit() tk.add( iPgm('zzcall', 'ZZCALL', { 'lib': 'XMLSERVICE' }).addParm(iData('INCHARA', '1a', 'a')).addParm( iData('INCHARB', '1a', 'b')).addParm( iData('INDEC1', '7p4', '32.1234')).addParm( iData('INDEC2', '12p2', '33.33')).addParm( iDS('INDS1').addData(iData( 'DSCHARA', '1a', 'a')).addData(iData('DSCHARB', '1a', 'b')).addData( iData('DSDEC1', '7p4', '32.1234')).addData( iData('DSDEC2', '12p2', '33.33')))) tk.call(transport) zzcall = tk.dict_out('zzcall') assert ('success' in zzcall) assert (zzcall['INCHARA'] == 'C') assert (zzcall['INCHARB'] == 'D') assert (zzcall['INDEC1'] == '321.1234') assert (zzcall['INDEC2'] == '1234567890.12') assert (zzcall['INDS1']['DSCHARA'] == 'E') assert (zzcall['INDS1']['DSCHARB'] == 'F') assert (zzcall['INDS1']['DSDEC1'] == '333.3330') assert (zzcall['INDS1']['DSDEC2'] == '4444444444.44')
def itoolkit_run_command(command): conn = dbi.connect() itransport = DirectTransport() itool = iToolKit() itool.add(iCmd('command', command, {'error': 'on'})) itool.call(itransport) rc = IBMi_COMMAND_RC_UNEXPECTED out = '' err = '' command_output = itool.dict_out('command') if 'success' in command_output: rc = IBMi_COMMAND_RC_SUCCESS out = command_output['success'] elif 'error' in command_output: command_error = command_output['error'] if 'joblog' in command_error: rc = IBMi_COMMAND_RC_ERROR err = command_error['joblog'] else: # should not be here, must xmlservice has internal error rc = IBMi_COMMAND_RC_ITOOLKIT_NO_KEY_JOBLOG err = "iToolKit result dict does not have key 'joblog', the output \ is %s" % command_output else: # should not be here, must xmlservice has internal error rc = IBMi_COMMAND_RC_ITOOLKIT_NO_KEY_ERROR err = "iToolKit result dict does not have key 'error', the output is \ %s" % command_output return rc, out, err
def test_cmd_error(transport): """Test calling a CL command with an invalid parameter returns an error""" transport.set_out( """<?xml version="1.0" ?><xmlservice><cmd error="fast" exec="cmd" var="cmderror"><error>*** error CHGLIBL LIBL(FROGLEGLONG)</error> <error>202</error> <version>XML Toolkit 1.9.9</version> <error> <status>202</status> <errnoxml>1100012</errnoxml> <xmlerrmsg>XML run cmd failed</xmlerrmsg> <xmlhint>CHGLIBL LIBL(FROGLEGLONG)</xmlhint> </error> <error> <status>202</status> <errnoxml>1100012</errnoxml> <xmlerrmsg>XML run cmd failed</xmlerrmsg> <xmlhint>CHGLIBL LIBL(FROGLEGLONG)</xmlhint> </error> <jobinfo> <jobipc>*na</jobipc> <jobipcskey>FFFFFFFF</jobipcskey> <jobname>QSQSRVR</jobname> <jobuser>QUSER</jobuser> <jobnbr>774740</jobnbr> <jobsts>*ACTIVE</jobsts> <curuser>KADLER</curuser> <ccsid>37</ccsid> <dftccsid>37</dftccsid> <paseccsid>0</paseccsid> <langid>ENU</langid> <cntryid>US</cntryid> <sbsname>QSYSWRK</sbsname> <sbslib>QSYS</sbslib> <curlib/> <syslibl>QSYS QSYS2 QHLPSYS QUSRSYS</syslibl> <usrlibl>QGPL QTEMP QDEVELOP QBLDSYS QBLDSYSR</usrlibl> <jobcpffind>see log scan, not error list</jobcpffind> </jobinfo> </cmd> </xmlservice>""") # noqa E501 tk = iToolKit() tk.add(iCmd('cmderror', 'CHGLIBL LIBL(FROGLEGLONG)')) tk.call(transport) cmderror = tk.dict_out('cmderror') for k, v in cmderror.items(): if not k.startswith('error'): continue item = cmderror[k] if 'errnoxml' not in item: continue assert (item['errnoxml'] == '1100012')
def test_database_transport_call_raises_when_closed(database_execute): schema = 'MYSCHEMA' transport = DatabaseTransport(database_execute, schema=schema) transport.close() with pytest.raises(TransportClosedException): tk = iToolKit() out = transport.call(tk)
def test_ssh_transport_raises_when_closed(mocker): ssh_client = mock_ssh(mocker) transport = SshTransport(ssh_client) transport.close() with pytest.raises(TransportClosedException): tk = iToolKit() out = transport.call(tk)
def test_direct_transport(mocker): mock = mock_direct(mocker) transport = DirectTransport() tk = iToolKit() out = transport.call(tk) assert_xmlservice_params_correct(mock) assert isinstance(out, (bytes, str))
def test_direct_transport_call_raises_when_closed(mocker): mock = mock_direct(mocker) transport = DirectTransport() transport.close() with pytest.raises(TransportClosedException): tk = iToolKit() out = transport.call(tk)
def test_direct_transport_unsupported(mocker): "Test that we get an error running on an unsupported platform" mock_direct = mocker.patch('itoolkit.transport.direct._direct', create=True) mock_direct.xmlservice = mocker.Mock(side_effect=NameError) transport = DirectTransport() tk = iToolKit() with pytest.raises(RuntimeError): transport.call(tk)
def test_ssh_transport_minimal(mocker): ssh_client = mock_ssh(mocker) transport = SshTransport(ssh_client) tk = iToolKit() out = transport.call(tk) assert isinstance(out, (bytes, str)) command = "/QOpenSys/pkgs/bin/xmlservice-cli" ssh_client.exec_command.assert_called_once_with(command)
def test_idb2call_transport_minimal_execute(database_execute): transport = iDB2Call(database_execute) tk = iToolKit() out = transport.call(tk) assert isinstance(out, (bytes, str)) cursor = database_execute.cursor() cursor.execute.assert_called_once() cursor.__iter__.assert_called_once()
def test_database_transport_callproc(database_callproc): transport = DatabaseTransport(database_callproc) tk = iToolKit() out = transport.call(tk) assert isinstance(out, (bytes, str)) cursor = database_callproc.cursor() cursor.callproc.assert_called_once() cursor.__iter__.assert_called_once()
def getNonconfigureDisk(imodule, time): conn = imodule.get_connection() itransport = DatabaseTransport(conn) itool = iToolKit() itool.add(iPgm('qyasrdi', 'QYASRDI') .addParm(iDS('DMIN0100_t', {'len': 'dmilen'}) .addData(iData('dniRet', '10i0', '')) .addData(iData('dmiAvl', '10i0', '')) .addData(iData('dmiOfset', '10i0', '')) .addData(iData('dmiNbr', '10i0', '', {'enddo': 'mycnt'})) .addData(iData('dmiLen', '10i0', '')) .addData(iData('dmiRes', '10i0', '')) .addData(iDS('res_t', {'dim': '999', 'dou': 'mycnt'}) .addData(iData('resDurn', '10a', '')) .addData(iData('resDuff', '1a', '')) .addData(iData('resTrnaswdu', '10a', '')) .addData(iData('resTnawdu', '4a', '')) .addData(iData('resDuaindpsf', '1a', '')) .addData(iData('resDuaiedpsf', '1a', '')) .addData(iData('resRes', '5a', '')) .addData(iData('resDpsn', '10i0', '')) .addData(iData('resCaadps', '10i0', '')) ) ) .addParm(iData('rcvlen', '10i0', '', {'setlen': 'dmilen'})) .addParm(iData('fmtnam', '10a', 'DMIN0100')) .addParm(iData('dmiDurna', '10a', '*UNCONFIG')) .addParm(iData('dmiNbr', '10i0', '1')) .addParm(iDS('ERRC0100_t', {'len': 'errlen'}) .addData(iData('errRet', '10i0', '')) .addData(iData('errAvl', '10i0', '')) .addData(iData('errExp', '7A', '', {'setlen': 'errlen'})) .addData(iData('errRsv', '1A', '')) ) ) itool.call(itransport) qyasrdi = itool.dict_out('qyasrdi') diskList = '' if 'success' in qyasrdi: DMIN0100_t = qyasrdi['DMIN0100_t'] if int(DMIN0100_t['dmiNbr']) > 0: res_t = DMIN0100_t['res_t'] if int(DMIN0100_t['dmiNbr']) == 1: diskList = res_t['resDurn'] else: for rec in res_t: diskList += rec['resDurn'] + ' ' if diskList.endswith(' '): diskList = diskList[:-1] job_log = imodule.itoolkit_get_job_log(time) return diskList, job_log
def test_http_transport_call_raises_when_closed(mocker): mock_urlopen = mock_http_urlopen(mocker) url = 'http://example.com/cgi-bin/xmlcgi.pgm' user = '******' password = '******' database = 'MYDB' transport = HttpTransport(url, user, password, database=database) transport.close() with pytest.raises(TransportClosedException): tk = iToolKit() out = transport.call(tk)
def qsygetph(self): special_value = False if self.pwd in ['*NOPWD', '*NOPWDCHK', '*NOPWDSTS']: self.pwd = ibmi_util.fmtTo10(self.pwd) special_value = True len_of_password = len(self.pwd) # Chang Le: the user name should be converted to upper case input_user = self.name.ljust(10).upper() input_password_len = str(len_of_password) + 'A' itransport = DatabaseTransport(self.conn) itool = iToolKit() if not special_value: itool.add( iPgm('qsygetph', 'qsygetph') .addParm(iData('userId', '10A', input_user)) .addParm(iData('pwd', input_password_len, self.pwd)) .addParm(iData('handle', '12A', '', {'hex': 'on'})) .addParm( iDS('ERRC0100_t', {'len': 'errlen'}) .addData(iData('errRet', '10i0', '')) .addData(iData('errAvl', '10i0', '')) .addData(iData('errExp', '7A', '', {'setlen': 'errlen'})) .addData(iData('errRsv', '1A', '')) ) .addParm(iData('len', '10i0', str(len_of_password))) .addParm(iData('ccsid', '10i0', '37')) ) else: itool.add( iPgm('qsygetph', 'qsygetph') .addParm(iData('userId', '10A', input_user)) .addParm(iData('pwd', '10A', self.pwd)) .addParm(iData('handle', '12A', '', {'hex': 'on'})) .addParm( iDS('ERRC0100_t', {'len': 'errlen'}) .addData(iData('errRet', '10i0', '')) .addData(iData('errAvl', '10i0', '')) .addData(iData('errExp', '7A', '', {'setlen': 'errlen'})) .addData(iData('errRsv', '1A', '')) ) ) itool.call(itransport) qsygetph = itool.dict_out('qsygetph') if 'success' in qsygetph: return qsygetph['handle'] else: return None
def test_cmd_rexx_no_row(transport): """Test calling command with output parms and irow=0 returns data in dict""" transport.set_out(_xml) tk = iToolKit(irow=0) tk.add(iCmd('rtvjoba', 'RTVJOBA USRLIBL(?) SYSLIBL(?) CCSID(?N) OUTQ(?)')) tk.call(transport) rtvjoba = tk.dict_out('rtvjoba') assert ('success' in rtvjoba) assert ('USRLIBL' in rtvjoba) assert ('SYSLIBL' in rtvjoba) assert ('CCSID' in rtvjoba) assert ('OUTQ' in rtvjoba)
def test_database_transport_callproc_schema(database_execute): schema = 'MYSCHEMA' transport = DatabaseTransport(database_execute, schema=schema) tk = iToolKit() out = transport.call(tk) assert isinstance(out, (bytes, str)) cursor = database_execute.cursor() cursor.execute.assert_called_once() cursor.__iter__.assert_called_once() assert len(cursor.execute.call_args[0]) > 0 assert schema in cursor.execute.call_args[0][0]
def itoolkit_run_command(command, asp_group): conn = dbi.connect() itransport = DatabaseTransport(conn) itool = iToolKit() if asp_group != '': itransport = DirectTransport() itool.add( iCmd( 'command', "SETASPGRP ASPGRP({asp_group_pattern})".format( asp_group_pattern=asp_group), {'error': 'on'})) itool.add(iCmd('command', command, {'error': 'on'})) itool.call(itransport) out = '' err = '' if asp_group != '' and isinstance( itool.dict_out('command'), list) and len(itool.dict_out('command')) > 1: command_output = itool.dict_out('command')[1] else: command_output = itool.dict_out('command') command_output = itool.dict_out('command') if 'success' in command_output: rc = IBMi_COMMAND_RC_SUCCESS out = command_output['success'] elif 'error' in command_output: command_error = command_output['error'] if 'joblog' in command_error: rc = IBMi_COMMAND_RC_ERROR err = command_error['joblog'] else: # should not be here, must xmlservice has internal error rc = IBMi_COMMAND_RC_ITOOLKIT_NO_KEY_JOBLOG err = "iToolKit result dict does not have key 'joblog', the output \ is %s" % command_output else: # should not be here, must xmlservice has internal error rc = IBMi_COMMAND_RC_ITOOLKIT_NO_KEY_ERROR err = "iToolKit result dict does not have key 'error', the output is \ %s" % command_output return rc, out, err
def itoolkit_run_sql(sql, db): if db.strip() != '': try: conn = dbi.connect(database='{db_pattern}'.format(db_pattern=db)) except Exception as e: out_list = [] err = "%s, most likely the database does not exist on the system" % str( e) rc = IBMi_COMMAND_RC_UNEXPECTED return rc, out_list, err else: conn = dbi.connect() itransport = DatabaseTransport(conn) itool = iToolKit() itool.add(iSqlQuery('query', sql, {'error': 'on'})) itool.add(iSqlFetch('fetch')) itool.add(iSqlFree('free')) itool.call(itransport) command_output = itool.dict_out('fetch') out_list = [] out = '' err = '' if 'error' in command_output: command_error = command_output['error'] if 'joblog' in command_error: rc = IBMi_COMMAND_RC_ERROR err = command_error['joblog'] else: # should not be here, must xmlservice has internal error rc = IBMi_COMMAND_RC_ITOOLKIT_NO_KEY_JOBLOG err = "iToolKit result dict does not have key 'joblog', the output is %s" % command_output if 'Row not found' in err: rc = 0 # treat as success but also indicate the Row not found message in stderr else: rc = IBMi_COMMAND_RC_SUCCESS out = command_output['row'] if isinstance(out, dict): out_list.append(out) elif isinstance(out, list): out_list = out return rc, out_list, err
def itoolkit_run_command(self, command): '''IBM i XMLSERVICE call *CMD not returning *OUTPUT''' itool = iToolKit() itransport = DatabaseTransport(self.conn) itool.add(iCmd('command', command)) itool.call(itransport) command_output = itool.dict_out('command') out = '' err = '' if 'success' in command_output: rc = ibmi_util.IBMi_COMMAND_RC_SUCCESS out = str(command_output) else: rc = ibmi_util.IBMi_COMMAND_RC_ERROR err = str(command_output) return rc, out, err
def itoolkit_sql_callproc(self, sql): itransport = DatabaseTransport(self.conn) itool = iToolKit(iparm=1) itool.add(iSqlQuery('query', sql)) itool.add(iSqlFree('free')) itool.call(itransport) command_output = itool.dict_out('query') out = '' err = '' if 'success' in command_output: rc = ibmi_util.IBMi_COMMAND_RC_SUCCESS out = str(command_output) else: rc = ibmi_util.IBMi_COMMAND_RC_ERROR err = str(command_output) return rc, out, err
def test_cmd_rexx_row(transport): """Test calling command with output parameters returns data in rows""" transport.set_out(_xml) tk = iToolKit(irow=1) tk.add(iCmd('rtvjoba', 'RTVJOBA USRLIBL(?) SYSLIBL(?) CCSID(?N) OUTQ(?)')) tk.call(transport) rtvjoba = tk.dict_out('rtvjoba') assert ('success' in rtvjoba) assert ('row' in rtvjoba) row = rtvjoba['row'] assert (len(row) == 4) assert ('USRLIBL' in row[0]) assert ('SYSLIBL' in row[1]) assert ('CCSID' in row[2]) assert ('OUTQ' in row[3])
def test_irestcall_transport_minimal(mocker): mock_urlopen = mock_http_urlopen(mocker) url = 'http://example.com/cgi-bin/xmlcgi.pgm' user = '******' password = '******' transport = iRestCall(url, user, password) tk = iToolKit() out = transport.call(tk) assert isinstance(out, (bytes, str)) assert_urlopen_params_correct( mock_urlopen, url, uid=user, pwd=password, )
def test_http_transport_with_database(mocker): mock_urlopen = mock_http_urlopen(mocker) url = 'http://example.com/cgi-bin/xmlcgi.pgm' user = '******' password = '******' database = 'MYDB' transport = HttpTransport(url, user, password, database=database) tk = iToolKit() out = transport.call(tk) assert isinstance(out, (bytes, str)) assert_urlopen_params_correct(mock_urlopen, url, uid=user, pwd=password, db2=database)