% CoAP layer test campaign

+ Syntax check
= Import the CoAP layer
from scapy.contrib.coap import *

+ Test CoAP
= CoAP default values
assert(raw(CoAP()) == b'\x40\x00\x00\x00')

= Token length calculation
p = CoAP(token='foobar')
assert(CoAP(raw(p)).tkl == 6)

= CON GET dissect
p = CoAP(b'\x40\x01\xd9\xe1\xbb\x2e\x77\x65\x6c\x6c\x2d\x6b\x6e\x6f\x77\x6e\x04\x63\x6f\x72\x65')
assert(p.code == 1)
assert(p.ver == 1)
assert(p.tkl == 0)
assert(p.tkl == 0)
assert(p.msg_id == 55777)
assert(p.token == b'')
assert(p.type == 0)
assert(p.options == [('Uri-Path', b'.well-known'), ('Uri-Path', b'core')])

= Extended option delta
assert(raw(CoAP(options=[("Uri-Query", "query")])) == b'\x40\x00\x00\x00\xd5\x02\x71\x75\x65\x72\x79')

= Extended option length
assert(raw(CoAP(options=[("Location-Path", 'x' * 280)])) == b'\x40\x00\x00\x00\x8e\x0b\x00' + b'\x78' * 280)

= Options should be ordered by option number
assert(raw(CoAP(options=[("Uri-Query", "b"),("Uri-Path","a")])) == b'\x40\x00\x00\x00\xb1\x61\x41\x62')

= Options of the same type should not be reordered
assert(raw(CoAP(options=[("Uri-Path", "b"),("Uri-Path","a")])) == b'\x40\x00\x00\x00\xb1\x62\x01\x61')

+ Test layer binding
= Destination port
p = UDP()/CoAP()
assert(p[UDP].dport == 5683)

= Source port
s = b'\x16\x33\xa0\xa4\x00\x78\xfe\x8b\x60\x45\xd9\xe1\xc1\x28\xff\x3c\x2f\x3e\x3b\x74\x69\x74\x6c\x65\x3d\x22\x47\x65' \
    b'\x6e\x65\x72\x61\x6c\x20\x49\x6e\x66\x6f\x22\x3b\x63\x74\x3d\x30\x2c\x3c\x2f\x74\x69\x6d\x65\x3e\x3b\x69\x66\x3d' \
    b'\x22\x63\x6c\x6f\x63\x6b\x22\x3b\x72\x74\x3d\x22\x54\x69\x63\x6b\x73\x22\x3b\x74\x69\x74\x6c\x65\x3d\x22\x49\x6e' \
    b'\x74\x65\x72\x6e\x61\x6c\x20\x43\x6c\x6f\x63\x6b\x22\x3b\x63\x74\x3d\x30\x3b\x6f\x62\x73\x2c\x3c\x2f\x61\x73\x79' \
    b'\x6e\x63\x3e\x3b\x63\x74\x3d\x30'
assert(CoAP in UDP(s))

= building with a text/plain payload
p = CoAP(ver = 1, type = 0, code = 0x42, msg_id = 0xface, options=[("Content-Format", b"\x00")], paymark = b"\xff")
p /= Raw(b"\xde\xad\xbe\xef")
assert(raw(p) == b'\x40\x42\xfa\xce\xc1\x00\xff\xde\xad\xbe\xef')

= dissection with a text/plain payload
p = CoAP(raw(p))
assert(p.ver == 1)
assert(p.type == 0)
assert(p.code == 0x42)
assert(p.msg_id == 0xface)
assert(isinstance(p.payload, Raw))
assert(p.payload.load == b'\xde\xad\xbe\xef')
