|
| 1 | +#include <gtest/gtest.h> |
| 2 | + |
| 3 | +#include <iostream> |
| 4 | +#include <memory> |
| 5 | +#include <sstream> |
| 6 | + |
| 7 | +#include "serializer.hpp" |
| 8 | + |
| 9 | +using geometry2d::Circle; |
| 10 | +using geometry2d::Serializer; |
| 11 | +using geometry2d::Shape; |
| 12 | +using geometry2d::Square; |
| 13 | +using geometry2d::Triangle; |
| 14 | + |
| 15 | +std::string capture_output(const std::function<void()>& printer_func) { |
| 16 | + const std::ostringstream oss; |
| 17 | + auto old_cout_buffer = std::cout.rdbuf(oss.rdbuf()); |
| 18 | + printer_func(); |
| 19 | + std::cout.rdbuf(old_cout_buffer); |
| 20 | + return oss.str(); |
| 21 | +} |
| 22 | + |
| 23 | +TEST(Serializer, ShapeCircle) { |
| 24 | + const Serializer serializer{}; |
| 25 | + const std::unique_ptr<Shape> shape = std::make_unique<Circle>(4); |
| 26 | + const std::string expected_output = |
| 27 | + "Circle:\n" |
| 28 | + "\tradius: 4\n" |
| 29 | + "\t\tperimeter: 25.1327\n" |
| 30 | + "\t\tarea: 50.2655\n"; |
| 31 | + const std::string output = capture_output([&]() { shape->visit_by(serializer); }); |
| 32 | + EXPECT_EQ(output, expected_output); |
| 33 | +} |
| 34 | + |
| 35 | +TEST(Serializer, ShapeSquare) { |
| 36 | + const Serializer serializer{}; |
| 37 | + const std::unique_ptr<Shape> shape = std::make_unique<Square>(5); |
| 38 | + const std::string expected_output = |
| 39 | + "Square:\n" |
| 40 | + "\tside: 5\n" |
| 41 | + "\t\tperimeter: 20\n" |
| 42 | + "\t\tarea: 25\n"; |
| 43 | + const std::string output = capture_output([&]() { shape->visit_by(serializer); }); |
| 44 | + EXPECT_EQ(output, expected_output); |
| 45 | +} |
| 46 | + |
| 47 | +TEST(Serializer, ShapeTriangle) { |
| 48 | + const Serializer serializer{}; |
| 49 | + const std::unique_ptr<Shape> shape = std::make_unique<Triangle>(3, 4, 5); |
| 50 | + const std::string expected_output = |
| 51 | + "Triangle:\n" |
| 52 | + "\tside1: 3\n" |
| 53 | + "\tside2: 4\n" |
| 54 | + "\tside3: 5\n" |
| 55 | + "\t\tperimeter: 12\n" |
| 56 | + "\t\tarea: 6\n"; |
| 57 | + const std::string output = capture_output([&]() { shape->visit_by(serializer); }); |
| 58 | + EXPECT_EQ(output, expected_output); |
| 59 | +} |
| 60 | + |
| 61 | +TEST(Serializer, InvalidCircleRadius) { EXPECT_THROW(Circle(-1), std::invalid_argument); } |
| 62 | + |
| 63 | +TEST(Serializer, InvalidSquareSide) { EXPECT_THROW(Square(0), std::invalid_argument); } |
| 64 | + |
| 65 | +TEST(Serializer, InvalidTriangleSides) { |
| 66 | + EXPECT_THROW(Triangle(1, 2, 3), std::invalid_argument); |
| 67 | + EXPECT_THROW(Triangle(-1, 2, 2), std::invalid_argument); |
| 68 | +} |
0 commit comments