Skip to content

Commit

Permalink
test: add websocket masking tests
Browse files Browse the repository at this point in the history
  • Loading branch information
c-cube committed Apr 4, 2024
1 parent dbd0025 commit 2eba43e
Show file tree
Hide file tree
Showing 5 changed files with 66 additions and 0 deletions.
6 changes: 6 additions & 0 deletions tests/unit/ws/dune
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@

(tests
(names t_ws t_ws_q)
(package tiny_httpd)
(deps masked.data)
(libraries tiny_httpd.ws qcheck-core qcheck-core.runner test_util))
Binary file added tests/unit/ws/masked.data
Binary file not shown.
Empty file added tests/unit/ws/t_ws.expected
Empty file.
21 changes: 21 additions & 0 deletions tests/unit/ws/t_ws.ml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
open Test_util

let read_file file : string =
let buf = Buffer.create 32 in
let ic = open_in_bin file in
Buffer.add_channel buf ic (in_channel_length ic);
Buffer.contents buf

let apply_masking = Tiny_httpd_ws.Private_.apply_masking

let decode ~key b =
let buf = Bytes.copy b in
apply_masking ~mask_key:key buf 0 (Bytes.length buf);
buf

let () =
let key = "\x57\x7d\xfd\x95" |> Bytes.unsafe_of_string in
let content = read_file "masked.data" in
let decoded = decode ~key (Bytes.unsafe_of_string content) in
print_endline (Bytes.unsafe_to_string decoded);
()
39 changes: 39 additions & 0 deletions tests/unit/ws/t_ws_q.ml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
open Test_util

let apply_masking = Tiny_httpd_ws.Private_.apply_masking

let decode ~key b =
let buf = Bytes.copy b in
apply_masking ~mask_key:key buf 0 (Bytes.length buf);
buf

let ppb b = Printf.sprintf "%S" (Bytes.unsafe_to_string b)

let () =
add_qcheck
@@ QCheck.Test.make ~count:10_000
Q.(
pair (bytes_of_size (Gen.return 4)) (bytes_of_size Gen.(0 -- 6000))
(* |> Q.add_stat ("b.size", fun (_k, b) -> Bytes.length b) *)
|> Q.add_shrink_invariant (fun (k, _) -> Bytes.length k = 4))
(fun (key, b) ->
Q.assume (Bytes.length key = 4);
let b2 = decode ~key b in

let is_zero =
Bytes.equal key (Bytes.unsafe_of_string "\x00\x00\x00\x00")
in

if Bytes.length b >= 2 && not is_zero then (
(* key must modify the byte vec *)
let are_eq = Bytes.equal b b2 in
if are_eq then
Q.Test.fail_reportf "key=%s, expected different: b=%S b2=%S"
(ppb key) (ppb b) (ppb b2)
);

let b3 = decode ~key b2 in
assert (Bytes.equal b b3);
true)

let () = run_qcheck_and_exit ()

0 comments on commit 2eba43e

Please sign in to comment.