def test_rtmmethods():
    # #.getTemplate()
    rtm = RTM.getInstance()
    tpl = rtm.getTemplate('IwontExist')
    assert tpl.getCode() == 500
    assert tpl.getDescription() == 'Response Template not found'

    # #.getTemplates()
    defaultones = sorted(['404', '500', 'error', 'httperror', 'empty', 'unauthorized', 'expired'])
    availableones = sorted(rtm.getTemplates().keys())
    assert defaultones == availableones

    # #.isTemplateMatchHash()
    tpl = RT('')
    assert rtm.isTemplateMatchHash(tpl.getHash(), 'empty') is True

    # #.isTemplateMatchPlain()
    assert rtm.isTemplateMatchPlain(tpl.getPlain(), 'empty') is True
def test_rpmethods():
    rtm = RTM.getInstance()
    rtm.addTemplate(
        'OK', rtm.generateTemplate('200', 'Command completed successfully'))

    # #.parse()
    plain = re.sub(r'/\r\nDESCRIPTION=/', '', rtm.generateTemplate('421', ''))
    assert RP.parse(plain)["DESCRIPTION"] is ""

    # #.serialize()
    # [w/ PROPERTY]
    r = rtm.getTemplate('OK').getHash()
    r["PROPERTY"] = {
        "DOMAIN": ['mydomain1.com', 'mydomain2.com', 'mydomain3.com'],
        "RATING": ['1', '2', '3'],
        "SUM": [3]
    }
    assert RP.serialize(r) == (
        '[RESPONSE]\r\nPROPERTY[DOMAIN][0]=mydomain1.com\r\nPROPERTY[DOMAIN' +
        '][1]=mydomain2.com\r\nPROPERTY[DOMAIN][2]=mydomain3.com\r\nPROPERT' +
        'Y[RATING][0]=1\r\nPROPERTY[RATING][1]=2\r\nPROPERTY[RATING][2]=3\r' +
        '\nPROPERTY[SUM][0]=3\r\nCODE=200\r\nDESCRIPTION=Command completed ' +
        'successfully\r\nEOF\r\n')

    # [w/o PROPERTY]
    tpl = rtm.getTemplate('OK')
    assert RP.serialize(tpl.getHash()) == tpl.getPlain()

    # [w/o CODE, w/o DESCRIPTION]
    h = rtm.getTemplate('OK').getHash()
    h.pop('CODE')
    h.pop('DESCRIPTION')
    assert RP.serialize(h) == '[RESPONSE]\r\nEOF\r\n'

    # [w/ QUEUETIME, w/ RUNTIME]
    h = rtm.getTemplate('OK').getHash()
    h["QUEUETIME"] = '0'
    h["RUNTIME"] = '0.12'
    assert RP.serialize(h) == (
        '[RESPONSE]\r\nCODE=200\r\nDESCRIPTION=Command completed successful' +
        'ly\r\nQUEUETIME=0\r\nRUNTIME=0.12\r\nEOF\r\n')
