|
| 1 | +// Copyright 2020 volkszaehler.org |
| 2 | +// |
| 3 | +// This file is part of libSML. |
| 4 | +// |
| 5 | +// libSML is free software: you can redistribute it and/or modify |
| 6 | +// it under the terms of the GNU General Public License as published by |
| 7 | +// the Free Software Foundation, either version 3 of the License, or |
| 8 | +// (at your option) any later version. |
| 9 | +// |
| 10 | +// libSML is distributed in the hope that it will be useful, |
| 11 | +// but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | +// GNU General Public License for more details. |
| 14 | +// |
| 15 | +// You should have received a copy of the GNU General Public License |
| 16 | +// along with libSML. If not, see <http://www.gnu.org/licenses/>. |
| 17 | + |
| 18 | +#include "../unity/unity_fixture.h" |
| 19 | +#include "test_helper.h" |
| 20 | +#include <sml/sml_shared.h> |
| 21 | + |
| 22 | +#include <unistd.h> |
| 23 | + |
| 24 | +TEST_GROUP(sml_error); |
| 25 | + |
| 26 | +TEST_SETUP(sml_error) { } |
| 27 | + |
| 28 | +TEST_TEAR_DOWN(sml_error) { } |
| 29 | + |
| 30 | +TEST(sml_error, default) { |
| 31 | + char *tmpfile="./test_sml_error.tmp"; // FIXME: should not be hardcoded |
| 32 | + char *test_string="this is a test"; |
| 33 | + char *expected_output="libsml: this is a test\n"; |
| 34 | + |
| 35 | + FILE *capture = fopen(tmpfile, "w"); |
| 36 | + TEST_ASSERT_NOT_NULL(capture); |
| 37 | + int stderr_backup=dup(2); // duplicate old stderr so it won't be closed |
| 38 | + dup2(fileno(capture),2); // assign capture-file to stderr |
| 39 | + |
| 40 | + sml_error(test_string); |
| 41 | + |
| 42 | + fclose(capture); |
| 43 | + dup2(stderr_backup,2); // restore stderr |
| 44 | + close(stderr_backup); // discard backup |
| 45 | + |
| 46 | + size_t len=strlen(expected_output)+1; |
| 47 | + char *buf=malloc(len); |
| 48 | + |
| 49 | + capture = fopen(tmpfile, "r"); |
| 50 | + size_t got=fread(buf,1,len-1,capture); |
| 51 | + *(buf+got)=0; // add zero termination |
| 52 | + //fprintf(stderr,"got: `%s`\n\n",buf); |
| 53 | + fclose(capture); |
| 54 | + unlink(tmpfile); |
| 55 | + |
| 56 | + TEST_ASSERT_EQUAL(0, strcmp(expected_output,buf)); |
| 57 | + |
| 58 | + free(buf); |
| 59 | +} |
| 60 | + |
| 61 | +const char *msg=NULL; |
| 62 | +void my_sml_error(const char *format, ... ){ |
| 63 | + msg=format; |
| 64 | +} |
| 65 | + |
| 66 | +TEST(sml_error, custom) { |
| 67 | + char *test_string="this is a test"; |
| 68 | + sml_error = my_sml_error; |
| 69 | + sml_error(test_string,1,2,3); |
| 70 | + sml_error = sml_error_default; |
| 71 | + TEST_ASSERT_NOT_NULL(msg); |
| 72 | + TEST_ASSERT_EQUAL(0, strcmp(msg,test_string)); |
| 73 | +} |
| 74 | + |
| 75 | +TEST_GROUP_RUNNER(sml_error) { |
| 76 | + RUN_TEST_CASE(sml_error, default); |
| 77 | + RUN_TEST_CASE(sml_error, custom); |
| 78 | +} |
0 commit comments