From 33a629105c266c8ed75ea5c78dcea850374d124c Mon Sep 17 00:00:00 2001 From: Matthias Grob Date: Tue, 17 Sep 2019 17:37:41 +0200 Subject: [PATCH] Matrix: add proper print function testing Before the print function was just implicitly called somewhere and that's why we had 100% line coverage. With this we have actual testing of the functions. --- matrix/Matrix.hpp | 9 +++++---- test/matrixAssignment.cpp | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/matrix/Matrix.hpp b/matrix/Matrix.hpp index d2eb7b0cb7..3849f66ac3 100644 --- a/matrix/Matrix.hpp +++ b/matrix/Matrix.hpp @@ -322,18 +322,19 @@ public: const Matrix &self = *this; for (size_t i = 0; i < M; i++) { for (size_t j = 0; j < N; j++) { - snprintf(buf + strlen(buf), n - strlen(buf), "\t%8.2g", double(self(i, j))); // directly append to the string buffer + snprintf(buf + strlen(buf), n - strlen(buf), "\t%8.8g", double(self(i, j))); // directly append to the string buffer } snprintf(buf + strlen(buf), n - strlen(buf), "\n"); } } - void print() const + void print(FILE *stream = stdout) const { - static const size_t n = 11*N*M + M; // for every entry a tab and 10 digits, for every row a newline + // element: tab, point, 8 digits; row: newline; string: \0 end + static const size_t n = 10*N*M + M + 1; char * buf = new char[n]; write_string(buf, n); - printf("%s\n", buf); + fprintf(stream, "%s\n", buf); delete[] buf; } diff --git a/test/matrixAssignment.cpp b/test/matrixAssignment.cpp index b4bb637111..00b6e88ab1 100644 --- a/test/matrixAssignment.cpp +++ b/test/matrixAssignment.cpp @@ -132,6 +132,44 @@ int main() m7.setNaN(); TEST(m7 != m8); + // check write_string() + float comma[6] = { + 1.f, 12345.678f, + 12345.67891f, 12345.67891f, + 1112345.67891f, 12345.111111111f + }; + Matrix Comma(comma); + const size_t len = 10*2*3 + 2 + 1; + char buffer[len]; + Comma.write_string(buffer, len); + char output[] = "\t 1\t12345.678\n\t12345.679\t12345.679\n\t1112345.6\t12345.111\n"; + for (size_t i = 0; i < len; i++) { + TEST(buffer[i] == output[i]); + if (buffer[i] == '\0') { + break; + } + } + + // check print() + // write + FILE *fp = fopen("testoutput.txt", "w+"); + TEST(fp != nullptr); + Comma.print(fp); + TEST(!fclose(fp)); + // read + fp = fopen("testoutput.txt", "r"); + TEST(fp != nullptr); + TEST(!fseek(fp, 0, SEEK_SET)); + for (size_t i = 0; i < len; i++) { + char c = static_cast(fgetc(fp)); + if (c == '\n') { + break; + } + printf("%d %d %c\n", static_cast(i), c, c); + TEST(c == output[i]); + } + TEST(!fclose(fp)); + return 0; }