use std::time::Duration;
use ocpp_kit::Version;
use ocpp_kit::engine::{Engine, EngineConfig, Input, Instant, Role, Timer};
use ocpp_kit::testkit::Recorder;
const NOW: Instant = Instant::ZERO;
fn raw(json: &str) -> Box<ocpp_kit::RawValue> {
ocpp_kit::RawValue::from_string(json.to_string()).unwrap()
}
#[test]
fn a_recorder_answers_the_questions_an_engine_test_actually_asks() {
let mut engine = Engine::new(EngineConfig::new(Role::ChargingStation, Version::V2_1));
engine.handle(
NOW,
Input::Connected {
version: Version::V2_1,
},
);
engine
.call(NOW, "BootNotification", raw(r#"{"reason":"PowerUp"}"#))
.unwrap();
let mut recorder = Recorder::new();
recorder.drain(&mut engine);
assert!(recorder.only_frame().contains("BootNotification"));
let id = recorder.only_frame_id();
assert!(recorder.timer(Timer::CallTimeout).is_some());
engine.handle(NOW, Input::Received(&format!(
r#"[3,"{id}",{{"currentTime":"2024-01-01T00:00:00Z","interval":300,"status":"Accepted"}}]"#
)));
recorder.drain(&mut engine);
let outcomes = recorder.outcomes();
assert_eq!(outcomes.len(), 1);
assert_eq!(outcomes[0].action, "BootNotification");
assert!(outcomes[0].result.is_ok());
assert!(recorder.failures().is_empty(), "{:?}", recorder.failures());
engine.handle(NOW, Input::Received(r#"[3,"never-sent",{}]"#));
recorder.drain(&mut engine);
assert_eq!(recorder.violations().len(), 1);
}
#[test]
fn a_recorder_makes_a_timing_rule_readable() {
let mut engine = Engine::new(
EngineConfig::new(Role::ChargingStation, Version::V2_1)
.with_call_timeout(Duration::from_secs(30)),
);
engine.handle(
NOW,
Input::Connected {
version: Version::V2_1,
},
);
engine
.call(NOW, "BootNotification", raw(r#"{"reason":"PowerUp"}"#))
.unwrap();
let mut recorder = Recorder::new();
recorder.drain(&mut engine);
assert_eq!(
recorder.timer(Timer::CallTimeout),
Some(Instant::from_millis(30_000))
);
engine.handle(Instant::from_millis(30_000), Input::Timeout);
recorder.drain(&mut engine);
assert_eq!(
recorder.failures(),
vec![("BootNotification", &ocpp_kit::engine::CallFailure::Timeout)]
);
}
#[cfg(feature = "tokio")]
mod peers {
use super::Duration;
use ocpp_kit::Version;
use ocpp_kit::testkit::{MockCsms, MockStation};
#[tokio::test]
async fn a_station_can_be_tested_against_a_csms_in_two_lines() {
let csms = MockCsms::start().await.expect("the mock CSMS starts");
let station = MockStation::connect(csms.url(), "CS-0001").expect("the station connects");
let boot = station.boot(Version::V2_1).await.expect("boot succeeds");
assert!(boot.get().contains("Accepted"), "{}", boot.get());
assert!(
csms.wait_for("BootNotification", Duration::from_secs(5))
.await
);
let exchange = csms
.exchanges()
.into_iter()
.find(|exchange| exchange.action == "BootNotification")
.expect("the CSMS recorded it");
assert_eq!(exchange.identity.as_str(), "CS-0001");
assert!(exchange.payload.contains("PowerUp"));
station.shutdown(Duration::from_secs(2)).await;
}
#[tokio::test]
async fn a_csms_can_call_a_mock_station_back() {
let csms = MockCsms::start().await.expect("the mock CSMS starts");
let station = MockStation::connect(csms.url(), "CS-0002").expect("the station connects");
station.boot(Version::V2_1).await.expect("boot succeeds");
let identity = station.identity().clone();
let session = tokio::time::timeout(Duration::from_secs(5), async {
loop {
if let Some(session) = csms.handle().session(&identity).await {
return session;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("the session appears in the router");
let reset = session
.call(ocpp_kit::v2_1::ResetRequest::new(
ocpp_kit::v2_1::ResetEnum::Immediate,
))
.await
.expect("the station answers");
assert_eq!(reset.status, ocpp_kit::v2_1::ResetStatus::Accepted);
assert!(station.saw("Reset"));
}
#[tokio::test]
async fn a_mock_station_offers_only_the_versions_it_is_given() {
use ocpp_kit::transport::{Ended, TransportError};
use ocpp_kit::version::NegotiationError;
let csms = MockCsms::start().await.expect("the mock CSMS starts");
let station = MockStation::builder("CS-16")
.versions([Version::V1_6])
.connect(csms.url())
.expect("the station connects");
station
.boot(Version::V1_6)
.await
.expect("a 1.6 boot is answered");
assert_eq!(station.handle().state().version, Version::V1_6);
let modern = MockCsms::builder()
.versions([Version::V2_1])
.start()
.await
.expect("the mock CSMS starts");
let old = MockStation::builder("CS-16")
.versions([Version::V1_6])
.connect(modern.url())
.expect("the station is spawned");
let ended = tokio::time::timeout(Duration::from_secs(5), old.handle().closed())
.await
.expect("the station ends");
assert!(
matches!(&ended, Ended::ConnectFailed(error)
if matches!(**error, TransportError::Negotiation(NegotiationError::NoSubprotocol))),
"{ended}"
);
}
#[tokio::test]
async fn a_csms_controls_a_simulated_vehicle_over_the_wire() {
use std::sync::{Arc, Mutex};
use ocpp_kit::engine::CallOptions;
use ocpp_kit::rpc::CallError;
use ocpp_kit::testkit::{Ev, Wallbox};
use ocpp_kit::types::Decimal;
use ocpp_kit::v2_1;
let csms = MockCsms::start().await.expect("the mock CSMS starts");
let start = "2026-11-20T18:00:00Z".parse().unwrap();
let wallbox = Arc::new(Mutex::new(Wallbox::new(Version::V2_1, start)));
let station = MockStation::builder("CS-0004")
.answer({
let wallbox = wallbox.clone();
move |_, request| {
let mut wallbox = wallbox
.lock()
.map_err(|_| CallError::internal("poisoned"))?;
wallbox
.answer(request)
.unwrap_or_else(|| Err(CallError::not_implemented(&request.action)))
}
})
.connect(csms.url())
.expect("the station connects");
station.boot(Version::V2_1).await.expect("boot succeeds");
let plugged = wallbox
.lock()
.unwrap()
.plug_in(Ev::builder().reaction(Duration::ZERO).build())
.unwrap();
for out in plugged {
let payload = ocpp_kit::RawValue::from_string(out.payload).unwrap();
let options = CallOptions::default();
station
.handle()
.call_raw(out.action, payload, options)
.await
.expect("the CSMS answers");
}
let identity = station.identity().clone();
let profile: v2_1::SetChargingProfileRequest = ocpp_kit::decode::from_str(
r#"{"evseId":1,"chargingProfile":{"id":1,"stackLevel":0,
"chargingProfilePurpose":"TxDefaultProfile","chargingProfileKind":"Relative",
"chargingSchedule":[{"id":1,"chargingRateUnit":"A","chargingSchedulePeriod":[
{"startPeriod":0,"limit":8}]}]}}"#,
)
.unwrap();
let answer = csms
.handle()
.call(&identity, profile)
.await
.expect("the wallbox answers");
assert_eq!(answer.status, v2_1::ChargingProfileStatus::Accepted);
let sent = wallbox.lock().unwrap().advance(Duration::from_secs(60));
assert_eq!(
wallbox.lock().unwrap().ev().unwrap().reading().current,
Decimal::from(8)
);
for out in sent {
let payload = ocpp_kit::RawValue::from_string(out.payload).unwrap();
station
.handle()
.call_raw(out.action, payload, CallOptions::default())
.await
.expect("the CSMS answers");
}
assert!(
csms.wait_for("NotifyEVChargingNeeds", Duration::from_secs(5))
.await
);
assert!(
csms.exchanges()
.iter()
.any(|e| e.payload.contains("MeterValuePeriodic"))
);
}
#[tokio::test]
async fn a_mock_can_be_made_to_refuse() {
use ocpp_kit::rpc::CallError;
let csms = MockCsms::builder()
.answer(|_, request| Err(CallError::not_supported(&request.action)))
.start()
.await
.expect("the mock CSMS starts");
let station = MockStation::connect(csms.url(), "CS-0003").expect("the station connects");
let error = station
.boot(Version::V2_1)
.await
.expect_err("the mock refuses everything");
assert_eq!(error.code, ocpp_kit::rpc::ErrorCode::NotSupported);
}
}
#[test]
fn a_sim_reads_as_a_transcript_and_drives_the_clock() {
use ocpp_kit::engine::{BootState, Timer};
use ocpp_kit::testkit::Sim;
let mut sim = Sim::new(EngineConfig::new(Role::ChargingStation, Version::V2_1));
sim.connect(Version::V2_1);
sim.call("BootNotification", r#"{"reason":"PowerUp"}"#)
.unwrap();
let id = sim.only_frame_id();
sim.recv(&format!(
r#"[3,"{id}",{{"currentTime":"2024-01-01T00:00:00Z","interval":60,"status":"Pending"}}]"#
));
assert_eq!(sim.engine().boot_state(), BootState::Pending);
assert_eq!(
sim.armed_at(Timer::BootRetry),
Some(Instant::from_millis(60_000))
);
sim.call("Heartbeat", "{}").unwrap();
assert!(sim.frames().is_empty(), "{:?}", sim.frames());
assert!(sim.advance_to_next_timer());
assert_eq!(sim.engine().boot_state(), BootState::Idle);
assert_eq!(sim.now(), Instant::from_millis(60_000));
}