Ejemplo n.º 3
0
def test_apiclientmethods():
    cl = AC()
    rtm = RTM.getInstance()
    rtm.addTemplate(
        'login200',
        '[RESPONSE]\r\nPROPERTY[SESSION][0]=h8JLZZHdF2WgWWXlwbKWzEG3XrzoW4y' +
        'shhvtqyg0LCYiX55QnhgYX9cB0W4mlpbx\r\nDESCRIPTION=Command completed' +
        ' successfully\r\nCODE=200\r\nQUEUETIME=0\r\nRUNTIME=0.169\r\nEOF\r' +
        '\n')
    rtm.addTemplate('login500',
                    rtm.generateTemplate('530', 'Authentication failed'))
    rtm.addTemplate(
        'OK', rtm.generateTemplate('200', 'Command completed successfully'))
    rtm.addTemplate(
        'listP0',
        '[RESPONSE]\r\nPROPERTY[TOTAL][0]=2701\r\nPROPERTY[FIRST][0]=0\r\nP' +
        'ROPERTY[DOMAIN][0]=0-60motorcycletimes.com\r\nPROPERTY[DOMAIN][1]=' +
        '0-be-s01-0.com\r\nPROPERTY[COUNT][0]=2\r\nPROPERTY[LAST][0]=1\r\nP' +
        'ROPERTY[LIMIT][0]=2\r\nDESCRIPTION=Command completed successfully' +
        '\r\nCODE=200\r\nQUEUETIME=0\r\nRUNTIME=0.023\r\nEOF\r\n')
    rtm.addTemplate(
        'listP1',
        '[RESPONSE]\r\nPROPERTY[TOTAL][0]=2701\r\nPROPERTY[FIRST][0]=2\r\nP' +
        'ROPERTY[DOMAIN][0]=0-qas-ao17-0.org\r\nPROPERTY[DOMAIN][1]=0-sunny' +
        'da222y.com\r\nPROPERTY[COUNT][0]=2\r\nPROPERTY[LAST][0]=3\r\nPROPE' +
        'RTY[LIMIT][0]=2\r\nDESCRIPTION=Command completed successfully\r\nC' +
        'ODE=200\r\nQUEUETIME=0\r\nRUNTIME=0.032\r\nEOF\r\n')
    rtm.addTemplate(
        'listFP0',
        '[RESPONSE]\r\nPROPERTY[TOTAL][0]=3\r\nPROPERTY[FIRST][0]=0\r\nPROP' +
        'ERTY[DOMAIN][0]=0-60motorcycletimes.com\r\nPROPERTY[COUNT][0]=1\r' +
        '\nPROPERTY[LAST][0]=1\r\nPROPERTY[LIMIT][0]=1\r\nDESCRIPTION=Comma' +
        'nd completed successfully\r\nCODE=200\r\nQUEUETIME=0\r\nRUNTIME=0.' +
        '023\r\nEOF\r\n')
    rtm.addTemplate(
        'listFP1',
        '[RESPONSE]\r\nPROPERTY[TOTAL][0]=3\r\nPROPERTY[FIRST][0]=1\r\nPROP' +
        'ERTY[DOMAIN][0]=0-be-s01-0.com\r\nPROPERTY[COUNT][0]=1\r\nPROPERTY' +
        '[LAST][0]=2\r\nPROPERTY[LIMIT][0]=1\r\nDESCRIPTION=Command complet' +
        'ed successfully\r\nCODE=200\r\nQUEUETIME=0\r\nRUNTIME=0.032\r\nEOF' +
        '\r\n')
    rtm.addTemplate(
        'listFP2',
        '[RESPONSE]\r\nPROPERTY[TOTAL][0]=3\r\nPROPERTY[FIRST][0]=2\r\nPROP' +
        'ERTY[DOMAIN][0]=0-qas-ao17-0.org\r\nPROPERTY[COUNT][0]=2\r\nPROPER' +
        'TY[LAST][0]=3\r\nPROPERTY[LIMIT][0]=1\r\nDESCRIPTION=Command compl' +
        'eted successfully\r\nCODE=200\r\nQUEUETIME=0\r\nRUNTIME=0.032\r\nE' +
        'OF\r\n')

    # #.getPOSTData()
    # test object input with special chars
    validate = (
        's_entity=54cd&s_command=COMMAND%3DModifyDomain%0AAUTH%3Dgwrgwqg%25' +
        '%26%5C44t3%2A')
    enc = cl.getPOSTData({
        'COMMAND': 'ModifyDomain',
        'AUTH': 'gwrgwqg%&\\44t3*'
    })
    assert enc == validate

    # test string input
    enc = cl.getPOSTData('gregergege')
    assert enc == 's_entity=54cd&s_command='

    # test object input with null value in parameter
    validate = 's_entity=54cd&s_command=COMMAND%3DModifyDomain'
    enc = cl.getPOSTData({"COMMAND": 'ModifyDomain', "AUTH": None})
    assert enc == validate

    # #.enableDebugMode()
    cl.enableDebugMode()
    cl.disableDebugMode()

    # #.getSession()
    # initial value
    session = cl.getSession()
    assert session is None
    # custom value
    sessid = 'testSessionID12345678'
    cl.setSession(sessid)
    session = cl.getSession()
    assert session is sessid
    cl.setSession('')

    # #.getURL()
    assert cl.getURL() == 'https://coreapi.1api.net/api/call.cgi'

    # #.setURL()
    tmp = 'http://coreapi.1api.net/api/call.cgi'
    url = cl.setURL(tmp).getURL()
    assert url is tmp
    cl.setURL('https://coreapi.1api.net/api/call.cgi')

    # #.setOTP()
    # [otp set]
    cl.setOTP('12345678')
    tmp = cl.getPOSTData({'COMMAND': 'StatusAccount'})
    exp = 's_entity=54cd&s_otp=12345678&s_command=COMMAND%3DStatusAccount'
    assert tmp == exp

    # [otp reset]
    cl.setOTP('')
    tmp = cl.getPOSTData({'COMMAND': 'StatusAccount'})
    exp = 's_entity=54cd&s_command=COMMAND%3DStatusAccount'
    assert tmp == exp

    # #.setSession()
    # [session set]
    cl.setSession('12345678')
    tmp = cl.getPOSTData({'COMMAND': 'StatusAccount'})
    exp = 's_entity=54cd&s_session=12345678&s_command=COMMAND%3DStatusAccount'
    assert tmp == exp

    # [credentials and session set]
    cl.setRoleCredentials('myaccountid', 'myrole', 'mypassword')
    cl.setOTP('12345678')
    cl.setSession('12345678')
    tmp = cl.getPOSTData({'COMMAND': 'StatusAccount'})
    exp = 's_entity=54cd&s_session=12345678&s_command=COMMAND%3DStatusAccount'
    assert tmp == exp

    # [session reset]
    cl.setSession('')
    tmp = cl.getPOSTData({'COMMAND': 'StatusAccount'})
    assert tmp == 's_entity=54cd&s_command=COMMAND%3DStatusAccount'

    # #.saveSession/reuseSession
    sessionobj = {}
    cl.setSession('12345678').saveSession(sessionobj)
    cl2 = AC()
    cl2.reuseSession(sessionobj)
    tmp = cl2.getPOSTData({'COMMAND': 'StatusAccount'})
    exp = 's_entity=54cd&s_session=12345678&s_command=COMMAND%3DStatusAccount'
    assert tmp == exp
    cl.setSession('')

    # #.setRemoteIPAddress()
    # [ip set]
    cl.setRemoteIPAddress('10.10.10.10')
    tmp = cl.getPOSTData({'COMMAND': 'StatusAccount'})
    exp = (
        's_entity=54cd&s_remoteaddr=10.10.10.10&s_command=COMMAND%3DStatusA' +
        'ccount')
    assert tmp == exp

    # [ip reset]
    cl.setRemoteIPAddress('')
    tmp = cl.getPOSTData({'COMMAND': 'StatusAccount'})
    assert tmp == 's_entity=54cd&s_command=COMMAND%3DStatusAccount'

    # #.setCredentials()
    # [credentials set]
    cl.setCredentials('myaccountid', 'mypassword')
    tmp = cl.getPOSTData({'COMMAND': 'StatusAccount'})
    exp = (
        's_entity=54cd&s_login=myaccountid&s_pw=mypassword&s_command=COMMAN' +
        'D%3DStatusAccount')
    assert tmp == exp

    # [session reset]
    cl.setCredentials('', '')
    tmp = cl.getPOSTData({'COMMAND': 'StatusAccount'})
    assert tmp == 's_entity=54cd&s_command=COMMAND%3DStatusAccount'

    # #.setRoleCredentials()
    # [role credentials set]
    cl.setRoleCredentials('myaccountid', 'myroleid', 'mypassword')
    tmp = cl.getPOSTData({'COMMAND': 'StatusAccount'})
    exp = (
        's_entity=54cd&s_login=myaccountid%21myroleid&s_pw=mypassword&s_com' +
        'mand=COMMAND%3DStatusAccount')
    assert tmp == exp

    # [role credentials reset]
    cl.setRoleCredentials('', '', '')
    tmp = cl.getPOSTData({'COMMAND': 'StatusAccount'})
    assert tmp == 's_entity=54cd&s_command=COMMAND%3DStatusAccount'

    # #.login()
    # [login succeeded; no role used]
    cl.useOTESystem()
    cl.setCredentials('test.user', 'test.passw0rd')
    cl.setRemoteIPAddress('1.2.3.4')
    r = cl.login()
    assert isinstance(r, R) is True
    assert r.isSuccess() is True, ("{0} {1}").format(r.getCode(),
                                                     r.getDescription())
    rec = r.getRecord(0)
    assert rec is not None
    assert rec.getDataByKey('SESSION') is not None

    # [login succeeded; role used]
    cl.useOTESystem()
    cl.setRoleCredentials('test.user', 'testrole', 'test.passw0rd')
    r = cl.login()
    assert isinstance(r, R)
    assert r.isSuccess() is True, ("{0} {1}").format(r.getCode(),
                                                     r.getDescription())
    rec = r.getRecord(0)
    assert rec is not None
    assert rec.getDataByKey('SESSION') is not None

    # [login failed; wrong credentials]
    cl.setCredentials('test.user', 'WRONGPASSWORD')
    r = cl.login()
    assert isinstance(r, R)
    assert r.isError() is True

    # [login failed; http error]
    tpl = rtm.getTemplate('httperror')
    old = cl.getURL()
    cl.setURL('https://iwontsucceedgregegeg343teagr43.com/api/call.cgi')
    cl.setCredentials('test.user', 'WRONGPASSWORD')
    r = cl.login()
    assert isinstance(r, R)
    assert r.isTmpError() is True
    assert r.getDescription() == tpl.getDescription()
    cl.setURL(old)

    # [login succeeded; no session returned]
    # TODO: need network mock
    # tpl = R(rtm.getTemplate('OK').getPlain())
    # cl.useOTESystem()
    # cl.setCredentials('test.user', 'test.passw0rd')
    # r = cl.login()
    # assert isinstance(r, R)
    # assert r.isSuccess() is True
    # rec = r.getRecord(0)
    # assert rec is Node

    # #.loginExtended()
    # [login succeeded; no role used]
    cl.useOTESystem()
    cl.setCredentials('test.user', 'test.passw0rd')
    r = cl.loginExtended({'TIMEOUT': 60})
    assert isinstance(r, R) is True
    assert r.isSuccess() is True
    rec = r.getRecord(0)
    assert rec is not None
    assert rec.getDataByKey('SESSION') is not None

    # #.logout()
    # [logout succeeded]
    r = cl.logout()
    assert isinstance(r, R)
    assert r.isSuccess() is True

    # [logout failed; session no longer exists]
    tpl = R(rtm.getTemplate('login200').getPlain())
    cl.enableDebugMode()
    cl.setSession(tpl.getRecord(0).getDataByKey('SESSION'))
    r = cl.logout()
    assert isinstance(r, R) is True
    assert r.isError() is True

    # #.request()
    # [200 < r.statusCode > 299]
    # TODO need network mock
    # tpl2 = R(rtm.getTemplate('httperror').getPlain())
    # cl.setCredentials('test.user', 'test.passw0rd')
    # cl.useOTESystem()
    # r = cl.request({ 'COMMAND': 'GetUserIndex' })
    # assert isinstance(r, R) is True
    # assert r.isTmpError() is True
    # assert r.getCode() == tpl2.getCode()
    # assert r.getDescription() == tpl2.getDescription()

    # [200 < r.statusCode > 299, no debug]
    # TODO need network mock
    # tpl2 = R(rtm.getTemplate('httperror').getPlain())
    # cl.disableDebugMode()
    # r = cl.request({ 'COMMAND': 'GetUserIndex' })
    # assert isinstance(r, R)
    # assert r.isTmpError() is True
    # assert r.getCode() == tpl2.getCode()
    # assert r.getDescription() == tpl2.getDescription()

    # .requestNextResponsePage
    # [no LAST set]
    cl.setCredentials('test.user', 'test.passw0rd')
    cl.useOTESystem()
    r = R(
        rtm.getTemplate('listP0').getPlain(), {
            'COMMAND': 'QueryDomainList',
            'LIMIT': 2,
            'FIRST': 0
        })
    nr = cl.requestNextResponsePage(r)
    assert r.isSuccess() is True
    assert nr.isSuccess() is True
    assert r.getRecordsLimitation() == 2
    assert nr.getRecordsLimitation() == 2
    assert r.getRecordsCount() == 2
    assert nr.getRecordsCount() == 2
    assert r.getFirstRecordIndex() == 0
    assert r.getLastRecordIndex() == 1
    assert nr.getFirstRecordIndex() == 2
    assert nr.getLastRecordIndex() == 3

    # [LAST set]
    r = R(
        rtm.getTemplate('listP0').getPlain(), {
            'COMMAND': 'QueryDomainList',
            'LIMIT': 2,
            'FIRST': 0,
            'LAST': 1
        })
    with pytest.raises(Exception, match=r'Parameter LAST in use.'):
        cl.requestNextResponsePage(r)

    # [no FIRST set]
    cl.disableDebugMode()
    r = R(
        rtm.getTemplate('listP0').getPlain(), {
            'COMMAND': 'QueryDomainList',
            'LIMIT': 2
        })
    nr = cl.requestNextResponsePage(r)
    assert r.isSuccess() is True
    assert nr.isSuccess() is True
    assert r.getRecordsLimitation() == 2
    assert nr.getRecordsLimitation() == 2
    assert r.getRecordsCount() == 2
    assert nr.getRecordsCount() == 2
    assert r.getFirstRecordIndex() == 0
    assert r.getLastRecordIndex() == 1
    assert nr.getFirstRecordIndex() == 2
    assert nr.getLastRecordIndex() == 3

    # #.requestAllResponsePages()
    # [success case]
    nr = cl.requestAllResponsePages({
        'COMMAND': 'QuerySSLCertList',
        'FIRST': 0,
        'LIMIT': 100
    })
    assert len(nr) > 0

    # #.setUserView()
    cl.setUserView('hexotestman.com')
    r = cl.request({'COMMAND': 'GetUserIndex'})
    assert isinstance(r, R) is True
    assert r.isSuccess() is True

    # #.resetUserView()
    cl.setUserView('')
    r = cl.request({'COMMAND': 'GetUserIndex'})
    assert isinstance(r, R) is True
    assert r.isSuccess() is True
