From 45bb17b3e828758841725e3ca966a574ca489425 Mon Sep 17 00:00:00 2001 From: sfja Date: Mon, 23 Mar 2026 19:57:02 +0100 Subject: [PATCH] add test infrastructure --- backend/Makefile | 32 ++++++++++++-------------------- backend/tests/assertions.h | 18 ++++++++++++++++++ backend/tests/true.cpp | 3 ++- 3 files changed, 32 insertions(+), 21 deletions(-) create mode 100644 backend/tests/assertions.h diff --git a/backend/Makefile b/backend/Makefile index 5202839..a43f801 100644 --- a/backend/Makefile +++ b/backend/Makefile @@ -28,41 +28,33 @@ else endif endif -NO_MAIN = 0 -ifeq ($(NO_MAIN),1) - CXXFLAGS += -Dmain="not_main" -endif - build_dir = build obj_dir = $(build_dir)/obj +src_dir = src +test_dir = tests -sources = \ - src/main.cpp \ - src/tcp.cpp \ - src/http.cpp +sources = $(shell find $(src_dir) -name '*.cpp' -and -not -name 'main.cpp') +sources_with_main=$(sources) src/main.cpp -tests = \ - tests/true.cpp +tests = $(shell find $(test_dir) -name '*.cpp') target=$(build_dir)/backend all: $(target) -$(target): $(sources:%.cpp=$(obj_dir)/%.o) +$(target): $(sources_with_main:%.cpp=$(obj_dir)/%.o) $(LD) -o $@ $(CXXFLAGS) $(LDFLAGS) $^ -$(obj_dir)/%.o: %.cpp +$(obj_dir)/%.o:%.cpp @mkdir -p $(dir $@) $(CXX) $< -c -o $@ -MMD -MP $(CXXFLAGS) -test: $(sources:%.cpp=$(obj_dir)/%.o) run_tests +test: $(tests:tests/%.cpp=$(build_dir)/tests/test_%) + printf "%s\n" $^ | xargs -I % sh -c 'echo "- %..." && ./% && echo "- %: OK" || (echo "- %: FAILED" && exit 1)' -run_tests: $(tests:tests/%.cpp=$(build_dir)/tests/test_%) - printf "%s\n" $2 | xargs -I % sh -c 'echo "- %..." && ./% && echo "- %: OK" || echo "- %: FAILED" && exit 1' - -$(build_dir)/tests/test_%: tests/%.cpp +$(build_dir)/tests/test_%: $(obj_dir)/tests/%.o $(sources:%.cpp=$(obj_dir)/%.o) @mkdir -p $(dir $@) - $(CXX) $< -o $@ -MMD -MP $(CXXFLAGS) + $(LD) -o $@ $(CXXFLAGS) $(LDFLAGS) $^ format: $(CLANG_FORMAT) -style=file -i src/* @@ -73,5 +65,5 @@ check: clean: rm -rf $(build_dir) --include $(sources:%.cpp=$(obj_dir)/%.d) +-include $(sources_with_main:%.cpp=$(obj_dir)/%.d) $(tests:%.cpp=$(obj_dir)/%.d) diff --git a/backend/tests/assertions.h b/backend/tests/assertions.h new file mode 100644 index 0000000..49bdecf --- /dev/null +++ b/backend/tests/assertions.h @@ -0,0 +1,18 @@ +#pragma once + +#include +#include +#include + +#define ASSERT_EQ(EXPR, VALUE) \ + do { \ + if ((EXPR) != (VALUE)) { \ + std::cerr << std::format( \ + "ASSERTION FAILED: Expected '{}' ({}) to be '{}' ({})\n", \ + #EXPR, \ + (EXPR), \ + #VALUE, \ + (VALUE)); \ + std::exit(1); \ + } \ + } while (false); diff --git a/backend/tests/true.cpp b/backend/tests/true.cpp index 2a1024a..7fdb7b8 100644 --- a/backend/tests/true.cpp +++ b/backend/tests/true.cpp @@ -1,6 +1,7 @@ +#include "assertions.h" #include int main() { - assert(true); + ASSERT_EQ(1 + 2, 3); }