% Regression tests for uds_utils
~ needs_root not_pypy automotive_comm

+ Configuration
~ conf

= Imports

with open(scapy_path("test/contrib/automotive/interface_mockup.py")) as f:
    exec(f.read())


############
############
+ Load general modules

= Load contribution layer
load_contrib("automotive.uds", globals_dict=globals())

= Test Session Enumerator
drain_bus(iface0)
drain_bus(iface1)

packet = ISOTP(b'Request')
succ = False

with new_can_socket0() as isocan1, ISOTPSocket(isocan1, sid=0x241, did=0x641, basecls=UDS) as sendSock, \
     new_can_socket0() as isocan2, ISOTPSocket(isocan2, sid=0x641, did=0x241, basecls=UDS) as recvSock:
    def answer(pkt):
        pkt.service = pkt.service + 0x40
        recvSock.send(pkt)
    def sniffer():
        global sniffed, succ
        sniffed = 0
        pkts = recvSock.sniff(timeout=10, prn=answer)
        sniffed = len(pkts)
        succ = True
    threadSniffer = threading.Thread(target=sniffer)
    threadSniffer.start()
    sessions = UDS_SessionEnumerator(sendSock, session_range=range(3))
    threadSniffer.join(timeout=30)

assert sniffed == 3*2
assert succ


= Test Service Enumerator
drain_bus(iface0)
drain_bus(iface1)

packet = ISOTP(b'Request')
succ = False

with new_can_socket0() as isocan1, ISOTPSocket(isocan1, sid=0x241, did=0x641, basecls=UDS) as sendSock, \
     new_can_socket0() as isocan2, ISOTPSocket(isocan2, sid=0x641, did=0x241, basecls=UDS) as recvSock:
    def answer(pkt):
        pkt.service = pkt.service + 0x40
        if pkt.service == 0x7f:
            pkt = UDS()/UDS_NR(requestServiceId=0x3f)
        recvSock.send(pkt)
    def sniffer():
        global sniffed, succ
        sniffed = 0
        pkts = recvSock.sniff(timeout=10, prn=answer)
        sniffed = len(pkts)
        succ = True
    threadSniffer = threading.Thread(target=sniffer)
    threadSniffer.start()
    services = UDS_ServiceEnumerator(sendSock)
    threadSniffer.join(timeout=30)

assert sniffed == 128
assert succ


= Test getTableEntry
a = ('DefaultSession', UDS()/UDS_SAPR())
b = ('ProgrammingSession', UDS()/UDS_NR(requestServiceId=0x10, negativeResponseCode=0x13))
c = ('ExtendedDiagnosticSession', UDS()/UDS_IOCBI())

res_a = getTableEntry(a)
res_b = getTableEntry(b)
res_c = getTableEntry(c)

#make_lined_table([a, b, c], getTableEntry)

assert res_a == ('DefaultSession', '0x27: SecurityAccess', 'PositiveResponse')
assert res_b == ('ProgrammingSession', '0x10: DiagnosticSessionControl', 'incorrectMessageLengthOrInvalidFormat')
assert res_c == ('ExtendedDiagnosticSession', '0x2f: InputOutputControlByIdentifier', 'PositiveResponse')

+ Cleanup

= Delete vcan interfaces

assert cleanup_interfaces()
