Skip to content

Commit

Permalink
Segmentation fault on publish BrakeCommand
Browse files Browse the repository at this point in the history
  • Loading branch information
DomasAquinas committed Jun 5, 2022
1 parent c67bf2f commit fc534c1
Show file tree
Hide file tree
Showing 5 changed files with 29 additions and 4 deletions.
16 changes: 12 additions & 4 deletions chapter-10-testing/examples/AutoBrake.h
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// AutoBrake class template
#pragma once

#include <stdexcept>

Expand All @@ -7,14 +8,21 @@

template <typename T>
struct AutoBrake {
AutoBrake(const T& Publish)
: collision_threshold_s { 5 },
AutoBrake(const T& publish)
: collision_threshold_s{ 5 },
speed_mps{},
publish{ publish } { };
void observe(const SpeedUpdate& su) {
speed_mps = su.velocity_mps;
};
void observe(const CarDetected& cd) { };
}
void observe(const CarDetected& cd) {
const auto relative_velocity_mps = speed_mps - cd.velocity_mps;
const auto time_to_collision_s = cd.distance_m / relative_velocity_mps;
if (time_to_collision_s > 0 &&
time_to_collision_s <= collision_threshold_s) {
publish(BrakeCommand{ time_to_collision_s });
}
}
void set_collision_threshold_s(double x) {
if (x < 1) throw std::runtime_error{ "Collision less than 1." };
collision_threshold_s = x;
Expand Down
1 change: 1 addition & 0 deletions chapter-10-testing/examples/AutoBrakePods.h
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// POD classes for the AutoBrake examples
#pragma once

struct SpeedUpdate {
double velocity_mps;
Expand Down
1 change: 1 addition & 0 deletions chapter-10-testing/examples/ServiceBus.h
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Service bus for the AutoBrake examples
#pragma once

struct BrakeCommand;

Expand Down
Binary file modified chapter-10-testing/examples/test_AutoBrake
Binary file not shown.
15 changes: 15 additions & 0 deletions chapter-10-testing/examples/test_AutoBrake.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,20 @@ void speed_is_saved() {
assert_that(0L == auto_brake.get_speed_mps(), "speed not saved to 0");
}

void alert_when_imminent() {
int brake_commands_published{};
AutoBrake auto_brake{
[&brake_commands_published](const BrakeCommand&) {
brake_commands_published++;
}
};
auto_brake.set_collision_threshold_s(10L);
auto_brake.observe(SpeedUpdate{ 100L });
auto_brake.observe(CarDetected{ 100L, 0L});
assert_that(brake_commands_published == 1,
"brake commands published not one");
}

// Test harness
void run_test(void(*unit_test)(), const char* name) {
try {
Expand All @@ -58,4 +72,5 @@ int main() {
run_test(initial_sensitivity_is_five, "initial sensitivity is 5");
run_test(sensitivity_greater_than_1, "sensitivity greater than 1");
run_test(speed_is_saved, "speed is saved");
run_test(alert_when_imminent, "alert when imminent");
}

0 comments on commit fc534c1

Please sign in to comment.