24#ifndef GOBY_MIDDLEWARE_TOOL_PUBSUB_TEST_H
25#define GOBY_MIDDLEWARE_TOOL_PUBSUB_TEST_H
39#include <google/protobuf/dynamic_message.h>
40#include <google/protobuf/io/tokenizer.h>
41#include <google/protobuf/text_format.h>
42#include <google/protobuf/util/json_util.h>
44#include <boost/units/systems/si.hpp>
46#include "dccl/dynamic_protobuf_manager.h"
73 std::vector<unsigned char>
bytes;
83 using Clock = std::chrono::steady_clock;
88 virtual const std::string&
name()
const = 0;
98 virtual void poll(std::chrono::milliseconds wait) = 0;
102template <
typename Portal,
typename PortalConfig>
107 : name_(
std::move(
name)), tool_name_(
std::move(tool_name)), portal_(cfg)
111 const std::string&
name()
const override {
return name_; }
125 portal_.subscribe_regex([
this, handler](
const std::vector<unsigned char>& bytes,
int scheme,
127 { handler({name_, bytes,
scheme, type, std::string(
group)}); },
131 void ready()
override { portal_.ready(); }
133 void poll(std::chrono::milliseconds wait)
override { portal_.poll(wait); }
137 std::string tool_name_;
144inline bool parse_intervehicle_group(
const std::string& s, std::uint32_t&
group)
146 static const std::regex number(
"[0-9]+");
147 if (!std::regex_match(s, number))
151 const auto value = std::stoull(s);
154 group =
static_cast<std::uint32_t
>(value);
157 catch (
const std::exception&)
164inline const google::protobuf::FieldDescriptor*
165group_field_descriptor(
const google::protobuf::Descriptor* desc,
const std::string& name)
167 using google::protobuf::FieldDescriptor;
168 const auto*
field = desc->FindFieldByName(name);
171 switch (
field->cpp_type())
173 case FieldDescriptor::CPPTYPE_INT32:
174 case FieldDescriptor::CPPTYPE_INT64:
175 case FieldDescriptor::CPPTYPE_UINT32:
176 case FieldDescriptor::CPPTYPE_UINT64:
return field;
177 default:
return nullptr;
182 const google::protobuf::FieldDescriptor*
field, std::uint32_t
group)
184 using google::protobuf::FieldDescriptor;
185 const auto* refl =
msg.GetReflection();
186 switch (
field->cpp_type())
188 case FieldDescriptor::CPPTYPE_INT32: refl->SetInt32(&
msg,
field,
group);
break;
189 case FieldDescriptor::CPPTYPE_INT64: refl->SetInt64(&
msg,
field,
group);
break;
190 case FieldDescriptor::CPPTYPE_UINT32: refl->SetUInt32(&
msg,
field,
group);
break;
191 case FieldDescriptor::CPPTYPE_UINT64: refl->SetUInt64(&
msg,
field,
group);
break;
197 const google::protobuf::FieldDescriptor*
field)
199 using google::protobuf::FieldDescriptor;
200 const auto* refl =
msg.GetReflection();
201 switch (
field->cpp_type())
203 case FieldDescriptor::CPPTYPE_INT32:
return refl->GetInt32(
msg,
field);
204 case FieldDescriptor::CPPTYPE_INT64:
return refl->GetInt64(
msg,
field);
205 case FieldDescriptor::CPPTYPE_UINT32:
return refl->GetUInt32(
msg,
field);
206 case FieldDescriptor::CPPTYPE_UINT64:
return refl->GetUInt64(
msg,
field);
214inline std::string json_scalar_to_string(
const nlohmann::json& j)
216 return j.is_string() ? j.get<std::string>() : j.dump();
219inline bool json_is_numeric(
const nlohmann::json& j,
double& d)
228 const std::string s = j.get<std::string>();
230 d = std::strtod(s.c_str(), &end);
231 return !s.empty() && end && *end ==
'\0';
237inline const nlohmann::json* json_lookup(
const nlohmann::json& root,
const std::string& path)
239 static const std::regex token_regex(
"([^.\\[\\]]+)|\\[([0-9]+)\\]");
240 const nlohmann::json* cur = &root;
241 for (
auto it = std::sregex_iterator(path.begin(), path.end(), token_regex);
242 it != std::sregex_iterator(); ++it)
244 if ((*it)[1].matched)
246 if (!cur->is_object() || !cur->contains((*it)[1].
str()))
248 cur = &(*cur)[(*it)[1].str()];
252 const auto idx = std::stoul((*it)[2].
str());
253 if (!cur->is_array() || idx >= cur->size())
262inline bool json_subset(
const nlohmann::json& expected,
const nlohmann::json& actual,
263 const std::string& path, std::string& why)
265 if (expected.is_object())
267 if (!actual.is_object())
269 why = path +
": expected an object";
272 for (
auto it = expected.begin(); it != expected.end(); ++it)
274 const std::string child = path.empty() ? it.key() : path +
"." + it.key();
275 if (!actual.contains(it.key()))
277 why = child +
": missing";
280 if (!json_subset(it.value(), actual[it.key()], child, why))
287 const bool equal = (json_is_numeric(expected, a) && json_is_numeric(actual, b))
289 : json_scalar_to_string(expected) == json_scalar_to_string(actual);
291 why = path +
": expected " + expected.dump() +
", got " + actual.dump();
295inline bool evaluate_condition(
const protobuf::PubSubTestCondition& cond,
const nlohmann::json&
msg,
298 using Op = protobuf::PubSubTestCondition;
299 const nlohmann::json* value = json_lookup(
msg, cond.field());
301 if (cond.op() == Op::EXISTS || cond.op() == Op::ABSENT)
303 const bool exists = value !=
nullptr;
304 if (exists != (cond.op() == Op::EXISTS))
305 why = cond.field() + (exists ?
": present" :
": absent");
306 return exists == (cond.op() == Op::EXISTS);
311 why = cond.field() +
": absent";
315 const std::string actual = json_scalar_to_string(*value);
319 case Op::REGEX:
ok = std::regex_match(actual, std::regex(cond.value()));
break;
321 case Op::ABSENT:
break;
326 json_is_numeric(*value, a) && json_is_numeric(nlohmann::json(cond.value()), b);
327 const int cmp = numeric ? (a < b ? -1 : (a > b ? 1 : 0)) : actual.compare(cond.value());
330 case Op::EQ:
ok = cmp == 0;
break;
331 case Op::NE:
ok = cmp != 0;
break;
332 case Op::LT:
ok = cmp < 0;
break;
333 case Op::LE:
ok = cmp <= 0;
break;
334 case Op::GT:
ok = cmp > 0;
break;
335 case Op::GE:
ok = cmp >= 0;
break;
341 why = cond.field() +
" " + Op::Op_Name(cond.op()) +
" " + cond.value() +
": got " + actual;
350 using google::protobuf::FieldDescriptor;
353 std::vector<const FieldDescriptor*> fields;
356 for (
const auto*
field : fields)
358 const std::string child = path.empty() ?
field->name() : path +
"." +
field->name();
359 if (
field->is_repeated())
361 const int n = refl->FieldSize(expected,
field);
362 if (actual_refl->FieldSize(actual,
field) != n)
364 why = child +
": expected " + std::to_string(n) +
" elements, got " +
365 std::to_string(actual_refl->FieldSize(actual,
field));
368 for (
int i = 0; i < n; ++i)
370 const std::string elem = child +
"[" + std::to_string(i) +
"]";
371 if (
field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE)
373 if (!protobuf_partial_match(refl->GetRepeatedMessage(expected,
field, i),
374 actual_refl->GetRepeatedMessage(actual,
field, i),
381 google::protobuf::TextFormat::PrintFieldValueToString(expected,
field, i, &e);
382 google::protobuf::TextFormat::PrintFieldValueToString(actual,
field, i, &a);
385 why = elem +
": expected " +
e +
", got " + a;
391 else if (
field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE)
393 if (!actual_refl->HasField(actual,
field))
395 why = child +
": missing";
398 if (!protobuf_partial_match(refl->GetMessage(expected,
field),
399 actual_refl->GetMessage(actual,
field), child, why))
404 if (!actual_refl->HasField(actual,
field))
406 why = child +
": missing";
410 google::protobuf::TextFormat::PrintFieldValueToString(expected,
field, -1, &e);
411 google::protobuf::TextFormat::PrintFieldValueToString(actual,
field, -1, &a);
414 why = child +
": expected " +
e +
", got " + a;
422inline double seconds_since(PubSubTestEndpoint::Clock::time_point start)
424 return std::chrono::duration<double>(PubSubTestEndpoint::Clock::now() - start).count();
427inline PubSubTestEndpoint::Clock::duration to_duration(
double seconds)
429 return std::chrono::duration_cast<PubSubTestEndpoint::Clock::duration>(
430 std::chrono::duration<double>(seconds));
434inline void parse_type_spec(
const protobuf::PubSubTestExpect& expect, std::set<int>& schemes,
435 std::string& type_regex)
437 const std::string& spec = expect.type();
438 const auto slash = spec.find(
'/');
439 if (slash != std::string::npos && slash > 0)
442 type_regex = spec.substr(slash + 1);
446 schemes = expect.has_scheme()
455inline bool is_intervehicle_report(
const protobuf::PubSubTestExpect& expect)
457 std::set<int> schemes;
459 parse_type_spec(expect, schemes, type);
473template <
typename Portal,
typename PortalConfig>
478 : name_(
std::move(
name)), portal_(cfg), intervehicle_(portal_)
482 const std::string&
name()
const override {
return name_; }
492 "' only publishes DCCL types (DCCL/<type>)");
494 std::shared_ptr<google::protobuf::Message>
msg =
495 dccl::DynamicProtobufManager::new_protobuf_message<
496 std::shared_ptr<google::protobuf::Message>>(type);
497 if (!google::protobuf::TextFormat::ParseFromString(pub.
value(),
msg.get()))
500 const auto group = numeric_group(pub.
group());
507 PublisherType::set_group_func_type set_group;
510 { detail::set_group_field(m,
field, g.numeric()); };
516 const std::string bytes = md.SerializeAsString();
517 handler_({name_, std::vector<unsigned char>(bytes.begin(), bytes.end()),
520 PublisherType::acked_func_type acked;
525 PublisherType::expired_func_type expired =
529 intervehicle_.template publish_dynamic<google::protobuf::Message, MarshallingScheme::DCCL>(
531 PublisherType(cfg, set_group, acked, expired));
546 portal_.subscribe_regex([
this](
const std::vector<unsigned char>& bytes,
int scheme,
548 { handler_({name_, bytes,
scheme, type, std::string(
group)}); },
554 if (detail::is_intervehicle_report(exp))
557 std::set<int> schemes;
559 detail::parse_type_spec(exp, schemes, type);
560 const auto* desc = dccl::DynamicProtobufManager::find_descriptor(type);
562 throw goby::Exception(
"intervehicle endpoint '" + name_ +
"': unknown type '" + type +
565 const auto group = numeric_group(exp.
group());
569 const std::string key = type +
"/" + std::to_string(
group) +
"/" + exp.
group_field() +
"/" +
571 if (!armed_.insert(key).second)
579 {
return Group(detail::get_group_field(m,
field)); };
582 [
this, type,
group](std::shared_ptr<const google::protobuf::Message>
msg)
588 handler_({name_, std::vector<unsigned char>(bytes.begin(), bytes.end()),
594 void ready()
override { portal_.ready(); }
596 void poll(std::chrono::milliseconds wait)
override { intervehicle_.
poll(wait); }
599 std::uint32_t numeric_group(
const std::string& s)
const
602 if (!detail::parse_intervehicle_group(s,
group))
603 throw goby::Exception(
"intervehicle endpoint '" + name_ +
"': group '" + s +
604 "' is not a numeric group");
608 const google::protobuf::FieldDescriptor* group_field(
const google::protobuf::Descriptor* desc,
609 const std::string&
name,
610 std::uint32_t
group)
const
615 throw goby::Exception(
"intervehicle endpoint '" + name_ +
"': group " +
616 std::to_string(
group) +
" needs a group_field");
619 const auto*
field = detail::group_field_descriptor(desc,
name);
622 "' is not a top-level integer field of " + desc->full_name());
628 InterVehicleForwarder<Portal> intervehicle_;
630 std::set<std::string> armed_;
636 const std::function<
void(std::string&,
const std::string&)>& f)
638 using google::protobuf::FieldDescriptor;
639 const auto* refl =
msg.GetReflection();
640 std::vector<const FieldDescriptor*> fields;
641 refl->ListFields(
msg, &fields);
642 for (
const auto*
field : fields)
644 const std::string fpath = path.empty() ?
field->name() : path +
"." +
field->name();
645 if (
field->cpp_type() == FieldDescriptor::CPPTYPE_STRING)
647 if (
field->is_repeated())
649 for (
int i = 0, n = refl->FieldSize(
msg,
field); i < n; ++i)
651 std::string s = refl->GetRepeatedString(
msg,
field, i);
652 f(s, fpath +
"[" + std::to_string(i) +
"]");
653 refl->SetRepeatedString(&
msg,
field, i, s);
658 std::string s = refl->GetString(
msg,
field);
663 else if (
field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE)
665 if (
field->is_repeated())
666 for (
int i = 0, n = refl->FieldSize(
msg,
field); i < n; ++i)
667 walk_strings(*refl->MutableRepeatedMessage(&
msg,
field, i),
668 fpath +
"[" + std::to_string(i) +
"]", f);
670 walk_strings(*refl->MutableMessage(&
msg,
field), fpath, f);
676inline std::string
substitute(
const std::string& s,
const std::map<std::string, std::string>& vars)
678 static const std::regex var(
"^\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}");
680 for (std::size_t i = 0; i < s.size();)
682 if (s.compare(i, 3,
"$${") == 0)
689 const std::string tail = s.substr(i, 256);
690 if (s[i] ==
'$' && std::regex_search(tail, m, var))
692 auto it = vars.find(m[1].
str());
693 if (it != vars.end())
713 for (
int i = 0, n = test.
run_size(); i < n; ++i)
715 const auto&
run = test.
run(i);
716 if (
run.repeat() == 0)
719 issue.
set_location(
"test.run[" + std::to_string(i) +
"].repeat");
721 issues.push_back(issue);
725 std::vector<std::map<std::string, std::string>> entries;
726 for (
const auto& p :
run.for_each())
728 entries.emplace_back();
729 for (
const auto& v : p.var()) entries.back()[v.key()] = v.value();
732 entries.emplace_back();
734 const unsigned total = entries.size() *
run.repeat();
735 const bool name_varies =
run.name().find(
"${") != std::string::npos;
737 for (
const auto& entry : entries)
739 for (
unsigned r = 0; r <
run.repeat(); ++r)
742 auto& copy = *out.Add();
745 copy.clear_for_each();
747 vars[
"ITERATION"] = std::to_string(pass);
748 detail::walk_strings(copy,
"", [&vars](std::string& s,
const std::string&)
749 { s = detail::substitute(s, vars); });
750 if (total > 1 && !name_varies)
751 copy.set_name((
run.name().empty() ?
"" :
run.name() +
" ") +
"[" +
752 std::to_string(pass) +
"/" + std::to_string(total) +
"]");
762 std::vector<protobuf::PubSubTestIssue>& issues,
763 const std::set<std::string>& allowed = {})
765 static const std::regex var(
"\\$\\{([A-Za-z_][A-Za-z0-9_]*)");
766 detail::walk_strings(
768 [&issues, &allowed](std::string& s,
const std::string& path)
770 for (
auto it = std::sregex_iterator(s.begin(), s.end(), var);
771 it != std::sregex_iterator(); ++it)
773 if ((it->position() > 0 && s[it->position() - 1] ==
'$') ||
774 allowed.count((*it)[1].str()))
779 "variable '" + (*it)[1].str() +
780 "' is not set (use --define, the environment, a ${NAME:-default}, "
781 "or a run's for_each)");
782 issues.push_back(issue);
790 detail::walk_strings(
msg,
"",
791 [](std::string& s,
const std::string&)
793 std::string::size_type pos = 0;
794 while ((pos = s.find(
"$${", pos)) != std::string::npos)
808 using Issues = std::vector<protobuf::PubSubTestIssue>;
811 std::string prefix =
"test")
812 : test_(test), endpoints_(
std::move(endpoint_names)), prefix_(
std::move(prefix))
819 std::string default_endpoint)
821 intervehicle_endpoints_ = std::move(names);
822 default_endpoint_ = std::move(default_endpoint);
829 if (endpoints_.empty())
830 add(
"endpoint",
"no endpoints are declared");
833 add(prefix_ +
".default_timeout",
"must be greater than zero");
835 add(prefix_ +
".connect_timeout",
"must be greater than zero");
840 const std::string loc = index(prefix_ +
".require_app", i);
841 check_endpoint(loc, req.endpoint());
842 if (req.name_size() == 0)
843 add(loc +
".name",
"at least one application name is required");
844 if (req.timeout() <= 0)
845 add(loc +
".timeout",
"must be greater than zero");
846 if (req.request_interval() <= 0)
847 add(loc +
".request_interval",
"must be greater than zero");
850 for (
int i = 0, n = test_.
run_size(); i < n; ++i)
852 const auto&
run = test_.
run(i);
853 const std::string loc = index(prefix_ +
".run", i);
854 if (
run.step_size() > 0 &&
855 (
run.publish_size() > 0 ||
run.expect_size() > 0 ||
run.has_wait()))
856 add(loc,
"a run has either steps or its own publish/expect/wait, not both");
857 check_leaf(loc,
run.publish(),
run.expect(),
run.has_timeout(),
run.timeout(),
859 for (
int j = 0, m =
run.step_size(); j < m; ++j)
861 const auto& step =
run.step(j);
862 check_leaf(index(loc +
".step", j), step.publish(), step.expect(),
863 step.has_timeout(), step.timeout(), step.wait());
873 void AddError(
int line,
int column,
const std::string& message)
override
875 errors.push_back(
"column " + std::to_string(column + 1) +
": " + message);
877 void AddWarning(
int,
int,
const std::string&)
override {}
878 std::vector<std::string> errors;
881 static std::string index(
const std::string& base,
int i)
883 return base +
"[" + std::to_string(i) +
"]";
886 void add(
const std::string& location,
const std::string& message)
888 protobuf::PubSubTestIssue issue;
890 issue.set_message(message);
891 issues_.push_back(issue);
894 void check_endpoint(
const std::string& loc,
const std::string& name)
896 if (!name.empty() && !endpoints_.count(name))
897 add(loc +
".endpoint",
"unknown endpoint '" + name +
"'");
900 void check_regex(
const std::string& loc,
const std::string& regex)
906 catch (
const std::regex_error& e)
908 add(loc,
"invalid regular expression '" + regex +
"': " +
e.what());
912 static const google::protobuf::Descriptor* find_descriptor(
const std::string& name)
916 return dccl::DynamicProtobufManager::find_descriptor(name);
918 catch (
const std::exception&)
924 static bool looks_literal(
const std::string& type)
926 static const std::regex literal(
"[A-Za-z0-9_.:]+");
927 return std::regex_match(type, literal);
930 void parse_textformat(
const std::string& loc,
const std::string& text,
931 const google::protobuf::Descriptor* desc,
bool allow_partial)
933 std::unique_ptr<google::protobuf::Message>
msg(dynamic_factory_.GetPrototype(desc)->New());
934 google::protobuf::TextFormat::Parser parser;
935 CollectingErrorCollector errors;
936 parser.RecordErrorsTo(&errors);
937 parser.AllowPartialMessage(allow_partial);
938 if (!parser.ParseFromString(text,
msg.get()))
940 if (errors.errors.empty())
941 add(loc,
"does not parse as " + desc->full_name());
942 for (
const auto& e : errors.errors)
943 add(loc,
"does not parse as " + desc->full_name() +
": " +
e);
947 void parse_json(
const std::string& loc,
const std::string& text)
951 nlohmann::json parsed = nlohmann::json::parse(text);
954 catch (
const std::exception& e)
956 add(loc, std::string(
"is not valid JSON: ") +
e.what());
960 void check_field_path(
const std::string& loc,
const std::string& path,
961 const google::protobuf::Descriptor* desc)
963 static const std::regex token_regex(
"([^.\\[\\]]+)|\\[([0-9]+)\\]");
964 const google::protobuf::FieldDescriptor*
field =
nullptr;
965 bool indexed =
false;
966 for (
auto it = std::sregex_iterator(path.begin(), path.end(), token_regex);
967 it != std::sregex_iterator(); ++it)
969 if ((*it)[1].matched)
971 if (
field &&
field->is_repeated() && !indexed)
973 add(loc,
"'" +
field->name() +
"' is repeated; index it, e.g. '" +
974 field->name() +
"[0]'");
979 if (
field->cpp_type() != google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE)
981 add(loc,
"'" +
field->name() +
"' is not a message");
984 desc =
field->message_type();
986 field = desc->FindFieldByName((*it)[1].
str());
990 add(loc, desc->full_name() +
" has no field '" + (*it)[1].str() +
"'");
996 if (!
field || !
field->is_repeated() || indexed)
999 "index " + (*it)[0].
str() +
" applied to a field that is not repeated");
1007 void check_publish(
const std::string& loc,
const protobuf::PubSubTestPublish& pub)
1009 check_endpoint(loc, pub.endpoint());
1010 if (pub.repeat() < 1)
1011 add(loc +
".repeat",
"must be at least 1");
1012 if (pub.interval() < 0)
1013 add(loc +
".interval",
"must not be negative");
1014 if (pub.delay() < 0)
1015 add(loc +
".delay",
"must not be negative");
1023 catch (
const std::exception&)
1025 add(loc +
".type",
"unknown marshalling scheme in '" + pub.type() +
"'");
1029 const google::protobuf::Descriptor* desc =
nullptr;
1035 desc = find_descriptor(type);
1038 "unknown type '" + type +
"' (is the library that defines it loaded?)");
1040 parse_textformat(loc +
".value", pub.value(), desc,
false);
1045 add(loc +
".type",
"'" + pub.type() +
1046 "' does not name a supported scheme; use PROTOBUF/<type>, "
1047 "DCCL/<type>, JSON/<type> or JSON");
1050 if (is_intervehicle(pub.endpoint()))
1053 add(loc +
".type",
"intervehicle endpoints publish DCCL types only (DCCL/<type>)");
1054 check_intervehicle_group(loc, pub.group(), pub.group_field(), desc);
1058 check_not_intervehicle(loc, pub.has_group_field(), pub.has_intervehicle());
1062 bool is_intervehicle(
const std::string& endpoint)
const
1064 return intervehicle_endpoints_.count(endpoint.empty() ? default_endpoint_ : endpoint);
1067 void check_intervehicle_group(
const std::string& loc,
const std::string&
group,
1068 const std::string& group_field,
1069 const google::protobuf::Descriptor* desc)
1071 std::uint32_t numeric;
1072 if (!detail::parse_intervehicle_group(
group, numeric))
1074 add(loc +
".group",
"'" +
group +
1075 "' is not a numeric group, which intervehicle "
1076 "endpoints require (e.g. \"7\")");
1079 if (group_field.empty())
1082 add(loc +
".group_field",
"is required for intervehicle group " +
group +
1083 " (only group 0, broadcast, needs none)");
1085 else if (desc && !detail::group_field_descriptor(desc, group_field))
1087 add(loc +
".group_field",
1088 "'" + group_field +
"' is not a top-level integer field of " + desc->full_name());
1092 void check_not_intervehicle(
const std::string& loc,
bool has_group_field,
bool has_intervehicle)
1094 if (has_group_field)
1095 add(loc +
".group_field",
"applies only to intervehicle endpoints");
1096 if (has_intervehicle)
1097 add(loc +
".intervehicle",
"applies only to intervehicle endpoints");
1100 void check_expect(
const std::string& loc,
const protobuf::PubSubTestExpect& exp)
1102 check_endpoint(loc, exp.endpoint());
1103 check_regex(loc +
".group", exp.group());
1105 std::set<int> schemes;
1106 std::string type_regex;
1109 detail::parse_type_spec(exp, schemes, type_regex);
1111 catch (
const std::exception&)
1113 add(loc +
".type",
"unknown marshalling scheme in '" + exp.type() +
"'");
1116 check_regex(loc +
".type", type_regex);
1118 if (exp.has_count() && (exp.has_min_count() || exp.has_max_count()))
1119 add(loc +
".count",
"'count' cannot be combined with 'min_count' or 'max_count'");
1120 if (!exp.has_count() && exp.has_max_count() && exp.max_count() < exp.min_count())
1121 add(loc +
".max_count",
"is less than min_count");
1122 if (exp.has_timeout() && exp.timeout() <= 0)
1123 add(loc +
".timeout",
"must be greater than zero");
1128 const bool json_only =
1131 const google::protobuf::Descriptor* desc =
1132 protobuf_like ? find_descriptor(type_regex) : nullptr;
1133 if (!desc && protobuf_like && !any && looks_literal(type_regex))
1135 "unknown type '" + type_regex +
"' (is the library that defines it loaded?)");
1137 if (exp.has_match())
1140 parse_textformat(loc +
".match", exp.match(), desc,
true);
1142 parse_json(loc +
".match", exp.match());
1145 if (is_intervehicle(exp.endpoint()) && detail::is_intervehicle_report(exp))
1147 if (exp.has_group_field() || exp.has_intervehicle())
1148 add(loc,
"group_field and intervehicle do not apply to acks and expiries, which "
1149 "report on this endpoint's own publications");
1151 else if (is_intervehicle(exp.endpoint()))
1155 "intervehicle endpoints receive DCCL types only (or PROTOBUF/"
1156 "goby.middleware.intervehicle.protobuf.AckData or ExpireData for the acks and "
1157 "expiries of their own publications)");
1159 add(loc +
".type",
"intervehicle endpoints subscribe to one type, so '" +
1160 type_regex +
"' must name a loaded DCCL type");
1161 check_intervehicle_group(loc, exp.group(), exp.group_field(), desc);
1162 if (exp.intervehicle().publisher_id_size() == 0)
1163 add(loc +
".intervehicle.publisher_id",
1164 "at least one is required: a subscription is forwarded only to these modem "
1169 check_not_intervehicle(loc, exp.has_group_field(), exp.has_intervehicle());
1172 for (
int i = 0, n = exp.condition_size(); i < n; ++i)
1174 const auto& cond = exp.condition(i);
1175 const std::string cloc = index(loc +
".condition", i);
1176 using Op = protobuf::PubSubTestCondition;
1177 if (cond.field().empty())
1178 add(cloc +
".field",
"must not be empty");
1180 check_field_path(cloc +
".field", cond.field(), desc);
1182 if (cond.op() == Op::REGEX)
1183 check_regex(cloc +
".value", cond.value());
1184 else if (cond.op() != Op::EXISTS && cond.op() != Op::ABSENT && !cond.has_value())
1185 add(cloc +
".value",
"is required for " + Op::Op_Name(cond.op()));
1189 void check_leaf(
const std::string& loc,
1192 bool has_timeout,
double timeout,
double wait)
1194 if (has_timeout && timeout <= 0)
1195 add(loc +
".timeout",
"must be greater than zero");
1197 add(loc +
".wait",
"must not be negative");
1198 for (
int i = 0, n = pubs.size(); i < n; ++i)
1199 check_publish(index(loc +
".publish", i), pubs[i]);
1200 for (
int i = 0, n = exps.size(); i < n; ++i)
1201 check_expect(index(loc +
".expect", i), exps[i]);
1204 const protobuf::PubSubTest& test_;
1205 std::set<std::string> endpoints_;
1206 std::string prefix_;
1207 std::set<std::string> intervehicle_endpoints_;
1208 std::string default_endpoint_;
1210 google::protobuf::DynamicMessageFactory dynamic_factory_;
1220 std::vector<std::unique_ptr<PubSubTestEndpoint>> endpoints)
1221 : test_(test), endpoints_(
std::move(endpoints))
1223 if (endpoints_.empty())
1226 std::set<std::string> names, intervehicle_names;
1227 for (
auto& ep : endpoints_)
1229 if (!endpoint_index_.insert({ep->name(), ep.get()}).second)
1231 names.insert(ep->name());
1232 if (ep->intervehicle())
1233 intervehicle_names.insert(ep->name());
1239 if (!issues.empty())
1240 throw goby::Exception(issues.front().location() +
": " + issues.front().message());
1249 report.set_name(test_.
name());
1250 const auto start = Clock::now();
1256 for (
auto& ep : endpoints_)
1262 ok = run_require_app(req, *report.add_require_app()) && ok;
1267 report.set_error(
"required applications did not respond");
1277 catch (
const std::exception& e)
1280 report.set_error(e.what());
1283 report.set_elapsed_with_units(detail::seconds_since(start) * boost::units::si::seconds);
1289 std::stringstream ss;
1290 ss << std::fixed << std::setprecision(2);
1291 ss <<
"Test: " << report.name() <<
" ... " << result_name(report.result()) <<
" ("
1292 << report.elapsed() <<
" s)";
1293 if (report.pass_size() > 0)
1296 for (
const auto& p : report.pass()) passed += p.result() ==
protobuf::PASS;
1297 ss <<
", " << passed <<
" of " << report.pass_size() <<
" passes passed";
1300 if (report.has_error())
1301 ss <<
" error: " << report.error() <<
"\n";
1302 for (
const auto& issue : report.issue())
1303 ss <<
" invalid: " << issue.location() <<
": " << issue.message() <<
"\n";
1305 for (
const auto& f : report.fixture())
1307 ss <<
" fixture [" << f.name() <<
"] ... " << result_name(f.result());
1308 if (f.has_ready_time())
1309 ss <<
" (ready after " << f.ready_time() <<
" s)";
1311 ss <<
", " << f.reason();
1313 if (f.has_log_file())
1314 ss <<
" log: " << f.log_file() <<
"\n";
1315 for (
const auto& line : f.output_tail()) ss <<
" | " << line <<
"\n";
1318 for (
const auto& req : report.require_app())
1320 ss <<
" require_app [" << req.endpoint() <<
"] ... " << result_name(req.result())
1321 <<
" (" << req.elapsed() <<
" s" << (req.from_coroner() ?
", via goby_coroner" :
"")
1323 if (!req.missing().empty())
1324 ss <<
" missing: " << join(req.missing());
1325 if (!req.unhealthy().empty())
1326 ss <<
" unhealthy: " << join(req.unhealthy());
1330 for (
int i = 0; i < report.run_size(); ++i)
1331 render_run(ss, report.run(i), std::to_string(i + 1));
1334 for (
const auto& p : report.pass())
1336 ss <<
" " << p.name() <<
" ... " << result_name(p.result()) <<
" (" << p.elapsed()
1342 std::getline(
detail, line);
1343 while (std::getline(
detail, line)) ss <<
" " << line <<
"\n";
1351 google::protobuf::util::JsonPrintOptions opts;
1352 opts.add_whitespace =
true;
1353 opts.preserve_proto_field_names =
true;
1354 google::protobuf::util::MessageToJsonString(report, &out, opts);
1363 std::set<int> schemes;
1364 std::regex type_regex;
1365 std::regex group_regex;
1370 Clock::time_point deadline;
1371 unsigned received{0};
1372 unsigned rejected{0};
1373 std::string last_rejected;
1374 bool resolved{
false};
1381 const protobuf::PubSubTestPublish* cfg;
1382 PubSubTestEndpoint* endpoint;
1383 Clock::time_point next;
1397 bool started{
false};
1400 Clock::time_point start;
1402 std::vector<Node> children;
1403 std::size_t next_child{0};
1404 std::vector<ExpectState> expects;
1405 std::vector<PublishState> publishes;
1406 std::vector<unsigned> publish_counts;
1409 PubSubTestEndpoint* endpoint(
const std::string& name)
1412 return endpoints_.front().get();
1413 auto it = endpoint_index_.find(name);
1414 if (it == endpoint_index_.end())
1421 for (
const auto&
run : test_.
run())
1423 for (
const auto& exp :
run.expect()) endpoint(exp.endpoint())->arm(exp);
1424 for (
const auto& step :
run.step())
1425 for (const auto& exp : step.expect()) endpoint(exp.endpoint())->arm(exp);
1431 if (cancelled_ && cancelled_())
1433 for (
auto& ep : endpoints_) ep->poll(
std::chrono::milliseconds(2));
1438 for (
auto& ep : endpoints_) ep->ready();
1439 const auto deadline = Clock::now() + detail::to_duration(test_.
connect_timeout());
1442 bool holding =
false;
1443 for (
auto& ep : endpoints_) holding = holding || ep->hold_state();
1446 if (Clock::now() > deadline)
1453 bool run_require_app(
const protobuf::PubSubTestRequireApp& req,
1454 protobuf::PubSubTestRequireAppReport& report)
1456 auto* ep = endpoint(req.endpoint());
1457 report.set_endpoint(ep->name());
1458 for (
const auto& n : req.name())
report.add_name(n);
1461 coroner_seen_ =
false;
1462 const auto start = Clock::now();
1463 const auto deadline = start + detail::to_duration(req.timeout());
1464 const auto interval = detail::to_duration(req.request_interval());
1465 auto next_request = start;
1467 auto satisfied = [&](std::vector<std::string>& missing, std::vector<std::string>& unhealthy)
1471 for (
const auto& n : req.name())
1473 auto it = health_.find(n);
1474 if (it == health_.end())
1475 missing.push_back(n);
1477 unhealthy.push_back(n);
1479 return missing.empty() && unhealthy.empty();
1482 std::vector<std::string> missing, unhealthy;
1485 if (satisfied(missing, unhealthy))
1487 const auto now = Clock::now();
1490 if (!coroner_seen_ && now >= next_request)
1492 ep->publish_health_request();
1493 next_request = now + interval;
1498 const bool ok = satisfied(missing, unhealthy);
1500 report.set_elapsed_with_units(detail::seconds_since(start) * boost::units::si::seconds);
1501 report.set_from_coroner(coroner_seen_);
1502 for (
const auto& n : missing)
report.add_missing(n);
1503 for (
const auto& n : unhealthy)
report.add_unhealthy(n);
1507 void run_all(protobuf::PubSubTestReport& report)
1510 root.mode = test_.
mode();
1511 root.publish_cfg =
nullptr;
1512 root.expect_cfg =
nullptr;
1514 for (
const auto&
run : test_.
run())
1518 b.mode =
run.mode();
1519 b.publish_cfg = &
run.publish();
1520 b.expect_cfg = &
run.expect();
1521 b.timeout =
run.has_timeout() ?
run.timeout() : root.timeout;
1522 b.wait =
run.wait();
1524 for (
const auto& step :
run.step())
1527 st.name = step.name();
1529 st.publish_cfg = &step.publish();
1530 st.expect_cfg = &step.expect();
1531 st.timeout = step.has_timeout() ? step.timeout() : b.timeout;
1532 st.wait = step.wait();
1533 b.children.push_back(std::move(st));
1535 root.children.push_back(std::move(b));
1546 for (
const auto& b : root.children)
1548 auto& br = *
report.add_run();
1549 br.set_name(b.name);
1550 br.set_mode(b.mode);
1551 br.set_result(b.result);
1552 br.set_elapsed_with_units(b.elapsed * boost::units::si::seconds);
1554 br.set_wait_with_units(b.wait * boost::units::si::seconds);
1555 write_leaf_report(b, *br.mutable_publish(), *br.mutable_expect());
1556 for (
const auto& st : b.children)
1558 auto& sr = *br.add_step();
1559 sr.set_name(st.name);
1560 sr.set_result(st.result);
1561 sr.set_elapsed_with_units(st.elapsed * boost::units::si::seconds);
1563 sr.set_wait_with_units(st.wait * boost::units::si::seconds);
1564 write_leaf_report(st, *sr.mutable_publish(), *sr.mutable_expect());
1567 report.set_result(root.result);
1571 write_leaf_report(
const Node& n,
1575 for (std::size_t i = 0; i < n.publishes.size(); ++i)
1577 auto& pr = *pubs.Add();
1578 pr.set_endpoint(n.publishes[i].endpoint->name());
1579 pr.set_group(n.publishes[i].cfg->group());
1580 pr.set_type(n.publishes[i].cfg->type());
1581 pr.set_count(n.publish_counts[i]);
1583 for (
const auto& e : n.expects) write_expect_report(
e, *exps.Add());
1586 void start_node(Node& s)
1589 s.start = Clock::now();
1591 if (!s.children.empty())
1594 for (
auto& child : s.children) start_node(child);
1596 start_node(s.children[s.next_child]);
1602 for (
const auto& exp : *s.expect_cfg)
1606 e.endpoint = endpoint(exp.endpoint());
1607 std::string type_regex;
1608 detail::parse_type_spec(exp,
e.schemes, type_regex);
1609 e.type_regex = std::regex(type_regex);
1610 e.group_regex = std::regex(exp.group());
1611 e.exact = exp.has_count();
1612 e.min_count =
e.exact ? exp.count() : exp.min_count();
1613 e.has_max =
e.exact || exp.has_max_count();
1614 e.max_count =
e.exact ? exp.count() : exp.max_count();
1616 s.start + detail::to_duration(exp.has_timeout() ? exp.timeout() : s.timeout);
1617 s.expects.push_back(std::move(e));
1623 for (
const auto& pub : *s.publish_cfg)
1627 p.endpoint = endpoint(pub.endpoint());
1628 p.next = s.start + detail::to_duration(pub.delay());
1629 p.remaining = pub.repeat();
1630 s.publishes.push_back(p);
1631 s.publish_counts.push_back(0);
1634 active_leaves_.insert(&s);
1640 active_leaves_.erase(&s);
1642 s.elapsed = detail::seconds_since(s.start);
1645 void tick_node(Node& s)
1647 if (s.done || !s.started)
1650 if (!s.children.empty())
1652 bool all_done =
true, any_fail =
false;
1653 for (
auto& child : s.children)
1663 s.next_child + 1 < s.children.size())
1665 start_node(s.children[++s.next_child]);
1673 const auto now = Clock::now();
1674 bool publishing =
false;
1675 for (std::size_t i = 0; i < s.publishes.size(); ++i)
1677 auto& p = s.publishes[i];
1678 while (p.remaining > 0 && now >= p.next)
1680 p.endpoint->publish(*p.cfg);
1682 p.next += detail::to_duration(p.cfg->interval());
1683 ++s.publish_counts[i];
1685 publishing = publishing || p.remaining > 0;
1688 bool all_resolved =
true, any_fail =
false;
1689 for (
auto& e : s.expects)
1693 const bool timed_out = now >
e.deadline;
1694 if (
e.has_max &&
e.received >
e.max_count)
1695 resolve(e,
false,
"received more than " + std::to_string(
e.max_count));
1696 else if (!
e.exact &&
e.received >=
e.min_count)
1697 resolve(e,
true,
"");
1698 else if (timed_out &&
e.received >=
e.min_count)
1699 resolve(e,
true,
"");
1702 "received " + std::to_string(
e.received) +
" of " +
1703 std::to_string(
e.min_count) +
" before timeout");
1705 all_resolved = all_resolved &&
e.resolved;
1706 any_fail = any_fail || (
e.resolved && !
e.passed);
1709 const bool waiting = now < s.start + detail::to_duration(s.wait);
1710 if (all_resolved && !publishing && !waiting)
1714 void resolve(ExpectState& e,
bool passed,
const std::string& reason)
1721 void write_expect_report(
const ExpectState& e, protobuf::PubSubTestExpectReport& r)
1723 r.set_endpoint(
e.endpoint->name());
1724 r.set_group(
e.cfg->group());
1725 r.set_type(
e.cfg->type());
1727 r.set_received(
e.received);
1728 r.set_rejected(
e.rejected);
1729 r.set_min_count(
e.min_count);
1731 r.set_max_count(
e.max_count);
1732 if (!
e.reason.empty())
1733 r.set_reason(
e.reason);
1734 if (!
e.last_rejected.empty())
1735 r.set_last_rejected(
e.last_rejected);
1738 void on_message(
const PubSubTestMessage&
msg)
1744 protobuf::ProcessHealth health;
1745 if (health.ParseFromArray(
msg.bytes.data(),
msg.bytes.size()))
1746 health_[health.name()] = health.main().state();
1751 protobuf::VehicleHealth
report;
1752 if (
report.ParseFromArray(
msg.bytes.data(),
msg.bytes.size()))
1754 coroner_seen_ =
true;
1755 for (
const auto& process :
report.process())
1759 health_.erase(process.name());
1761 health_[process.name()] = process.main().state();
1768 for (
auto* block : active_leaves_)
1770 for (
auto& e : block->expects)
1772 if (
e.resolved ||
e.endpoint->name() !=
msg.endpoint)
1775 !
e.schemes.count(
msg.scheme))
1777 if (!std::regex_match(
msg.type,
e.type_regex) ||
1778 !std::regex_match(
msg.group,
e.group_regex))
1782 if (matches(e,
msg, why))
1789 e.last_rejected = why;
1795 bool matches(
const ExpectState& e,
const PubSubTestMessage&
msg, std::string& why)
1797 if (!
e.cfg->has_match() &&
e.cfg->condition_size() == 0)
1800 log::LogEntry entry(
msg.bytes,
msg.scheme,
msg.type, DynamicGroup(
msg.group));
1801 nlohmann::json
json;
1811 why =
"could not decode message";
1814 const auto& pb = *msgs.front();
1816 if (
e.cfg->has_match())
1818 std::unique_ptr<google::protobuf::Message> expected(pb.New());
1819 google::protobuf::TextFormat::Parser parser;
1820 parser.AllowPartialMessage(
true);
1821 if (!parser.ParseFromString(
e.cfg->match(), expected.get()))
1823 why =
"invalid 'match' for " + pb.GetDescriptor()->full_name();
1826 if (!detail::protobuf_partial_match(*expected, pb,
"", why))
1830 if (
e.cfg->condition_size() > 0)
1833 google::protobuf::util::JsonPrintOptions opts;
1834 opts.preserve_proto_field_names =
true;
1835 google::protobuf::util::MessageToJsonString(pb, &jstr, opts);
1836 json = nlohmann::json::parse(jstr);
1842 if (
e.cfg->has_match() &&
1843 !detail::json_subset(nlohmann::json::parse(
e.cfg->match()),
json,
"", why))
1853 catch (
const std::exception& ex)
1855 why = std::string(
"could not decode message: ") + ex.what();
1859 for (
const auto& cond :
e.cfg->condition())
1860 if (!
detail::evaluate_condition(cond,
json, why))
1873 for (
const auto& s : v) out += (out.empty() ?
"" :
", ") + s;
1878 render_leaf(std::stringstream& ss,
const std::string& indent,
1882 for (
const auto& p : pubs)
1883 ss << indent <<
"publish [" << p.endpoint() <<
"] " << p.
group() <<
" " << p.
type()
1884 <<
": sent " << p.count() <<
"\n";
1885 for (
const auto& e : exps)
1887 ss << indent <<
"expect [" <<
e.endpoint() <<
"] " <<
e.group() <<
" " <<
e.type()
1888 <<
": " << result_name(
e.result()) <<
", " <<
e.received() <<
" received";
1889 if (
e.rejected() > 0)
1890 ss <<
", " <<
e.rejected() <<
" rejected";
1892 ss <<
", " <<
e.reason();
1893 if (
e.has_last_rejected())
1894 ss <<
" (last rejected: " <<
e.last_rejected() <<
")";
1899 static void render_run(std::stringstream& ss,
const protobuf::PubSubTestRunReport& b,
1900 const std::string& index)
1902 ss <<
" [" <<
index <<
"] " << b.name();
1903 if (b.step_size() > 0)
1905 ss <<
" ... " << result_name(b.result()) <<
" (" << b.elapsed() <<
" s)\n";
1907 ss <<
" wait " << b.wait() <<
" s\n";
1908 render_leaf(ss,
" ", b.publish(), b.expect());
1909 for (
int i = 0; i < b.step_size(); ++i)
1911 const auto& st = b.step(i);
1912 ss <<
" [" <<
index <<
"." << i + 1 <<
"] " << st.name() <<
" ... "
1913 << result_name(st.result()) <<
" (" << st.elapsed() <<
" s)\n";
1915 ss <<
" wait " << st.wait() <<
" s\n";
1916 render_leaf(ss,
" ", st.publish(), st.expect());
1921 const protobuf::PubSubTest& test_;
1922 std::vector<std::unique_ptr<PubSubTestEndpoint>> endpoints_;
1923 std::map<std::string, PubSubTestEndpoint*> endpoint_index_;
1924 log::ProtobufPlugin protobuf_plugin_;
1925 log::DCCLPlugin dccl_plugin_;
1926 log::JSONPlugin json_plugin_;
1927 std::set<Node*> active_leaves_;
1929 std::map<std::string, protobuf::HealthState> health_;
1930 bool coroner_seen_{
false};
1931 std::function<
bool()> cancelled_;
simple exception class for goby applications
bool ack_required() const
Implementation of Group for dynamic (run-time) instantiations. Use Group directly for static (compile...
Class for grouping publications in the Goby middleware. Analogous to "topics" in ROS,...
static constexpr std::uint32_t broadcast_group
Special group number representing the broadcast group (used when no grouping is required for a given ...
static constexpr std::uint32_t invalid_numeric_group
Special group number representing an invalid numeric group (unsuitable for intervehicle and outer lay...
void subscribe_dynamic(std::function< void(const Data &)> f, const Group &group=Group(), const Subscriber< Data > &subscriber=Subscriber< Data >())
Subscribe to a specific run-time defined group and data type (const reference variant)....
int poll(const std::chrono::time_point< Clock, Duration > &timeout=std::chrono::time_point< Clock, Duration >::max())
poll for data. Blocks until a data event occurs or a timeout when a particular time has been reached
Class that holds additional metadata and callback functions related to a publication (and is optional...
Class that holds additional metadata and callback functions related to a subscription (and is optiona...
std::function< Group(const Data &)> group_func_type
static const ::PROTOBUF_NAMESPACE_ID::Descriptor * descriptor()
static const ::PROTOBUF_NAMESPACE_ID::Descriptor * descriptor()
const ::goby::acomms::protobuf::DynamicBufferConfig & buffer() const
std::shared_ptr< nlohmann::json > parse_message(LogEntry &log_entry)
std::vector< std::shared_ptr< google::protobuf::Message > > parse_message(LogEntry &log_entry)
const std::string & group_field() const
const std::string & group() const
const ::goby::middleware::intervehicle::protobuf::TransporterConfig & intervehicle() const
void set_location(ArgT0 &&arg0, ArgT... args)
void set_message(ArgT0 &&arg0, ArgT... args)
const ::goby::middleware::intervehicle::protobuf::TransporterConfig & intervehicle() const
const std::string & type() const
const std::string & group_field() const
const std::string & value() const
const std::string & group() const
const std::string & name() const
void Swap(PubSubTestRun *other)
const std::string & name() const
const ::goby::middleware::protobuf::PubSubTestRequireApp & require_app(int index) const
::goby::middleware::protobuf::PubSubTestRun * mutable_run(int index)
const ::goby::middleware::protobuf::PubSubTestRun & run(int index) const
::goby::middleware::protobuf::PubSubTestRunMode mode() const
double connect_timeout() const
int require_app_size() const
double default_timeout() const
::goby::middleware::intervehicle::protobuf::TransporterConfig * mutable_intervehicle()
const Reflection * GetReflection() const
void ListFields(const Message &message, std::vector< const FieldDescriptor * > *output) const
goby::util::logger::GroupSetter group(std::string n)
detail namespace with internal helper functions
extern ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ::goby::acomms::protobuf::ModemReport, ::PROTOBUF_NAMESPACE_ID::internal::MessageTypeTraits< ::goby::acomms::iridium::protobuf::Report >, 11, false > report
constexpr goby::middleware::Group health_report
constexpr goby::middleware::Group health_response
const std::string & PubSubTestResult_Name(T enum_t_value)
constexpr int scheme()
Placeholder to provide an interface for the scheme() function family.
std::string str(TimeType value=SystemClock::now< TimeType >())
Returns the provided time (or current time if omitted) as a human-readable string.
The global namespace for the Goby project.
extern ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ::PROTOBUF_NAMESPACE_ID::FieldOptions, ::PROTOBUF_NAMESPACE_ID::internal::MessageTypeTraits< ::goby::GobyFieldOptions >, 11, false > field
extern ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ::PROTOBUF_NAMESPACE_ID::MessageOptions, ::PROTOBUF_NAMESPACE_ID::internal::MessageTypeTraits< ::goby::GobyMessageOptions >, 11, false > msg
int run(const goby::middleware::ConfiguratorInterface< typename App::ConfigType > &cfgtor)
Run a Goby application using the provided Configurator.
uint32_t index(const std::array< int8_t, 256 > &rdata, char symbol)
type
Categories for the various JSON types used in JWTs.
static int from_string(const std::string &s)
Convert from a string to a marshalling scheme id.
static std::string to_string(int e)
Convert a known marshalling scheme to a human-readable string or an unknown scheme to the string repr...
Class for parsing and serializing a given marshalling scheme. Must be specialized for a particular sc...