1
// SPDX-License-Identifier: BSD-2-Clause
2
/*
3
 * dtls_psk_client_server_test.rs - Tests for DTLS PSK clients+servers.
4
 * This file is part of the libcoap-rs crate, see the README and LICENSE files for
5
 * more information and terms of use.
6
 * Copyright © 2021-2024 The NAMIB Project Developers, all rights reserved.
7
 * See the README as well as the LICENSE file for more information.
8
 */
9

            
10
#![cfg(feature = "dtls-psk")]
11
use std::time::Duration;
12

            
13
use libcoap_rs::crypto::psk::PskKey;
14
use libcoap_rs::crypto::psk::{ClientPskContextBuilder, ServerPskContextBuilder};
15
use libcoap_rs::session::CoapClientSession;
16
use libcoap_rs::{
17
    message::CoapMessageCommon,
18
    protocol::{CoapMessageCode, CoapResponseCode},
19
    session::CoapSessionCommon,
20
    CoapContext,
21
};
22

            
23
mod common;
24

            
25
#[test]
26
4
pub fn dtls_psk_client_server_request() {
27
4
    let server_address = common::get_unused_server_addr();
28
4
    let dummy_key = PskKey::new(Some("dtls_test_id"), "dtls_test_key___");
29
4
    let client_psk_context = ClientPskContextBuilder::new(dummy_key.clone()).build();
30
4

            
31
4
    let server_handle = common::spawn_test_server(move |mut context| {
32
4
        let server_psk_context = ServerPskContextBuilder::new(dummy_key.clone()).build();
33
4
        context.set_psk_context(server_psk_context).unwrap();
34
4
        context.add_endpoint_dtls(server_address).unwrap();
35
4
        context
36
4
    });
37
4

            
38
4
    let mut context = CoapContext::new().unwrap();
39
4
    let session = CoapClientSession::connect_dtls(&mut context, server_address, client_psk_context).unwrap();
40
4

            
41
4
    let request = common::gen_test_request();
42
4
    let req_handle = session.send_request(request).unwrap();
43
    loop {
44
22
        assert!(context.do_io(Some(Duration::from_secs(10))).expect("error during IO") <= Duration::from_secs(10));
45
22
        for response in session.poll_handle(&req_handle) {
46
4
            assert_eq!(response.code(), CoapMessageCode::Response(CoapResponseCode::Content));
47
4
            assert_eq!(response.data().unwrap().as_ref(), "Hello World!".as_bytes());
48
4
            server_handle.join().expect("Test server crashed with failure.");
49
4
            return;
50
4
        }
51
4
    }
52
4
}