Ejemplo n.º 4
0
def test_responsemethods():
    rtm = RTM.getInstance()
    rtm.addTemplate(
        'listP0',
        '[RESPONSE]\r\nPROPERTY[TOTAL][0]=2701\r\nPROPERTY[FIRST][0]=0\r\nP' +
        'ROPERTY[DOMAIN][0]=0-60motorcycletimes.com\r\nPROPERTY[DOMAIN][1]=' +
        '0-be-s01-0.com\r\nPROPERTY[COUNT][0]=2\r\nPROPERTY[LAST][0]=1\r\nP' +
        'ROPERTY[LIMIT][0]=2\r\nDESCRIPTION=Command completed successfully' +
        '\r\nCODE=200\r\nQUEUETIME=0\r\nRUNTIME=0.023\r\nEOF\r\n')
    rtm.addTemplate(
        'OK', rtm.generateTemplate('200', 'Command completed successfully'))

    # #.getCurrentPageNumber()
    # [w/ entries in response]
    r = R(rtm.getTemplate('listP0').getPlain())
    assert r.getCurrentPageNumber() == 1

    # [w/o entries in response]
    r = R(rtm.getTemplate('OK').getPlain())
    assert r.getCurrentPageNumber() is None

    # #.getFirstRecordIndex()
    # [w/o FIRST in response, no rows]
    r = R(rtm.getTemplate('OK').getPlain())
    assert r.getFirstRecordIndex() is None

    # [w/o FIRST in response, rows]
    h = rtm.getTemplate('OK').getHash()
    h["PROPERTY"] = {"DOMAIN": ['mydomain1.com', 'mydomain2.com']}
    r = R(RP.serialize(h))
    assert r.getFirstRecordIndex() == 0

    # #.getColumns()
    r = R(rtm.getTemplate('listP0').getPlain())
    cols = r.getColumns()
    assert len(cols) == 6

    # #.getColumnIndex()
    # [colum exists]
    r = R(rtm.getTemplate('listP0').getPlain())
    assert r.getColumnIndex('DOMAIN', 0) == '0-60motorcycletimes.com'

    # [colum does not exist]
    assert r.getColumnIndex('COLUMN_NOT_EXISTS', 0) is None

    # #.getColumnKeys()
    colkeys = r.getColumnKeys()
    assert len(colkeys) == 6
    assert sorted(colkeys) == sorted(
        ['COUNT', 'DOMAIN', 'FIRST', 'LAST', 'LIMIT', 'TOTAL'])

    # #.getCurrentRecord()
    # [records available]
    rec = r.getCurrentRecord()
    assert rec.getData() == {
        'COUNT': '2',
        'DOMAIN': '0-60motorcycletimes.com',
        'FIRST': '0',
        'LAST': '1',
        'LIMIT': '2',
        'TOTAL': '2701'
    }

    # [no records available]
    r = R(rtm.getTemplate('OK').getPlain())
    assert r.getCurrentRecord() is None

    # #.getListHash()
    r = R(rtm.getTemplate('listP0').getPlain())
    lh = r.getListHash()
    assert len(lh["LIST"]) == 2
    assert lh["meta"]["columns"] is r.getColumnKeys()
    assert lh["meta"]["pg"] == r.getPagination()

    # #.getNextRecord()
    rec = r.getNextRecord()
    assert rec.getData() == {'DOMAIN': '0-be-s01-0.com'}
    rec = r.getNextRecord()
    assert rec is None

    # #.getPagination()
    pager = r.getPagination()
    assert sorted(pager.keys()) == sorted([
        'COUNT', 'CURRENTPAGE', 'FIRST', 'LAST', 'LIMIT', 'NEXTPAGE', 'PAGES',
        'PREVIOUSPAGE', 'TOTAL'
    ])

    # #.getPreviousRecord()
    r.getNextRecord()
    assert r.getPreviousRecord().getData() == {
        'COUNT': '2',
        'DOMAIN': '0-60motorcycletimes.com',
        'FIRST': '0',
        'LAST': '1',
        'LIMIT': '2',
        'TOTAL': '2701'
    }
    assert r.getPreviousRecord() is None

    # #.hasNextPage()
    # [no rows]
    r = R(rtm.getTemplate('OK').getPlain())
    assert r.hasNextPage() is False

    # [rows]
    r = R(rtm.getTemplate('listP0').getPlain())
    assert r.hasNextPage() is True

    # #.hasPreviousPage()
    # [no rows]
    r = R(rtm.getTemplate('OK').getPlain())
    assert r.hasPreviousPage() is False

    # [rows]
    r = R(rtm.getTemplate('listP0').getPlain())
    assert r.hasPreviousPage() is False

    # #.getLastRecordIndex()
    # [no rows]
    r = R(rtm.getTemplate('OK').getPlain())
    assert r.getLastRecordIndex() is None

    # [rows]
    h = rtm.getTemplate('OK').getHash()
    h["PROPERTY"] = {"DOMAIN": ['mydomain1.com', 'mydomain2.com']}
    r = R(RP.serialize(h))
    assert r.getLastRecordIndex() == 1

    # #.getNextPageNumber()
    # [no rows]
    r = R(rtm.getTemplate('OK').getPlain())
    assert r.getNextPageNumber() is None

    # [rows]
    r = R(rtm.getTemplate('listP0').getPlain())
    assert r.getNextPageNumber() == 2

    # #.getNumberOfPages()
    r = R(rtm.getTemplate('OK').getPlain())
    assert r.getNumberOfPages() == 0

    # #.getPreviousPageNumber()
    # [no rows]
    r = R(rtm.getTemplate('OK').getPlain())
    assert r.getPreviousPageNumber() is None

    # [rows]
    r = R(rtm.getTemplate('listP0').getPlain())
    assert r.getPreviousPageNumber() is None

    # #.rewindRecordList()
    r = R(rtm.getTemplate('listP0').getPlain())
    assert r.getPreviousRecord() is None
    assert r.getNextRecord() is not None
    assert r.getNextRecord() is None
    assert r.rewindRecordList().getPreviousRecord() is None