diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..6be5afbb --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* binary diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..6ad1df1f --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,263 @@ +name: CI + +on: + workflow_dispatch: + push: + paths-ignore: + - 'docs/**' + - 'LICENSE' + - 'read.me' + - 'README.md' + pull_request: + paths-ignore: + - 'docs/**' + - 'LICENSE' + - 'read.me' + - 'README.md' + +env: + TEST_REF_FORBID_GEN_REFS: true + +jobs: +# tests-ubuntu2004-gpp: +# strategy: +# matrix: +# os: [ubuntu-20.04] +# compiler: [g++] +# version: [9, 10] +# name: Use ${{ matrix.compiler }}-${{ matrix.version }} on ${{ matrix.os }} +# runs-on: ${{ matrix.os }} +# steps: +# - uses: actions/checkout@v3 +# - name: Run tests +# run: | +# cd tests +# bash ./run.sh ${{ matrix.compiler }} v${{ matrix.version }} +# +# tests-ubuntu2004-clang: +# strategy: +# matrix: +# os: [ubuntu-20.04] +# compiler: [clang++] +# version: [10, 11, 12] +# name: Use ${{ matrix.compiler }}-${{ matrix.version }} on ${{ matrix.os }} +# runs-on: ${{ matrix.os }} +# steps: +# - uses: actions/checkout@v3 +# - name: Run tests +# run: | +# cd tests +# bash ./run.sh ${{ matrix.compiler }} v${{ matrix.version }} + + tests-ubuntu2204-gpp: + strategy: + matrix: + os: [ubuntu-22.04] + compiler: [g++] + version: [10, 11, 12] + name: Use ${{ matrix.compiler }}-${{ matrix.version }} on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v3 + - name: Run tests + run: | + cd tests + bash ./run.sh ${{ matrix.compiler }} v${{ matrix.version }} + + tests-ubuntu2204-clang: + strategy: + matrix: + os: [ubuntu-22.04] + compiler: [clang++] + version: [13, 14] + name: Use ${{ matrix.compiler }}-${{ matrix.version }} on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v3 + - name: Run tests + run: | + cd tests + bash ./run.sh ${{ matrix.compiler }} v${{ matrix.version }} + +# tests-ubuntu2004-gpp-32: +# strategy: +# matrix: +# os: [ubuntu-20.04] +# compiler: [g++] +# version: [9, 10] +# name: Use ${{ matrix.compiler }}-${{ matrix.version }} -m32 on ${{ matrix.os }} +# runs-on: ${{ matrix.os }} +# steps: +# - uses: actions/checkout@v3 +# - name: Run tests +# run: | +# sudo apt-get update +# sudo apt-get install gcc-${{ matrix.version }}-multilib g++-${{ matrix.version }}-multilib +# cd tests +# bash ./run.sh ${{ matrix.compiler }} v${{ matrix.version }} 32 +# +# tests-ubuntu2004-clang-32: +# strategy: +# matrix: +# os: [ubuntu-20.04] +# compiler: [clang++] +# version: [10, 11, 12] +# name: Use ${{ matrix.compiler }}-${{ matrix.version }} -m32 on ${{ matrix.os }} +# runs-on: ${{ matrix.os }} +# steps: +# - uses: actions/checkout@v3 +# - name: Run tests +# run: | +# sudo apt-get update +# sudo apt-get install gcc-multilib g++-multilib +# cd tests +# bash ./run.sh ${{ matrix.compiler }} v${{ matrix.version }} 32 + + tests-ubuntu2204-gpp-32: + strategy: + matrix: + os: [ubuntu-22.04] + compiler: [g++] + version: [9, 10, 11] + name: Use ${{ matrix.compiler }}-${{ matrix.version }} -m32 on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v3 + - name: Run tests + run: | + sudo apt-get update + sudo apt-get install gcc-${{ matrix.version }}-multilib g++-${{ matrix.version }}-multilib + cd tests + bash ./run.sh ${{ matrix.compiler }} v${{ matrix.version }} 32 + + tests-ubuntu2204-clang-32: + strategy: + matrix: + os: [ubuntu-22.04] + compiler: [clang++] + version: [13, 14] + name: Use ${{ matrix.compiler }}-${{ matrix.version }} -m32 on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v3 + - name: Run tests + run: | + sudo apt-get update + sudo apt-get install gcc-multilib g++-multilib + cd tests + bash ./run.sh ${{ matrix.compiler }} v${{ matrix.version }} 32 + + tests-macos14-gpp: + strategy: + matrix: + os: [macos-14] + compiler: [g++] + version: [13, 14, 15] + name: Use ${{ matrix.compiler }}-${{ matrix.version }} on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v3 + - name: Run tests + run: | + cd tests + bash ./run.sh ${{ matrix.compiler }} v${{ matrix.version }} + + tests-macos14-clang: + strategy: + matrix: + os: [macos-14] + compiler: [clang++] + name: Use ${{ matrix.compiler }} on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v3 + - name: Run tests + run: | + cd tests + bash ./run.sh ${{ matrix.compiler }} + + tests-macos15-gpp: + strategy: + matrix: + os: [macos-15] + compiler: [g++] + version: [13, 14, 15] + name: Use ${{ matrix.compiler }}-${{ matrix.version }} on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v3 + - name: Run tests + run: | + cd tests + bash ./run.sh ${{ matrix.compiler }} v${{ matrix.version }} + + tests-macos15-clang: + strategy: + matrix: + os: [macos-15] + compiler: [clang++] + name: Use ${{ matrix.compiler }} on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v3 + - name: Run tests + run: | + cd tests + bash ./run.sh ${{ matrix.compiler }} + + tests-macos26-gpp: + strategy: + matrix: + os: [macos-26] + compiler: [g++] + version: [13, 14, 15] + name: Use ${{ matrix.compiler }}-${{ matrix.version }} on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v3 + - name: Run tests + run: | + cd tests + bash ./run.sh ${{ matrix.compiler }} v${{ matrix.version }} + + tests-macos26-clang: + strategy: + matrix: + os: [macos-26] + compiler: [clang++] + name: Use ${{ matrix.compiler }} on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v3 + - name: Run tests + run: | + cd tests + bash ./run.sh ${{ matrix.compiler }} + + tests-windows-2019: + strategy: + matrix: + os: [windows-2019] + compiler: [msvc, g++, clang++] + name: Use ${{ matrix.compiler }} on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v3 + - name: Run tests + run: | + cd tests + bash ./run.sh ${{ matrix.compiler }} + + tests-windows-2022: + strategy: + matrix: + os: [windows-2022] + compiler: [msvc, g++, clang++] + name: Use ${{ matrix.compiler }} on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v3 + - name: Run tests + run: | + cd tests + bash ./run.sh ${{ matrix.compiler }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..45e858c6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +.idea +cmake-build-debug + +*.exe +*.o +*.obj +CMakeLists.txt \ No newline at end of file diff --git a/README.md b/README.md index 8aba124b..b3c5a848 100644 --- a/README.md +++ b/README.md @@ -2,17 +2,17 @@ ## Intro -This project contains C++ implementation of the testlib. It is already being used on many programming contests in Russia (Russian National Olympiad in Informatics, different stages of ACM-ICPC). Join! +This project contains a C++ implementation of testlib. It is already being used in many programming contests in Russia, such as the Russian National Olympiad in Informatics and different stages of ICPC. Join! -The library C++ code is tested for compatibility with Borland C++ (5.6), Microsoft Visual C++ (2003+), g++ (MinGW 4.0.2). Also we don't hear any issues about incorrect work with other compilers. +The library's C++ code is tested for compatibility with standard C++11 and higher on different versions of `g++`, `clang++`, and Microsoft Visual C++. -This code used many times on Open Team Programming Collegiate Cup contests (http://opencup.ru/) running on Linux platform and compiled by g++ compiler. +This code has been used many times in Codeforces contests. ## Samples ### Checker -This is sample checker which expects in the output and in the answer the same integer. It ignores all white-spaces. See more examples in the package. +This sample checker expects the same integer in the output and the answer. It ignores all white-spaces. See more examples in the package. ```c++ #include "testlib.h" @@ -30,9 +30,9 @@ int main(int argc, char * argv[]) { ### Interactor -This sample interactor reads pairs of numbers from input file, sends it to the other program, reads -result and writes it to output file (to be verified later). Another option could be terminating -interactor with `quitf(_wa, )`. +This sample interactor reads pairs of numbers from the input file, sends them to another program, reads +the result, and writes it to an output file (to be verified later). Another option could be to terminate +the interactor with `quitf(_wa, )`. ```c++ #include "testlib.h" @@ -65,8 +65,7 @@ int main(int argc, char* argv[]) { ### Validator -This code reads input from the standard input and checks that it contains the only integer between 1 and 100, inclusive. Also validates that file ends with EOLN and EOF. On Windows it expects #13#10 as EOLN and it expects #10 as EOLN on other platforms. It doesn't ignore white-spaces, so it works very strict. It will return non-zero code in case of illegal input and writes message into the standard output. See more examples in the package. - +This code reads input from the standard input and checks that it contains only one integer between 1 and 100, inclusive. It also validates that the file ends with EOLN and EOF. On Windows, it expects #13#10 as EOLN, and it expects #10 as EOLN on other platforms. It does not ignore white-spaces, so it works very strictly. It will return a non-zero code in the case of illegal input and write a message to the standard output. See more examples in the package. ```c++ #include "testlib.h" @@ -81,28 +80,23 @@ int main(int argc, char* argv[]) { ### Generator -This generator outputs into the standard output random token, containing Latin letters or digits. The length of the token will be between 1 and 1000, inclusive. It will use uniformly distributed random. To generate different values, call it with different command line parameters. It is typical behaviour of testlib generator to setup randseed by command line. See more examples in the package. +This generator outputs a random token to the standard output, containing Latin letters or digits. The length of the token will be between 1 and 1000, inclusive. It will use a uniformly distributed random generator. To generate different values, call it with different command-line parameters. It is typical behavior for a testlib generator to set up randseed by command line. See more examples in the package. ```c++ #include "testlib.h" -#include - -using namespace std; int main(int argc, char* argv[]) { registerGen(argc, argv, 1); - cout << rnd.next(1, 10) << endl; /* Random number in the range [1,10]. */ - cout << rnd.next("[a-zA-Z0-9]{1,1000}") << endl; /* Random word of length [1,1000]. */ + println(rnd.next(1, 10)); /* Random number in the range [1,10]. */ + println(rnd.next("[a-zA-Z0-9]{1,1000}")); /* Random word of length [1,1000]. */ } ``` -This generator outputs random permutation, the size equals to the first command line argument. +This generator outputs a random permutation; the size is equal to the first command-line argument. ```c++ #include "testlib.h" -using namespace std; - int main(int argc, char* argv[]) { registerGen(argc, argv, 1); diff --git a/checkers/acmp.cpp b/checkers/acmp.cpp index 18fccb99..52dd84aa 100644 --- a/checkers/acmp.cpp +++ b/checkers/acmp.cpp @@ -1,19 +1,17 @@ #include "testlib.h" -#include -#include +#include const double EPS = 1.5E-6; -int main(int argc, char * argv[]) -{ +int main(int argc, char *argv[]) { setName("compare two doubles, maximal absolute error = %.10f", EPS); registerTestlibCmd(argc, argv); - + double ja = ans.readDouble(); double pa = ouf.readDouble(); if (fabs(ja - pa) > EPS + 1E-15) quitf(_wa, "expected %.10f, found %.10f", ja, pa); - + quitf(_ok, "answer is %.10f", ja); } diff --git a/checkers/caseicmp.cpp b/checkers/caseicmp.cpp index bdc1acb6..482154f3 100644 --- a/checkers/caseicmp.cpp +++ b/checkers/caseicmp.cpp @@ -9,51 +9,24 @@ */ #include "testlib.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include -#include -#include -#include -#include -#include -#include -#include -#include +#include using namespace std; -#define forn(i, n) for (int i = 0; i < int(n); i++) - -vector readStream(InStream& in, TResult pe) -{ +vector readStream(InStream &in) { vector result; - for (int testCase = 1; !in.seekEof(); testCase++) - { + for (int testCase = 1; !in.seekEof(); testCase++) { string caseStr = in.readToken(); if (caseStr != "Case") - quitf(pe, "Expected 'Case' but found '%s' [test case %d]", compress(caseStr).c_str(), testCase); + in.quitf(_pe, "Expected 'Case' but found '%s' [test case %d]", compress(caseStr).c_str(), testCase); - string numExpStr; - stringstream ss; - ss << testCase; - ss >> numExpStr; - numExpStr += ":"; + string numExpStr = to_string(testCase) + ":"; string numStr = in.readToken(); if (numExpStr != numStr) - quitf(pe, "Expected '%s' but found '%s' [test case %d]", compress(numExpStr).c_str(), compress(numStr).c_str(), testCase); + in.quitf(_pe, "Expected '%s' but found '%s' [test case %d]", compress(numExpStr).c_str(), + compress(numStr).c_str(), testCase); result.push_back(in.readLong()); } @@ -61,33 +34,29 @@ vector readStream(InStream& in, TResult pe) return result; } -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { setName("Single int64 checker with testcase-support"); registerTestlibCmd(argc, argv); - vector ja = readStream(ans, _fail); - vector pa = readStream(ouf, _pe); + vector ja = readStream(ans); + vector pa = readStream(ouf); - forn(i, min(ja.size(), pa.size())) + for (unsigned int i = 0; i < min(ja.size(), pa.size()); i++) if (ja[i] != pa[i]) quitf(_wa, "Expected %s found %s [test case %d]", vtos(ja[i]).c_str(), vtos(pa[i]).c_str(), i + 1); if (ja.size() != pa.size()) - quitf(_pe, "Expected %u test case(s) but found %u", (unsigned int)(ja.size()), (unsigned int)(pa.size())); + quitf(_pe, "Expected %u test case(s) but found %u", (unsigned int) (ja.size()), (unsigned int) (pa.size())); - string message = format("%u case(s):", (unsigned int)(ja.size())); - if (ja.size() <= 5) - { - forn(i, ja.size()) - message += " " + vtos(ja[i]); - } - else - { - forn(i, 3) + string message = format("%u case(s):", (unsigned int) (ja.size())); + if (ja.size() <= 5) { + for (auto elem: ja) + message += " " + vtos(elem); + } else { + for (int i = 0; i < 3; i++) message += " " + vtos(ja[i]); message += " ..."; - forn(i, 2) + for (int i = 0; i < 2; i++) message += " " + vtos(ja[ja.size() - 2 + i]); } diff --git a/checkers/casencmp.cpp b/checkers/casencmp.cpp index 3c0656f7..d86c7650 100644 --- a/checkers/casencmp.cpp +++ b/checkers/casencmp.cpp @@ -9,59 +9,28 @@ */ #include "testlib.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include -#include -#include -#include -#include -#include -#include -#include -#include +#include using namespace std; -#define forn(i, n) for (int i = 0; i < int(n); i++) - -string token; - -vector readStreamCase(InStream& in, TResult pe, int testCase, bool& prereadCase) -{ - if (!prereadCase) - { +vector readStreamCase(InStream &in, int testCase, bool &prereadCase) { + if (!prereadCase) { string caseStr = in.readToken(); if (caseStr != "Case") - quitf(pe, "Expected 'Case' but found '%s' [test case %d]", compress(caseStr).c_str(), testCase); + in.quitf(_pe, "Expected 'Case' but found '%s' [test case %d]", compress(caseStr).c_str(), testCase); } - string numExpStr; - stringstream ss; - ss << testCase; - ss >> numExpStr; - numExpStr += ":"; + string numExpStr = to_string(testCase) + ":"; string numStr = in.readToken(); if (numExpStr != numStr) - quitf(pe, "Expected '%s' but found '%s' [test case %d]", compress(numExpStr).c_str(), compress(numStr).c_str(), testCase); + in.quitf(_pe, "Expected '%s' but found '%s' [test case %d]", compress(numExpStr).c_str(), + compress(numStr).c_str(), testCase); vector result; - while (!in.seekEof()) - { - in.readTokenTo(token); - if (token == "Case") - { + while (!in.seekEof()) { + string token = in.readToken(); + if (token == "Case") { prereadCase = true; break; } @@ -72,31 +41,26 @@ vector readStreamCase(InStream& in, TResult pe, int testCase, bool& p return result; } -string longLongsToString(const vector& a) -{ +string longLongsToString(const vector &a) { if (a.empty()) return "\"\" [size=0]"; - + string elems; - if (a.size() <= 5) - { - forn(i, a.size()) - elems += vtos(a[i]) + " "; - } - else - { - forn(i, 3) + if (a.size() <= 5) { + for (auto elem: a) + elems += vtos(elem) + " "; + } else { + for (int i = 0; i < 3; i++) elems += vtos(a[i]) + " "; elems += "... "; - forn(i, 2) + for (int i = 0; i < 2; i++) elems += vtos(a[a.size() - 2 + i]) + " "; } - return format("\"%s\" [size=%u]", trim(elems).c_str(), (unsigned int)(a.size())); + return format("\"%s\" [size=%u]", trim(elems).c_str(), (unsigned int) (a.size())); } -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { setName("Many int64s checker with testcase-support"); registerTestlibCmd(argc, argv); @@ -105,18 +69,17 @@ int main(int argc, char* argv[]) bool ansPrereadCase = false; bool oufPrereadCase = false; - while (!ans.seekEof()) - { + while (!ans.seekEof()) { testCase++; - vector ja = readStreamCase(ans, _fail, testCase, ansPrereadCase); - vector pa = readStreamCase(ouf, _pe, testCase, oufPrereadCase); + vector ja = readStreamCase(ans, testCase, ansPrereadCase); + vector pa = readStreamCase(ouf, testCase, oufPrereadCase); - if (ja != pa) - { + if (ja != pa) { string js = longLongsToString(ja); string ps = longLongsToString(pa); - quitf(_wa, "Sequences differ: jury has %s, but participant has %s [test case %d]", js.c_str(), ps.c_str(), testCase); + quitf(_wa, "Sequences differ: jury has %s, but participant has %s [test case %d]", js.c_str(), ps.c_str(), + testCase); } } diff --git a/checkers/casewcmp.cpp b/checkers/casewcmp.cpp index f74c6646..98641beb 100644 --- a/checkers/casewcmp.cpp +++ b/checkers/casewcmp.cpp @@ -6,62 +6,32 @@ * ... * Case n: ... * + * Tokens in each case should not contain "Case" */ #include "testlib.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include -#include -#include -#include -#include -#include -#include -#include -#include +#include using namespace std; -#define forn(i, n) for (int i = 0; i < int(n); i++) - -string token; - -vector readStreamCase(InStream& in, TResult pe, int testCase, bool& prereadCase) -{ - if (!prereadCase) - { +vector readStreamCase(InStream &in, int testCase, bool &prereadCase) { + if (!prereadCase) { string caseStr = in.readToken(); if (caseStr != "Case") - quitf(pe, "Expected 'Case' but found '%s' [test case %d]", compress(caseStr).c_str(), testCase); + in.quitf(_pe, "Expected 'Case' but found '%s' [test case %d]", compress(caseStr).c_str(), testCase); } - string numExpStr; - stringstream ss; - ss << testCase; - ss >> numExpStr; - numExpStr += ":"; + string numExpStr = to_string(testCase) + ":"; string numStr = in.readToken(); if (numExpStr != numStr) - quitf(pe, "Expected '%s' but found '%s' [test case %d]", compress(numExpStr).c_str(), compress(numStr).c_str(), testCase); + in.quitf(_pe, "Expected '%s' but found '%s' [test case %d]", compress(numExpStr).c_str(), + compress(numStr).c_str(), testCase); vector result; - while (!in.seekEof()) - { - in.readTokenTo(token); - if (token == "Case") - { + while (!in.seekEof()) { + string token = in.readToken(); + if (token == "Case") { prereadCase = true; break; } @@ -72,20 +42,18 @@ vector readStreamCase(InStream& in, TResult pe, int testCase, bool& prer return result; } -string stringsToString(const vector& a) -{ +string stringsToString(const vector &a) { if (a.empty()) return "\"\" [size=0]"; - + string elems; - forn(i, a.size()) - elems += a[i] + " "; + for (const auto& token: a) + elems += token + " "; - return format("\"%s\" [size=%u]", compress(trim(elems)).c_str(), (unsigned int)(a.size())); + return format("\"%s\" [size=%u]", compress(trim(elems)).c_str(), (unsigned int) (a.size())); } -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { setName("Tokens checker with testcase-support"); registerTestlibCmd(argc, argv); @@ -94,18 +62,17 @@ int main(int argc, char* argv[]) bool ansPrereadCase = false; bool oufPrereadCase = false; - while (!ans.seekEof()) - { + while (!ans.seekEof()) { testCase++; - vector ja = readStreamCase(ans, _fail, testCase, ansPrereadCase); - vector pa = readStreamCase(ouf, _pe, testCase, oufPrereadCase); + vector ja = readStreamCase(ans, testCase, ansPrereadCase); + vector pa = readStreamCase(ouf, testCase, oufPrereadCase); - if (ja != pa) - { + if (ja != pa) { string js = stringsToString(ja); string ps = stringsToString(pa); - quitf(_wa, "Sequences differ: jury has %s, but participant has %s [test case %d]", js.c_str(), ps.c_str(), testCase); + quitf(_wa, "Sequences differ: jury has %s, but participant has %s [test case %d]", js.c_str(), ps.c_str(), + testCase); } } diff --git a/checkers/dcmp.cpp b/checkers/dcmp.cpp index 2e8980d9..713bb8ec 100644 --- a/checkers/dcmp.cpp +++ b/checkers/dcmp.cpp @@ -1,19 +1,16 @@ #include "testlib.h" -#include -#include const double EPS = 1E-6; -int main(int argc, char * argv[]) -{ +int main(int argc, char *argv[]) { setName("compare two doubles, maximal absolute or relative error = %.10f", EPS); registerTestlibCmd(argc, argv); - + double ja = ans.readDouble(); double pa = ouf.readDouble(); - + if (!doubleCompare(ja, pa, EPS)) quitf(_wa, "expected %.10f, found %.10f", ja, pa); - + quitf(_ok, "answer is %.10f", ja); } diff --git a/checkers/fcmp.cpp b/checkers/fcmp.cpp index a140a31d..4e023f94 100644 --- a/checkers/fcmp.cpp +++ b/checkers/fcmp.cpp @@ -1,24 +1,20 @@ #include "testlib.h" #include -#include -#include using namespace std; -int main(int argc, char * argv[]) -{ +int main(int argc, char *argv[]) { setName("compare files as sequence of lines"); registerTestlibCmd(argc, argv); std::string strAnswer; int n = 0; - while (!ans.eof()) - { + while (!ans.eof()) { std::string j = ans.readString(); - if (j == "" && ans.eof()) - break; + if (j.empty() && ans.eof()) + break; strAnswer = j; std::string p = ouf.readString(); @@ -26,11 +22,12 @@ int main(int argc, char * argv[]) n++; if (j != p) - quitf(_wa, "%d%s lines differ - expected: '%s', found: '%s'", n, englishEnding(n).c_str(), compress(j).c_str(), compress(p).c_str()); + quitf(_wa, "%d%s lines differ - expected: '%s', found: '%s'", n, englishEnding(n).c_str(), + compress(j).c_str(), compress(p).c_str()); } - + if (n == 1) quitf(_ok, "single line: '%s'", compress(strAnswer).c_str()); - + quitf(_ok, "%d lines", n); } diff --git a/checkers/hcmp.cpp b/checkers/hcmp.cpp index 5235be4d..9a8fa470 100644 --- a/checkers/hcmp.cpp +++ b/checkers/hcmp.cpp @@ -1,21 +1,18 @@ #include "testlib.h" - #include using namespace std; pattern pnum("0|-?[1-9][0-9]*"); -bool isNumeric(const string& p) -{ +bool isNumeric(const string &p) { return pnum.matches(p); } -int main(int argc, char * argv[]) -{ +int main(int argc, char *argv[]) { setName("compare two signed huge integers"); registerTestlibCmd(argc, argv); - + string ja = ans.readWord(); string pa = ouf.readWord(); @@ -24,12 +21,12 @@ int main(int argc, char * argv[]) if (!ans.seekEof()) quitf(_fail, "expected exactly one token in the answer file"); - + if (!isNumeric(pa)) quitf(_pe, "%s is not a valid integer", compress(pa).c_str()); if (ja != pa) quitf(_wa, "expected '%s', found '%s'", compress(ja).c_str(), compress(pa).c_str()); - + quitf(_ok, "answer is '%s'", compress(ja).c_str()); } diff --git a/checkers/icmp.cpp b/checkers/icmp.cpp index 6512f220..3d88898d 100644 --- a/checkers/icmp.cpp +++ b/checkers/icmp.cpp @@ -1,16 +1,14 @@ #include "testlib.h" -#include -int main(int argc, char * argv[]) -{ +int main(int argc, char *argv[]) { setName("compare two signed int%d's", 8 * int(sizeof(int))); registerTestlibCmd(argc, argv); - + int ja = ans.readInt(); int pa = ouf.readInt(); - + if (ja != pa) quitf(_wa, "expected %d, found %d", ja, pa); - + quitf(_ok, "answer is %d", ja); } diff --git a/checkers/lcmp.cpp b/checkers/lcmp.cpp index 1e3ace42..0800f064 100644 --- a/checkers/lcmp.cpp +++ b/checkers/lcmp.cpp @@ -5,11 +5,10 @@ using namespace std; -bool compareWords(string a, string b) -{ +bool compareWords(const string& a, const string& b) { vector va, vb; stringstream sa; - + sa << a; string cur; while (sa >> cur) @@ -23,32 +22,31 @@ bool compareWords(string a, string b) return (va == vb); } -int main(int argc, char * argv[]) -{ +int main(int argc, char *argv[]) { setName("compare files as sequence of tokens in lines"); registerTestlibCmd(argc, argv); - std::string strAnswer; + string strAnswer; int n = 0; - while (!ans.eof()) - { + while (!ans.eof()) { std::string j = ans.readString(); - if (j == "" && ans.eof()) - break; - - std::string p = ouf.readString(); + if (j.empty() && ans.eof()) + break; + + string p = ouf.readString(); strAnswer = p; n++; if (!compareWords(j, p)) - quitf(_wa, "%d%s lines differ - expected: '%s', found: '%s'", n, englishEnding(n).c_str(), compress(j).c_str(), compress(p).c_str()); + quitf(_wa, "%d%s lines differ - expected: '%s', found: '%s'", n, englishEnding(n).c_str(), + compress(j).c_str(), compress(p).c_str()); } - + if (n == 1) quitf(_ok, "single line: '%s'", compress(strAnswer).c_str()); - + quitf(_ok, "%d lines", n); } diff --git a/checkers/ncmp.cpp b/checkers/ncmp.cpp index fbd68c13..9a5cd9af 100644 --- a/checkers/ncmp.cpp +++ b/checkers/ncmp.cpp @@ -1,10 +1,8 @@ #include "testlib.h" -#include using namespace std; -int main(int argc, char * argv[]) -{ +int main(int argc, char *argv[]) { setName("compare ordered sequences of signed int%d numbers", 8 * int(sizeof(long long))); registerTestlibCmd(argc, argv); @@ -12,44 +10,42 @@ int main(int argc, char * argv[]) int n = 0; string firstElems; - while (!ans.seekEof() && !ouf.seekEof()) - { + while (!ans.seekEof() && !ouf.seekEof()) { n++; long long j = ans.readLong(); long long p = ouf.readLong(); if (j != p) - quitf(_wa, "%d%s numbers differ - expected: '%s', found: '%s'", n, englishEnding(n).c_str(), vtos(j).c_str(), vtos(p).c_str()); - else - if (n <= 5) - { - if (firstElems.length() > 0) - firstElems += " "; - firstElems += vtos(j); - } + quitf(_wa, "%d%s numbers differ - expected: '%s', found: '%s'", n, englishEnding(n).c_str(), + vtos(j).c_str(), vtos(p).c_str()); + else if (n <= 5) { + if (firstElems.length() > 0) + firstElems += " "; + firstElems += vtos(j); + } } int extraInAnsCount = 0; - while (!ans.seekEof()) - { + while (!ans.seekEof()) { ans.readLong(); extraInAnsCount++; } - + int extraInOufCount = 0; - while (!ouf.seekEof()) - { + while (!ouf.seekEof()) { ouf.readLong(); extraInOufCount++; } if (extraInAnsCount > 0) - quitf(_wa, "Answer contains longer sequence [length = %d], but output contains %d elements", n + extraInAnsCount, n); - + quitf(_wa, "Answer contains longer sequence [length = %d], but output contains %d elements", + n + extraInAnsCount, n); + if (extraInOufCount > 0) - quitf(_wa, "Output contains longer sequence [length = %d], but answer contains %d elements", n + extraInOufCount, n); - + quitf(_wa, "Output contains longer sequence [length = %d], but answer contains %d elements", + n + extraInOufCount, n); + if (n <= 5) quitf(_ok, "%d number(s): \"%s\"", n, compress(firstElems).c_str()); else diff --git a/checkers/nyesno.cpp b/checkers/nyesno.cpp index 88137c10..bad67323 100644 --- a/checkers/nyesno.cpp +++ b/checkers/nyesno.cpp @@ -6,22 +6,20 @@ using namespace std; const string YES = "YES"; const string NO = "NO"; -int main(int argc, char * argv[]) -{ - setName("%s", ("multiple " + YES + "/" + NO + " (case insensetive)").c_str()); +int main(int argc, char *argv[]) { + setName("%s", ("multiple " + YES + "/" + NO + " (case insensitive)").c_str()); registerTestlibCmd(argc, argv); int index = 0, yesCount = 0, noCount = 0; - std::string pa; - while (!ans.seekEof() && !ouf.seekEof()) - { + string pa; + while (!ans.seekEof() && !ouf.seekEof()) { index++; - std::string ja = upperCase(ans.readToken()); + string ja = upperCase(ans.readToken()); pa = upperCase(ouf.readToken()); if (ja != YES && ja != NO) quitf(_fail, "%s or %s expected in answer, but %s found [%d%s token]", - YES.c_str(), NO.c_str(), compress(ja).c_str(), index, englishEnding(index).c_str()); + YES.c_str(), NO.c_str(), compress(ja).c_str(), index, englishEnding(index).c_str()); if (pa == YES) yesCount++; @@ -29,32 +27,32 @@ int main(int argc, char * argv[]) noCount++; else quitf(_pe, "%s or %s expected, but %s found [%d%s token]", - YES.c_str(), NO.c_str(), compress(pa).c_str(), index, englishEnding(index).c_str()); + YES.c_str(), NO.c_str(), compress(pa).c_str(), index, englishEnding(index).c_str()); if (ja != pa) quitf(_wa, "expected %s, found %s [%d%s token]", - compress(ja).c_str(), compress(pa).c_str(), index, englishEnding(index).c_str()); + compress(ja).c_str(), compress(pa).c_str(), index, englishEnding(index).c_str()); } int extraInAnsCount = 0; - while (!ans.seekEof()) - { + while (!ans.seekEof()) { ans.readToken(); extraInAnsCount++; } - + int extraInOufCount = 0; - while (!ouf.seekEof()) - { + while (!ouf.seekEof()) { ouf.readToken(); extraInOufCount++; } if (extraInAnsCount > 0) - quitf(_wa, "Answer contains longer sequence [length = %d], but output contains %d elements", index + extraInAnsCount, index); - + quitf(_wa, "Answer contains longer sequence [length = %d], but output contains %d elements", + index + extraInAnsCount, index); + if (extraInOufCount > 0) - quitf(_wa, "Output contains longer sequence [length = %d], but answer contains %d elements", index + extraInOufCount, index); + quitf(_wa, "Output contains longer sequence [length = %d], but answer contains %d elements", + index + extraInOufCount, index); if (index == 0) quitf(_ok, "Empty output"); diff --git a/checkers/pointscmp.cpp b/checkers/pointscmp.cpp index b91d2d77..a2a446ce 100644 --- a/checkers/pointscmp.cpp +++ b/checkers/pointscmp.cpp @@ -2,8 +2,7 @@ using namespace std; -int main(int argc, char * argv[]) -{ +int main(int argc, char *argv[]) { setName("example of scored checker"); registerTestlibCmd(argc, argv); diff --git a/checkers/pointsinfo.cpp b/checkers/pointsinfo.cpp index d0611db1..e6993fff 100644 --- a/checkers/pointsinfo.cpp +++ b/checkers/pointsinfo.cpp @@ -2,14 +2,13 @@ using namespace std; -int main(int argc, char * argv[]) -{ +int main(int argc, char *argv[]) { setName("example of checker with points_info"); registerTestlibCmd(argc, argv); double pa = ouf.readDouble(); double ja = ans.readDouble(); - + string points_info = "pa=" + to_string(pa) + ",ja=" + to_string(ja); quitpi(points_info, "d=" + to_string(abs(ja - pa))); } diff --git a/checkers/rcmp.cpp b/checkers/rcmp.cpp index 18fccb99..52dd84aa 100644 --- a/checkers/rcmp.cpp +++ b/checkers/rcmp.cpp @@ -1,19 +1,17 @@ #include "testlib.h" -#include -#include +#include const double EPS = 1.5E-6; -int main(int argc, char * argv[]) -{ +int main(int argc, char *argv[]) { setName("compare two doubles, maximal absolute error = %.10f", EPS); registerTestlibCmd(argc, argv); - + double ja = ans.readDouble(); double pa = ouf.readDouble(); if (fabs(ja - pa) > EPS + 1E-15) quitf(_wa, "expected %.10f, found %.10f", ja, pa); - + quitf(_ok, "answer is %.10f", ja); } diff --git a/checkers/rcmp4.cpp b/checkers/rcmp4.cpp index 2eb0095c..22654378 100644 --- a/checkers/rcmp4.cpp +++ b/checkers/rcmp4.cpp @@ -1,32 +1,28 @@ #include "testlib.h" -#include using namespace std; const double EPS = 1E-4; -int main(int argc, char * argv[]) -{ +int main(int argc, char *argv[]) { setName("compare two sequences of doubles, max absolute or relative error = %.5f", EPS); registerTestlibCmd(argc, argv); int n = 0; double j = 0, p = 0; - while (!ans.seekEof()) - { + while (!ans.seekEof()) { n++; j = ans.readDouble(); p = ouf.readDouble(); - if (!doubleCompare(j, p, EPS)) - { + if (!doubleCompare(j, p, EPS)) { quitf(_wa, "%d%s numbers differ - expected: '%.5f', found: '%.5f', error = '%.5f'", - n, englishEnding(n).c_str(), j, p, doubleDelta(j, p)); + n, englishEnding(n).c_str(), j, p, doubleDelta(j, p)); } } if (n == 1) quitf(_ok, "found '%.5f', expected '%.5f', error '%.5f'", p, j, doubleDelta(j, p)); - + quitf(_ok, "%d numbers", n); } diff --git a/checkers/rcmp6.cpp b/checkers/rcmp6.cpp index 03920af7..9136fcac 100644 --- a/checkers/rcmp6.cpp +++ b/checkers/rcmp6.cpp @@ -1,27 +1,23 @@ #include "testlib.h" -#include using namespace std; const double EPS = 1E-6; -int main(int argc, char * argv[]) -{ +int main(int argc, char *argv[]) { setName("compare two sequences of doubles, max absolute or relative error = %.7f", EPS); registerTestlibCmd(argc, argv); int n = 0; double j = 0, p = 0; - while (!ans.seekEof()) - { + while (!ans.seekEof()) { n++; j = ans.readDouble(); p = ouf.readDouble(); - if (!doubleCompare(j, p, EPS)) - { + if (!doubleCompare(j, p, EPS)) { quitf(_wa, "%d%s numbers differ - expected: '%.7f', found: '%.7f', error = '%.7f'", - n, englishEnding(n).c_str(), j, p, doubleDelta(j, p)); + n, englishEnding(n).c_str(), j, p, doubleDelta(j, p)); } } diff --git a/checkers/rcmp9.cpp b/checkers/rcmp9.cpp index 2640f93d..c6f0c469 100644 --- a/checkers/rcmp9.cpp +++ b/checkers/rcmp9.cpp @@ -1,27 +1,23 @@ #include "testlib.h" -#include using namespace std; const double EPS = 1E-9; -int main(int argc, char * argv[]) -{ +int main(int argc, char *argv[]) { setName("compare two sequences of doubles, max absolute or relative error = %.10f", EPS); registerTestlibCmd(argc, argv); int n = 0; double j = 0, p = 0; - while (!ans.seekEof()) - { + while (!ans.seekEof()) { n++; j = ans.readDouble(); p = ouf.readDouble(); - if (!doubleCompare(j, p, EPS)) - { + if (!doubleCompare(j, p, EPS)) { quitf(_wa, "%d%s numbers differ - expected: '%.10f', found: '%.10f', error = '%.10f'", - n, englishEnding(n).c_str(), j, p, doubleDelta(j, p)); + n, englishEnding(n).c_str(), j, p, doubleDelta(j, p)); } } diff --git a/checkers/rncmp.cpp b/checkers/rncmp.cpp index c4410be5..13f5bd53 100644 --- a/checkers/rncmp.cpp +++ b/checkers/rncmp.cpp @@ -5,14 +5,12 @@ using namespace std; const double EPS = 1.5E-5; -int main(int argc, char * argv[]) -{ +int main(int argc, char *argv[]) { setName("compare two sequences of doubles, maximal absolute error = %.10f", EPS); registerTestlibCmd(argc, argv); int n = 0; - while (!ans.seekEof()) - { + while (!ans.seekEof()) { n++; double j = ans.readDouble(); double p = ouf.readDouble(); diff --git a/checkers/uncmp.cpp b/checkers/uncmp.cpp index d288f4a8..f42f0525 100644 --- a/checkers/uncmp.cpp +++ b/checkers/uncmp.cpp @@ -3,9 +3,8 @@ using namespace std; -int main(int argc, char * argv[]) -{ - setName("compare unordered sequences of signed int%lu numbers", 8 * sizeof(long long)); +int main(int argc, char *argv[]) { + setName("compare unordered sequences of signed int%u numbers", int(8 * sizeof(long long))); registerTestlibCmd(argc, argv); @@ -18,16 +17,17 @@ int main(int argc, char * argv[]) pa.push_back(ouf.readLong()); if (ja.size() != pa.size()) - quitf(_wa, "Expected %u elements, but %u found", (unsigned int)(ja.size()), (unsigned int)(pa.size())); + quitf(_wa, "Expected %u elements, but %u found", (unsigned int) (ja.size()), (unsigned int) (pa.size())); sort(ja.begin(), ja.end()); sort(pa.begin(), pa.end()); if (ja != pa) - quitf(_wa, "Expected sequence and output are different (as unordered sequences) [size=%u]", (unsigned int)(ja.size())); + quitf(_wa, "Expected sequence and output are different (as unordered sequences) [size=%u]", + (unsigned int) (ja.size())); string message; - + if (ja.size() != 1) if (ja.empty()) message = "empty sequence"; @@ -35,18 +35,17 @@ int main(int argc, char * argv[]) message = vtos(ja.size()) + " numbers (in increasing order):"; else message = vtos(ja.size()) + " number:"; - + if (ja.size() <= 5) for (int i = 0; i < min(int(ja.size()), 5); i++) message += " " + vtos(ja[i]); - else - { + else { for (int i = 0; i < 2; i++) message += " " + vtos(ja[i]); message += " ..."; for (int i = 0; i < 2; i++) message += " " + vtos(ja[ja.size() - 2 + i]); } - + quitf(_ok, "%s", message.c_str()); } diff --git a/checkers/wcmp.cpp b/checkers/wcmp.cpp index abc60914..16471d3e 100644 --- a/checkers/wcmp.cpp +++ b/checkers/wcmp.cpp @@ -2,34 +2,30 @@ using namespace std; -int main(int argc, char * argv[]) -{ +int main(int argc, char *argv[]) { setName("compare sequences of tokens"); registerTestlibCmd(argc, argv); int n = 0; string j, p; - while (!ans.seekEof() && !ouf.seekEof()) - { + while (!ans.seekEof() && !ouf.seekEof()) { n++; ans.readWordTo(j); ouf.readWordTo(p); - + if (j != p) - quitf(_wa, "%d%s words differ - expected: '%s', found: '%s'", n, englishEnding(n).c_str(), compress(j).c_str(), compress(p).c_str()); + quitf(_wa, "%d%s words differ - expected: '%s', found: '%s'", n, englishEnding(n).c_str(), + compress(j).c_str(), compress(p).c_str()); } - if (ans.seekEof() && ouf.seekEof()) - { + if (ans.seekEof() && ouf.seekEof()) { if (n == 1) quitf(_ok, "\"%s\"", compress(j).c_str()); else quitf(_ok, "%d tokens", n); - } - else - { + } else { if (ans.seekEof()) quitf(_wa, "Participant output contains extra tokens"); else diff --git a/checkers/yesno.cpp b/checkers/yesno.cpp index ad6ed8ac..70407ed5 100644 --- a/checkers/yesno.cpp +++ b/checkers/yesno.cpp @@ -6,9 +6,8 @@ using namespace std; const string YES = "YES"; const string NO = "NO"; -int main(int argc, char * argv[]) -{ - setName("%s", (YES + " or " + NO + " (case insensetive)").c_str()); +int main(int argc, char *argv[]) { + setName("%s", (YES + " or " + NO + " (case insensitive)").c_str()); registerTestlibCmd(argc, argv); std::string ja = upperCase(ans.readWord()); diff --git a/docs/read.me b/docs/read.me index 2b5d32f6..b3c5a848 100644 --- a/docs/read.me +++ b/docs/read.me @@ -1,19 +1,107 @@ -TESTLIB - -== What is it? == -Testlib is simple library which helps you to write - * checkers - * validators - * generators - * interactors -for programming competitions problems. -You can find latest release of the library on https://github.com/MikeMirzayanov/testlib/ -Problem development management system Polygon completely supports testlib. - -== How to use? == -Easest way is to read c++ sources in the checkers/, validators/, generators/ and interactors/ folders. -Also some classes and methods in testlib have documentation. - -Thanks for using testlib, -Mike Mirzayanov - +# Testlib + +## Intro + +This project contains a C++ implementation of testlib. It is already being used in many programming contests in Russia, such as the Russian National Olympiad in Informatics and different stages of ICPC. Join! + +The library's C++ code is tested for compatibility with standard C++11 and higher on different versions of `g++`, `clang++`, and Microsoft Visual C++. + +This code has been used many times in Codeforces contests. + +## Samples + +### Checker + +This sample checker expects the same integer in the output and the answer. It ignores all white-spaces. See more examples in the package. + +```c++ +#include "testlib.h" + +int main(int argc, char * argv[]) { + setName("compares two signed integers"); + registerTestlibCmd(argc, argv); + int ja = ans.readInt(); + int pa = ouf.readInt(); + if (ja != pa) + quitf(_wa, "expected %d, found %d", ja, pa); + quitf(_ok, "answer is %d", ja); +} +``` + +### Interactor + +This sample interactor reads pairs of numbers from the input file, sends them to another program, reads +the result, and writes it to an output file (to be verified later). Another option could be to terminate +the interactor with `quitf(_wa, )`. + +```c++ +#include "testlib.h" +#include + +using namespace std; + +int main(int argc, char* argv[]) { + setName("Interactor A+B"); + registerInteraction(argc, argv); + + // reads number of queries from test (input) file + int n = inf.readInt(); + for (int i = 0; i < n; i++) { + // reads query from test (input) file + int a = inf.readInt(); + int b = inf.readInt(); + + // writes query to the solution, endl makes flush + cout << a << " " << b << endl; + + // writes output file to be verified by checker later + tout << ouf.readInt() << endl; + } + + // just message + quitf(_ok, "%d queries processed", n); +} +``` + +### Validator + +This code reads input from the standard input and checks that it contains only one integer between 1 and 100, inclusive. It also validates that the file ends with EOLN and EOF. On Windows, it expects #13#10 as EOLN, and it expects #10 as EOLN on other platforms. It does not ignore white-spaces, so it works very strictly. It will return a non-zero code in the case of illegal input and write a message to the standard output. See more examples in the package. + +```c++ +#include "testlib.h" + +int main(int argc, char* argv[]) { + registerValidation(argc, argv); + inf.readInt(1, 100, "n"); + inf.readEoln(); + inf.readEof(); +} +``` + +### Generator + +This generator outputs a random token to the standard output, containing Latin letters or digits. The length of the token will be between 1 and 1000, inclusive. It will use a uniformly distributed random generator. To generate different values, call it with different command-line parameters. It is typical behavior for a testlib generator to set up randseed by command line. See more examples in the package. + +```c++ +#include "testlib.h" + +int main(int argc, char* argv[]) { + registerGen(argc, argv, 1); + println(rnd.next(1, 10)); /* Random number in the range [1,10]. */ + println(rnd.next("[a-zA-Z0-9]{1,1000}")); /* Random word of length [1,1000]. */ +} +``` + +This generator outputs a random permutation; the size is equal to the first command-line argument. + +```c++ +#include "testlib.h" + +int main(int argc, char* argv[]) { + registerGen(argc, argv, 1); + + int n = opt(1); + println(n); + println(rnd.perm(n, 1)); +} +``` diff --git a/generators/bgen.cpp b/generators/bgen.cpp index 04a21dba..5074d266 100644 --- a/generators/bgen.cpp +++ b/generators/bgen.cpp @@ -1,6 +1,6 @@ /* * Outputs random 100-digits binary string mostly containing 0's. - * In average it contrains only 10% of 1's. + * In average, it contains only 10% of 1's. * * To generate different values, call "bgen.exe" with different parameters. * @@ -8,13 +8,10 @@ */ #include "testlib.h" -#include using namespace std; -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { registerGen(argc, argv, 1); println(rnd.next("[0000000001]{100}")); - return 0; } diff --git a/generators/gen-array-with-opt.cpp b/generators/gen-array-with-opt.cpp new file mode 100644 index 00000000..a9963247 --- /dev/null +++ b/generators/gen-array-with-opt.cpp @@ -0,0 +1,50 @@ +/** + * gen-array-with-opt -test-count + * -sum-n + * [-min-n ] + * [-min-value ] [-max-value ] + * [-value-bias ] + * + * Generate a test with `test-count` test cases, each test case is an + * array. The sum of lengths of all arrays will equal `sum-n`. + * + * Arguments: + * -test-count: specify the number of test cases. Required. + * -sum-n: specify the sum of array lengths over all test cases. Required. + * -min-n: specify the minimum array length for all test cases. Default: 1. + * -min-value: specify the minimum value for the array element. Default: 1. + * -max-value: specify the maximum value for the array element. Default: 10^9. + * -value-bias: specify the bias for generating the value. The bigger the + * _positive_ value-bias, the closer the element to max-value. The smaller the + * _negative_ value-bias, the closer the element to min-value. See rnd.wnext() + * function. Default: 0 (no bias). + */ +#include "testlib.h" +#include +using namespace std; + +int main(int argc, char** argv) { + registerGen(argc, argv, 1); + + int test_count = opt("test-count"); + int sum_n = opt("sum-n"); + int min_n = opt("min-n", 1); + + int min_value = opt("min-value", 1); + int max_value = opt("max-value", 1000 * 1000 * 1000); + int value_bias = opt("value-bias", 0); + + vector n_list = rnd.partition(test_count, sum_n, min_n); + + println(test_count); + for (int test_case = 0; test_case < test_count; ++test_case) { + int n = n_list[test_case]; + vector arr(n); + for (int i = 0; i < n; ++i) { + arr[i] = rnd.wnext(min_value, max_value, value_bias); + } + println(n); + println(arr); + } +} + diff --git a/generators/gen-bipartite-graph.cpp b/generators/gen-bipartite-graph.cpp index a52240eb..0d8ee081 100644 --- a/generators/gen-bipartite-graph.cpp +++ b/generators/gen-bipartite-graph.cpp @@ -1,33 +1,11 @@ #include "testlib.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include -#include -#include -#include #include -#include -#include -#include -#include - -#define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { registerGen(argc, argv, 1); int n = opt(1); @@ -36,31 +14,21 @@ int main(int argc, char* argv[]) int t = rnd.next(-2, 2); - set > edges; + set> edges; - while (edges.size() < k) - { + while (edges.size() < k) { int a = rnd.wnext(n, t); int b = rnd.wnext(m, t); edges.insert(make_pair(a, b)); } - vector > e(edges.begin(), edges.end()); + vector> e(edges.begin(), edges.end()); shuffle(e.begin(), e.end()); - vector pa(n); - for (int i = 0; i < n; i++) - pa[i] = i + 1; - shuffle(pa.begin(), pa.end()); - - vector pb(m); - for (int i = 0; i < m; i++) - pb[i] = i + 1; - shuffle(pb.begin(), pb.end()); + vector pa = rnd.perm(n, 1); + vector pb = rnd.perm(m, 1); println(n, m, e.size()); - forn(i, e.size()) - println(pa[e[i].first], pb[e[i].second]); - - return 0; + for (auto edge: e) + println(pa[edge.first], pb[edge.second]); } diff --git a/generators/gen-rooted-tree-graph.cpp b/generators/gen-rooted-tree-graph.cpp index 9751f3fd..1e0e6100 100644 --- a/generators/gen-rooted-tree-graph.cpp +++ b/generators/gen-rooted-tree-graph.cpp @@ -1,60 +1,30 @@ #include "testlib.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include -#include -#include -#include -#include -#include -#include -#include -#include - -#define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { registerGen(argc, argv, 1); int n = opt(1); int t = opt(2); vector p(n); - forn(i, n) - if (i > 0) - p[i] = rnd.wnext(i, t); + // p[i] is the parent of i-th vertex in 0-numeration without shuffling + for (int i = 1; i < n; i++) + p[i] = rnd.wnext(i, t); - printf("%d\n", n); vector perm(n); - forn(i, n) + for (int i = 0; i < n; i++) perm[i] = i; shuffle(perm.begin() + 1, perm.end()); - vector pp(n); + vector pp(n - 1); + // pp[i] is the parent of (i+2)-nd vertex in 1-numeration after shuffling for (int i = 1; i < n; i++) - pp[perm[i]] = perm[p[i]]; + pp[perm[i] - 1] = perm[p[i]] + 1; - for (int i = 1; i < n; i++) - { - printf("%d", pp[i] + 1); - if (i + 1 < n) - printf(" "); - } - printf("\n"); - - return 0; + println(n); + println(pp); } diff --git a/generators/gen-tree-graph.cpp b/generators/gen-tree-graph.cpp index 5e69d24d..5a8ebf8d 100644 --- a/generators/gen-tree-graph.cpp +++ b/generators/gen-tree-graph.cpp @@ -1,50 +1,22 @@ #include "testlib.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include -#include -#include -#include -#include -#include -#include -#include -#include - -#define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { registerGen(argc, argv, 1); int n = opt(1); int t = opt(2); vector p(n); - forn(i, n) - if (i > 0) - p[i] = rnd.wnext(i, t); + for (int i = 1; i < n; i++) + p[i] = rnd.wnext(i, t); - printf("%d\n", n); - vector perm(n); - forn(i, n) - perm[i] = i; - shuffle(perm.begin() + 1, perm.end()); - vector > edges; + vector perm = rnd.perm(n); + vector> edges; for (int i = 1; i < n; i++) if (rnd.next(2)) edges.push_back(make_pair(perm[i], perm[p[i]])); @@ -53,8 +25,7 @@ int main(int argc, char* argv[]) shuffle(edges.begin(), edges.end()); - for (int i = 0; i + 1 < n; i++) - printf("%d %d\n", edges[i].first + 1, edges[i].second + 1); - - return 0; + println(n); + for (auto edge: edges) + println(edge.first + 1, edge.second + 1); } diff --git a/generators/gs.cpp b/generators/gs.cpp index 94a7c40e..fcf37cf1 100644 --- a/generators/gs.cpp +++ b/generators/gs.cpp @@ -10,11 +10,12 @@ */ #include "testlib.h" -#include + +#include using namespace std; -int main(int argc, char* argv[]) { +int main(int argc, char *argv[]) { registerGen(argc, argv, 1); string t; int n = opt(1); diff --git a/generators/igen.cpp b/generators/igen.cpp index c883a680..38be107e 100644 --- a/generators/igen.cpp +++ b/generators/igen.cpp @@ -7,15 +7,11 @@ */ #include "testlib.h" -#include using namespace std; -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { registerGen(argc, argv, 1); - cout << rnd.next(1, 1000000) << endl; - - return 0; + println(rnd.next(1, 1000000)); } diff --git a/generators/iwgen.cpp b/generators/iwgen.cpp index 6fb383ab..617b7bb3 100644 --- a/generators/iwgen.cpp +++ b/generators/iwgen.cpp @@ -24,15 +24,11 @@ */ #include "testlib.h" -#include using namespace std; -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { registerGen(argc, argv, 1); - cout << rnd.wnext(1, 1000000, opt(1)) << endl; - - return 0; + println(rnd.wnext(1, 1000000, opt(1))); } diff --git a/generators/multigen.cpp b/generators/multigen.cpp index 8f2c2027..46a82f55 100644 --- a/generators/multigen.cpp +++ b/generators/multigen.cpp @@ -3,32 +3,28 @@ * as test indices. * * For example, this generator writes 10 files (tests) from 1 to 10. - * This type of generators supported by Polygon too, but I believe - * that stdout-generators are more preferred. + * This type of generators is supported by Polygon too, but + * stdout-generators are more preferred. * - * The generator for A+B problem, generates 10 tests where each + * The generator is for A+B problem, generates 10 tests where each * number is between 1 and 100, and tests grow with indices. */ #include "testlib.h" -#include using namespace std; -void writeTest(int test) -{ +void writeTest(int test) { startTest(test); - - cout << rnd.next(1, test * test) - << " " << rnd.next(1, test * test) << endl; + + int a = rnd.next(1, test * test); + int b = rnd.next(1, test * test); + println(a, b); } -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { registerGen(argc, argv, 1); for (int i = 1; i <= 10; i++) writeTest(i); - - return 0; } diff --git a/generators/sgen.cpp b/generators/sgen.cpp index 74d612a0..83344cc8 100644 --- a/generators/sgen.cpp +++ b/generators/sgen.cpp @@ -10,15 +10,11 @@ */ #include "testlib.h" -#include using namespace std; -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { registerGen(argc, argv, 1); - cout << rnd.next("[a-zA-Z0-9]{1,1000}") << endl; - - return 0; + println(rnd.next("[a-zA-Z0-9]{1,1000}")); } diff --git a/generators/swgen.cpp b/generators/swgen.cpp index 26204746..35b6c433 100644 --- a/generators/swgen.cpp +++ b/generators/swgen.cpp @@ -13,16 +13,12 @@ */ #include "testlib.h" -#include using namespace std; -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { registerGen(argc, argv, 1); int length = rnd.wnext(1, 1000, opt(1)); - cout << rnd.next("[a-zA-Z0-9]{1,%d}", length) << endl; - - return 0; + println(rnd.next("[a-zA-Z0-9]{1,%d}", length)); } diff --git a/interactors/interactor-a-plus-b.cpp b/interactors/interactor-a-plus-b.cpp index 587c57ae..e19e1487 100644 --- a/interactors/interactor-a-plus-b.cpp +++ b/interactors/interactor-a-plus-b.cpp @@ -3,15 +3,13 @@ using namespace std; -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { setName("Interactor A+B"); registerInteraction(argc, argv); - + // reads number of queries from test (input) file int n = inf.readInt(); - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { // reads query from test (input) file int a = inf.readInt(); int b = inf.readInt(); diff --git a/testlib.h b/testlib.h index 2eedfe83..349b839f 100644 --- a/testlib.h +++ b/testlib.h @@ -1,16 +1,16 @@ -/* - * It is strictly recommended to include "testlib.h" before any other include +/* + * It is strictly recommended to include "testlib.h" before any other include * in your code. In this case testlib overrides compiler specific "random()". * - * If you can't compile your code and compiler outputs something about - * ambiguous call of "random_shuffle", "rand" or "srand" it means that + * If you can't compile your code and compiler outputs something about + * ambiguous call of "random_shuffle", "rand" or "srand" it means that * you shouldn't use them. Use "shuffle", and "rnd.next()" instead of them - * because these calls produce stable result for any C++ compiler. Read + * because these calls produce stable result for any C++ compiler. Read * sample generator sources for clarification. * * Please read the documentation for class "random_t" and use "rnd" instance in - * generators. Probably, these sample calls will be usefull for you: - * rnd.next(); rnd.next(100); rnd.next(1, 2); + * generators. Probably, these sample calls will be useful for you: + * rnd.next(); rnd.next(100); rnd.next(1, 2); * rnd.next(3.14); rnd.next("[a-z]{1,100}"). * * Also read about wnext() to generate off-center random distribution. @@ -22,18 +22,18 @@ #define _TESTLIB_H_ /* - * Copyright (c) 2005-2021 + * Copyright (c) 2005-2025 */ -#define VERSION "0.9.37-SNAPSHOT" +#define VERSION "0.9.45" -/* +/* * Mike Mirzayanov * * This material is provided "as is", with absolutely no warranty expressed * or implied. Any use is at your own risk. * - * Permission to use or copy this software for any purpose is hereby granted + * Permission to use or copy this software for any purpose is hereby granted * without fee, provided the above notices are retained on all copies. * Permission to modify the code and to distribute modified code is granted, * provided the above notices are retained, and a notice that the code was @@ -47,15 +47,15 @@ * check.exe [ [-appes]], * If result file is specified it will contain results. * - * Validator, using testlib running format: + * Validator, using testlib running format: * validator.exe < input.txt, * It will return non-zero exit code and writes message to standard output. * - * Generator, using testlib running format: + * Generator, using testlib running format: * gen.exe [parameter-1] [parameter-2] [... paramerter-n] * You can write generated test(s) into standard output or into the file(s). * - * Interactor, using testlib running format: + * Interactor, using testlib running format: * interactor.exe [ [ [-appes]]], * Reads test from inf (mapped to args[1]), writes result to tout (mapped to argv[2], * can be judged by checker later), reads program output from ouf (mapped to stdin), @@ -63,6 +63,15 @@ */ const char *latestFeatures[] = { + "Remove incorrect const attributes", + "Added ConstantBoundsLog, VariablesLog to validator testOverviewLogFile", + "Use setAppesModeEncoding to change xml encoding from windows-1251 to other", + "rnd.any/wany use distance/advance instead of -/+: now they support sets/multisets", + "Use syntax `int t = inf.readInt(1, 3, \"~t\");` to skip the lower bound check. Tildes can be used on either side or both: ~t, t~, ~t~", + "Supported EJUDGE support in registerTestlibCmd", + "Supported '--testMarkupFileName fn' and '--testCase tc/--testCaseFileName fn' for validators", + "Added opt defaults via opt(key/index, default_val); check unused opts when using has_opt or default opt (turn off this check with suppressEnsureNoUnusedOpt()).", + "For checker added --group and --testset command line params (like for validator), use checker.group() or checker.testset() to get values", "Added quitpi(points_info, message) function to return with _points exit code 7 and given points_info", "rnd.partition(size, sum[, min_part=1]) returns random (unsorted) partition which is a representation of the given `sum` as a sum of `size` positive integers (or >=min_part if specified)", "rnd.distinct(size, n) and rnd.distinct(size, from, to)", @@ -93,7 +102,7 @@ const char *latestFeatures[] = { "Introduced space-separated read functions: readWords/readTokens, multilines read functions: readStrings/readLines", "Introduced space-separated read functions: readInts/readIntegers/readLongs/readUnsignedLongs/readDoubles/readReals/readStrictDoubles/readStrictReals", "Introduced split/tokenize functions to separate string by given char", - "Introduced InStream::readUnsignedLong and InStream::readLong with unsigned long long paramerters", + "Introduced InStream::readUnsignedLong and InStream::readLong with unsigned long long parameters", "Supported --testOverviewLogFileName for validator: bounds hits + features", "Fixed UB (sequence points) in random_t", "POINTS_EXIT_CODE returned back to 7 (instead of 0)", @@ -170,6 +179,7 @@ const char *latestFeatures[] = { #include #include #include +#include #include #include #include @@ -177,8 +187,14 @@ const char *latestFeatures[] = { #include #include #include +#include +#include + +#ifdef TESTLIB_THROW_EXIT_EXCEPTION_INSTEAD_OF_EXIT +# include +#endif -#if (_WIN32 || __WIN32__ || _WIN64 || __WIN64__ || __CYGWIN__) +#if (_WIN32 || __WIN32__ || __WIN32 || _WIN64 || __WIN64__ || __WIN64 || WINNT || __WINNT || __WINNT__ || __CYGWIN__) # if !defined(_MSC_VER) || _MSC_VER > 1400 # define NOMINMAX 1 # include @@ -315,15 +331,21 @@ static int __testlib_format_buffer_usage_count = 0; result = std::string(__testlib_format_buffer); \ __testlib_format_buffer_usage_count--; \ +#ifdef __GNUC__ +__attribute__ ((format (printf, 1, 2))) +#endif +std::string testlib_format_(const char *fmt, ...); +std::string testlib_format_(const std::string fmt, ...); + const long long __TESTLIB_LONGLONG_MAX = 9223372036854775807LL; +const int __TESTLIB_MAX_TEST_CASE = 1073741823; + +int __testlib_exitCode; bool __testlib_hasTestCase; int __testlib_testCase = -1; -void setTestCase(int testCase) { - __testlib_hasTestCase = true; - __testlib_testCase = testCase; -} +void setTestCase(int testCase); void unsetTestCase() { __testlib_hasTestCase = false; @@ -333,20 +355,47 @@ void unsetTestCase() { NORETURN static void __testlib_fail(const std::string &message); template +#ifdef __GNUC__ +__attribute__((const)) +#endif static inline T __testlib_abs(const T &x) { return x > 0 ? x : -x; } template +#ifdef __GNUC__ +__attribute__((const)) +#endif static inline T __testlib_min(const T &a, const T &b) { return a < b ? a : b; } template +#ifdef __GNUC__ +__attribute__((const)) +#endif static inline T __testlib_max(const T &a, const T &b) { return a > b ? a : b; } +template +#ifdef __GNUC__ +__attribute__((const)) +#endif +static inline T __testlib_crop(T value, T a, T b) { + return __testlib_min(__testlib_max(value, a), --b); +} + +#ifdef __GNUC__ +__attribute__((const)) +#endif +static inline double __testlib_crop(double value, double a, double b) { + value = __testlib_min(__testlib_max(value, a), b); + if (value >= b) + value = std::nexttoward(b, a); + return value; +} + static bool __testlib_prelimIsNaN(double r) { volatile double ra = r; #ifndef __BORLANDC__ @@ -359,20 +408,24 @@ static bool __testlib_prelimIsNaN(double r) { static std::string removeDoubleTrailingZeroes(std::string value) { while (!value.empty() && value[value.length() - 1] == '0' && value.find('.') != std::string::npos) value = value.substr(0, value.length() - 1); - return value + '0'; + if (!value.empty() && value[value.length() - 1] == '.') + return value + '0'; + else + return value; } -#ifdef __GNUC__ -__attribute__ ((format (printf, 1, 2))) -#endif -std::string format(const char *fmt, ...) { - FMT_TO_RESULT(fmt, fmt, result); - return result; +inline std::string upperCase(std::string s) { + for (size_t i = 0; i < s.length(); i++) + if ('a' <= s[i] && s[i] <= 'z') + s[i] = char(s[i] - 'a' + 'A'); + return s; } -std::string format(const std::string fmt, ...) { - FMT_TO_RESULT(fmt, fmt.c_str(), result); - return result; +inline std::string lowerCase(std::string s) { + for (size_t i = 0; i < s.length(); i++) + if ('A' <= s[i] && s[i] <= 'Z') + s[i] = char(s[i] - 'A' + 'a'); + return s; } static std::string __testlib_part(const std::string &s); @@ -444,32 +497,154 @@ inline double doubleDelta(double expected, double result) { return absolute; } -#if !defined(_MSC_VER) || _MSC_VER < 1900 -#ifndef _fileno -#define _fileno(_stream) ((_stream)->_file) -#endif +/** It does nothing on non-windows and files differ from stdin/stdout/stderr. */ +static void __testlib_set_binary(std::FILE *file) { + if (NULL != file) { +#ifdef ON_WINDOWS +# ifdef _O_BINARY + if (stdin == file) +# ifdef STDIN_FILENO + return void(_setmode(STDIN_FILENO, _O_BINARY)); +# else + return void(_setmode(_fileno(stdin), _O_BINARY)); +# endif + if (stdout == file) +# ifdef STDOUT_FILENO + return void(_setmode(STDOUT_FILENO, _O_BINARY)); +# else + return void(_setmode(_fileno(stdout), _O_BINARY)); +# endif + if (stderr == file) +# ifdef STDERR_FILENO + return void(_setmode(STDERR_FILENO, _O_BINARY)); +# else + return void(_setmode(_fileno(stderr), _O_BINARY)); +# endif +# elif O_BINARY + if (stdin == file) +# ifdef STDIN_FILENO + return void(setmode(STDIN_FILENO, O_BINARY)); +# else + return void(setmode(fileno(stdin), O_BINARY)); +# endif + if (stdout == file) +# ifdef STDOUT_FILENO + return void(setmode(STDOUT_FILENO, O_BINARY)); +# else + return void(setmode(fileno(stdout), O_BINARY)); +# endif + if (stderr == file) +# ifdef STDERR_FILENO + return void(setmode(STDERR_FILENO, O_BINARY)); +# else + return void(setmode(fileno(stderr), O_BINARY)); +# endif +# endif #endif + } +} -#ifndef O_BINARY -static void __testlib_set_binary( -#ifdef __GNUC__ - __attribute__((unused)) -#endif - std::FILE* file -) +#if __cplusplus > 199711L || defined(_MSC_VER) +template +static std::string vtos(const T &t, std::true_type) { + if (t == 0) + return "0"; + else { + T n(t); + bool negative = n < 0; + std::string s; + while (n != 0) { + T digit = n % 10; + if (digit < 0) + digit = -digit; + s += char('0' + digit); + n /= 10; + } + std::reverse(s.begin(), s.end()); + return negative ? "-" + s : s; + } +} + +template +static std::string vtos(const T &t, std::false_type) { + std::string s; + static std::stringstream ss; + ss.str(std::string()); + ss.clear(); + ss << t; + ss >> s; + return s; +} + +template +static std::string vtos(const T &t) { + return vtos(t, std::is_integral()); +} + +/* signed case. */ +template +static std::string toHumanReadableString(const T &n, std::false_type) { + if (n == 0) + return vtos(n); + int trailingZeroCount = 0; + T n_ = n; + while (n_ % 10 == 0) + n_ /= 10, trailingZeroCount++; + if (trailingZeroCount >= 7) { + if (n_ == 1) + return "10^" + vtos(trailingZeroCount); + else if (n_ == -1) + return "-10^" + vtos(trailingZeroCount); + else + return vtos(n_) + "*10^" + vtos(trailingZeroCount); + } else + return vtos(n); +} + +/* unsigned case. */ +template +static std::string toHumanReadableString(const T &n, std::true_type) { + if (n == 0) + return vtos(n); + int trailingZeroCount = 0; + T n_ = n; + while (n_ % 10 == 0) + n_ /= 10, trailingZeroCount++; + if (trailingZeroCount >= 7) { + if (n_ == 1) + return "10^" + vtos(trailingZeroCount); + else + return vtos(n_) + "*10^" + vtos(trailingZeroCount); + } else + return vtos(n); +} + +template +static std::string toHumanReadableString(const T &n) { + return toHumanReadableString(n, std::is_unsigned()); +} #else -static void __testlib_set_binary(std::FILE *file) -#endif +template +static std::string vtos(const T& t) { -#ifdef O_BINARY - if (NULL != file) { -#ifndef __BORLANDC__ - _setmode(_fileno(file), O_BINARY); -#else - setmode(fileno(file), O_BINARY); -#endif - } + std::string s; + static std::stringstream ss; + ss.str(std::string()); + ss.clear(); + ss << t; + ss >> s; + return s; +} + +template +static std::string toHumanReadableString(const T &n) { + return vtos(n); +} #endif + +template +static std::string toString(const T &t) { + return vtos(t); } #if __cplusplus > 199711L || defined(_MSC_VER) @@ -477,20 +652,44 @@ static void __testlib_set_binary(std::FILE *file) void prepareOpts(int argc, char* argv[]); #endif +FILE* testlib_fopen_(const char* path, const char* mode) { +#ifdef _MSC_VER + FILE* result = NULL; + if (fopen_s(&result, path, mode) != 0) + return NULL; + else + return result; +#else + return std::fopen(path, mode); +#endif +} + +FILE* testlib_freopen_(const char* path, const char* mode, FILE* file) { +#ifdef _MSC_VER + FILE* result = NULL; + if (freopen_s(&result, path, mode, file) != 0) + return NULL; + else + return result; +#else + return std::freopen(path, mode, file); +#endif +} + /* * Very simple regex-like pattern. * It used for two purposes: validation and generation. - * + * * For example, pattern("[a-z]{1,5}").next(rnd) will return - * random string from lowercase latin letters with length - * from 1 to 5. It is easier to call rnd.next("[a-z]{1,5}") - * for the same effect. - * + * random string from lowercase latin letters with length + * from 1 to 5. It is easier to call rnd.next("[a-z]{1,5}") + * for the same effect. + * * Another samples: * "mike|john" will generate (match) "mike" or "john"; * "-?[1-9][0-9]{0,3}" will generate (match) non-zero integers from -9999 to 9999; * "id-([ac]|b{2})" will generate (match) "id-a", "id-bb", "id-c"; - * "[^0-9]*" will match sequences (empty or non-empty) without digits, you can't + * "[^0-9]*" will match sequences (empty or non-empty) without digits, you can't * use it for generations. * * You can't use pattern for generation if it contains meta-symbol '*'. Also it @@ -498,14 +697,14 @@ void prepareOpts(int argc, char* argv[]); * * For matching very simple greedy algorithm is used. For example, pattern * "[0-9]?1" will not match "1", because of greedy nature of matching. - * Alternations (meta-symbols "|") are processed with brute-force algorithm, so + * Alternations (meta-symbols "|") are processed with brute-force algorithm, so * do not use many alternations in one expression. * * If you want to use one expression many times it is better to compile it into - * a single pattern like "pattern p("[a-z]+")". Later you can use + * a single pattern like "pattern p("[a-z]+")". Later you can use * "p.matches(std::string s)" or "p.next(random_t& rd)" to check matching or generate * new string by pattern. - * + * * Simpler way to read token and check it for pattern matching is "inf.readToken("[a-z]+")". * * All spaces are ignored in regex, unless escaped with \. For example, ouf.readLine("NO SOLUTION") @@ -538,9 +737,9 @@ class pattern { int to; }; -/* - * Use random_t instances to generate random values. It is preffered - * way to use randoms instead of rand() function or self-written +/* + * Use random_t instances to generate random values. It is preferred + * way to use randoms instead of rand() function or self-written * randoms. * * Testlib defines global variable "rnd" of random_t class. @@ -600,8 +799,8 @@ class random_t { /* Sets seed by given value. */ void setSeed(long long _seed) { - _seed = (_seed ^ multiplier) & mask; - seed = _seed; + seed = (unsigned long long) _seed; + seed = (seed ^ multiplier) & mask; } #ifndef __BORLANDC__ @@ -718,37 +917,43 @@ class random_t { double next() { long long left = ((long long) (nextBits(26)) << 27); long long right = nextBits(27); - return (double) (left + right) / (double) (1LL << 53); + return __testlib_crop((double) (left + right) / (double) (1LL << 53), 0.0, 1.0); } /* Random double value in range [0, n). */ double next(double n) { - return n * next(); + if (n <= 0.0) + __testlib_fail("random_t::next(double): n should be positive"); + return __testlib_crop(n * next(), 0.0, n); } /* Random double value in range [from, to). */ double next(double from, double to) { - if (from > to) - __testlib_fail("random_t::next(double from, double to): from can't not exceed to"); + if (from >= to) + __testlib_fail("random_t::next(double from, double to): from should be strictly less than to"); return next(to - from) + from; } /* Returns random element from container. */ template typename Container::value_type any(const Container &c) { - size_t size = c.size(); + int size = int(c.size()); if (size <= 0) __testlib_fail("random_t::any(const Container& c): c.size() must be positive"); - return *(c.begin() + next(size)); + typename Container::const_iterator it = c.begin(); + std::advance(it, next(size)); + return *it; } /* Returns random element from iterator range. */ template typename Iter::value_type any(const Iter &begin, const Iter &end) { - int size = int(end - begin); + int size = static_cast(std::distance(begin, end)); if (size <= 0) __testlib_fail("random_t::any(const Iter& begin, const Iter& end): range must have positive length"); - return *(begin + next(size)); + Iter it = begin; + std::advance(it, next(size)); + return *it; } /* Random string value by given pattern (see pattern documentation). */ @@ -760,7 +965,7 @@ class random_t { return next(ptrn); } - /* + /* * Weighted next. If type == 0 than it is usual "next()". * * If type = 1, than it returns "max(next(), next())" @@ -790,7 +995,7 @@ class random_t { else p = 1 - std::pow(next() + 0.0, 1.0 / (-type + 1)); - return int(n * p); + return __testlib_crop((int) (double(n) * p), 0, n); } } @@ -815,37 +1020,13 @@ class random_t { if (type > 0) p = std::pow(next() + 0.0, 1.0 / (type + 1)); else - p = std::pow(next() + 0.0, -type + 1); - - return __testlib_min(__testlib_max((long long) (double(n) * p), 0LL), n - 1LL); - } - } - - /* See wnext(int, int). It uses the same algorithms. */ - double wnext(int type) { - if (abs(type) < random_t::lim) { - double result = next(); - - for (int i = 0; i < +type; i++) - result = __testlib_max(result, next()); - - for (int i = 0; i < -type; i++) - result = __testlib_min(result, next()); - - return result; - } else { - double p; - - if (type > 0) - p = std::pow(next() + 0.0, 1.0 / (type + 1)); - else - p = std::pow(next() + 0.0, -type + 1); + p = 1 - std::pow(next() + 0.0, 1.0 / (-type + 1)); - return p; + return __testlib_crop((long long) (double(n) * p), 0LL, n); } } - /* See wnext(int, int). It uses the same algorithms. */ + /* Returns value in [0, n). See wnext(int, int). It uses the same algorithms. */ double wnext(double n, int type) { if (n <= 0) __testlib_fail("random_t::wnext(double n, int type): n must be positive"); @@ -866,12 +1047,17 @@ class random_t { if (type > 0) p = std::pow(next() + 0.0, 1.0 / (type + 1)); else - p = std::pow(next() + 0.0, -type + 1); + p = 1 - std::pow(next() + 0.0, 1.0 / (-type + 1)); - return n * p; + return __testlib_crop(n * p, 0.0, n); } } + /* Returns value in [0, 1). See wnext(int, int). It uses the same algorithms. */ + double wnext(int type) { + return wnext(1.0, type); + } + /* See wnext(int, int). It uses the same algorithms. */ unsigned int wnext(unsigned int n, int type) { if (n >= INT_MAX) @@ -945,35 +1131,41 @@ class random_t { /* Returns weighted random double value in range [from, to). */ double wnext(double from, double to, int type) { - if (from > to) - __testlib_fail("random_t::wnext(double from, double to, int type): from can't not exceed to"); + if (from >= to) + __testlib_fail("random_t::wnext(double from, double to, int type): from should be strictly less than to"); return wnext(to - from, type) + from; } /* Returns weighted random element from container. */ template typename Container::value_type wany(const Container &c, int type) { - size_t size = c.size(); + int size = int(c.size()); if (size <= 0) __testlib_fail("random_t::wany(const Container& c, int type): c.size() must be positive"); - return *(c.begin() + wnext(size, type)); + typename Container::const_iterator it = c.begin(); + std::advance(it, wnext(size, type)); + return *it; } /* Returns weighted random element from iterator range. */ template typename Iter::value_type wany(const Iter &begin, const Iter &end, int type) { - int size = int(end - begin); + int size = static_cast(std::distance(begin, end)); if (size <= 0) __testlib_fail( "random_t::any(const Iter& begin, const Iter& end, int type): range must have positive length"); - return *(begin + wnext(size, type)); + Iter it = begin; + std::advance(it, wnext(size, type)); + return *it; } /* Returns random permutation of the given size (values are between `first` and `first`+size-1)*/ template std::vector perm(T size, E first) { - if (size <= 0) - __testlib_fail("random_t::perm(T size, E first = 0): size must be positive"); + if (size < 0) + __testlib_fail("random_t::perm(T size, E first = 0): size must non-negative"); + else if (size == 0) + return std::vector(); std::vector p(size); E current = first; for (T i = 0; i < size; i++) @@ -989,7 +1181,7 @@ class random_t { std::vector perm(T size) { return perm(size, T(0)); } - + /* Returns `size` unordered (unsorted) distinct numbers between `from` and `to`. */ template std::vector distinct(int size, T from, T to) { @@ -1010,7 +1202,7 @@ class random_t { double expected = 0.0; for (int i = 1; i <= size; i++) expected += double(n) / double(n - i + 1); - + if (expected < double(n)) { std::set vals; while (int(vals.size()) < size) { @@ -1035,12 +1227,12 @@ class random_t { __testlib_fail("random_t::distinct expected size >= 0"); if (size == 0) return std::vector(); - + if (upper <= 0) __testlib_fail("random_t::distinct expected upper > 0"); if (size > upper) __testlib_fail("random_t::distinct expected size <= upper"); - + return distinct(size, T(0), upper - 1); } @@ -1072,19 +1264,19 @@ class random_t { for (std::size_t i = 0; i < result.size(); i++) result[i] += min_part; - + T result_sum = 0; for (std::size_t i = 0; i < result.size(); i++) result_sum += result[i]; if (result_sum != sum_) __testlib_fail("random_t::partition: partition sum is expected to be the given sum"); - + if (*std::min_element(result.begin(), result.end()) < min_part) __testlib_fail("random_t::partition: partition min is expected to be no less than the given min_part"); - + if (int(result.size()) != size || result.size() != (size_t) size) __testlib_fail("random_t::partition: partition size is expected to be equal to the given size"); - + return result; } @@ -1234,7 +1426,11 @@ static void __pattern_scanCounts(const std::string &s, size_t &pos, int &from, i if (parts[i].length() == 0) __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\""); int number; +#ifdef _MSC_VER + if (sscanf_s(parts[i].c_str(), "%d", &number) != 1) +#else if (std::sscanf(parts[i].c_str(), "%d", &number) != 1) +#endif __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\""); numbers.push_back(number); } @@ -1441,7 +1637,7 @@ enum TResult { }; enum TTestlibMode { - _unknown, _checker, _validator, _generator, _interactor + _unknown, _checker, _validator, _generator, _interactor, _scorer }; #define _pc(exitCode) (TResult(_partially + (exitCode))) @@ -1473,6 +1669,10 @@ const std::string outcomes[] = { class InputStreamReader { public: + virtual void setTestCase(int testCase) = 0; + + virtual std::vector getReadChars() = 0; + virtual int curChar() = 0; virtual int nextChar() = 0; @@ -1506,6 +1706,14 @@ class StringInputStreamReader : public InputStreamReader { // No operations. } + void setTestCase(int) { + __testlib_fail("setTestCase not implemented in StringInputStreamReader"); + } + + std::vector getReadChars() { + __testlib_fail("getReadChars not implemented in StringInputStreamReader"); + } + int curChar() { if (pos >= s.length()) return EOFC; @@ -1527,7 +1735,7 @@ class StringInputStreamReader : public InputStreamReader { void unreadChar(int c) { if (pos == 0) - __testlib_fail("FileFileInputStreamReader::unreadChar(int): pos == 0."); + __testlib_fail("StringInputStreamReader::unreadChar(int): pos == 0."); pos--; if (pos < s.length()) s[pos] = char(c); @@ -1556,6 +1764,8 @@ class FileInputStreamReader : public InputStreamReader { std::string name; int line; std::vector undoChars; + std::vector readChars; + std::vector undoReadChars; inline int postprocessGetc(int getcResult) { if (getcResult != EOF) @@ -1566,19 +1776,29 @@ class FileInputStreamReader : public InputStreamReader { int getc(FILE *file) { int c; - if (undoChars.empty()) - c = ::getc(file); - else { + int rc; + + if (undoChars.empty()) { + c = rc = ::getc(file); + } else { c = undoChars.back(); undoChars.pop_back(); + rc = undoReadChars.back(); + undoReadChars.pop_back(); } if (c == LF) line++; + + readChars.push_back(rc); return c; } int ungetc(int c/*, FILE* file*/) { + if (!readChars.empty()) { + undoReadChars.push_back(readChars.back()); + readChars.pop_back(); + } if (c == LF) line--; undoChars.push_back(c); @@ -1590,6 +1810,16 @@ class FileInputStreamReader : public InputStreamReader { // No operations. } + void setTestCase(int testCase) { + if (testCase < 0 || testCase > __TESTLIB_MAX_TEST_CASE) + __testlib_fail(testlib_format_("testCase expected fit in [1,%d], but %d doesn't", __TESTLIB_MAX_TEST_CASE, testCase)); + readChars.push_back(testCase + 256); + } + + std::vector getReadChars() { + return readChars; + } + int curChar() { if (feof(file)) return EOFC; @@ -1708,6 +1938,14 @@ class BufferedFileInputStreamReader : public InputStreamReader { } } + void setTestCase(int) { + __testlib_fail("setTestCase not implemented in BufferedFileInputStreamReader"); + } + + std::vector getReadChars() { + __testlib_fail("getReadChars not implemented in BufferedFileInputStreamReader"); + } + int curChar() { if (!refill()) return EOFC; @@ -1794,6 +2032,9 @@ struct InStream { void init(std::FILE *f, TMode mode); + void setTestCase(int testCase); + std::vector getReadChars(); + /* Moves stream pointer to the first non-white-space character or EOF. */ void skipBlanks(); @@ -1827,9 +2068,9 @@ struct InStream { /* Moves pointer to the first non-white-space character and calls "eof()". */ bool seekEof(); - /* - * Checks that current position contains EOLN. - * If not it doesn't move stream pointer. + /* + * Checks that current position contains EOLN. + * If not it doesn't move stream pointer. * In strict mode expects "#13#10" for windows or "#10" for other platforms. */ bool eoln(); @@ -1840,13 +2081,13 @@ struct InStream { /* Moves stream pointer to the first character of the next line (if exists). */ void nextLine(); - /* - * Reads new token. Ignores white-spaces into the non-strict mode - * (strict mode is used in validators usually). + /* + * Reads new token. Ignores white-spaces into the non-strict mode + * (strict mode is used in validators usually). */ std::string readWord(); - /* The same as "readWord()", it is preffered to use "readToken()". */ + /* The same as "readWord()", it is preferred to use "readToken()". */ std::string readToken(); /* The same as "readWord()", but ensures that token matches to given pattern. */ @@ -1887,23 +2128,23 @@ struct InStream { void readTokenTo(std::string &result, const std::string &ptrn, const std::string &variableName = ""); - /* - * Reads new long long value. Ignores white-spaces into the non-strict mode - * (strict mode is used in validators usually). + /* + * Reads new long long value. Ignores white-spaces into the non-strict mode + * (strict mode is used in validators usually). */ long long readLong(); unsigned long long readUnsignedLong(); /* - * Reads new int. Ignores white-spaces into the non-strict mode - * (strict mode is used in validators usually). + * Reads new int. Ignores white-spaces into the non-strict mode + * (strict mode is used in validators usually). */ int readInteger(); /* - * Reads new int. Ignores white-spaces into the non-strict mode - * (strict mode is used in validators usually). + * Reads new int. Ignores white-spaces into the non-strict mode + * (strict mode is used in validators usually). */ int readInt(); @@ -1951,15 +2192,15 @@ struct InStream { /* Reads space-separated sequence of integers. */ std::vector readInts(int size, int indexBase = 1); - /* - * Reads new double. Ignores white-spaces into the non-strict mode - * (strict mode is used in validators usually). + /* + * Reads new double. Ignores white-spaces into the non-strict mode + * (strict mode is used in validators usually). */ double readReal(); /* - * Reads new double. Ignores white-spaces into the non-strict mode - * (strict mode is used in validators usually). + * Reads new double. Ignores white-spaces into the non-strict mode + * (strict mode is used in validators usually). */ double readDouble(); @@ -1979,7 +2220,7 @@ struct InStream { std::vector readDoubles(int size, int indexBase = 1); - /* + /* * As "readReal()" but ensures that value in the range [minv,maxv] and * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount] * and number is in the form "[-]digit(s)[.digit(s)]". @@ -1992,7 +2233,7 @@ struct InStream { int minAfterPointDigitCount, int maxAfterPointDigitCount, const std::string &variablesName = "", int indexBase = 1); - /* + /* * As "readDouble()" but ensures that value in the range [minv,maxv] and * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount] * and number is in the form "[-]digit(s)[.digit(s)]". @@ -2034,9 +2275,9 @@ struct InStream { /* The same as "readLine()/readString()", but ensures that line matches to the given pattern. */ void readStringTo(std::string &result, const std::string &ptrn, const std::string &variableName = ""); - /* - * Reads line from the current position to EOLN or EOF. Moves stream pointer to - * the first character of the new line (if possible). + /* + * Reads line from the current position to EOLN or EOF. Moves stream pointer to + * the first character of the new line (if possible). */ std::string readLine(); @@ -2072,12 +2313,12 @@ struct InStream { /* Reads EOF or fails. Use it in validators. Calls "eof()" method internally. */ void readEof(); - /* + /* * Quit-functions aborts program with and : * input/answer streams replace any result to FAIL. */ NORETURN void quit(TResult result, const char *msg); - /* + /* * Quit-functions aborts program with and : * input/answer streams replace any result to FAIL. */ @@ -2088,14 +2329,14 @@ struct InStream { * input/answer streams replace any result to FAIL. */ void quitif(bool condition, TResult result, const char *msg, ...); - /* + /* * Quit-functions aborts program with and : * input/answer streams replace any result to FAIL. */ NORETURN void quits(TResult result, std::string msg); - /* - * Checks condition and aborts a program if codition is false. + /* + * Checks condition and aborts a program if condition is false. * Returns _wa for ouf and _fail on any other streams. */ #ifdef __GNUC__ @@ -2125,6 +2366,9 @@ struct InStream { void xmlSafeWrite(std::FILE *file, const char *msg); + /* Skips UTF-8 Byte Order Mark. */ + void skipBom(); + private: InStream(const InStream &); @@ -2135,12 +2379,15 @@ InStream inf; InStream ouf; InStream ans; bool appesMode; +std::string appesModeEncoding = "windows-1251"; std::string resultName; std::string checkerName = "untitled checker"; random_t rnd; TTestlibMode testlibMode = _unknown; double __testlib_points = std::numeric_limits::infinity(); +const size_t VALIDATOR_MAX_VARIABLE_COUNT = 255; + struct ValidatorBoundsHit { static const double EPS; bool minHit; @@ -2149,26 +2396,66 @@ struct ValidatorBoundsHit { ValidatorBoundsHit(bool minHit = false, bool maxHit = false) : minHit(minHit), maxHit(maxHit) { }; - ValidatorBoundsHit merge(const ValidatorBoundsHit &validatorBoundsHit) { + ValidatorBoundsHit merge(const ValidatorBoundsHit &validatorBoundsHit, bool ignoreMinBound, bool ignoreMaxBound) { return ValidatorBoundsHit( - __testlib_max(minHit, validatorBoundsHit.minHit), - __testlib_max(maxHit, validatorBoundsHit.maxHit) + __testlib_max(minHit, validatorBoundsHit.minHit) || ignoreMinBound, + __testlib_max(maxHit, validatorBoundsHit.maxHit) || ignoreMaxBound ); } }; +struct ConstantBound { + std::string value; + bool broken; + + template + void adjust(T t) { + std::string t_string = std::to_string(t); + if (t_string.length() >= 32) { + broken = true; + value = ""; + } else { + if (!broken && value.empty()) + value = t_string; + if (!broken && value != t_string) { + broken = true; + value = ""; + } + } + } + + bool has_value() { + return !value.empty() && !broken && value.length() < 32; + } +}; + +struct ConstantBounds { + ConstantBound lowerBound; + ConstantBound upperBound; +}; + const double ValidatorBoundsHit::EPS = 1E-12; class Validator { private: + const static std::string TEST_MARKUP_HEADER; + const static std::string TEST_CASE_OPEN_TAG; + const static std::string TEST_CASE_CLOSE_TAG; + bool _initialized; std::string _testset; std::string _group; std::string _testOverviewLogFileName; + std::string _testMarkupFileName; + int _testCase = -1; + std::string _testCaseFileName; + std::map _boundsHitByVariableName; + std::map _constantBoundsByVariableName; std::set _features; std::set _hitFeatures; + std::set _variables; bool isVariableNameBoundsAnalyzable(const std::string &variableName) { for (size_t i = 0; i < variableName.length(); i++) @@ -2208,6 +2495,18 @@ class Validator { return _testOverviewLogFileName; } + std::string testMarkupFileName() const { + return _testMarkupFileName; + } + + int testCase() const { + return _testCase; + } + + std::string testCaseFileName() const { + return _testCaseFileName; + } + void setTestset(const char *const testset) { _testset = testset; } @@ -2220,10 +2519,69 @@ class Validator { _testOverviewLogFileName = testOverviewLogFileName; } + void setTestMarkupFileName(const char *const testMarkupFileName) { + _testMarkupFileName = testMarkupFileName; + } + + void setTestCase(int testCase) { + _testCase = testCase; + } + + void setTestCaseFileName(const char *const testCaseFileName) { + _testCaseFileName = testCaseFileName; + } + + std::string prepVariableName(const std::string &variableName) { + if (variableName.length() >= 2 && variableName != "~~") { + if (variableName[0] == '~' && variableName.back() != '~') + return variableName.substr(1); + if (variableName[0] != '~' && variableName.back() == '~') + return variableName.substr(0, variableName.length() - 1); + if (variableName[0] == '~' && variableName.back() == '~') + return variableName.substr(1, variableName.length() - 2); + } + return variableName; + } + + bool ignoreMinBound(const std::string &variableName) { + return variableName.length() >= 2 && variableName != "~~" && variableName[0] == '~'; + } + + bool ignoreMaxBound(const std::string &variableName) { + return variableName.length() >= 2 && variableName != "~~" && variableName.back() == '~'; + } + void addBoundsHit(const std::string &variableName, ValidatorBoundsHit boundsHit) { - if (isVariableNameBoundsAnalyzable(variableName)) { - _boundsHitByVariableName[variableName] - = boundsHit.merge(_boundsHitByVariableName[variableName]); + if (isVariableNameBoundsAnalyzable(variableName) + && _boundsHitByVariableName.size() < VALIDATOR_MAX_VARIABLE_COUNT) { + std::string preparedVariableName = prepVariableName(variableName); + _boundsHitByVariableName[preparedVariableName] = boundsHit.merge(_boundsHitByVariableName[preparedVariableName], + ignoreMinBound(variableName), ignoreMaxBound(variableName)); + } + } + + void addVariable(const std::string &variableName) { + if (isVariableNameBoundsAnalyzable(variableName) + && _variables.size() < VALIDATOR_MAX_VARIABLE_COUNT) { + std::string preparedVariableName = prepVariableName(variableName); + _variables.insert(preparedVariableName); + } + } + + std::string getVariablesLog() { + std::string result; + for (const std::string &variableName: _variables) + result += "variable \"" + variableName + "\"\n"; + return result; + } + + template + void adjustConstantBounds(const std::string &variableName, T lower, T upper) { + if (isVariableNameBoundsAnalyzable(variableName) + && _constantBoundsByVariableName.size() < VALIDATOR_MAX_VARIABLE_COUNT) { + std::string preparedVariableName = prepVariableName(variableName); + _constantBoundsByVariableName[preparedVariableName].lowerBound.adjust(lower); + _constantBoundsByVariableName[preparedVariableName].upperBound.adjust(upper); } } @@ -2242,6 +2600,27 @@ class Validator { return result; } + std::string getConstantBoundsLog() { + std::string result; + for (std::map::iterator i = _constantBoundsByVariableName.begin(); + i != _constantBoundsByVariableName.end(); + i++) { + if (i->second.lowerBound.has_value() || i->second.upperBound.has_value()) { + result += "constant-bounds \"" + i->first + "\":"; + if (i->second.lowerBound.has_value()) + result += " " + i->second.lowerBound.value; + else + result += " ?"; + if (i->second.upperBound.has_value()) + result += " " + i->second.upperBound.value; + else + result += " ?"; + result += "\n"; + } + } + return result; + } + std::string getFeaturesLog() { std::string result; for (std::set::iterator i = _features.begin(); @@ -2259,13 +2638,115 @@ class Validator { if (!_testOverviewLogFileName.empty()) { std::string fileName(_testOverviewLogFileName); _testOverviewLogFileName = ""; - FILE *testOverviewLogFile = fopen(fileName.c_str(), "w"); - if (NULL == testOverviewLogFile) - __testlib_fail("Validator::writeTestOverviewLog: can't test overview log to (" + fileName + ")"); - fprintf(testOverviewLogFile, "%s%s", getBoundsHitLog().c_str(), getFeaturesLog().c_str()); - if (fclose(testOverviewLogFile)) - __testlib_fail( - "Validator::writeTestOverviewLog: can't close test overview log file (" + fileName + ")"); + + FILE* f; + bool standard_file = false; + if (fileName == "stdout") + f = stdout, standard_file = true; + else if (fileName == "stderr") + f = stderr, standard_file = true; + else { + f = testlib_fopen_(fileName.c_str(), "wb"); + if (NULL == f) + __testlib_fail("Validator::writeTestOverviewLog: can't write test overview log to (" + fileName + ")"); + } + fprintf(f, "%s%s%s%s", + getBoundsHitLog().c_str(), + getFeaturesLog().c_str(), + getConstantBoundsLog().c_str(), + getVariablesLog().c_str()); + std::fflush(f); + if (!standard_file) + if (std::fclose(f)) + __testlib_fail("Validator::writeTestOverviewLog: can't close test overview log file (" + fileName + ")"); + } + } + + void writeTestMarkup() { + if (!_testMarkupFileName.empty()) { + std::vector readChars = inf.getReadChars(); + if (!readChars.empty()) { + std::string markup(TEST_MARKUP_HEADER); + for (size_t i = 0; i < readChars.size(); i++) { + int c = readChars[i]; + if (i + 1 == readChars.size() && c == -1) + continue; + if (c <= 256) { + char cc = char(c); + if (cc == '\\' || cc == '!') + markup += '\\'; + markup += cc; + } else { + markup += TEST_CASE_OPEN_TAG; + markup += toString(c - 256); + markup += TEST_CASE_CLOSE_TAG; + } + } + FILE* f; + bool standard_file = false; + if (_testMarkupFileName == "stdout") + f = stdout, standard_file = true; + else if (_testMarkupFileName == "stderr") + f = stderr, standard_file = true; + else { + f = testlib_fopen_(_testMarkupFileName.c_str(), "wb"); + if (NULL == f) + __testlib_fail("Validator::writeTestMarkup: can't write test markup to (" + _testMarkupFileName + ")"); + } + std::fprintf(f, "%s", markup.c_str()); + std::fflush(f); + if (!standard_file) + if (std::fclose(f)) + __testlib_fail("Validator::writeTestMarkup: can't close test markup file (" + _testCaseFileName + ")"); + } + } + } + + void writeTestCase() { + if (_testCase > 0) { + std::vector readChars = inf.getReadChars(); + if (!readChars.empty()) { + std::string content, testCaseContent; + bool matchedTestCase = false; + for (size_t i = 0; i < readChars.size(); i++) { + int c = readChars[i]; + if (i + 1 == readChars.size() && c == -1) + continue; + if (c <= 256) + content += char(c); + else { + if (matchedTestCase) { + testCaseContent = content; + matchedTestCase = false; + } + content = ""; + int testCase = c - 256; + if (testCase == _testCase) + matchedTestCase = true; + } + } + if (matchedTestCase) + testCaseContent = content; + + if (!testCaseContent.empty()) { + FILE* f; + bool standard_file = false; + if (_testCaseFileName.empty() || _testCaseFileName == "stdout") + f = stdout, standard_file = true; + else if (_testCaseFileName == "stderr") + f = stderr, standard_file = true; + else { + f = testlib_fopen_(_testCaseFileName.c_str(), "wb"); + if (NULL == f) + __testlib_fail("Validator::writeTestCase: can't write test case to (" + _testCaseFileName + ")"); + } + std::fprintf(f, "%s", testCaseContent.c_str()); + std::fflush(f); + if (!standard_file) + if (std::fclose(f)) + __testlib_fail("Validator::writeTestCase: can't close test case file (" + _testCaseFileName + ")"); + } + } } } @@ -2289,8 +2770,14 @@ class Validator { } } validator; +const std::string Validator::TEST_MARKUP_HEADER = "MU\xF3\x01"; +const std::string Validator::TEST_CASE_OPEN_TAG = "!c"; +const std::string Validator::TEST_CASE_CLOSE_TAG = ";"; + struct TestlibFinalizeGuard { static bool alive; + static bool registered; + int quitCount, readEofCount; TestlibFinalizeGuard() : quitCount(0), readEofCount(0) { @@ -2307,14 +2794,29 @@ struct TestlibFinalizeGuard { if (testlibMode == _validator && readEofCount == 0 && quitCount == 0) __testlib_fail("Validator must end with readEof call."); + + /* opts */ + autoEnsureNoUnusedOpts(); + + if (!registered) + __testlib_fail("Call register-function in the first line of the main (registerTestlibCmd or other similar)"); } - validator.writeTestOverviewLog(); + if (__testlib_exitCode == 0) { + validator.writeTestOverviewLog(); + validator.writeTestMarkup(); + validator.writeTestCase(); + } } + +private: + /* opts */ + void autoEnsureNoUnusedOpts(); }; bool TestlibFinalizeGuard::alive = true; -TestlibFinalizeGuard testlibFinalizeGuard; +bool TestlibFinalizeGuard::registered = false; +extern TestlibFinalizeGuard testlibFinalizeGuard; /* * Call it to disable checks on finalization. @@ -2330,109 +2832,6 @@ std::fstream tout; /* implementation */ -#if __cplusplus > 199711L || defined(_MSC_VER) -template -static std::string vtos(const T &t, std::true_type) { - if (t == 0) - return "0"; - else { - T n(t); - bool negative = n < 0; - std::string s; - while (n != 0) { - T digit = n % 10; - if (digit < 0) - digit = -digit; - s += char('0' + digit); - n /= 10; - } - std::reverse(s.begin(), s.end()); - return negative ? "-" + s : s; - } -} - -template -static std::string vtos(const T &t, std::false_type) { - std::string s; - static std::stringstream ss; - ss.str(std::string()); - ss.clear(); - ss << t; - ss >> s; - return s; -} - -template -static std::string vtos(const T &t) { - return vtos(t, std::is_integral()); -} - -/* signed case. */ -template -static std::string toHumanReadableString(const T &n, std::false_type) { - if (n == 0) - return vtos(n); - int trailingZeroCount = 0; - T n_ = n; - while (n_ % 10 == 0) - n_ /= 10, trailingZeroCount++; - if (trailingZeroCount >= 7) { - if (n_ == 1) - return "10^" + vtos(trailingZeroCount); - else if (n_ == -1) - return "-10^" + vtos(trailingZeroCount); - else - return vtos(n_) + "*10^" + vtos(trailingZeroCount); - } else - return vtos(n); -} - -/* unsigned case. */ -template -static std::string toHumanReadableString(const T &n, std::true_type) { - if (n == 0) - return vtos(n); - int trailingZeroCount = 0; - T n_ = n; - while (n_ % 10 == 0) - n_ /= 10, trailingZeroCount++; - if (trailingZeroCount >= 7) { - if (n_ == 1) - return "10^" + vtos(trailingZeroCount); - else - return vtos(n_) + "*10^" + vtos(trailingZeroCount); - } else - return vtos(n); -} - -template -static std::string toHumanReadableString(const T &n) { - return toHumanReadableString(n, std::is_unsigned()); -} -#else -template -static std::string vtos(const T& t) -{ - std::string s; - static std::stringstream ss; - ss.str(std::string()); - ss.clear(); - ss << t; - ss >> s; - return s; -} - -template -static std::string toHumanReadableString(const T &n) { - return vtos(n); -} -#endif - -template -static std::string toString(const T &t) { - return vtos(t); -} - InStream::InStream() { reader = NULL; lastLine = -1; @@ -2470,6 +2869,38 @@ InStream::~InStream() { } } +void InStream::setTestCase(int testCase) { + if (testlibMode != _validator || mode != _input || !stdfile || this != &inf) + __testlib_fail("InStream::setTestCase can be used only for inf in validator-mode." + " Actually, prefer setTestCase function instead of InStream member"); + reader->setTestCase(testCase); +} + +std::vector InStream::getReadChars() { + if (testlibMode != _validator || mode != _input || !stdfile || this != &inf) + __testlib_fail("InStream::getReadChars can be used only for inf in validator-mode."); + return reader == NULL ? std::vector() : reader->getReadChars(); +} + +void setTestCase(int testCase) { + static bool first_run = true; + static bool zero_based = false; + + if (first_run && testCase == 0) + zero_based = true; + + if (zero_based) + testCase++; + + __testlib_hasTestCase = true; + __testlib_testCase = testCase; + + if (testlibMode == _validator) + inf.setTestCase(testCase); + + first_run = false; +} + #ifdef __GNUC__ __attribute__((const)) #endif @@ -2532,12 +2963,26 @@ void InStream::textColor( #endif } +#ifdef TESTLIB_THROW_EXIT_EXCEPTION_INSTEAD_OF_EXIT +class exit_exception: public std::exception { +private: + int exitCode; +public: + exit_exception(int exitCode): exitCode(exitCode) {} + int getExitCode() { return exitCode; } +}; +#endif + NORETURN void halt(int exitCode) { #ifdef FOOTER InStream::textColor(InStream::LightGray); std::fprintf(stderr, "Checker: \"%s\"\n", checkerName.c_str()); std::fprintf(stderr, "Exit code: %d\n", exitCode); InStream::textColor(InStream::LightGray); +#endif + __testlib_exitCode = exitCode; +#ifdef TESTLIB_THROW_EXIT_EXCEPTION_INSTEAD_OF_EXIT + throw exit_exception(exitCode); #endif std::exit(exitCode); } @@ -2613,7 +3058,7 @@ NORETURN void InStream::quit(TResult result, const char *msg) { message = trim(message); if (__testlib_hasTestCase) { - if (result != _ok) + if (result != _ok && result != _points) message = __testlib_appendMessage(message, "test case " + vtos(__testlib_testCase)); else { if (__testlib_testCase == 1) @@ -2636,6 +3081,9 @@ NORETURN void InStream::quit(TResult result, const char *msg) { result = _pe; #endif + if (testlibMode == _scorer && result != _fail) + quits(_fail, "Scorer should return points only. Don't use a quit function."); + if (mode != _output && result != _fail) { if (mode == _input && testlibMode == _validator && lastLine != -1) quits(_fail, __testlib_appendMessage(__testlib_appendMessage(message, name), "line " + vtos(lastLine))); @@ -2686,7 +3134,7 @@ NORETURN void InStream::quit(TResult result, const char *msg) { break; default: if (result >= _partially) { - errorName = format("partially correct (%d) ", pctype); + errorName = testlib_format_("partially correct (%d) ", pctype); isPartial = true; quitscrS(LightYellow, errorName); } else @@ -2694,13 +3142,13 @@ NORETURN void InStream::quit(TResult result, const char *msg) { } if (resultName != "") { - resultFile = std::fopen(resultName.c_str(), "w"); + resultFile = testlib_fopen_(resultName.c_str(), "w"); if (resultFile == NULL) { resultName = ""; quit(_fail, "Can not write to the result file"); } if (appesMode) { - std::fprintf(resultFile, ""); + std::fprintf(resultFile, "", appesModeEncoding.c_str()); if (isPartial) std::fprintf(resultFile, "", outcomes[(int) _partially].c_str(), pctype); @@ -2710,7 +3158,7 @@ NORETURN void InStream::quit(TResult result, const char *msg) { else { if (__testlib_points == std::numeric_limits::infinity()) quit(_fail, "Expected points, but infinity found"); - std::string stringPoints = removeDoubleTrailingZeroes(format("%.10f", __testlib_points)); + std::string stringPoints = removeDoubleTrailingZeroes(testlib_format_("%.10f", __testlib_points)); std::fprintf(resultFile, "", outcomes[(int) result].c_str(), stringPoints.c_str()); } @@ -2811,7 +3259,7 @@ void InStream::reset(std::FILE *file) { close(); if (!stdfile && NULL == file) - if (NULL == (file = std::fopen(name.c_str(), "rb"))) { + if (NULL == (file = testlib_fopen_(name.c_str(), "rb"))) { if (mode == _output) quits(_pe, std::string("Output file not found: \"") + name + "\""); @@ -2821,7 +3269,6 @@ void InStream::reset(std::FILE *file) { if (NULL != file) { opened = true; - __testlib_set_binary(file); if (stdfile) @@ -2873,6 +3320,21 @@ void InStream::init(std::FILE *f, TMode mode) { reset(f); } +void InStream::skipBom() { + const std::string utf8Bom = "\xEF\xBB\xBF"; + size_t index = 0; + while (index < utf8Bom.size() && curChar() == utf8Bom[index]) { + index++; + skipChar(); + } + if (index < utf8Bom.size()) { + while (index != 0) { + unreadChar(utf8Bom[index - 1]); + index--; + } + } +} + char InStream::curChar() { return char(reader->curChar()); } @@ -3018,11 +3480,15 @@ std::string InStream::readWord(const pattern &p, const std::string &variableName "\"").c_str()); } } + if (strict && !variableName.empty()) + validator.addVariable(variableName); return _tmpReadToken; } std::vector InStream::readWords(int size, const pattern &p, const std::string &variablesName, int indexBase) { + if (strict && !variablesName.empty()) + validator.addVariable(variablesName); __testlib_readMany(readWords, readWord(p, variablesName), std::string, true); } @@ -3037,6 +3503,8 @@ std::string InStream::readWord(const std::string &ptrn, const std::string &varia std::vector InStream::readWords(int size, const std::string &ptrn, const std::string &variablesName, int indexBase) { pattern p(ptrn); + if (strict && !variablesName.empty()) + validator.addVariable(variablesName); __testlib_readMany(readWords, readWord(p, variablesName), std::string, true); } @@ -3046,6 +3514,8 @@ std::string InStream::readToken(const pattern &p, const std::string &variableNam std::vector InStream::readTokens(int size, const pattern &p, const std::string &variablesName, int indexBase) { + if (strict && !variablesName.empty()) + validator.addVariable(variablesName); __testlib_readMany(readTokens, readToken(p, variablesName), std::string, true); } @@ -3060,6 +3530,8 @@ std::string InStream::readToken(const std::string &ptrn, const std::string &vari std::vector InStream::readTokens(int size, const std::string &ptrn, const std::string &variablesName, int indexBase) { pattern p(ptrn); + if (strict && !variablesName.empty()) + validator.addVariable(variablesName); __testlib_readMany(readTokens, readWord(p, variablesName), std::string, true); } @@ -3073,6 +3545,8 @@ void InStream::readWordTo(std::string &result, const pattern &p, const std::stri quit(_wa, ("Token parameter [name=" + variableName + "] equals to \"" + __testlib_part(result) + "\", doesn't correspond to pattern \"" + p.src() + "\"").c_str()); } + if (strict && !variableName.empty()) + validator.addVariable(variableName); } void InStream::readWordTo(std::string &result, const std::string &ptrn, const std::string &variableName) { @@ -3153,7 +3627,7 @@ static inline bool equals(unsigned long long integer, const char *s) { } static inline double stringToDouble(InStream &in, const char *buffer) { - double retval; + double result; size_t length = strlen(buffer); @@ -3186,14 +3660,20 @@ static inline double stringToDouble(InStream &in, const char *buffer) { in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str()); char *suffix = new char[length + 1]; - int scanned = std::sscanf(buffer, "%lf%s", &retval, suffix); + std::memset(suffix, 0, length + 1); + int scanned; +#ifdef _MSC_VER + scanned = sscanf_s(buffer, "%lf%s", &result, suffix, (unsigned int)(length + 1)); +#else + scanned = std::sscanf(buffer, "%lf%s", &result, suffix); +#endif bool empty = strlen(suffix) == 0; delete[] suffix; if (scanned == 1 || (scanned == 2 && empty)) { - if (__testlib_isNaN(retval)) + if (__testlib_isNaN(result)) in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str()); - return retval; + return result; } else in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str()); } @@ -3202,7 +3682,7 @@ static inline double stringToDouble(InStream &in, const std::string& buffer) { for (size_t i = 0; i < buffer.length(); i++) if (buffer[i] == '\0') in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found (it contains \\0)").c_str()); - return stringToDouble(in, buffer.c_str()); + return stringToDouble(in, buffer.c_str()); } static inline double stringToStrictDouble(InStream &in, const char *buffer, @@ -3214,7 +3694,7 @@ static inline double stringToStrictDouble(InStream &in, const char *buffer, in.quit(_fail, "stringToStrictDouble: minAfterPointDigitCount should be less or equal to maxAfterPointDigitCount."); - double retval; + double result; size_t length = strlen(buffer); @@ -3262,16 +3742,22 @@ static inline double stringToStrictDouble(InStream &in, const char *buffer, in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str()); char *suffix = new char[length + 1]; - int scanned = std::sscanf(buffer, "%lf%s", &retval, suffix); + std::memset(suffix, 0, length + 1); + int scanned; +#ifdef _MSC_VER + scanned = sscanf_s(buffer, "%lf%s", &result, suffix, (unsigned int)(length + 1)); +#else + scanned = std::sscanf(buffer, "%lf%s", &result, suffix); +#endif bool empty = strlen(suffix) == 0; delete[] suffix; if (scanned == 1 || (scanned == 2 && empty)) { - if (__testlib_isNaN(retval) || __testlib_isInfinite(retval)) + if (__testlib_isNaN(result) || __testlib_isInfinite(result)) in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str()); - if (buffer[0] == '-' && retval >= 0) + if (buffer[0] == '-' && result >= 0) in.quit(_pe, ("Redundant minus in \"" + __testlib_part(buffer) + "\" found").c_str()); - return retval; + return result; } else in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str()); } @@ -3285,24 +3771,15 @@ static inline double stringToStrictDouble(InStream &in, const std::string& buffe } static inline long long stringToLongLong(InStream &in, const char *buffer) { - if (strcmp(buffer, "-9223372036854775808") == 0) - return LLONG_MIN; - - bool minus = false; size_t length = strlen(buffer); - - if (length > 1 && buffer[0] == '-') - minus = true; - - if (length > 20) + if (length == 0 || length > 20) in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str()); - long long retval = 0LL; - + bool has_minus = (length > 1 && buffer[0] == '-'); int zeroes = 0; bool processingZeroes = true; - for (int i = (minus ? 1 : 0); i < int(length); i++) { + for (int i = (has_minus ? 1 : 0); i < int(length); i++) { if (buffer[i] == '0' && processingZeroes) zeroes++; else @@ -3310,65 +3787,60 @@ static inline long long stringToLongLong(InStream &in, const char *buffer) { if (buffer[i] < '0' || buffer[i] > '9') in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str()); - retval = retval * 10 + (buffer[i] - '0'); } - if (retval < 0) + long long int result; + try { + result = std::stoll(buffer); + } catch (const std::exception&) { in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str()); - - if ((zeroes > 0 && (retval != 0 || minus)) || zeroes > 1) + } catch (...) { in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str()); + } - retval = (minus ? -retval : +retval); - - if (length < 19) - return retval; + if ((zeroes > 0 && (result != 0 || has_minus)) || zeroes > 1) + in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str()); - if (equals(retval, buffer)) - return retval; - else - in.quit(_pe, ("Expected int64, but \"" + __testlib_part(buffer) + "\" found").c_str()); + return result; } static inline long long stringToLongLong(InStream &in, const std::string& buffer) { for (size_t i = 0; i < buffer.length(); i++) if (buffer[i] == '\0') in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found (it contains \\0)").c_str()); - return stringToLongLong(in, buffer.c_str()); + return stringToLongLong(in, buffer.c_str()); } static inline unsigned long long stringToUnsignedLongLong(InStream &in, const char *buffer) { size_t length = strlen(buffer); - if (length > 20) + if (length == 0 || length > 20) in.quit(_pe, ("Expected unsigned integer, but \"" + __testlib_part(buffer) + "\" found").c_str()); if (length > 1 && buffer[0] == '0') in.quit(_pe, ("Expected unsigned integer, but \"" + __testlib_part(buffer) + "\" found").c_str()); - unsigned long long retval = 0LL; for (int i = 0; i < int(length); i++) { if (buffer[i] < '0' || buffer[i] > '9') in.quit(_pe, ("Expected unsigned integer, but \"" + __testlib_part(buffer) + "\" found").c_str()); - retval = retval * 10 + (buffer[i] - '0'); } - if (length < 19) - return retval; - - if (length == 20 && strcmp(buffer, "18446744073709551615") > 0) - in.quit(_pe, ("Expected unsigned int64, but \"" + __testlib_part(buffer) + "\" found").c_str()); + unsigned long long result; + try { + result = std::stoull(buffer); + } catch (const std::exception&) { + in.quit(_pe, ("Expected unsigned integer, but \"" + __testlib_part(buffer) + "\" found").c_str()); + } catch (...) { + in.quit(_pe, ("Expected unsigned integer, but \"" + __testlib_part(buffer) + "\" found").c_str()); + } - if (equals(retval, buffer)) - return retval; - else - in.quit(_pe, ("Expected unsigned int64, but \"" + __testlib_part(buffer) + "\" found").c_str()); + return result; } static inline long long stringToUnsignedLongLong(InStream &in, const std::string& buffer) { for (size_t i = 0; i < buffer.length(); i++) if (buffer[i] == '\0') in.quit(_pe, ("Expected unsigned integer, but \"" + __testlib_part(buffer) + "\" found (it contains \\0)").c_str()); - return stringToUnsignedLongLong(in, buffer.c_str()); + return stringToUnsignedLongLong(in, buffer.c_str()); } int InStream::readInteger() { @@ -3424,14 +3896,19 @@ long long InStream::readLong(long long minv, long long maxv, const std::string & } } - if (strict && !variableName.empty()) + if (strict && !variableName.empty()) { validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result)); + validator.adjustConstantBounds(variableName, minv, maxv); + validator.addVariable(variableName); + } return result; } std::vector InStream::readLongs(int size, long long minv, long long maxv, const std::string &variablesName, int indexBase) { + if (strict && !variablesName.empty()) + validator.addVariable(variablesName); __testlib_readMany(readLongs, readLong(minv, maxv, variablesName), long long, true) } @@ -3465,14 +3942,19 @@ InStream::readUnsignedLong(unsigned long long minv, unsigned long long maxv, con } } - if (strict && !variableName.empty()) + if (strict && !variableName.empty()) { validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result)); + validator.adjustConstantBounds(variableName, minv, maxv); + validator.addVariable(variableName); + } return result; } std::vector InStream::readUnsignedLongs(int size, unsigned long long minv, unsigned long long maxv, const std::string &variablesName, int indexBase) { + if (strict && !variablesName.empty()) + validator.addVariable(variablesName); __testlib_readMany(readUnsignedLongs, readUnsignedLong(minv, maxv, variablesName), unsigned long long, true) } @@ -3511,8 +3993,11 @@ int InStream::readInt(int minv, int maxv, const std::string &variableName) { } } - if (strict && !variableName.empty()) + if (strict && !variableName.empty()) { validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result)); + validator.adjustConstantBounds(variableName, minv, maxv); + validator.addVariable(variableName); + } return result; } @@ -3522,6 +4007,8 @@ int InStream::readInteger(int minv, int maxv, const std::string &variableName) { } std::vector InStream::readInts(int size, int minv, int maxv, const std::string &variablesName, int indexBase) { + if (strict && !variablesName.empty()) + validator.addVariable(variablesName); __testlib_readMany(readInts, readInt(minv, maxv, variablesName), int, true) } @@ -3530,6 +4017,8 @@ std::vector InStream::readInts(int size, int indexBase) { } std::vector InStream::readIntegers(int size, int minv, int maxv, const std::string &variablesName, int indexBase) { + if (strict && !variablesName.empty()) + validator.addVariable(variablesName); __testlib_readMany(readIntegers, readInt(minv, maxv, variablesName), int, true) } @@ -3570,17 +4059,22 @@ double InStream::readReal(double minv, double maxv, const std::string &variableN } } - if (strict && !variableName.empty()) + if (strict && !variableName.empty()) { validator.addBoundsHit(variableName, ValidatorBoundsHit( doubleDelta(minv, result) < ValidatorBoundsHit::EPS, doubleDelta(maxv, result) < ValidatorBoundsHit::EPS )); - + validator.adjustConstantBounds(variableName, minv, maxv); + validator.addVariable(variableName); + } + return result; } std::vector InStream::readReals(int size, double minv, double maxv, const std::string &variablesName, int indexBase) { + if (strict && !variablesName.empty()) + validator.addVariable(variablesName); __testlib_readMany(readReals, readReal(minv, maxv, variablesName), double, true) } @@ -3594,6 +4088,8 @@ double InStream::readDouble(double minv, double maxv, const std::string &variabl std::vector InStream::readDoubles(int size, double minv, double maxv, const std::string &variablesName, int indexBase) { + if (strict && !variablesName.empty()) + validator.addVariable(variablesName); __testlib_readMany(readDoubles, readDouble(minv, maxv, variablesName), double, true) } @@ -3629,11 +4125,14 @@ double InStream::readStrictReal(double minv, double maxv, } } - if (strict && !variableName.empty()) + if (strict && !variableName.empty()) { validator.addBoundsHit(variableName, ValidatorBoundsHit( doubleDelta(minv, result) < ValidatorBoundsHit::EPS, doubleDelta(maxv, result) < ValidatorBoundsHit::EPS )); + validator.adjustConstantBounds(variableName, minv, maxv); + validator.addVariable(variableName); + } return result; } @@ -3641,6 +4140,8 @@ double InStream::readStrictReal(double minv, double maxv, std::vector InStream::readStrictReals(int size, double minv, double maxv, int minAfterPointDigitCount, int maxAfterPointDigitCount, const std::string &variablesName, int indexBase) { + if (strict && !variablesName.empty()) + validator.addVariable(variablesName); __testlib_readMany(readStrictReals, readStrictReal(minv, maxv, minAfterPointDigitCount, maxAfterPointDigitCount, variablesName), double, true) @@ -3657,6 +4158,8 @@ double InStream::readStrictDouble(double minv, double maxv, std::vector InStream::readStrictDoubles(int size, double minv, double maxv, int minAfterPointDigitCount, int maxAfterPointDigitCount, const std::string &variablesName, int indexBase) { + if (strict && !variablesName.empty()) + validator.addVariable(variablesName); __testlib_readMany(readStrictDoubles, readStrictDouble(minv, maxv, minAfterPointDigitCount, maxAfterPointDigitCount, variablesName), double, true) @@ -3818,6 +4321,8 @@ void InStream::readStringTo(std::string &result, const pattern &p, const std::st __testlib_part(result) + "\", doesn't correspond to pattern \"" + p.src() + "\"").c_str()); } } + if (strict && !variableName.empty()) + validator.addVariable(variableName); } void InStream::readStringTo(std::string &result, const std::string &ptrn, const std::string &variableName) { @@ -3831,6 +4336,8 @@ std::string InStream::readString(const pattern &p, const std::string &variableNa std::vector InStream::readStrings(int size, const pattern &p, const std::string &variablesName, int indexBase) { + if (strict && !variablesName.empty()) + validator.addVariable(variablesName); __testlib_readMany(readStrings, readString(p, variablesName), std::string, false) } @@ -3842,6 +4349,8 @@ std::string InStream::readString(const std::string &ptrn, const std::string &var std::vector InStream::readStrings(int size, const std::string &ptrn, const std::string &variablesName, int indexBase) { pattern p(ptrn); + if (strict && !variablesName.empty()) + validator.addVariable(variablesName); __testlib_readMany(readStrings, readString(p, variablesName), std::string, false) } @@ -3871,6 +4380,8 @@ std::string InStream::readLine(const pattern &p, const std::string &variableName std::vector InStream::readLines(int size, const pattern &p, const std::string &variablesName, int indexBase) { + if (strict && !variablesName.empty()) + validator.addVariable(variablesName); __testlib_readMany(readLines, readString(p, variablesName), std::string, false) } @@ -3881,6 +4392,8 @@ std::string InStream::readLine(const std::string &ptrn, const std::string &varia std::vector InStream::readLines(int size, const std::string &ptrn, const std::string &variablesName, int indexBase) { pattern p(ptrn); + if (strict && !variablesName.empty()) + validator.addVariable(variablesName); __testlib_readMany(readLines, readString(p, variablesName), std::string, false) } @@ -3917,9 +4430,26 @@ NORETURN void quit(TResult result, const char *msg) { ouf.quit(result, msg); } -NORETURN void __testlib_quitp(double points, const char *message) { - __testlib_points = points; - std::string stringPoints = removeDoubleTrailingZeroes(format("%.10f", points)); +double __testlib_preparePoints(double points_) { + volatile double points = points_; + if (__testlib_isNaN(points)) + quit(_fail, "Parameter 'points' can't be nan"); + if (__testlib_isInfinite(points)) + quit(_fail, "Parameter 'points' can't be infinite"); + if (points < -1E-8) + quit(_fail, "Parameter 'points' can't be negative"); + if (points <= 0.0) + points = +0.0; + if (points > 1E6 + 1E-8) + quit(_fail, "Parameter 'points' can't be greater than 1E6"); + if (points >= 1E6) + points = 1E6; + return points; +} + +NORETURN void __testlib_quitp(double points, const char *message) { + __testlib_points = __testlib_preparePoints(points); + std::string stringPoints = removeDoubleTrailingZeroes(testlib_format_("%.10f", __testlib_points)); std::string quitMessage; if (NULL == message || 0 == strlen(message)) @@ -3931,8 +4461,8 @@ NORETURN void __testlib_quitp(double points, const char *message) { } NORETURN void __testlib_quitp(int points, const char *message) { - __testlib_points = points; - std::string stringPoints = format("%d", points); + __testlib_points = __testlib_preparePoints(points); + std::string stringPoints = testlib_format_("%d", points); std::string quitMessage; if (NULL == message || 0 == strlen(message)) @@ -4010,8 +4540,9 @@ NORETURN void __testlib_help() { std::fprintf(stderr, "\n"); std::fprintf(stderr, "Program must be run with the following arguments: \n"); - std::fprintf(stderr, " [ [<-appes>]]\n\n"); + std::fprintf(stderr, " [--testset testset] [--group group] [ [<-appes>]]\n\n"); + __testlib_exitCode = FAIL_EXIT_CODE; std::exit(FAIL_EXIT_CODE); } @@ -4035,12 +4566,41 @@ static void __testlib_ensuresPreconditions() { quit(_fail, "Function __testlib_isNaN is not working correctly: possible reason is '-ffast-math'"); } +std::string __testlib_testset; + +std::string getTestset() { + return __testlib_testset; +} + +std::string __testlib_group; + +std::string getGroup() { + return __testlib_group; +} + +static void __testlib_set_testset_and_group(int argc, char* argv[]) { + for (int i = 1; i < argc; i++) { + if (!strcmp("--testset", argv[i])) { + if (i + 1 < argc && strlen(argv[i + 1]) > 0) + __testlib_testset = argv[++i]; + else + quit(_fail, std::string("Expected non-empty testset after --testset command line parameter")); + } else if (!strcmp("--group", argv[i])) { + if (i + 1 < argc) + __testlib_group = argv[++i]; + else + quit(_fail, std::string("Expected group after --group command line parameter")); + } + } +} + void registerGen(int argc, char *argv[], int randomGeneratorVersion) { if (randomGeneratorVersion < 0 || randomGeneratorVersion > 1) quitf(_fail, "Random generator version is expected to be 0 or 1."); random_t::version = randomGeneratorVersion; __testlib_ensuresPreconditions(); + TestlibFinalizeGuard::registered = true; testlibMode = _generator; __testlib_set_binary(stdin); @@ -4082,8 +4642,34 @@ void registerGen(int argc, char *argv[]) { } #endif +void setAppesModeEncoding(std::string appesModeEncoding) { + static const char* const ENCODINGS[] = {"ascii", "utf-7", "utf-8", "utf-16", "utf-16le", "utf-16be", "utf-32", "utf-32le", "utf-32be", "iso-8859-1", +"iso-8859-2", "iso-8859-3", "iso-8859-4", "iso-8859-5", "iso-8859-6", "iso-8859-7", "iso-8859-8", "iso-8859-9", "iso-8859-10", "iso-8859-11", +"iso-8859-13", "iso-8859-14", "iso-8859-15", "iso-8859-16", "windows-1250", "windows-1251", "windows-1252", "windows-1253", "windows-1254", "windows-1255", +"windows-1256", "windows-1257", "windows-1258", "gb2312", "gbk", "gb18030", "big5", "shift-jis", "euc-jp", "euc-kr", +"euc-cn", "euc-tw", "koi8-r", "koi8-u", "tis-620", "ibm437", "ibm850", "ibm852", "ibm855", "ibm857", +"ibm860", "ibm861", "ibm862", "ibm863", "ibm865", "ibm866", "ibm869", "macroman", "maccentraleurope", "maciceland", +"maccroatian", "macromania", "maccyrillic", "macukraine", "macgreek", "macturkish", "machebrew", "macarabic", "macthai", "hz-gb-2312", +"iso-2022-jp", "iso-2022-kr", "iso-2022-cn", "armscii-8", "tscii", "iscii", "viscii", "geostd8", "cp949", "cp874", +"cp1006", "cp775", "cp858", "cp737", "cp853", "cp856", "cp922", "cp1046", "cp1125", "cp1131", +"ptcp154", "koi8-t", "koi8-ru", "mulelao-1", "cp1133", "iso-ir-166", "tcvn", "iso-ir-14", "iso-ir-87", "iso-ir-159"}; + + appesModeEncoding = lowerCase(appesModeEncoding); + bool valid = false; + for (size_t i = 0; i < sizeof(ENCODINGS) / sizeof(ENCODINGS[0]); i++) + if (appesModeEncoding == ENCODINGS[i]) { + valid = true; + break; + } + if (!valid) + quit(_fail, "Unexpected encoding for setAppesModeEncoding(encoding)"); + ::appesModeEncoding = appesModeEncoding; +} + void registerInteraction(int argc, char *argv[]) { __testlib_ensuresPreconditions(); + __testlib_set_testset_and_group(argc, argv); + TestlibFinalizeGuard::registered = true; testlibMode = _interactor; __testlib_set_binary(stdin); @@ -4135,9 +4721,13 @@ void registerInteraction(int argc, char *argv[]) { void registerValidation() { __testlib_ensuresPreconditions(); + TestlibFinalizeGuard::registered = true; testlibMode = _validator; + __testlib_set_binary(stdin); + __testlib_set_binary(stdout); + __testlib_set_binary(stderr); inf.init(stdin, _input); inf.strict = true; @@ -4145,29 +4735,60 @@ void registerValidation() { void registerValidation(int argc, char *argv[]) { registerValidation(); + __testlib_set_testset_and_group(argc, argv); + validator.initialize(); + TestlibFinalizeGuard::registered = true; + + std::string comment = "Validator must be run with the following arguments:" + " [--testset testset]" + " [--group group]" + " [--testOverviewLogFileName fileName]" + " [--testMarkupFileName fileName]" + " [--testCase testCase]" + " [--testCaseFileName fileName]" + ; for (int i = 1; i < argc; i++) { if (!strcmp("--testset", argv[i])) { if (i + 1 < argc && strlen(argv[i + 1]) > 0) validator.setTestset(argv[++i]); else - quit(_fail, std::string("Validator must be run with the following arguments: ") + - "[--testset testset] [--group group] [--testOverviewLogFileName fileName]"); + quit(_fail, comment); } if (!strcmp("--group", argv[i])) { if (i + 1 < argc) validator.setGroup(argv[++i]); else - quit(_fail, std::string("Validator must be run with the following arguments: ") + - "[--testset testset] [--group group] [--testOverviewLogFileName fileName]"); + quit(_fail, comment); } if (!strcmp("--testOverviewLogFileName", argv[i])) { if (i + 1 < argc) validator.setTestOverviewLogFileName(argv[++i]); else - quit(_fail, std::string("Validator must be run with the following arguments: ") + - "[--testset testset] [--group group] [--testOverviewLogFileName fileName]"); + quit(_fail, comment); + } + if (!strcmp("--testMarkupFileName", argv[i])) { + if (i + 1 < argc) + validator.setTestMarkupFileName(argv[++i]); + else + quit(_fail, comment); + } + if (!strcmp("--testCase", argv[i])) { + if (i + 1 < argc) { + long long testCase = stringToLongLong(inf, argv[++i]); + if (testCase < 1 || testCase >= __TESTLIB_MAX_TEST_CASE) + quit(_fail, testlib_format_("Argument testCase should be between 1 and %d, but ", __TESTLIB_MAX_TEST_CASE) + + toString(testCase) + " found"); + validator.setTestCase(int(testCase)); + } else + quit(_fail, comment); + } + if (!strcmp("--testCaseFileName", argv[i])) { + if (i + 1 < argc) { + validator.setTestCaseFileName(argv[++i]); + } else + quit(_fail, comment); } } } @@ -4184,18 +4805,74 @@ void feature(const std::string &feature) { validator.feature(feature); } +class Checker { +private: + bool _initialized; + std::string _testset; + std::string _group; + +public: + Checker() : _initialized(false), _testset("tests"), _group() { + } + + void initialize() { + _initialized = true; + } + + std::string testset() const { + if (!_initialized) + __testlib_fail("Checker should be initialized with registerTestlibCmd(argc, argv) instead of registerTestlibCmd() to support checker.testset()"); + return _testset; + } + + std::string group() const { + if (!_initialized) + __testlib_fail("Checker should be initialized with registerTestlibCmd(argc, argv) instead of registerTestlibCmd() to support checker.group()"); + return _group; + } + + void setTestset(const char *const testset) { + _testset = testset; + } + + void setGroup(const char *const group) { + _group = group; + } +} checker; + void registerTestlibCmd(int argc, char *argv[]) { __testlib_ensuresPreconditions(); + __testlib_set_testset_and_group(argc, argv); + TestlibFinalizeGuard::registered = true; testlibMode = _checker; __testlib_set_binary(stdin); - if (argc > 1 && !strcmp("--help", argv[1])) + std::vector args(1, argv[0]); + checker.initialize(); + + for (int i = 1; i < argc; i++) { + if (!strcmp("--testset", argv[i])) { + if (i + 1 < argc && strlen(argv[i + 1]) > 0) + checker.setTestset(argv[++i]); + else + quit(_fail, std::string("Expected testset after --testset command line parameter")); + } else if (!strcmp("--group", argv[i])) { + if (i + 1 < argc) + checker.setGroup(argv[++i]); + else + quit(_fail, std::string("Expected group after --group command line parameter")); + } else + args.push_back(argv[i]); + } + + argc = int(args.size()); + if (argc > 1 && "--help" == args[1]) __testlib_help(); if (argc < 4 || argc > 6) { quit(_fail, std::string("Program must be run with the following arguments: ") + - std::string(" [ [<-appes>]]") + + std::string("[--testset testset] [--group group] [ [<-appes>]]") + "\nUse \"--help\" to get help information"); } @@ -4204,24 +4881,27 @@ void registerTestlibCmd(int argc, char *argv[]) { appesMode = false; } +#ifndef EJUDGE if (argc == 5) { - resultName = argv[4]; + resultName = args[4]; appesMode = false; } if (argc == 6) { - if (strcmp("-APPES", argv[5]) && strcmp("-appes", argv[5])) { + if ("-APPES" != args[5] && "-appes" != args[5]) { quit(_fail, std::string("Program must be run with the following arguments: ") + " [ [<-appes>]]"); } else { - resultName = argv[4]; + resultName = args[4]; appesMode = true; } } +#endif - inf.init(argv[1], _input); - ouf.init(argv[2], _output); - ans.init(argv[3], _answer); + inf.init(args[1], _input); + ouf.init(args[2], _output); + ouf.skipBom(); + ans.init(args[3], _answer); } void registerTestlib(int argc, ...) { @@ -4256,10 +4936,10 @@ static inline void __testlib_ensure(bool cond, const char *msg) { quit(_fail, msg); } -#define ensure(cond) __testlib_ensure(cond, "Condition failed: \"" #cond "\"") -#define STRINGIZE_DETAIL(x) #x -#define STRINGIZE(x) STRINGIZE_DETAIL(x) -#define ensure_ext(cond) __testlib_ensure(cond, "Line " STRINGIZE(__LINE__) ": Condition failed: \"" #cond "\"") +#define ensure(cond) __testlib_ensure((cond), "Condition failed: \"" #cond "\"") +#define STRINGIZE_DETAIL(x) (#x) +#define STRINGIZE(x) STRINGIZE_DETAIL((x)) +#define ensure_ext(cond) __testlib_ensure((cond), "Line " STRINGIZE(__LINE__) ": Condition failed: \"" #cond "\"") #ifdef __GNUC__ __attribute__ ((format (printf, 2, 3))) @@ -4283,7 +4963,7 @@ void setName(const char *format, ...) { checkerName = name; } -/* +/* * Do not use random_shuffle, because it will produce different result * for different C++ compilers. * @@ -4347,24 +5027,10 @@ void srand(unsigned int seed) RAND_THROW_STATEMENT void startTest(int test) { const std::string testFileName = vtos(test); - if (NULL == freopen(testFileName.c_str(), "wt", stdout)) + if (NULL == testlib_freopen_(testFileName.c_str(), "wt", stdout)) __testlib_fail("Unable to write file '" + testFileName + "'"); } -inline std::string upperCase(std::string s) { - for (size_t i = 0; i < s.length(); i++) - if ('a' <= s[i] && s[i] <= 'z') - s[i] = char(s[i] - 'a' + 'A'); - return s; -} - -inline std::string lowerCase(std::string s) { - for (size_t i = 0; i < s.length(); i++) - if ('A' <= s[i] && s[i] <= 'Z') - s[i] = char(s[i] - 'A' + 'a'); - return s; -} - inline std::string compress(const std::string &s) { return __testlib_part(s); } @@ -4413,7 +5079,7 @@ std::string join(const _Collection &collection) { /** * Splits string s by character separator returning exactly k+1 items, - * where k is the number of separator occurences. + * where k is the number of separator occurrences. */ std::vector split(const std::string &s, char separator) { std::vector result; @@ -4430,7 +5096,7 @@ std::vector split(const std::string &s, char separator) { /** * Splits string s by character separators returning exactly k+1 items, - * where k is the number of separator occurences. + * where k is the number of separator occurrences. */ std::vector split(const std::string &s, const std::string &separators) { if (separators.empty()) @@ -4500,17 +5166,17 @@ std::vector tokenize(const std::string &s, const std::string &separ NORETURN void __testlib_expectedButFound(TResult result, std::string expected, std::string found, const char *prepend) { std::string message; if (strlen(prepend) != 0) - message = format("%s: expected '%s', but found '%s'", + message = testlib_format_("%s: expected '%s', but found '%s'", compress(prepend).c_str(), compress(expected).c_str(), compress(found).c_str()); else - message = format("expected '%s', but found '%s'", + message = testlib_format_("expected '%s', but found '%s'", compress(expected).c_str(), compress(found).c_str()); quit(result, message); } NORETURN void __testlib_expectedButFound(TResult result, double expected, double found, const char *prepend) { - std::string expectedString = removeDoubleTrailingZeroes(format("%.12f", expected)); - std::string foundString = removeDoubleTrailingZeroes(format("%.12f", found)); + std::string expectedString = removeDoubleTrailingZeroes(testlib_format_("%.12f", expected)); + std::string foundString = removeDoubleTrailingZeroes(testlib_format_("%.12f", found)); __testlib_expectedButFound(result, expectedString, foundString, prepend); } @@ -4541,8 +5207,8 @@ __attribute__ ((format (printf, 4, 5))) #endif NORETURN void expectedButFound(TResult result, double expected, double found, const char *prependFormat, ...) { FMT_TO_RESULT(prependFormat, prependFormat, prepend); - std::string expectedString = removeDoubleTrailingZeroes(format("%.12f", expected)); - std::string foundString = removeDoubleTrailingZeroes(format("%.12f", found)); + std::string expectedString = removeDoubleTrailingZeroes(testlib_format_("%.12f", expected)); + std::string foundString = removeDoubleTrailingZeroes(testlib_format_("%.12f", found)); __testlib_expectedButFound(result, expectedString, foundString, prepend.c_str()); } @@ -4758,7 +5424,32 @@ void println(const A &a, const B &b, const C &c, const D &d, const E &e, const F } /* opts */ -size_t getOptType(char* s) { + +/** + * A struct for a singular testlib opt, containing the raw string value, + * and a boolean value for marking whether the opt is used. + */ +struct TestlibOpt { + std::string value; + bool used; + + TestlibOpt() : value(), used(false) {} +}; + +/** + * Get the type of opt based on the number of `-` at the beginning and the + * _validity_ of the key name. + * + * A valid key name must start with an alphabetical character. + * + * Returns: 1 if s has one `-` at the beginning, that is, "-keyName". + * 2 if s has two `-` at the beginning, that is, "--keyName". + * 0 otherwise. That is, if s has no `-` at the beginning, or has more + * than 2 at the beginning ("---keyName", "----keyName", ...), or the + * keyName is invalid (the first character is not an alphabetical + * character). + */ +size_t getOptType(char *s) { if (!s || strlen(s) <= 1) return 0; @@ -4772,7 +5463,36 @@ size_t getOptType(char* s) { return 0; } -size_t parseOpt(size_t argc, char* argv[], size_t index, std::map& opts) { +/** + * Parse the opt at a given index, and put it into the opts maps. + * + * An opt can has the following form: + * 1) -keyName=value or --keyName=value (ex. -n=10 --test-count=20) + * 2) -keyName value or --keyName value (ex. -n 10 --test-count 20) + * 3) -kNumval or --kNumval (ex. -n10 --t20) + * 4) -boolProperty or --boolProperty (ex. -sorted --tree-only) + * + * Only the second form consumes 2 arguments. The other consumes only 1 + * argument. + * + * In the third form, the key is a single character, and after the key is the + * value. The value _should_ be a number. + * + * In the forth form, the value is true. + * + * Params: + * - argc and argv: the number of command line arguments and the command line + * arguments themselves. + * - index: the starting index of the opts. + * - opts: the map containing the resulting opt. + * + * Returns: the number of consumed arguments to parse the opt. + * 0 if there is no arguments to parse. + * + * Algorithm details: + * TODO. Please refer to the implementation to see how the code handles the 3rd and 4th forms separately. + */ +size_t parseOpt(size_t argc, char *argv[], size_t index, std::map &opts) { if (index >= argc) return 0; @@ -4796,7 +5516,7 @@ size_t parseOpt(size_t argc, char* argv[], size_t index, std::map __testlib_argv; -std::map __testlib_opts; -void prepareOpts(int argc, char* argv[]) { +/** + * Global dictionary containing all the parsed opts. + */ +std::map __testlib_opts; + +/** + * Whether automatic no unused opts ensurement should be done. This flag will + * be turned on when `has_opt` or `opt(key, default_value)` is called. + * + * The automatic ensurement can be suppressed when + * __testlib_ensureNoUnusedOptsSuppressed is true. + */ +bool __testlib_ensureNoUnusedOptsFlag = false; + +/** + * Suppress no unused opts automatic ensurement. Can be set to true with + * `suppressEnsureNoUnusedOpts()`. + */ +bool __testlib_ensureNoUnusedOptsSuppressed = false; + +/** + * Parse command line arguments into opts. + * The results are stored into __testlib_argv and __testlib_opts. + */ +void prepareOpts(int argc, char *argv[]) { if (argc <= 0) __testlib_fail("Opts: expected argc>=0 but found " + toString(argc)); size_t n = static_cast(argc); // NOLINT(hicpp-use-auto,modernize-use-auto) - __testlib_opts = std::map(); + __testlib_opts = std::map(); for (size_t index = 1; index < n; index += parseOpt(n, argv, index, __testlib_opts)); __testlib_argv = std::vector(n); for (size_t index = 0; index < n; index++) __testlib_argv[index] = argv[index]; } +/** + * An utility function to get the argument with a given index. This function + * also print a readable message when no arguments are found. + */ std::string __testlib_indexToArgv(int index) { if (index < 0 || index >= int(__testlib_argv.size())) - __testlib_fail("Opts: index '" + toString(index) + "' is out of range [0," + toString(__testlib_argv.size()) + ")"); + __testlib_fail("Opts: index '" + toString(index) + "' is out of range [0," + + toString(__testlib_argv.size()) + ")"); return __testlib_argv[size_t(index)]; } -std::string __testlib_keyToOpts(const std::string& key) { - if (__testlib_opts.count(key) == 0) +/** + * An utility function to get the opt with a given key . This function + * also print a readable message when no opts are found. + */ +std::string __testlib_keyToOpts(const std::string &key) { + auto it = __testlib_opts.find(key); + if (it == __testlib_opts.end()) __testlib_fail("Opts: unknown key '" + compress(key) + "'"); - return __testlib_opts[key]; + it->second.used = true; + return it->second.value; } template -T optValueToIntegral(const std::string& s, bool nonnegative); +T optValueToIntegral(const std::string &s, bool nonnegative); -long double optValueToLongDouble(const std::string& s); +long double optValueToLongDouble(const std::string &s); -std::string parseExponentialOptValue(const std::string& s) { +std::string parseExponentialOptValue(const std::string &s) { size_t pos = std::string::npos; for (size_t i = 0; i < s.length(); i++) if (s[i] == 'e' || s[i] == 'E') { @@ -4898,7 +5655,7 @@ std::string parseExponentialOptValue(const std::string& s) { } template -T optValueToIntegral(const std::string& s_, bool nonnegative) { +T optValueToIntegral(const std::string &s_, bool nonnegative) { std::string s(parseExponentialOptValue(s_)); if (s.empty()) __testlib_fail("Opts: expected integer but '" + compress(s_) + "' found"); @@ -4915,7 +5672,7 @@ T optValueToIntegral(const std::string& s_, bool nonnegative) { for (size_t i = pos; i < s.length(); i++) { if (s[i] < '0' || s[i] > '9') __testlib_fail("Opts: expected integer but '" + compress(s_) + "' found"); - value = value * 10 + s[i] - '0'; + value = T(value * 10 + s[i] - '0'); about = about * 10 + s[i] - '0'; } value *= sign; @@ -4925,7 +5682,7 @@ T optValueToIntegral(const std::string& s_, bool nonnegative) { return value; } -long double optValueToLongDouble(const std::string& s_) { +long double optValueToLongDouble(const std::string &s_) { std::string s(parseExponentialOptValue(s_)); if (s.empty()) __testlib_fail("Opts: expected float number but '" + compress(s_) + "' found"); @@ -4960,87 +5717,166 @@ long double optValueToLongDouble(const std::string& s_) { return value; } -bool has_opt(const std::string key) { +/** + * Return true if there is an opt with a given key. + * + * By calling this function, automatic ensurement for no unused opts will be + * done when the program is finalized. Call suppressEnsureNoUnusedOpts() to + * turn it off. + */ +bool has_opt(const std::string &key) { + __testlib_ensureNoUnusedOptsFlag = true; return __testlib_opts.count(key) != 0; } +/* About the following part for opt with 2 and 3 arguments. + * + * To parse the argv/opts correctly for a give type (integer, floating point or + * string), some meta programming must be done to determine the type of + * the type, and use the correct parsing function accordingly. + * + * The pseudo algorithm for determining the type of T and parse it accordingly + * is as follows: + * + * if (T is integral type) { + * if (T is unsigned) { + * parse the argv/opt as an **unsigned integer** of type T. + * } else { + * parse the argv/opt as an **signed integer** of type T. + * } else { + * if (T is floating point type) { + * parse the argv/opt as an **floating point** of type T. + * } else { + * // T should be std::string + * just the raw content of the argv/opts. + * } + * } + * + * To help with meta programming, some `opt` function with 2 or 3 arguments are + * defined. + * + * Opt with 3 arguments: T opt(true/false is_integral, true/false is_unsigned, index/key) + * + * + The first argument is for determining whether the type T is an integral + * type. That is, the result of std::is_integral() should be passed to + * this argument. When false, the type _should_ be either floating point or a + * std::string. + * + * + The second argument is for determining whether the signedness of the type + * T (if it is unsigned or signed). That is, the result of + * std::is_unsigned() should be passed to this argument. This argument can + * be ignored if the first one is false, because it only applies to integer. + * + * Opt with 2 arguments: T opt(true/false is_floating_point, index/key) + * + The first argument is for determining whether the type T is a floating + * point type. That is, the result of std::is_floating_point() should be + * passed to this argument. When false, the type _should_ be a std::string. + */ + template -T opt(std::false_type, int index); +T opt(std::false_type is_floating_point, int index); template<> -std::string opt(std::false_type, int index) { +std::string opt(std::false_type /*is_floating_point*/, int index) { return __testlib_indexToArgv(index); } template -T opt(std::true_type, int index) { +T opt(std::true_type /*is_floating_point*/, int index) { return T(optValueToLongDouble(__testlib_indexToArgv(index))); } template -T opt(std::false_type, U, int index) { +T opt(std::false_type /*is_integral*/, U /*is_unsigned*/, int index) { return opt(std::is_floating_point(), index); } template -T opt(std::true_type, std::false_type, int index) { +T opt(std::true_type /*is_integral*/, std::false_type /*is_unsigned*/, int index) { return optValueToIntegral(__testlib_indexToArgv(index), false); } template -T opt(std::true_type, std::true_type, int index) { +T opt(std::true_type /*is_integral*/, std::true_type /*is_unsigned*/, int index) { return optValueToIntegral(__testlib_indexToArgv(index), true); } template<> -bool opt(std::true_type, std::true_type, int index) { +bool opt(std::true_type /*is_integral*/, std::true_type /*is_unsigned*/, int index) { std::string value = __testlib_indexToArgv(index); if (value == "true" || value == "1") return true; if (value == "false" || value == "0") return false; - __testlib_fail("Opts: opt by index '" + toString(index) + "': expected bool true/false or 0/1 but '" + compress(value) + "' found"); + __testlib_fail("Opts: opt by index '" + toString(index) + "': expected bool true/false or 0/1 but '" + + compress(value) + "' found"); } +/** + * Return the parsed argv by a given index. + */ template T opt(int index) { return opt(std::is_integral(), std::is_unsigned(), index); } +/** + * Return the raw string value of an argv by a given index. + */ std::string opt(int index) { return opt(index); } +/** + * Return the parsed argv by a given index. If the index is bigger than + * the number of argv, return the given default_value. + */ template -T opt(std::false_type, const std::string& key); +T opt(int index, const T &default_value) { + if (index >= int(__testlib_argv.size())) { + return default_value; + } + return opt(index); +} + +/** + * Return the raw string value of an argv by a given index. If the index is + * bigger than the number of argv, return the given default_value. + */ +std::string opt(int index, const std::string &default_value) { + return opt(index, default_value); +} + +template +T opt(std::false_type is_floating_point, const std::string &key); template<> -std::string opt(std::false_type, const std::string& key) { +std::string opt(std::false_type /*is_floating_point*/, const std::string &key) { return __testlib_keyToOpts(key); } template -T opt(std::true_type, const std::string& key) { +T opt(std::true_type /*is_integral*/, const std::string &key) { return T(optValueToLongDouble(__testlib_keyToOpts(key))); } template -T opt(std::false_type, U, const std::string& key) { +T opt(std::false_type /*is_integral*/, U, const std::string &key) { return opt(std::is_floating_point(), key); } template -T opt(std::true_type, std::false_type, const std::string& key) { +T opt(std::true_type /*is_integral*/, std::false_type /*is_unsigned*/, const std::string &key) { return optValueToIntegral(__testlib_keyToOpts(key), false); } template -T opt(std::true_type, std::true_type, const std::string& key) { +T opt(std::true_type /*is_integral*/, std::true_type /*is_unsigned*/, const std::string &key) { return optValueToIntegral(__testlib_keyToOpts(key), true); } template<> -bool opt(std::true_type, std::true_type, const std::string& key) { +bool opt(std::true_type /*is_integral*/, std::true_type /*is_unsigned*/, const std::string &key) { if (!has_opt(key)) return false; std::string value = __testlib_keyToOpts(key); @@ -5048,16 +5884,369 @@ bool opt(std::true_type, std::true_type, const std::string& key) { return true; if (value == "false" || value == "0") return false; - __testlib_fail("Opts: key '" + compress(key) + "': expected bool true/false or 0/1 but '" + compress(value) + "' found"); + __testlib_fail("Opts: key '" + compress(key) + "': expected bool true/false or 0/1 but '" + + compress(value) + "' found"); } +/** + * Return the parsed opt by a given key. + */ template -T opt(const std::string key) { +T opt(const std::string &key) { return opt(std::is_integral(), std::is_unsigned(), key); } -std::string opt(const std::string key) { +/** + * Return the raw string value of an opt by a given key + */ +std::string opt(const std::string &key) { return opt(key); } + +/* Scorer started. */ + +enum TestResultVerdict { + SKIPPED, + OK, + WRONG_ANSWER, + RUNTIME_ERROR, + TIME_LIMIT_EXCEEDED, + IDLENESS_LIMIT_EXCEEDED, + MEMORY_LIMIT_EXCEEDED, + COMPILATION_ERROR, + CRASHED, + FAILED +}; + +std::string serializeVerdict(TestResultVerdict verdict) { + switch (verdict) { + case SKIPPED: return "SKIPPED"; + case OK: return "OK"; + case WRONG_ANSWER: return "WRONG_ANSWER"; + case RUNTIME_ERROR: return "RUNTIME_ERROR"; + case TIME_LIMIT_EXCEEDED: return "TIME_LIMIT_EXCEEDED"; + case IDLENESS_LIMIT_EXCEEDED: return "IDLENESS_LIMIT_EXCEEDED"; + case MEMORY_LIMIT_EXCEEDED: return "MEMORY_LIMIT_EXCEEDED"; + case COMPILATION_ERROR: return "COMPILATION_ERROR"; + case CRASHED: return "CRASHED"; + case FAILED: return "FAILED"; + } + throw "Unexpected verdict"; +} + +TestResultVerdict deserializeTestResultVerdict(std::string s) { + if (s == "SKIPPED") + return SKIPPED; + else if (s == "OK") + return OK; + else if (s == "WRONG_ANSWER") + return WRONG_ANSWER; + else if (s == "RUNTIME_ERROR") + return RUNTIME_ERROR; + else if (s == "TIME_LIMIT_EXCEEDED") + return TIME_LIMIT_EXCEEDED; + else if (s == "IDLENESS_LIMIT_EXCEEDED") + return IDLENESS_LIMIT_EXCEEDED; + else if (s == "MEMORY_LIMIT_EXCEEDED") + return MEMORY_LIMIT_EXCEEDED; + else if (s == "COMPILATION_ERROR") + return COMPILATION_ERROR; + else if (s == "CRASHED") + return CRASHED; + else if (s == "FAILED") + return FAILED; + ensuref(false, "Unexpected serialized TestResultVerdict"); + // No return actually. + return FAILED; +} + +struct TestResult { + int testIndex; + std::string testset; + std::string group; + TestResultVerdict verdict; + double points; + long long timeConsumed; + long long memoryConsumed; + std::string input; + std::string output; + std::string answer; + int exitCode; + std::string checkerComment; +}; + +std::string serializePoints(double points) { + if (std::isnan(points)) + return ""; + else { + char c[64]; + snprintf(c, 64, "%.03lf", points); + return c; + } +} + +double deserializePoints(std::string s) { + if (s.empty()) + return std::numeric_limits::quiet_NaN(); + else { + double result; +#ifdef _MSC_VER + ensuref(sscanf_s(s.c_str(), "%lf", &result) == 1, "Invalid serialized points"); +#else + ensuref(std::sscanf(s.c_str(), "%lf", &result) == 1, "Invalid serialized points"); #endif + return result; + } +} + +std::string escapeTestResultString(std::string s) { + std::string result; + for (size_t i = 0; i < s.length(); i++) { + if (s[i] == '\r') + continue; + if (s[i] == '\n') { + result += "\\n"; + continue; + } + if (s[i] == '\\' || s[i] == ';') + result += '\\'; + result += s[i]; + } + return result; +} + +std::string unescapeTestResultString(std::string s) { + std::string result; + for (size_t i = 0; i < s.length(); i++) { + if (s[i] == '\\' && i + 1 < s.length()) { + if (s[i + 1] == 'n') { + result += '\n'; + i++; + continue; + } else if (s[i + 1] == ';' || s[i + 1] == '\\') { + result += s[i + 1]; + i++; + continue; + } + } + result += s[i]; + } + return result; +} + +std::string serializeTestResult(TestResult tr) { + std::string result; + result += std::to_string(tr.testIndex); + result += ";"; + result += escapeTestResultString(tr.testset); + result += ";"; + result += escapeTestResultString(tr.group); + result += ";"; + result += serializeVerdict(tr.verdict); + result += ";"; + result += serializePoints(tr.points); + result += ";"; + result += std::to_string(tr.timeConsumed); + result += ";"; + result += std::to_string(tr.memoryConsumed); + result += ";"; + result += escapeTestResultString(tr.input); + result += ";"; + result += escapeTestResultString(tr.output); + result += ";"; + result += escapeTestResultString(tr.answer); + result += ";"; + result += std::to_string(tr.exitCode); + result += ";"; + result += escapeTestResultString(tr.checkerComment); + return result; +} + +TestResult deserializeTestResult(std::string s) { + std::vector items; + std::string t; + for (size_t i = 0; i < s.length(); i++) { + if (s[i] == '\\') { + t += s[i]; + if (i + 1 < s.length()) + t += s[i + 1]; + i++; + continue; + } else { + if (s[i] == ';') { + items.push_back(t); + t = ""; + } else + t += s[i]; + } + } + items.push_back(t); + + ensuref(items.size() == 12, "Invalid TestResult serialization: expected exactly 12 items"); + + TestResult tr; + size_t pos = 0; + tr.testIndex = stoi(items[pos++]); + tr.testset = unescapeTestResultString(items[pos++]); + tr.group = unescapeTestResultString(items[pos++]); + tr.verdict = deserializeTestResultVerdict(items[pos++]); + tr.points = deserializePoints(items[pos++]); + tr.timeConsumed = stoll(items[pos++]); + tr.memoryConsumed = stoll(items[pos++]); + tr.input = unescapeTestResultString(items[pos++]); + tr.output = unescapeTestResultString(items[pos++]); + tr.answer = unescapeTestResultString(items[pos++]); + tr.exitCode = stoi(items[pos++]); + tr.checkerComment = unescapeTestResultString(items[pos++]); + + return tr; +} + +std::vector readTestResults(std::string fileName) { + std::ifstream stream; + stream.open(fileName.c_str(), std::ios::in); + ensuref(stream.is_open(), "Can't read test results file '%s'", fileName.c_str()); + std::vector result; + std::string line; + while (getline(stream, line)) + if (!line.empty()) + result.push_back(deserializeTestResult(line)); + stream.close(); + return result; +} + +std::function)> __testlib_scorer; + +struct TestlibScorerGuard { + ~TestlibScorerGuard() { + if (testlibMode == _scorer) { + std::vector testResults; + while (!inf.eof()) { + std::string line = inf.readLine(); + if (!line.empty()) + testResults.push_back(deserializeTestResult(line)); + } + inf.readEof(); + printf("%.3f\n", __testlib_scorer(testResults)); + } + } +} __testlib_scorer_guard; + +void registerScorer(int argc, char *argv[], std::function)> scorer) { + /* Suppress unused. */ + (void)(argc), (void)(argv); + + __testlib_ensuresPreconditions(); + + testlibMode = _scorer; + __testlib_set_binary(stdin); + + inf.init(stdin, _input); + inf.strict = false; + + __testlib_scorer = scorer; +} + +/* Scorer ended. */ + +/** + * Return the parsed opt by a given key. If no opts with the given key are + * found, return the given default_value. + * + * By calling this function, automatic ensurement for no unused opts will be + * done when the program is finalized. Call suppressEnsureNoUnusedOpts() to + * turn it off. + */ +template +T opt(const std::string &key, const T &default_value) { + if (!has_opt(key)) { + return default_value; + } + return opt(key); +} + +/** + * Return the raw string value of an opt by a given key. If no opts with the + * given key are found, return the given default_value. + * + * By calling this function, automatic ensurement for no unused opts will be + * done when the program is finalized. Call suppressEnsureNoUnusedOpts() to + * turn it off. + */ +std::string opt(const std::string &key, const std::string &default_value) { + return opt(key, default_value); +} + +/** + * Check if all opts are used. If not, __testlib_fail is called. + * Should be used after calling all opt() function calls. + * + * This function is useful when opt() with default_value for checking typos + * in the opt's key. + */ +void ensureNoUnusedOpts() { + for (const auto &opt: __testlib_opts) { + if (!opt.second.used) { + __testlib_fail(testlib_format_("Opts: unused key '%s'", compress(opt.first).c_str())); + } + } +} + +void suppressEnsureNoUnusedOpts() { + __testlib_ensureNoUnusedOptsSuppressed = true; +} + +void TestlibFinalizeGuard::autoEnsureNoUnusedOpts() { + if (__testlib_ensureNoUnusedOptsFlag && !__testlib_ensureNoUnusedOptsSuppressed) { + ensureNoUnusedOpts(); + } +} + +TestlibFinalizeGuard testlibFinalizeGuard; +#endif + +#ifdef __GNUC__ +__attribute__ ((format (printf, 1, 2))) +#endif +std::string testlib_format_(const char *fmt, ...) { + FMT_TO_RESULT(fmt, fmt, result); + return result; +} + +std::string testlib_format_(const std::string fmt, ...) { + FMT_TO_RESULT(fmt, fmt.c_str(), result); + return result; +} + +#if (__cplusplus >= 202002L && __has_include()) || __cpp_lib_format +template +std::string format(const char* fmt, Args&&... args) { + size_t size = size_t(std::snprintf(nullptr, 0, fmt, args...) + 1); + std::vector buffer(size); + std::snprintf(buffer.data(), size, fmt, args...); + return std::string(buffer.data()); +} + +template +std::string format(const std::string fmt, Args&&... args) { + size_t size = size_t(std::snprintf(nullptr, 0, fmt.c_str(), args...) + 1); + std::vector buffer(size); + std::snprintf(buffer.data(), size, fmt.c_str(), args...); + return std::string(buffer.data()); +} +#else +#ifdef __GNUC__ +__attribute__ ((format (printf, 1, 2))) +#endif +std::string format(const char *fmt, ...) { + FMT_TO_RESULT(fmt, fmt, result); + return result; +} + +std::string format(const std::string fmt, ...) { + FMT_TO_RESULT(fmt, fmt.c_str(), result); + return result; +} +#endif + #endif diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 00000000..ff0c4460 --- /dev/null +++ b/tests/README.md @@ -0,0 +1,33 @@ +# Tests + +Some features of the library are covered by tests. If you understand well how this or that functionality of the library works, then you can add a test for it. + +First of all, consider adding a test to `test-004_use-test.h` (carefully study the design of this test). + +Note the use of `test-ref` script in the tests, which checks that a process has exited with the expected exit code, standard output, and standard error. + +It is highly desirable to cover all new functionality with tests. If the functionality is such that it is not very difficult to write tests, then the presence of tests is required. + +## CI + +On each push and pull requests tests will run. Please make sure that your changes didn't break them. + +## How run tests locally + +Use `tests\run.sh`. Also you can use `t.sh` (or `t.bat`) to run shortcut of `run.sh g++ 11 v0 $*`. + +### Parameters (use can use all combinations): + +* `g++`, `clang++`, `msvc` - to specify compiler(s) +* `11`, `14`, `17`, `20`, `23` - to specify standard(s) +* `vxx` (example `v10`) - to try `-10` suffix to run compilers, like `g++-10`, use `v0` to run without any suffixes +* `test-` - to specify test(s) + +### Examples: + +* `bash run.sh` - to run all tests on all compilers on multiple standards +* `bash run.sh g++` - to run all tests on `g++` on multiple standards +* `bash run.sh g++ 11` - to run all tests on `g++` with `--std=c++11` +* `bash run.sh g++ 11 test-001_run-sval` - to run `test-001_run-sval` on `g++` with `--std=c++11` +* `bash run.sh test-001_run-sval` - to run `test-001_run-sval` on all compilers on multiple standards +* `bash run.sh g++ 11 17` - to run all tests on `g++` with `--std=c++11` and with `--std=c++17` diff --git a/tests/docker/clang-11/Dockerfile b/tests/docker/clang-11/Dockerfile new file mode 100644 index 00000000..04b5ba5d --- /dev/null +++ b/tests/docker/clang-11/Dockerfile @@ -0,0 +1,7 @@ +FROM silkeh/clang:11 +RUN apt-get update +RUN apt-get install -y git default-jre +COPY startup.sh / +WORKDIR / +RUN chmod +x /startup.sh +CMD ["/bin/bash", "/startup.sh"] diff --git a/tests/docker/clang-11/build.bat b/tests/docker/clang-11/build.bat new file mode 100644 index 00000000..77d2722d --- /dev/null +++ b/tests/docker/clang-11/build.bat @@ -0,0 +1,4 @@ +"C:\Program Files\Docker\Docker"\DockerCli.exe -SwitchLinuxEngine + +docker build . -t test-testlib-clang-11 + diff --git a/tests/docker/clang-11/run.bat b/tests/docker/clang-11/run.bat new file mode 100644 index 00000000..988e97a0 --- /dev/null +++ b/tests/docker/clang-11/run.bat @@ -0,0 +1,7 @@ +@echo off + +SET IMAGE_NAME=test-testlib-clang-11 +for /f "tokens=*" %%i in ('git rev-parse --abbrev-ref HEAD') do set CURRENT_BRANCH=%%i + +"C:\Program Files\Docker\Docker"\DockerCli.exe -SwitchLinuxEngine +docker run --rm -it %IMAGE_NAME% /bin/bash /startup.sh %CURRENT_BRANCH% diff --git a/tests/docker/clang-11/startup.sh b/tests/docker/clang-11/startup.sh new file mode 100644 index 00000000..db2f1e72 --- /dev/null +++ b/tests/docker/clang-11/startup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +set -e -o pipefail + +CPP_STANDARD=14 + +BRANCH=${1:-dev-mikemirzayanov} +echo "Use branch ""$BRANCH""" + +git clone https://github.com/MikeMirzayanov/testlib.git +cd testlib +git checkout "$BRANCH" +cd tests +./run.sh clang++ v0 "$CPP_STANDARD" +cd / +rm -rf testlib diff --git a/tests/docker/clang-3.5/Dockerfile b/tests/docker/clang-3.5/Dockerfile new file mode 100644 index 00000000..f00b409e --- /dev/null +++ b/tests/docker/clang-3.5/Dockerfile @@ -0,0 +1,7 @@ +FROM silkeh/clang:3.5 +RUN apt-get update +RUN apt-get install -y git default-jre +COPY startup.sh / +WORKDIR / +RUN chmod +x /startup.sh +CMD ["/bin/bash", "/startup.sh"] diff --git a/tests/docker/clang-3.5/build.bat b/tests/docker/clang-3.5/build.bat new file mode 100644 index 00000000..04ce3502 --- /dev/null +++ b/tests/docker/clang-3.5/build.bat @@ -0,0 +1,4 @@ +"C:\Program Files\Docker\Docker"\DockerCli.exe -SwitchLinuxEngine + +docker build . -t test-testlib-clang-3.5 + diff --git a/tests/docker/clang-3.5/run.bat b/tests/docker/clang-3.5/run.bat new file mode 100644 index 00000000..f753598e --- /dev/null +++ b/tests/docker/clang-3.5/run.bat @@ -0,0 +1,7 @@ +@echo off + +SET IMAGE_NAME=test-testlib-clang-3.5 +for /f "tokens=*" %%i in ('git rev-parse --abbrev-ref HEAD') do set CURRENT_BRANCH=%%i + +"C:\Program Files\Docker\Docker"\DockerCli.exe -SwitchLinuxEngine +docker run --rm -it %IMAGE_NAME% /bin/bash /startup.sh %CURRENT_BRANCH% diff --git a/tests/docker/clang-3.5/startup.sh b/tests/docker/clang-3.5/startup.sh new file mode 100644 index 00000000..060cd4bc --- /dev/null +++ b/tests/docker/clang-3.5/startup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +set -e -o pipefail + +CPP_STANDARD=11 + +BRANCH=${1:-dev-mikemirzayanov} +echo "Use branch ""$BRANCH""" + +git clone https://github.com/MikeMirzayanov/testlib.git +cd testlib +git checkout "$BRANCH" +cd tests +./run.sh clang++ v0 "$CPP_STANDARD" +cd / +rm -rf testlib diff --git a/tests/docker/clang-7/Dockerfile b/tests/docker/clang-7/Dockerfile new file mode 100644 index 00000000..23181651 --- /dev/null +++ b/tests/docker/clang-7/Dockerfile @@ -0,0 +1,7 @@ +FROM silkeh/clang:7 +RUN apt-get update +RUN apt-get install -y git default-jre +COPY startup.sh / +WORKDIR / +RUN chmod +x /startup.sh +CMD ["/bin/bash", "/startup.sh"] diff --git a/tests/docker/clang-7/build.bat b/tests/docker/clang-7/build.bat new file mode 100644 index 00000000..90127877 --- /dev/null +++ b/tests/docker/clang-7/build.bat @@ -0,0 +1,4 @@ +"C:\Program Files\Docker\Docker"\DockerCli.exe -SwitchLinuxEngine + +docker build . -t test-testlib-clang-7 + diff --git a/tests/docker/clang-7/run.bat b/tests/docker/clang-7/run.bat new file mode 100644 index 00000000..3a3f30dc --- /dev/null +++ b/tests/docker/clang-7/run.bat @@ -0,0 +1,7 @@ +@echo off + +SET IMAGE_NAME=test-testlib-clang-7 +for /f "tokens=*" %%i in ('git rev-parse --abbrev-ref HEAD') do set CURRENT_BRANCH=%%i + +"C:\Program Files\Docker\Docker"\DockerCli.exe -SwitchLinuxEngine +docker run --rm -it %IMAGE_NAME% /bin/bash /startup.sh %CURRENT_BRANCH% diff --git a/tests/docker/clang-7/startup.sh b/tests/docker/clang-7/startup.sh new file mode 100644 index 00000000..060cd4bc --- /dev/null +++ b/tests/docker/clang-7/startup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +set -e -o pipefail + +CPP_STANDARD=11 + +BRANCH=${1:-dev-mikemirzayanov} +echo "Use branch ""$BRANCH""" + +git clone https://github.com/MikeMirzayanov/testlib.git +cd testlib +git checkout "$BRANCH" +cd tests +./run.sh clang++ v0 "$CPP_STANDARD" +cd / +rm -rf testlib diff --git a/tests/docker/clang-latest/Dockerfile b/tests/docker/clang-latest/Dockerfile new file mode 100644 index 00000000..0633e031 --- /dev/null +++ b/tests/docker/clang-latest/Dockerfile @@ -0,0 +1,7 @@ +FROM silkeh/clang:latest +RUN apt-get update +RUN apt-get install -y git default-jre valgrind +COPY startup.sh / +WORKDIR / +RUN chmod +x /startup.sh +CMD ["/bin/bash", "/startup.sh"] diff --git a/tests/docker/clang-latest/build.bat b/tests/docker/clang-latest/build.bat new file mode 100644 index 00000000..11735b43 --- /dev/null +++ b/tests/docker/clang-latest/build.bat @@ -0,0 +1,4 @@ +"C:\Program Files\Docker\Docker"\DockerCli.exe -SwitchLinuxEngine + +docker build . -t test-testlib-clang-latest + diff --git a/tests/docker/clang-latest/run.bat b/tests/docker/clang-latest/run.bat new file mode 100644 index 00000000..fd485aee --- /dev/null +++ b/tests/docker/clang-latest/run.bat @@ -0,0 +1,7 @@ +@echo off + +SET IMAGE_NAME=test-testlib-clang-latest +for /f "tokens=*" %%i in ('git rev-parse --abbrev-ref HEAD') do set CURRENT_BRANCH=%%i + +"C:\Program Files\Docker\Docker"\DockerCli.exe -SwitchLinuxEngine +docker run --rm -it %IMAGE_NAME% /bin/bash /startup.sh %CURRENT_BRANCH% diff --git a/tests/docker/clang-latest/startup.sh b/tests/docker/clang-latest/startup.sh new file mode 100644 index 00000000..0762cb44 --- /dev/null +++ b/tests/docker/clang-latest/startup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +set -e -o pipefail + +CPP_STANDARD=20 + +BRANCH=${1:-dev-mikemirzayanov} +echo "Use branch ""$BRANCH""" + +git clone https://github.com/MikeMirzayanov/testlib.git +cd testlib +git checkout "$BRANCH" +cd tests +./run.sh clang++ v0 "$CPP_STANDARD" +cd / +rm -rf testlib diff --git a/tests/docker/gcc-7/Dockerfile b/tests/docker/gcc-7/Dockerfile new file mode 100644 index 00000000..a6e2d858 --- /dev/null +++ b/tests/docker/gcc-7/Dockerfile @@ -0,0 +1,7 @@ +FROM gcc:7 +RUN apt-get update +RUN apt-get install -y git default-jre valgrind +COPY startup.sh / +WORKDIR / +RUN chmod +x /startup.sh +CMD ["/bin/bash", "/startup.sh"] diff --git a/tests/docker/gcc-7/build.bat b/tests/docker/gcc-7/build.bat new file mode 100644 index 00000000..947e59ce --- /dev/null +++ b/tests/docker/gcc-7/build.bat @@ -0,0 +1,4 @@ +"C:\Program Files\Docker\Docker"\DockerCli.exe -SwitchLinuxEngine + +docker build . -t test-testlib-gcc-7 + diff --git a/tests/docker/gcc-7/run.bat b/tests/docker/gcc-7/run.bat new file mode 100644 index 00000000..6733c70a --- /dev/null +++ b/tests/docker/gcc-7/run.bat @@ -0,0 +1,7 @@ +@echo off + +SET IMAGE_NAME=test-testlib-gcc-7 +for /f "tokens=*" %%i in ('git rev-parse --abbrev-ref HEAD') do set CURRENT_BRANCH=%%i + +"C:\Program Files\Docker\Docker"\DockerCli.exe -SwitchLinuxEngine +docker run --rm -it %IMAGE_NAME% /bin/bash /startup.sh %CURRENT_BRANCH% diff --git a/tests/docker/gcc-7/startup.sh b/tests/docker/gcc-7/startup.sh new file mode 100644 index 00000000..88c8bf86 --- /dev/null +++ b/tests/docker/gcc-7/startup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +set -e -o pipefail + +CPP_STANDARD=11 + +BRANCH=${1:-dev-mikemirzayanov} +echo "Use branch ""$BRANCH""" + +git clone https://github.com/MikeMirzayanov/testlib.git +cd testlib +git checkout "$BRANCH" +cd tests +./run.sh g++ v0 "$CPP_STANDARD" +cd / +rm -rf testlib diff --git a/tests/docker/gcc-latest/Dockerfile b/tests/docker/gcc-latest/Dockerfile new file mode 100644 index 00000000..9eb83203 --- /dev/null +++ b/tests/docker/gcc-latest/Dockerfile @@ -0,0 +1,7 @@ +FROM gcc:latest +RUN apt-get update +RUN apt-get install -y git default-jre valgrind +COPY startup.sh / +WORKDIR / +RUN chmod +x /startup.sh +CMD ["/bin/bash", "/startup.sh"] diff --git a/tests/docker/gcc-latest/build.bat b/tests/docker/gcc-latest/build.bat new file mode 100644 index 00000000..f5a6ac89 --- /dev/null +++ b/tests/docker/gcc-latest/build.bat @@ -0,0 +1,4 @@ +"C:\Program Files\Docker\Docker"\DockerCli.exe -SwitchLinuxEngine + +docker build . -t test-testlib-gcc-latest + diff --git a/tests/docker/gcc-latest/run.bat b/tests/docker/gcc-latest/run.bat new file mode 100644 index 00000000..b2da6b35 --- /dev/null +++ b/tests/docker/gcc-latest/run.bat @@ -0,0 +1,7 @@ +@echo off + +SET IMAGE_NAME=test-testlib-gcc-latest +for /f "tokens=*" %%i in ('git rev-parse --abbrev-ref HEAD') do set CURRENT_BRANCH=%%i + +"C:\Program Files\Docker\Docker"\DockerCli.exe -SwitchLinuxEngine +docker run --rm -it %IMAGE_NAME% /bin/bash /startup.sh %CURRENT_BRANCH% diff --git a/tests/docker/gcc-latest/startup.sh b/tests/docker/gcc-latest/startup.sh new file mode 100644 index 00000000..ae9107ff --- /dev/null +++ b/tests/docker/gcc-latest/startup.sh @@ -0,0 +1,15 @@ +#!/bin/bash +set -e -o pipefail + +CPP_STANDARD=23 + +BRANCH=${1:-dev-mikemirzayanov} +echo "Use branch ""$BRANCH""" + +git clone https://github.com/MikeMirzayanov/testlib.git +cd testlib +git checkout "$BRANCH" +cd tests +./run.sh g++ v0 "$CPP_STANDARD" +cd / +rm -rf testlib diff --git a/tests/file-runner.py b/tests/file-runner.py new file mode 100644 index 00000000..e768b71e --- /dev/null +++ b/tests/file-runner.py @@ -0,0 +1,9 @@ +import subprocess +import sys + +if len(sys.argv) > 1: + file_path = sys.argv[1] + subprocess.run([file_path]) +else: + print("Use python runner.py ") + sys.exit(1) diff --git a/tests/lib/testlib.h b/tests/lib/testlib.h new file mode 100644 index 00000000..8dab4c3e --- /dev/null +++ b/tests/lib/testlib.h @@ -0,0 +1,5944 @@ +/* + * It is strictly recommended to include "testlib.h" before any other include + * in your code. In this case testlib overrides compiler specific "random()". + * + * If you can't compile your code and compiler outputs something about + * ambiguous call of "random_shuffle", "rand" or "srand" it means that + * you shouldn't use them. Use "shuffle", and "rnd.next()" instead of them + * because these calls produce stable result for any C++ compiler. Read + * sample generator sources for clarification. + * + * Please read the documentation for class "random_t" and use "rnd" instance in + * generators. Probably, these sample calls will be useful for you: + * rnd.next(); rnd.next(100); rnd.next(1, 2); + * rnd.next(3.14); rnd.next("[a-z]{1,100}"). + * + * Also read about wnext() to generate off-center random distribution. + * + * See https://github.com/MikeMirzayanov/testlib/ to get latest version or bug tracker. + */ + +#ifndef _TESTLIB_H_ +#define _TESTLIB_H_ + +/* + * Copyright (c) 2005-2022 + */ + +#define VERSION "0.9.40-SNAPSHOT" + +/* + * Mike Mirzayanov + * + * This material is provided "as is", with absolutely no warranty expressed + * or implied. Any use is at your own risk. + * + * Permission to use or copy this software for any purpose is hereby granted + * without fee, provided the above notices are retained on all copies. + * Permission to modify the code and to distribute modified code is granted, + * provided the above notices are retained, and a notice that the code was + * modified is included with the above copyright notice. + * + */ + +/* NOTE: This file contains testlib library for C++. + * + * Check, using testlib running format: + * check.exe [ [-appes]], + * If result file is specified it will contain results. + * + * Validator, using testlib running format: + * validator.exe < input.txt, + * It will return non-zero exit code and writes message to standard output. + * + * Generator, using testlib running format: + * gen.exe [parameter-1] [parameter-2] [... paramerter-n] + * You can write generated test(s) into standard output or into the file(s). + * + * Interactor, using testlib running format: + * interactor.exe [ [ [-appes]]], + * Reads test from inf (mapped to args[1]), writes result to tout (mapped to argv[2], + * can be judged by checker later), reads program output from ouf (mapped to stdin), + * writes output to program via stdout (use cout, printf, etc). + */ + +const char *latestFeatures[] = { + "Supported '--testMarkupFileName fn' and '--testCase tc/--testCaseFileName fn' for validators", + "Added opt defaults via opt(key/index, default_val); check unused opts when using has_opt or default opt (turn off this check with suppressEnsureNoUnusedOpt()).", + "For checker added --group and --testset command line params (like for validator), use checker.group() or checker.testset() to get values", + "Added quitpi(points_info, message) function to return with _points exit code 7 and given points_info", + "rnd.partition(size, sum[, min_part=1]) returns random (unsorted) partition which is a representation of the given `sum` as a sum of `size` positive integers (or >=min_part if specified)", + "rnd.distinct(size, n) and rnd.distinct(size, from, to)", + "opt(\"some_missing_key\") returns false now", + "has_opt(key)", + "Abort validator on validator.testset()/validator.group() if registered without using command line", + "Print integer range violations in a human readable way like `violates the range [1, 10^9]`", + "Opts supported: use them like n = opt(\"n\"), in a command line you can use an exponential notation", + "Reformatted", + "Use setTestCase(i) or unsetTestCase() to support test cases (you can use it in any type of program: generator, interactor, validator or checker)", + "Fixed issue #87: readStrictDouble accepts \"-0.00\"", + "Fixed issue #83: added InStream::quitif(condition, ...)", + "Fixed issue #79: fixed missed guard against repeated header include", + "Fixed issue #80: fixed UB in case of huge quitf message", + "Fixed issue #84: added readXs(size, indexBase = 1)", + "Fixed stringstream repeated usage issue", + "Fixed compilation in g++ (for std=c++03)", + "Batch of println functions (support collections, iterator ranges)", + "Introduced rnd.perm(size, first = 0) to generate a `first`-indexed permutation", + "Allow any whitespace in readInts-like functions for non-validators", + "Ignore 4+ command line arguments ifdef EJUDGE", + "Speed up of vtos", + "Show line number in validators in case of incorrect format", + "Truncate huge checker/validator/interactor message", + "Fixed issue with readTokenTo of very long tokens, now aborts with _pe/_fail depending of a stream type", + "Introduced InStream::ensure/ensuref checking a condition, returns wa/fail depending of a stream type", + "Fixed compilation in VS 2015+", + "Introduced space-separated read functions: readWords/readTokens, multilines read functions: readStrings/readLines", + "Introduced space-separated read functions: readInts/readIntegers/readLongs/readUnsignedLongs/readDoubles/readReals/readStrictDoubles/readStrictReals", + "Introduced split/tokenize functions to separate string by given char", + "Introduced InStream::readUnsignedLong and InStream::readLong with unsigned long long parameters", + "Supported --testOverviewLogFileName for validator: bounds hits + features", + "Fixed UB (sequence points) in random_t", + "POINTS_EXIT_CODE returned back to 7 (instead of 0)", + "Removed disable buffers for interactive problems, because it works unexpectedly in wine", + "InStream over string: constructor of InStream from base InStream to inherit policies and std::string", + "Added expectedButFound quit function, examples: expectedButFound(_wa, 10, 20), expectedButFound(_fail, ja, pa, \"[n=%d,m=%d]\", n, m)", + "Fixed incorrect interval parsing in patterns", + "Use registerGen(argc, argv, 1) to develop new generator, use registerGen(argc, argv, 0) to compile old generators (originally created for testlib under 0.8.7)", + "Introduced disableFinalizeGuard() to switch off finalization checkings", + "Use join() functions to format a range of items as a single string (separated by spaces or other separators)", + "Use -DENABLE_UNEXPECTED_EOF to enable special exit code (by default, 8) in case of unexpected eof. It is good idea to use it in interactors", + "Use -DUSE_RND_AS_BEFORE_087 to compile in compatibility mode with random behavior of versions before 0.8.7", + "Fixed bug with nan in stringToDouble", + "Fixed issue around overloads for size_t on x64", + "Added attribute 'points' to the XML output in case of result=_points", + "Exit codes can be customized via macros, e.g. -DPE_EXIT_CODE=14", + "Introduced InStream function readWordTo/readTokenTo/readStringTo/readLineTo for faster reading", + "Introduced global functions: format(), englishEnding(), upperCase(), lowerCase(), compress()", + "Manual buffer in InStreams, some IO speed improvements", + "Introduced quitif(bool, const char* pattern, ...) which delegates to quitf() in case of first argument is true", + "Introduced guard against missed quitf() in checker or readEof() in validators", + "Supported readStrictReal/readStrictDouble - to use in validators to check strictly float numbers", + "Supported registerInteraction(argc, argv)", + "Print checker message to the stderr instead of stdout", + "Supported TResult _points to output calculated score, use quitp(...) functions", + "Fixed to be compilable on Mac", + "PC_BASE_EXIT_CODE=50 in case of defined TESTSYS", + "Fixed issues 19-21, added __attribute__ format printf", + "Some bug fixes", + "ouf.readInt(1, 100) and similar calls return WA", + "Modified random_t to avoid integer overflow", + "Truncated checker output [patch by Stepan Gatilov]", + "Renamed class random -> class random_t", + "Supported name parameter for read-and-validation methods, like readInt(1, 2, \"n\")", + "Fixed bug in readDouble()", + "Improved ensuref(), fixed nextLine to work in case of EOF, added startTest()", + "Supported \"partially correct\", example: quitf(_pc(13), \"result=%d\", result)", + "Added shuffle(begin, end), use it instead of random_shuffle(begin, end)", + "Added readLine(const string& ptrn), fixed the logic of readLine() in the validation mode", + "Package extended with samples of generators and validators", + "Written the documentation for classes and public methods in testlib.h", + "Implemented random routine to support generators, use registerGen() to switch it on", + "Implemented strict mode to validate tests, use registerValidation() to switch it on", + "Now ncmp.cpp and wcmp.cpp are return WA if answer is suffix or prefix of the output", + "Added InStream::readLong() and removed InStream::readLongint()", + "Now no footer added to each report by default (use directive FOOTER to switch on)", + "Now every checker has a name, use setName(const char* format, ...) to set it", + "Now it is compatible with TTS (by Kittens Computing)", + "Added \'ensure(condition, message = \"\")\' feature, it works like assert()", + "Fixed compatibility with MS C++ 7.1", + "Added footer with exit code information", + "Added compatibility with EJUDGE (compile with EJUDGE directive)", + "Added compatibility with Contester (compile with CONTESTER directive)" +}; + +#ifdef _MSC_VER +#define _CRT_SECURE_NO_DEPRECATE +#define _CRT_SECURE_NO_WARNINGS +#define _CRT_NO_VA_START_VALIDATION +#endif + +/* Overrides random() for Borland C++. */ +#define random __random_deprecated +#include +#include +#include +#include +#undef random + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef TESTLIB_THROW_EXIT_EXCEPTION_INSTEAD_OF_EXIT +# include +#endif + +#if (_WIN32 || __WIN32__ || __WIN32 || _WIN64 || __WIN64__ || __WIN64 || WINNT || __WINNT || __WINNT__ || __CYGWIN__) +# if !defined(_MSC_VER) || _MSC_VER > 1400 +# define NOMINMAX 1 +# include +# else +# define WORD unsigned short +# include +# endif +# include +# define ON_WINDOWS +# if defined(_MSC_VER) && _MSC_VER > 1400 +# pragma warning( disable : 4127 ) +# pragma warning( disable : 4146 ) +# pragma warning( disable : 4458 ) +# endif +#else +# define WORD unsigned short +# include +#endif + +#if defined(FOR_WINDOWS) && defined(FOR_LINUX) +#error Only one target system is allowed +#endif + +#ifndef LLONG_MIN +#define LLONG_MIN (-9223372036854775807LL - 1) +#endif + +#ifndef ULLONG_MAX +#define ULLONG_MAX (18446744073709551615) +#endif + +#define LF ((char)10) +#define CR ((char)13) +#define TAB ((char)9) +#define SPACE ((char)' ') +#define EOFC (255) + +#ifndef OK_EXIT_CODE +# ifdef CONTESTER +# define OK_EXIT_CODE 0xAC +# else +# define OK_EXIT_CODE 0 +# endif +#endif + +#ifndef WA_EXIT_CODE +# ifdef EJUDGE +# define WA_EXIT_CODE 5 +# elif defined(CONTESTER) +# define WA_EXIT_CODE 0xAB +# else +# define WA_EXIT_CODE 1 +# endif +#endif + +#ifndef PE_EXIT_CODE +# ifdef EJUDGE +# define PE_EXIT_CODE 4 +# elif defined(CONTESTER) +# define PE_EXIT_CODE 0xAA +# else +# define PE_EXIT_CODE 2 +# endif +#endif + +#ifndef FAIL_EXIT_CODE +# ifdef EJUDGE +# define FAIL_EXIT_CODE 6 +# elif defined(CONTESTER) +# define FAIL_EXIT_CODE 0xA3 +# else +# define FAIL_EXIT_CODE 3 +# endif +#endif + +#ifndef DIRT_EXIT_CODE +# ifdef EJUDGE +# define DIRT_EXIT_CODE 6 +# else +# define DIRT_EXIT_CODE 4 +# endif +#endif + +#ifndef POINTS_EXIT_CODE +# define POINTS_EXIT_CODE 7 +#endif + +#ifndef UNEXPECTED_EOF_EXIT_CODE +# define UNEXPECTED_EOF_EXIT_CODE 8 +#endif + +#ifndef PC_BASE_EXIT_CODE +# ifdef TESTSYS +# define PC_BASE_EXIT_CODE 50 +# else +# define PC_BASE_EXIT_CODE 0 +# endif +#endif + +#ifdef __GNUC__ +# define __TESTLIB_STATIC_ASSERT(condition) typedef void* __testlib_static_assert_type[(condition) ? 1 : -1] __attribute__((unused)) +#else +# define __TESTLIB_STATIC_ASSERT(condition) typedef void* __testlib_static_assert_type[(condition) ? 1 : -1] +#endif + +#ifdef ON_WINDOWS +#define I64 "%I64d" +#define U64 "%I64u" +#else +#define I64 "%lld" +#define U64 "%llu" +#endif + +#ifdef _MSC_VER +# define NORETURN __declspec(noreturn) +#elif defined __GNUC__ +# define NORETURN __attribute__ ((noreturn)) +#else +# define NORETURN +#endif + +static char __testlib_format_buffer[16777216]; +static int __testlib_format_buffer_usage_count = 0; + +#define FMT_TO_RESULT(fmt, cstr, result) std::string result; \ + if (__testlib_format_buffer_usage_count != 0) \ + __testlib_fail("FMT_TO_RESULT::__testlib_format_buffer_usage_count != 0"); \ + __testlib_format_buffer_usage_count++; \ + va_list ap; \ + va_start(ap, fmt); \ + vsnprintf(__testlib_format_buffer, sizeof(__testlib_format_buffer), cstr, ap); \ + va_end(ap); \ + __testlib_format_buffer[sizeof(__testlib_format_buffer) - 1] = 0; \ + result = std::string(__testlib_format_buffer); \ + __testlib_format_buffer_usage_count--; \ + +const long long __TESTLIB_LONGLONG_MAX = 9223372036854775807LL; +const int __TESTLIB_MAX_TEST_CASE = 1073741823; + +int __testlib_exitCode; + +bool __testlib_hasTestCase; +int __testlib_testCase = -1; + +void setTestCase(int testCase); + +void unsetTestCase() { + __testlib_hasTestCase = false; + __testlib_testCase = -1; +} + +NORETURN static void __testlib_fail(const std::string &message); + +template +static inline T __testlib_abs(const T &x) { + return x > 0 ? x : -x; +} + +template +static inline T __testlib_min(const T &a, const T &b) { + return a < b ? a : b; +} + +template +static inline T __testlib_max(const T &a, const T &b) { + return a > b ? a : b; +} + +template +static inline T __testlib_crop(T value, T a, T b) { + return __testlib_min(__testlib_max(value, a), --b); +} + +static inline double __testlib_crop(double value, double a, double b) { + value = __testlib_min(__testlib_max(value, a), b); + if (value >= b) + value = std::nexttoward(b, a); + return value; +} + +static bool __testlib_prelimIsNaN(double r) { + volatile double ra = r; +#ifndef __BORLANDC__ + return ((ra != ra) == true) && ((ra == ra) == false) && ((1.0 > ra) == false) && ((1.0 < ra) == false); +#else + return std::_isnan(ra); +#endif +} + +static std::string removeDoubleTrailingZeroes(std::string value) { + while (!value.empty() && value[value.length() - 1] == '0' && value.find('.') != std::string::npos) + value = value.substr(0, value.length() - 1); + if (!value.empty() && value[value.length() - 1] == '.') + return value + '0'; + else + return value; +} + +#ifdef __GNUC__ +__attribute__ ((format (printf, 1, 2))) +#endif +std::string format(const char *fmt, ...) { + FMT_TO_RESULT(fmt, fmt, result); + return result; +} + +std::string format(const std::string fmt, ...) { + FMT_TO_RESULT(fmt, fmt.c_str(), result); + return result; +} + +static std::string __testlib_part(const std::string &s); + +static bool __testlib_isNaN(double r) { + __TESTLIB_STATIC_ASSERT(sizeof(double) == sizeof(long long)); + volatile double ra = r; + long long llr1, llr2; + std::memcpy((void *) &llr1, (void *) &ra, sizeof(double)); + ra = -ra; + std::memcpy((void *) &llr2, (void *) &ra, sizeof(double)); + long long llnan = 0xFFF8000000000000LL; + return __testlib_prelimIsNaN(r) || llnan == llr1 || llnan == llr2; +} + +static double __testlib_nan() { + __TESTLIB_STATIC_ASSERT(sizeof(double) == sizeof(long long)); +#ifndef NAN + long long llnan = 0xFFF8000000000000LL; + double nan; + std::memcpy(&nan, &llnan, sizeof(double)); + return nan; +#else + return NAN; +#endif +} + +static bool __testlib_isInfinite(double r) { + volatile double ra = r; + return (ra > 1E300 || ra < -1E300); +} + +#ifdef __GNUC__ +__attribute__((const)) +#endif +inline bool doubleCompare(double expected, double result, double MAX_DOUBLE_ERROR) { + MAX_DOUBLE_ERROR += 1E-15; + if (__testlib_isNaN(expected)) { + return __testlib_isNaN(result); + } else if (__testlib_isInfinite(expected)) { + if (expected > 0) { + return result > 0 && __testlib_isInfinite(result); + } else { + return result < 0 && __testlib_isInfinite(result); + } + } else if (__testlib_isNaN(result) || __testlib_isInfinite(result)) { + return false; + } else if (__testlib_abs(result - expected) <= MAX_DOUBLE_ERROR) { + return true; + } else { + double minv = __testlib_min(expected * (1.0 - MAX_DOUBLE_ERROR), + expected * (1.0 + MAX_DOUBLE_ERROR)); + double maxv = __testlib_max(expected * (1.0 - MAX_DOUBLE_ERROR), + expected * (1.0 + MAX_DOUBLE_ERROR)); + return result >= minv && result <= maxv; + } +} + +#ifdef __GNUC__ +__attribute__((const)) +#endif +inline double doubleDelta(double expected, double result) { + double absolute = __testlib_abs(result - expected); + + if (__testlib_abs(expected) > 1E-9) { + double relative = __testlib_abs(absolute / expected); + return __testlib_min(absolute, relative); + } else + return absolute; +} + +/** It does nothing on non-windows and files differ from stdin/stdout/stderr. */ +static void __testlib_set_binary(std::FILE *file) { + if (NULL != file) { +#ifdef ON_WINDOWS +# ifdef _O_BINARY + if (stdin == file) +# ifdef STDIN_FILENO + return void(_setmode(STDIN_FILENO, _O_BINARY)); +# else + return void(_setmode(_fileno(stdin), _O_BINARY)); +# endif + if (stdout == file) +# ifdef STDOUT_FILENO + return void(_setmode(STDOUT_FILENO, _O_BINARY)); +# else + return void(_setmode(_fileno(stdout), _O_BINARY)); +# endif + if (stderr == file) +# ifdef STDERR_FILENO + return void(_setmode(STDERR_FILENO, _O_BINARY)); +# else + return void(_setmode(_fileno(stderr), _O_BINARY)); +# endif +# elif O_BINARY + if (stdin == file) +# ifdef STDIN_FILENO + return void(setmode(STDIN_FILENO, O_BINARY)); +# else + return void(setmode(fileno(stdin), O_BINARY)); +# endif + if (stdout == file) +# ifdef STDOUT_FILENO + return void(setmode(STDOUT_FILENO, O_BINARY)); +# else + return void(setmode(fileno(stdout), O_BINARY)); +# endif + if (stderr == file) +# ifdef STDERR_FILENO + return void(setmode(STDERR_FILENO, O_BINARY)); +# else + return void(setmode(fileno(stderr), O_BINARY)); +# endif +# endif +#endif + } +} + +#if __cplusplus > 199711L || defined(_MSC_VER) +template +static std::string vtos(const T &t, std::true_type) { + if (t == 0) + return "0"; + else { + T n(t); + bool negative = n < 0; + std::string s; + while (n != 0) { + T digit = n % 10; + if (digit < 0) + digit = -digit; + s += char('0' + digit); + n /= 10; + } + std::reverse(s.begin(), s.end()); + return negative ? "-" + s : s; + } +} + +template +static std::string vtos(const T &t, std::false_type) { + std::string s; + static std::stringstream ss; + ss.str(std::string()); + ss.clear(); + ss << t; + ss >> s; + return s; +} + +template +static std::string vtos(const T &t) { + return vtos(t, std::is_integral()); +} + +/* signed case. */ +template +static std::string toHumanReadableString(const T &n, std::false_type) { + if (n == 0) + return vtos(n); + int trailingZeroCount = 0; + T n_ = n; + while (n_ % 10 == 0) + n_ /= 10, trailingZeroCount++; + if (trailingZeroCount >= 7) { + if (n_ == 1) + return "10^" + vtos(trailingZeroCount); + else if (n_ == -1) + return "-10^" + vtos(trailingZeroCount); + else + return vtos(n_) + "*10^" + vtos(trailingZeroCount); + } else + return vtos(n); +} + +/* unsigned case. */ +template +static std::string toHumanReadableString(const T &n, std::true_type) { + if (n == 0) + return vtos(n); + int trailingZeroCount = 0; + T n_ = n; + while (n_ % 10 == 0) + n_ /= 10, trailingZeroCount++; + if (trailingZeroCount >= 7) { + if (n_ == 1) + return "10^" + vtos(trailingZeroCount); + else + return vtos(n_) + "*10^" + vtos(trailingZeroCount); + } else + return vtos(n); +} + +template +static std::string toHumanReadableString(const T &n) { + return toHumanReadableString(n, std::is_unsigned()); +} +#else +template +static std::string vtos(const T& t) +{ + std::string s; + static std::stringstream ss; + ss.str(std::string()); + ss.clear(); + ss << t; + ss >> s; + return s; +} + +template +static std::string toHumanReadableString(const T &n) { + return vtos(n); +} +#endif + +template +static std::string toString(const T &t) { + return vtos(t); +} + +#if __cplusplus > 199711L || defined(_MSC_VER) +/* opts */ +void prepareOpts(int argc, char* argv[]); +#endif + +/* + * Very simple regex-like pattern. + * It used for two purposes: validation and generation. + * + * For example, pattern("[a-z]{1,5}").next(rnd) will return + * random string from lowercase latin letters with length + * from 1 to 5. It is easier to call rnd.next("[a-z]{1,5}") + * for the same effect. + * + * Another samples: + * "mike|john" will generate (match) "mike" or "john"; + * "-?[1-9][0-9]{0,3}" will generate (match) non-zero integers from -9999 to 9999; + * "id-([ac]|b{2})" will generate (match) "id-a", "id-bb", "id-c"; + * "[^0-9]*" will match sequences (empty or non-empty) without digits, you can't + * use it for generations. + * + * You can't use pattern for generation if it contains meta-symbol '*'. Also it + * is not recommended to use it for char-sets with meta-symbol '^' like [^a-z]. + * + * For matching very simple greedy algorithm is used. For example, pattern + * "[0-9]?1" will not match "1", because of greedy nature of matching. + * Alternations (meta-symbols "|") are processed with brute-force algorithm, so + * do not use many alternations in one expression. + * + * If you want to use one expression many times it is better to compile it into + * a single pattern like "pattern p("[a-z]+")". Later you can use + * "p.matches(std::string s)" or "p.next(random_t& rd)" to check matching or generate + * new string by pattern. + * + * Simpler way to read token and check it for pattern matching is "inf.readToken("[a-z]+")". + * + * All spaces are ignored in regex, unless escaped with \. For example, ouf.readLine("NO SOLUTION") + * will expect "NOSOLUTION", the correct call should be ouf.readLine("NO\\ SOLUTION") or + * ouf.readLine(R"(NO\ SOLUTION)") if you prefer raw string literals from C++11. + */ +class random_t; + +class pattern { +public: + /* Create pattern instance by string. */ + pattern(std::string s); + + /* Generate new string by pattern and given random_t. */ + std::string next(random_t &rnd) const; + + /* Checks if given string match the pattern. */ + bool matches(const std::string &s) const; + + /* Returns source string of the pattern. */ + std::string src() const; + +private: + bool matches(const std::string &s, size_t pos) const; + + std::string s; + std::vector children; + std::vector chars; + int from; + int to; +}; + +/* + * Use random_t instances to generate random values. It is preferred + * way to use randoms instead of rand() function or self-written + * randoms. + * + * Testlib defines global variable "rnd" of random_t class. + * Use registerGen(argc, argv, 1) to setup random_t seed be command + * line (to use latest random generator version). + * + * Random generates uniformly distributed values if another strategy is + * not specified explicitly. + */ +class random_t { +private: + unsigned long long seed; + static const unsigned long long multiplier; + static const unsigned long long addend; + static const unsigned long long mask; + static const int lim; + + long long nextBits(int bits) { + if (bits <= 48) { + seed = (seed * multiplier + addend) & mask; + return (long long) (seed >> (48 - bits)); + } else { + if (bits > 63) + __testlib_fail("random_t::nextBits(int bits): n must be less than 64"); + + int lowerBitCount = (random_t::version == 0 ? 31 : 32); + + long long left = (nextBits(31) << 32); + long long right = nextBits(lowerBitCount); + + return left ^ right; + } + } + +public: + static int version; + + /* New random_t with fixed seed. */ + random_t() + : seed(3905348978240129619LL) { + } + + /* Sets seed by command line. */ + void setSeed(int argc, char *argv[]) { + random_t p; + + seed = 3905348978240129619LL; + for (int i = 1; i < argc; i++) { + std::size_t le = std::strlen(argv[i]); + for (std::size_t j = 0; j < le; j++) + seed = seed * multiplier + (unsigned int) (argv[i][j]) + addend; + seed += multiplier / addend; + } + + seed = seed & mask; + } + + /* Sets seed by given value. */ + void setSeed(long long _seed) { + seed = (unsigned long long) _seed; + seed = (seed ^ multiplier) & mask; + } + +#ifndef __BORLANDC__ + + /* Random string value by given pattern (see pattern documentation). */ + std::string next(const std::string &ptrn) { + pattern p(ptrn); + return p.next(*this); + } + +#else + /* Random string value by given pattern (see pattern documentation). */ + std::string next(std::string ptrn) + { + pattern p(ptrn); + return p.next(*this); + } +#endif + + /* Random value in range [0, n-1]. */ + int next(int n) { + if (n <= 0) + __testlib_fail("random_t::next(int n): n must be positive"); + + if ((n & -n) == n) // n is a power of 2 + return (int) ((n * (long long) nextBits(31)) >> 31); + + const long long limit = INT_MAX / n * n; + + long long bits; + do { + bits = nextBits(31); + } while (bits >= limit); + + return int(bits % n); + } + + /* Random value in range [0, n-1]. */ + unsigned int next(unsigned int n) { + if (n >= INT_MAX) + __testlib_fail("random_t::next(unsigned int n): n must be less INT_MAX"); + return (unsigned int) next(int(n)); + } + + /* Random value in range [0, n-1]. */ + long long next(long long n) { + if (n <= 0) + __testlib_fail("random_t::next(long long n): n must be positive"); + + const long long limit = __TESTLIB_LONGLONG_MAX / n * n; + + long long bits; + do { + bits = nextBits(63); + } while (bits >= limit); + + return bits % n; + } + + /* Random value in range [0, n-1]. */ + unsigned long long next(unsigned long long n) { + if (n >= (unsigned long long) (__TESTLIB_LONGLONG_MAX)) + __testlib_fail("random_t::next(unsigned long long n): n must be less LONGLONG_MAX"); + return (unsigned long long) next((long long) (n)); + } + + /* Random value in range [0, n-1]. */ + long next(long n) { + return (long) next((long long) (n)); + } + + /* Random value in range [0, n-1]. */ + unsigned long next(unsigned long n) { + if (n >= (unsigned long) (LONG_MAX)) + __testlib_fail("random_t::next(unsigned long n): n must be less LONG_MAX"); + return (unsigned long) next((unsigned long long) (n)); + } + + /* Returns random value in range [from,to]. */ + int next(int from, int to) { + return int(next((long long) to - from + 1) + from); + } + + /* Returns random value in range [from,to]. */ + unsigned int next(unsigned int from, unsigned int to) { + return (unsigned int) (next((long long) to - from + 1) + from); + } + + /* Returns random value in range [from,to]. */ + long long next(long long from, long long to) { + return next(to - from + 1) + from; + } + + /* Returns random value in range [from,to]. */ + unsigned long long next(unsigned long long from, unsigned long long to) { + if (from > to) + __testlib_fail("random_t::next(unsigned long long from, unsigned long long to): from can't not exceed to"); + return next(to - from + 1) + from; + } + + /* Returns random value in range [from,to]. */ + long next(long from, long to) { + return next(to - from + 1) + from; + } + + /* Returns random value in range [from,to]. */ + unsigned long next(unsigned long from, unsigned long to) { + if (from > to) + __testlib_fail("random_t::next(unsigned long from, unsigned long to): from can't not exceed to"); + return next(to - from + 1) + from; + } + + /* Random double value in range [0, 1). */ + double next() { + long long left = ((long long) (nextBits(26)) << 27); + long long right = nextBits(27); + return __testlib_crop((double) (left + right) / (double) (1LL << 53), 0.0, 1.0); + } + + /* Random double value in range [0, n). */ + double next(double n) { + if (n <= 0.0) + __testlib_fail("random_t::next(double): n should be positive"); + return __testlib_crop(n * next(), 0.0, n); + } + + /* Random double value in range [from, to). */ + double next(double from, double to) { + if (from >= to) + __testlib_fail("random_t::next(double from, double to): from should be strictly less than to"); + return next(to - from) + from; + } + + /* Returns random element from container. */ + template + typename Container::value_type any(const Container &c) { + int size = int(c.size()); + if (size <= 0) + __testlib_fail("random_t::any(const Container& c): c.size() must be positive"); + return *(c.begin() + next(size)); + } + + /* Returns random element from iterator range. */ + template + typename Iter::value_type any(const Iter &begin, const Iter &end) { + int size = int(end - begin); + if (size <= 0) + __testlib_fail("random_t::any(const Iter& begin, const Iter& end): range must have positive length"); + return *(begin + next(size)); + } + + /* Random string value by given pattern (see pattern documentation). */ +#ifdef __GNUC__ + __attribute__ ((format (printf, 2, 3))) +#endif + std::string next(const char *format, ...) { + FMT_TO_RESULT(format, format, ptrn); + return next(ptrn); + } + + /* + * Weighted next. If type == 0 than it is usual "next()". + * + * If type = 1, than it returns "max(next(), next())" + * (the number of "max" functions equals to "type"). + * + * If type < 0, than "max" function replaces with "min". + */ + int wnext(int n, int type) { + if (n <= 0) + __testlib_fail("random_t::wnext(int n, int type): n must be positive"); + + if (abs(type) < random_t::lim) { + int result = next(n); + + for (int i = 0; i < +type; i++) + result = __testlib_max(result, next(n)); + + for (int i = 0; i < -type; i++) + result = __testlib_min(result, next(n)); + + return result; + } else { + double p; + + if (type > 0) + p = std::pow(next() + 0.0, 1.0 / (type + 1)); + else + p = 1 - std::pow(next() + 0.0, 1.0 / (-type + 1)); + + return __testlib_crop((int) (double(n) * p), 0, n); + } + } + + /* See wnext(int, int). It uses the same algorithms. */ + long long wnext(long long n, int type) { + if (n <= 0) + __testlib_fail("random_t::wnext(long long n, int type): n must be positive"); + + if (abs(type) < random_t::lim) { + long long result = next(n); + + for (int i = 0; i < +type; i++) + result = __testlib_max(result, next(n)); + + for (int i = 0; i < -type; i++) + result = __testlib_min(result, next(n)); + + return result; + } else { + double p; + + if (type > 0) + p = std::pow(next() + 0.0, 1.0 / (type + 1)); + else + p = 1 - std::pow(next() + 0.0, 1.0 / (-type + 1)); + + return __testlib_crop((long long) (double(n) * p), 0LL, n); + } + } + + /* Returns value in [0, n). See wnext(int, int). It uses the same algorithms. */ + double wnext(double n, int type) { + if (n <= 0) + __testlib_fail("random_t::wnext(double n, int type): n must be positive"); + + if (abs(type) < random_t::lim) { + double result = next(); + + for (int i = 0; i < +type; i++) + result = __testlib_max(result, next()); + + for (int i = 0; i < -type; i++) + result = __testlib_min(result, next()); + + return n * result; + } else { + double p; + + if (type > 0) + p = std::pow(next() + 0.0, 1.0 / (type + 1)); + else + p = 1 - std::pow(next() + 0.0, 1.0 / (-type + 1)); + + return __testlib_crop(n * p, 0.0, n); + } + } + + /* Returns value in [0, 1). See wnext(int, int). It uses the same algorithms. */ + double wnext(int type) { + return wnext(1.0, type); + } + + /* See wnext(int, int). It uses the same algorithms. */ + unsigned int wnext(unsigned int n, int type) { + if (n >= INT_MAX) + __testlib_fail("random_t::wnext(unsigned int n, int type): n must be less INT_MAX"); + return (unsigned int) wnext(int(n), type); + } + + /* See wnext(int, int). It uses the same algorithms. */ + unsigned long long wnext(unsigned long long n, int type) { + if (n >= (unsigned long long) (__TESTLIB_LONGLONG_MAX)) + __testlib_fail("random_t::wnext(unsigned long long n, int type): n must be less LONGLONG_MAX"); + + return (unsigned long long) wnext((long long) (n), type); + } + + /* See wnext(int, int). It uses the same algorithms. */ + long wnext(long n, int type) { + return (long) wnext((long long) (n), type); + } + + /* See wnext(int, int). It uses the same algorithms. */ + unsigned long wnext(unsigned long n, int type) { + if (n >= (unsigned long) (LONG_MAX)) + __testlib_fail("random_t::wnext(unsigned long n, int type): n must be less LONG_MAX"); + + return (unsigned long) wnext((unsigned long long) (n), type); + } + + /* Returns weighted random value in range [from, to]. */ + int wnext(int from, int to, int type) { + if (from > to) + __testlib_fail("random_t::wnext(int from, int to, int type): from can't not exceed to"); + return wnext(to - from + 1, type) + from; + } + + /* Returns weighted random value in range [from, to]. */ + int wnext(unsigned int from, unsigned int to, int type) { + if (from > to) + __testlib_fail("random_t::wnext(unsigned int from, unsigned int to, int type): from can't not exceed to"); + return int(wnext(to - from + 1, type) + from); + } + + /* Returns weighted random value in range [from, to]. */ + long long wnext(long long from, long long to, int type) { + if (from > to) + __testlib_fail("random_t::wnext(long long from, long long to, int type): from can't not exceed to"); + return wnext(to - from + 1, type) + from; + } + + /* Returns weighted random value in range [from, to]. */ + unsigned long long wnext(unsigned long long from, unsigned long long to, int type) { + if (from > to) + __testlib_fail( + "random_t::wnext(unsigned long long from, unsigned long long to, int type): from can't not exceed to"); + return wnext(to - from + 1, type) + from; + } + + /* Returns weighted random value in range [from, to]. */ + long wnext(long from, long to, int type) { + if (from > to) + __testlib_fail("random_t::wnext(long from, long to, int type): from can't not exceed to"); + return wnext(to - from + 1, type) + from; + } + + /* Returns weighted random value in range [from, to]. */ + unsigned long wnext(unsigned long from, unsigned long to, int type) { + if (from > to) + __testlib_fail("random_t::wnext(unsigned long from, unsigned long to, int type): from can't not exceed to"); + return wnext(to - from + 1, type) + from; + } + + /* Returns weighted random double value in range [from, to). */ + double wnext(double from, double to, int type) { + if (from >= to) + __testlib_fail("random_t::wnext(double from, double to, int type): from should be strictly less than to"); + return wnext(to - from, type) + from; + } + + /* Returns weighted random element from container. */ + template + typename Container::value_type wany(const Container &c, int type) { + size_t size = c.size(); + if (size <= 0) + __testlib_fail("random_t::wany(const Container& c, int type): c.size() must be positive"); + return *(c.begin() + wnext(size, type)); + } + + /* Returns weighted random element from iterator range. */ + template + typename Iter::value_type wany(const Iter &begin, const Iter &end, int type) { + int size = int(end - begin); + if (size <= 0) + __testlib_fail( + "random_t::any(const Iter& begin, const Iter& end, int type): range must have positive length"); + return *(begin + wnext(size, type)); + } + + /* Returns random permutation of the given size (values are between `first` and `first`+size-1)*/ + template + std::vector perm(T size, E first) { + if (size < 0) + __testlib_fail("random_t::perm(T size, E first = 0): size must non-negative"); + else if (size == 0) + return std::vector(); + std::vector p(size); + E current = first; + for (T i = 0; i < size; i++) + p[i] = current++; + if (size > 1) + for (T i = 1; i < size; i++) + std::swap(p[i], p[next(i + 1)]); + return p; + } + + /* Returns random permutation of the given size (values are between 0 and size-1)*/ + template + std::vector perm(T size) { + return perm(size, T(0)); + } + + /* Returns `size` unordered (unsorted) distinct numbers between `from` and `to`. */ + template + std::vector distinct(int size, T from, T to) { + std::vector result; + if (size == 0) + return result; + + if (from > to) + __testlib_fail("random_t::distinct expected from <= to"); + + if (size < 0) + __testlib_fail("random_t::distinct expected size >= 0"); + + uint64_t n = to - from + 1; + if (uint64_t(size) > n) + __testlib_fail("random_t::distinct expected size <= to - from + 1"); + + double expected = 0.0; + for (int i = 1; i <= size; i++) + expected += double(n) / double(n - i + 1); + + if (expected < double(n)) { + std::set vals; + while (int(vals.size()) < size) { + T x = T(next(from, to)); + if (vals.insert(x).second) + result.push_back(x); + } + } else { + if (n > 1000000000) + __testlib_fail("random_t::distinct here expected to - from + 1 <= 1000000000"); + std::vector p(perm(int(n), from)); + result.insert(result.end(), p.begin(), p.begin() + size); + } + + return result; + } + + /* Returns `size` unordered (unsorted) distinct numbers between `0` and `upper`-1. */ + template + std::vector distinct(int size, T upper) { + if (size < 0) + __testlib_fail("random_t::distinct expected size >= 0"); + if (size == 0) + return std::vector(); + + if (upper <= 0) + __testlib_fail("random_t::distinct expected upper > 0"); + if (size > upper) + __testlib_fail("random_t::distinct expected size <= upper"); + + return distinct(size, T(0), upper - 1); + } + + /* Returns random (unsorted) partition which is a representation of sum as a sum of integers not less than min_part. */ + template + std::vector partition(int size, T sum, T min_part) { + if (size < 0) + __testlib_fail("random_t::partition: size < 0"); + if (size == 0 && sum != 0) + __testlib_fail("random_t::partition: size == 0 && sum != 0"); + if (min_part * size > sum) + __testlib_fail("random_t::partition: min_part * size > sum"); + if (size == 0 && sum == 0) + return std::vector(); + + T sum_ = sum; + sum -= min_part * size; + + std::vector septums(size); + std::vector d = distinct(size - 1, T(1), T(sum + size - 1)); + for (int i = 0; i + 1 < size; i++) + septums[i + 1] = d[i]; + sort(septums.begin(), septums.end()); + + std::vector result(size); + for (int i = 0; i + 1 < size; i++) + result[i] = septums[i + 1] - septums[i] - 1; + result[size - 1] = sum + size - 1 - septums.back(); + + for (std::size_t i = 0; i < result.size(); i++) + result[i] += min_part; + + T result_sum = 0; + for (std::size_t i = 0; i < result.size(); i++) + result_sum += result[i]; + if (result_sum != sum_) + __testlib_fail("random_t::partition: partition sum is expected to be the given sum"); + + if (*std::min_element(result.begin(), result.end()) < min_part) + __testlib_fail("random_t::partition: partition min is expected to be no less than the given min_part"); + + if (int(result.size()) != size || result.size() != (size_t) size) + __testlib_fail("random_t::partition: partition size is expected to be equal to the given size"); + + return result; + } + + /* Returns random (unsorted) partition which is a representation of sum as a sum of positive integers. */ + template + std::vector partition(int size, T sum) { + return partition(size, sum, T(1)); + } +}; + +const int random_t::lim = 25; +const unsigned long long random_t::multiplier = 0x5DEECE66DLL; +const unsigned long long random_t::addend = 0xBLL; +const unsigned long long random_t::mask = (1LL << 48) - 1; +int random_t::version = -1; + +/* Pattern implementation */ +bool pattern::matches(const std::string &s) const { + return matches(s, 0); +} + +static bool __pattern_isSlash(const std::string &s, size_t pos) { + return s[pos] == '\\'; +} + +#ifdef __GNUC__ +__attribute__((pure)) +#endif +static bool __pattern_isCommandChar(const std::string &s, size_t pos, char value) { + if (pos >= s.length()) + return false; + + int slashes = 0; + + int before = int(pos) - 1; + while (before >= 0 && s[before] == '\\') + before--, slashes++; + + return slashes % 2 == 0 && s[pos] == value; +} + +static char __pattern_getChar(const std::string &s, size_t &pos) { + if (__pattern_isSlash(s, pos)) + pos += 2; + else + pos++; + + return s[pos - 1]; +} + +#ifdef __GNUC__ +__attribute__((pure)) +#endif +static int __pattern_greedyMatch(const std::string &s, size_t pos, const std::vector chars) { + int result = 0; + + while (pos < s.length()) { + char c = s[pos++]; + if (!std::binary_search(chars.begin(), chars.end(), c)) + break; + else + result++; + } + + return result; +} + +std::string pattern::src() const { + return s; +} + +bool pattern::matches(const std::string &s, size_t pos) const { + std::string result; + + if (to > 0) { + int size = __pattern_greedyMatch(s, pos, chars); + if (size < from) + return false; + if (size > to) + size = to; + pos += size; + } + + if (children.size() > 0) { + for (size_t child = 0; child < children.size(); child++) + if (children[child].matches(s, pos)) + return true; + return false; + } else + return pos == s.length(); +} + +std::string pattern::next(random_t &rnd) const { + std::string result; + result.reserve(20); + + if (to == INT_MAX) + __testlib_fail("pattern::next(random_t& rnd): can't process character '*' for generation"); + + if (to > 0) { + int count = rnd.next(to - from + 1) + from; + for (int i = 0; i < count; i++) + result += chars[rnd.next(int(chars.size()))]; + } + + if (children.size() > 0) { + int child = rnd.next(int(children.size())); + result += children[child].next(rnd); + } + + return result; +} + +static void __pattern_scanCounts(const std::string &s, size_t &pos, int &from, int &to) { + if (pos >= s.length()) { + from = to = 1; + return; + } + + if (__pattern_isCommandChar(s, pos, '{')) { + std::vector parts; + std::string part; + + pos++; + + while (pos < s.length() && !__pattern_isCommandChar(s, pos, '}')) { + if (__pattern_isCommandChar(s, pos, ',')) + parts.push_back(part), part = "", pos++; + else + part += __pattern_getChar(s, pos); + } + + if (part != "") + parts.push_back(part); + + if (!__pattern_isCommandChar(s, pos, '}')) + __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\""); + + pos++; + + if (parts.size() < 1 || parts.size() > 2) + __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\""); + + std::vector numbers; + + for (size_t i = 0; i < parts.size(); i++) { + if (parts[i].length() == 0) + __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\""); + int number; + if (std::sscanf(parts[i].c_str(), "%d", &number) != 1) + __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\""); + numbers.push_back(number); + } + + if (numbers.size() == 1) + from = to = numbers[0]; + else + from = numbers[0], to = numbers[1]; + + if (from > to) + __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\""); + } else { + if (__pattern_isCommandChar(s, pos, '?')) { + from = 0, to = 1, pos++; + return; + } + + if (__pattern_isCommandChar(s, pos, '*')) { + from = 0, to = INT_MAX, pos++; + return; + } + + if (__pattern_isCommandChar(s, pos, '+')) { + from = 1, to = INT_MAX, pos++; + return; + } + + from = to = 1; + } +} + +static std::vector __pattern_scanCharSet(const std::string &s, size_t &pos) { + if (pos >= s.length()) + __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\""); + + std::vector result; + + if (__pattern_isCommandChar(s, pos, '[')) { + pos++; + bool negative = __pattern_isCommandChar(s, pos, '^'); + if (negative) + pos++; + + char prev = 0; + + while (pos < s.length() && !__pattern_isCommandChar(s, pos, ']')) { + if (__pattern_isCommandChar(s, pos, '-') && prev != 0) { + pos++; + + if (pos + 1 == s.length() || __pattern_isCommandChar(s, pos, ']')) { + result.push_back(prev); + prev = '-'; + continue; + } + + char next = __pattern_getChar(s, pos); + if (prev > next) + __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\""); + + for (char c = prev; c != next; c++) + result.push_back(c); + result.push_back(next); + + prev = 0; + } else { + if (prev != 0) + result.push_back(prev); + prev = __pattern_getChar(s, pos); + } + } + + if (prev != 0) + result.push_back(prev); + + if (!__pattern_isCommandChar(s, pos, ']')) + __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\""); + + pos++; + + if (negative) { + std::sort(result.begin(), result.end()); + std::vector actuals; + for (int code = 0; code < 255; code++) { + char c = char(code); + if (!std::binary_search(result.begin(), result.end(), c)) + actuals.push_back(c); + } + result = actuals; + } + + std::sort(result.begin(), result.end()); + } else + result.push_back(__pattern_getChar(s, pos)); + + return result; +} + +pattern::pattern(std::string s) : s(s), from(0), to(0) { + std::string t; + for (size_t i = 0; i < s.length(); i++) + if (!__pattern_isCommandChar(s, i, ' ')) + t += s[i]; + s = t; + + int opened = 0; + int firstClose = -1; + std::vector seps; + + for (size_t i = 0; i < s.length(); i++) { + if (__pattern_isCommandChar(s, i, '(')) { + opened++; + continue; + } + + if (__pattern_isCommandChar(s, i, ')')) { + opened--; + if (opened == 0 && firstClose == -1) + firstClose = int(i); + continue; + } + + if (opened < 0) + __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\""); + + if (__pattern_isCommandChar(s, i, '|') && opened == 0) + seps.push_back(int(i)); + } + + if (opened != 0) + __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\""); + + if (seps.size() == 0 && firstClose + 1 == (int) s.length() + && __pattern_isCommandChar(s, 0, '(') && __pattern_isCommandChar(s, s.length() - 1, ')')) { + children.push_back(pattern(s.substr(1, s.length() - 2))); + } else { + if (seps.size() > 0) { + seps.push_back(int(s.length())); + int last = 0; + + for (size_t i = 0; i < seps.size(); i++) { + children.push_back(pattern(s.substr(last, seps[i] - last))); + last = seps[i] + 1; + } + } else { + size_t pos = 0; + chars = __pattern_scanCharSet(s, pos); + __pattern_scanCounts(s, pos, from, to); + if (pos < s.length()) + children.push_back(pattern(s.substr(pos))); + } + } +} + +/* End of pattern implementation */ + +template +inline bool isEof(C c) { + return c == EOFC; +} + +template +inline bool isEoln(C c) { + return (c == LF || c == CR); +} + +template +inline bool isBlanks(C c) { + return (c == LF || c == CR || c == SPACE || c == TAB); +} + +inline std::string trim(const std::string &s) { + if (s.empty()) + return s; + + int left = 0; + while (left < int(s.length()) && isBlanks(s[left])) + left++; + if (left >= int(s.length())) + return ""; + + int right = int(s.length()) - 1; + while (right >= 0 && isBlanks(s[right])) + right--; + if (right < 0) + return ""; + + return s.substr(left, right - left + 1); +} + +enum TMode { + _input, _output, _answer +}; + +/* Outcomes 6-15 are reserved for future use. */ +enum TResult { + _ok = 0, + _wa = 1, + _pe = 2, + _fail = 3, + _dirt = 4, + _points = 5, + _unexpected_eof = 8, + _partially = 16 +}; + +enum TTestlibMode { + _unknown, _checker, _validator, _generator, _interactor, _scorer +}; + +#define _pc(exitCode) (TResult(_partially + (exitCode))) + +/* Outcomes 6-15 are reserved for future use. */ +const std::string outcomes[] = { + "accepted", + "wrong-answer", + "presentation-error", + "fail", + "fail", +#ifndef PCMS2 + "points", +#else + "relative-scoring", +#endif + "reserved", + "reserved", + "unexpected-eof", + "reserved", + "reserved", + "reserved", + "reserved", + "reserved", + "reserved", + "reserved", + "partially-correct" +}; + +class InputStreamReader { +public: + virtual void setTestCase(int testCase) = 0; + + virtual std::vector getReadChars() = 0; + + virtual int curChar() = 0; + + virtual int nextChar() = 0; + + virtual void skipChar() = 0; + + virtual void unreadChar(int c) = 0; + + virtual std::string getName() = 0; + + virtual bool eof() = 0; + + virtual void close() = 0; + + virtual int getLine() = 0; + + virtual ~InputStreamReader() = 0; +}; + +InputStreamReader::~InputStreamReader() { + // No operations. +} + +class StringInputStreamReader : public InputStreamReader { +private: + std::string s; + size_t pos; + +public: + StringInputStreamReader(const std::string &content) : s(content), pos(0) { + // No operations. + } + + void setTestCase(int) { + __testlib_fail("setTestCase not implemented in StringInputStreamReader"); + } + + std::vector getReadChars() { + __testlib_fail("getReadChars not implemented in StringInputStreamReader"); + } + + int curChar() { + if (pos >= s.length()) + return EOFC; + else + return s[pos]; + } + + int nextChar() { + if (pos >= s.length()) { + pos++; + return EOFC; + } else + return s[pos++]; + } + + void skipChar() { + pos++; + } + + void unreadChar(int c) { + if (pos == 0) + __testlib_fail("StringInputStreamReader::unreadChar(int): pos == 0."); + pos--; + if (pos < s.length()) + s[pos] = char(c); + } + + std::string getName() { + return __testlib_part(s); + } + + int getLine() { + return -1; + } + + bool eof() { + return pos >= s.length(); + } + + void close() { + // No operations. + } +}; + +class FileInputStreamReader : public InputStreamReader { +private: + std::FILE *file; + std::string name; + int line; + std::vector undoChars; + std::vector readChars; + std::vector undoReadChars; + + inline int postprocessGetc(int getcResult) { + if (getcResult != EOF) + return getcResult; + else + return EOFC; + } + + int getc(FILE *file) { + int c; + int rc; + + if (undoChars.empty()) { + c = rc = ::getc(file); + } else { + c = undoChars.back(); + undoChars.pop_back(); + rc = undoReadChars.back(); + undoReadChars.pop_back(); + } + + if (c == LF) + line++; + + readChars.push_back(rc); + return c; + } + + int ungetc(int c/*, FILE* file*/) { + if (!readChars.empty()) { + undoReadChars.push_back(readChars.back()); + readChars.pop_back(); + } + if (c == LF) + line--; + undoChars.push_back(c); + return c; + } + +public: + FileInputStreamReader(std::FILE *file, const std::string &name) : file(file), name(name), line(1) { + // No operations. + } + + void setTestCase(int testCase) { + if (testCase < 0 || testCase > __TESTLIB_MAX_TEST_CASE) + __testlib_fail(format("testCase expected fit in [1,%d], but %d doesn't", __TESTLIB_MAX_TEST_CASE, testCase)); + readChars.push_back(testCase + 256); + } + + std::vector getReadChars() { + return readChars; + } + + int curChar() { + if (feof(file)) + return EOFC; + else { + int c = getc(file); + ungetc(c/*, file*/); + return postprocessGetc(c); + } + } + + int nextChar() { + if (feof(file)) + return EOFC; + else + return postprocessGetc(getc(file)); + } + + void skipChar() { + getc(file); + } + + void unreadChar(int c) { + ungetc(c/*, file*/); + } + + std::string getName() { + return name; + } + + int getLine() { + return line; + } + + bool eof() { + if (NULL == file || feof(file)) + return true; + else { + int c = nextChar(); + if (c == EOFC || (c == EOF && feof(file))) + return true; + unreadChar(c); + return false; + } + } + + void close() { + if (NULL != file) { + fclose(file); + file = NULL; + } + } +}; + +class BufferedFileInputStreamReader : public InputStreamReader { +private: + static const size_t BUFFER_SIZE; + static const size_t MAX_UNREAD_COUNT; + + std::FILE *file; + std::string name; + int line; + + char *buffer; + bool *isEof; + int bufferPos; + size_t bufferSize; + + bool refill() { + if (NULL == file) + __testlib_fail("BufferedFileInputStreamReader: file == NULL (" + getName() + ")"); + + if (bufferPos >= int(bufferSize)) { + size_t readSize = fread( + buffer + MAX_UNREAD_COUNT, + 1, + BUFFER_SIZE - MAX_UNREAD_COUNT, + file + ); + + if (readSize < BUFFER_SIZE - MAX_UNREAD_COUNT + && ferror(file)) + __testlib_fail("BufferedFileInputStreamReader: unable to read (" + getName() + ")"); + + bufferSize = MAX_UNREAD_COUNT + readSize; + bufferPos = int(MAX_UNREAD_COUNT); + std::memset(isEof + MAX_UNREAD_COUNT, 0, sizeof(isEof[0]) * readSize); + + return readSize > 0; + } else + return true; + } + + char increment() { + char c; + if ((c = buffer[bufferPos++]) == LF) + line++; + return c; + } + +public: + BufferedFileInputStreamReader(std::FILE *file, const std::string &name) : file(file), name(name), line(1) { + buffer = new char[BUFFER_SIZE]; + isEof = new bool[BUFFER_SIZE]; + bufferSize = MAX_UNREAD_COUNT; + bufferPos = int(MAX_UNREAD_COUNT); + } + + ~BufferedFileInputStreamReader() { + if (NULL != buffer) { + delete[] buffer; + buffer = NULL; + } + if (NULL != isEof) { + delete[] isEof; + isEof = NULL; + } + } + + void setTestCase(int) { + __testlib_fail("setTestCase not implemented in BufferedFileInputStreamReader"); + } + + std::vector getReadChars() { + __testlib_fail("getReadChars not implemented in BufferedFileInputStreamReader"); + } + + int curChar() { + if (!refill()) + return EOFC; + + return isEof[bufferPos] ? EOFC : buffer[bufferPos]; + } + + int nextChar() { + if (!refill()) + return EOFC; + + return isEof[bufferPos] ? EOFC : increment(); + } + + void skipChar() { + increment(); + } + + void unreadChar(int c) { + bufferPos--; + if (bufferPos < 0) + __testlib_fail("BufferedFileInputStreamReader::unreadChar(int): bufferPos < 0"); + isEof[bufferPos] = (c == EOFC); + buffer[bufferPos] = char(c); + if (c == LF) + line--; + } + + std::string getName() { + return name; + } + + int getLine() { + return line; + } + + bool eof() { + return !refill() || EOFC == curChar(); + } + + void close() { + if (NULL != file) { + fclose(file); + file = NULL; + } + } +}; + +const size_t BufferedFileInputStreamReader::BUFFER_SIZE = 2000000; +const size_t BufferedFileInputStreamReader::MAX_UNREAD_COUNT = BufferedFileInputStreamReader::BUFFER_SIZE / 2; + +/* + * Streams to be used for reading data in checkers or validators. + * Each read*() method moves pointer to the next character after the + * read value. + */ +struct InStream { + /* Do not use them. */ + InStream(); + + ~InStream(); + + /* Wrap std::string with InStream. */ + InStream(const InStream &baseStream, std::string content); + + InputStreamReader *reader; + int lastLine; + + std::string name; + TMode mode; + bool opened; + bool stdfile; + bool strict; + + int wordReserveSize; + std::string _tmpReadToken; + + int readManyIteration; + size_t maxFileSize; + size_t maxTokenLength; + size_t maxMessageLength; + + void init(std::string fileName, TMode mode); + + void init(std::FILE *f, TMode mode); + + void setTestCase(int testCase); + std::vector getReadChars(); + + /* Moves stream pointer to the first non-white-space character or EOF. */ + void skipBlanks(); + + /* Returns current character in the stream. Doesn't remove it from stream. */ + char curChar(); + + /* Moves stream pointer one character forward. */ + void skipChar(); + + /* Returns current character and moves pointer one character forward. */ + char nextChar(); + + /* Returns current character and moves pointer one character forward. */ + char readChar(); + + /* As "readChar()" but ensures that the result is equal to given parameter. */ + char readChar(char c); + + /* As "readChar()" but ensures that the result is equal to the space (code=32). */ + char readSpace(); + + /* Puts back the character into the stream. */ + void unreadChar(char c); + + /* Reopens stream, you should not use it. */ + void reset(std::FILE *file = NULL); + + /* Checks that current position is EOF. If not it doesn't move stream pointer. */ + bool eof(); + + /* Moves pointer to the first non-white-space character and calls "eof()". */ + bool seekEof(); + + /* + * Checks that current position contains EOLN. + * If not it doesn't move stream pointer. + * In strict mode expects "#13#10" for windows or "#10" for other platforms. + */ + bool eoln(); + + /* Moves pointer to the first non-space and non-tab character and calls "eoln()". */ + bool seekEoln(); + + /* Moves stream pointer to the first character of the next line (if exists). */ + void nextLine(); + + /* + * Reads new token. Ignores white-spaces into the non-strict mode + * (strict mode is used in validators usually). + */ + std::string readWord(); + + /* The same as "readWord()", it is preferred to use "readToken()". */ + std::string readToken(); + + /* The same as "readWord()", but ensures that token matches to given pattern. */ + std::string readWord(const std::string &ptrn, const std::string &variableName = ""); + + std::string readWord(const pattern &p, const std::string &variableName = ""); + + std::vector + readWords(int size, const std::string &ptrn, const std::string &variablesName = "", int indexBase = 1); + + std::vector + readWords(int size, const pattern &p, const std::string &variablesName = "", int indexBase = 1); + + std::vector readWords(int size, int indexBase = 1); + + /* The same as "readToken()", but ensures that token matches to given pattern. */ + std::string readToken(const std::string &ptrn, const std::string &variableName = ""); + + std::string readToken(const pattern &p, const std::string &variableName = ""); + + std::vector + readTokens(int size, const std::string &ptrn, const std::string &variablesName = "", int indexBase = 1); + + std::vector + readTokens(int size, const pattern &p, const std::string &variablesName = "", int indexBase = 1); + + std::vector readTokens(int size, int indexBase = 1); + + void readWordTo(std::string &result); + + void readWordTo(std::string &result, const pattern &p, const std::string &variableName = ""); + + void readWordTo(std::string &result, const std::string &ptrn, const std::string &variableName = ""); + + void readTokenTo(std::string &result); + + void readTokenTo(std::string &result, const pattern &p, const std::string &variableName = ""); + + void readTokenTo(std::string &result, const std::string &ptrn, const std::string &variableName = ""); + + /* + * Reads new long long value. Ignores white-spaces into the non-strict mode + * (strict mode is used in validators usually). + */ + long long readLong(); + + unsigned long long readUnsignedLong(); + + /* + * Reads new int. Ignores white-spaces into the non-strict mode + * (strict mode is used in validators usually). + */ + int readInteger(); + + /* + * Reads new int. Ignores white-spaces into the non-strict mode + * (strict mode is used in validators usually). + */ + int readInt(); + + /* As "readLong()" but ensures that value in the range [minv,maxv]. */ + long long readLong(long long minv, long long maxv, const std::string &variableName = ""); + + /* Reads space-separated sequence of long longs. */ + std::vector + readLongs(int size, long long minv, long long maxv, const std::string &variablesName = "", int indexBase = 1); + + /* Reads space-separated sequence of long longs. */ + std::vector readLongs(int size, int indexBase = 1); + + unsigned long long + readUnsignedLong(unsigned long long minv, unsigned long long maxv, const std::string &variableName = ""); + + std::vector + readUnsignedLongs(int size, unsigned long long minv, unsigned long long maxv, const std::string &variablesName = "", + int indexBase = 1); + + std::vector readUnsignedLongs(int size, int indexBase = 1); + + unsigned long long readLong(unsigned long long minv, unsigned long long maxv, const std::string &variableName = ""); + + std::vector + readLongs(int size, unsigned long long minv, unsigned long long maxv, const std::string &variablesName = "", + int indexBase = 1); + + /* As "readInteger()" but ensures that value in the range [minv,maxv]. */ + int readInteger(int minv, int maxv, const std::string &variableName = ""); + + /* As "readInt()" but ensures that value in the range [minv,maxv]. */ + int readInt(int minv, int maxv, const std::string &variableName = ""); + + /* Reads space-separated sequence of integers. */ + std::vector + readIntegers(int size, int minv, int maxv, const std::string &variablesName = "", int indexBase = 1); + + /* Reads space-separated sequence of integers. */ + std::vector readIntegers(int size, int indexBase = 1); + + /* Reads space-separated sequence of integers. */ + std::vector readInts(int size, int minv, int maxv, const std::string &variablesName = "", int indexBase = 1); + + /* Reads space-separated sequence of integers. */ + std::vector readInts(int size, int indexBase = 1); + + /* + * Reads new double. Ignores white-spaces into the non-strict mode + * (strict mode is used in validators usually). + */ + double readReal(); + + /* + * Reads new double. Ignores white-spaces into the non-strict mode + * (strict mode is used in validators usually). + */ + double readDouble(); + + /* As "readReal()" but ensures that value in the range [minv,maxv]. */ + double readReal(double minv, double maxv, const std::string &variableName = ""); + + std::vector + readReals(int size, double minv, double maxv, const std::string &variablesName = "", int indexBase = 1); + + std::vector readReals(int size, int indexBase = 1); + + /* As "readDouble()" but ensures that value in the range [minv,maxv]. */ + double readDouble(double minv, double maxv, const std::string &variableName = ""); + + std::vector + readDoubles(int size, double minv, double maxv, const std::string &variablesName = "", int indexBase = 1); + + std::vector readDoubles(int size, int indexBase = 1); + + /* + * As "readReal()" but ensures that value in the range [minv,maxv] and + * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount] + * and number is in the form "[-]digit(s)[.digit(s)]". + */ + double readStrictReal(double minv, double maxv, + int minAfterPointDigitCount, int maxAfterPointDigitCount, + const std::string &variableName = ""); + + std::vector readStrictReals(int size, double minv, double maxv, + int minAfterPointDigitCount, int maxAfterPointDigitCount, + const std::string &variablesName = "", int indexBase = 1); + + /* + * As "readDouble()" but ensures that value in the range [minv,maxv] and + * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount] + * and number is in the form "[-]digit(s)[.digit(s)]". + */ + double readStrictDouble(double minv, double maxv, + int minAfterPointDigitCount, int maxAfterPointDigitCount, + const std::string &variableName = ""); + + std::vector readStrictDoubles(int size, double minv, double maxv, + int minAfterPointDigitCount, int maxAfterPointDigitCount, + const std::string &variablesName = "", int indexBase = 1); + + /* As readLine(). */ + std::string readString(); + + /* Read many lines. */ + std::vector readStrings(int size, int indexBase = 1); + + /* See readLine(). */ + void readStringTo(std::string &result); + + /* The same as "readLine()/readString()", but ensures that line matches to the given pattern. */ + std::string readString(const pattern &p, const std::string &variableName = ""); + + /* The same as "readLine()/readString()", but ensures that line matches to the given pattern. */ + std::string readString(const std::string &ptrn, const std::string &variableName = ""); + + /* Read many lines. */ + std::vector + readStrings(int size, const pattern &p, const std::string &variableName = "", int indexBase = 1); + + /* Read many lines. */ + std::vector + readStrings(int size, const std::string &ptrn, const std::string &variableName = "", int indexBase = 1); + + /* The same as "readLine()/readString()", but ensures that line matches to the given pattern. */ + void readStringTo(std::string &result, const pattern &p, const std::string &variableName = ""); + + /* The same as "readLine()/readString()", but ensures that line matches to the given pattern. */ + void readStringTo(std::string &result, const std::string &ptrn, const std::string &variableName = ""); + + /* + * Reads line from the current position to EOLN or EOF. Moves stream pointer to + * the first character of the new line (if possible). + */ + std::string readLine(); + + /* Read many lines. */ + std::vector readLines(int size, int indexBase = 1); + + /* See readLine(). */ + void readLineTo(std::string &result); + + /* The same as "readLine()", but ensures that line matches to the given pattern. */ + std::string readLine(const pattern &p, const std::string &variableName = ""); + + /* The same as "readLine()", but ensures that line matches to the given pattern. */ + std::string readLine(const std::string &ptrn, const std::string &variableName = ""); + + /* Read many lines. */ + std::vector + readLines(int size, const pattern &p, const std::string &variableName = "", int indexBase = 1); + + /* Read many lines. */ + std::vector + readLines(int size, const std::string &ptrn, const std::string &variableName = "", int indexBase = 1); + + /* The same as "readLine()", but ensures that line matches to the given pattern. */ + void readLineTo(std::string &result, const pattern &p, const std::string &variableName = ""); + + /* The same as "readLine()", but ensures that line matches to the given pattern. */ + void readLineTo(std::string &result, const std::string &ptrn, const std::string &variableName = ""); + + /* Reads EOLN or fails. Use it in validators. Calls "eoln()" method internally. */ + void readEoln(); + + /* Reads EOF or fails. Use it in validators. Calls "eof()" method internally. */ + void readEof(); + + /* + * Quit-functions aborts program with and : + * input/answer streams replace any result to FAIL. + */ + NORETURN void quit(TResult result, const char *msg); + /* + * Quit-functions aborts program with and : + * input/answer streams replace any result to FAIL. + */ + NORETURN void quitf(TResult result, const char *msg, ...); + + /* + * Quit-functions aborts program with and : + * input/answer streams replace any result to FAIL. + */ + void quitif(bool condition, TResult result, const char *msg, ...); + /* + * Quit-functions aborts program with and : + * input/answer streams replace any result to FAIL. + */ + NORETURN void quits(TResult result, std::string msg); + + /* + * Checks condition and aborts a program if condition is false. + * Returns _wa for ouf and _fail on any other streams. + */ +#ifdef __GNUC__ + __attribute__ ((format (printf, 3, 4))) +#endif + void ensuref(bool cond, const char *format, ...); + + void __testlib_ensure(bool cond, std::string message); + + void close(); + + const static int NO_INDEX = INT_MAX; + const static char OPEN_BRACKET = char(11); + const static char CLOSE_BRACKET = char(17); + + const static WORD LightGray = 0x07; + const static WORD LightRed = 0x0c; + const static WORD LightCyan = 0x0b; + const static WORD LightGreen = 0x0a; + const static WORD LightYellow = 0x0e; + + static void textColor(WORD color); + + static void quitscr(WORD color, const char *msg); + + static void quitscrS(WORD color, std::string msg); + + void xmlSafeWrite(std::FILE *file, const char *msg); + + /* Skips UTF-8 Byte Order Mark. */ + void skipBom(); + +private: + InStream(const InStream &); + + InStream &operator=(const InStream &); +}; + +InStream inf; +InStream ouf; +InStream ans; +bool appesMode; +std::string resultName; +std::string checkerName = "untitled checker"; +random_t rnd; +TTestlibMode testlibMode = _unknown; +double __testlib_points = std::numeric_limits::infinity(); + +struct ValidatorBoundsHit { + static const double EPS; + bool minHit; + bool maxHit; + + ValidatorBoundsHit(bool minHit = false, bool maxHit = false) : minHit(minHit), maxHit(maxHit) { + }; + + ValidatorBoundsHit merge(const ValidatorBoundsHit &validatorBoundsHit) { + return ValidatorBoundsHit( + __testlib_max(minHit, validatorBoundsHit.minHit), + __testlib_max(maxHit, validatorBoundsHit.maxHit) + ); + } +}; + +const double ValidatorBoundsHit::EPS = 1E-12; + +class Validator { +private: + const static std::string TEST_MARKUP_HEADER; + const static std::string TEST_CASE_OPEN_TAG; + const static std::string TEST_CASE_CLOSE_TAG; + + bool _initialized; + std::string _testset; + std::string _group; + + std::string _testOverviewLogFileName; + std::string _testMarkupFileName; + int _testCase = -1; + std::string _testCaseFileName; + + std::map _boundsHitByVariableName; + std::set _features; + std::set _hitFeatures; + + bool isVariableNameBoundsAnalyzable(const std::string &variableName) { + for (size_t i = 0; i < variableName.length(); i++) + if ((variableName[i] >= '0' && variableName[i] <= '9') || variableName[i] < ' ') + return false; + return true; + } + + bool isFeatureNameAnalyzable(const std::string &featureName) { + for (size_t i = 0; i < featureName.length(); i++) + if (featureName[i] < ' ') + return false; + return true; + } + +public: + Validator() : _initialized(false), _testset("tests"), _group() { + } + + void initialize() { + _initialized = true; + } + + std::string testset() const { + if (!_initialized) + __testlib_fail("Validator should be initialized with registerValidation(argc, argv) instead of registerValidation() to support validator.testset()"); + return _testset; + } + + std::string group() const { + if (!_initialized) + __testlib_fail("Validator should be initialized with registerValidation(argc, argv) instead of registerValidation() to support validator.group()"); + return _group; + } + + std::string testOverviewLogFileName() const { + return _testOverviewLogFileName; + } + + std::string testMarkupFileName() const { + return _testMarkupFileName; + } + + int testCase() const { + return _testCase; + } + + std::string testCaseFileName() const { + return _testCaseFileName; + } + + void setTestset(const char *const testset) { + _testset = testset; + } + + void setGroup(const char *const group) { + _group = group; + } + + void setTestOverviewLogFileName(const char *const testOverviewLogFileName) { + _testOverviewLogFileName = testOverviewLogFileName; + } + + void setTestMarkupFileName(const char *const testMarkupFileName) { + _testMarkupFileName = testMarkupFileName; + } + + void setTestCase(int testCase) { + _testCase = testCase; + } + + void setTestCaseFileName(const char *const testCaseFileName) { + _testCaseFileName = testCaseFileName; + } + + void addBoundsHit(const std::string &variableName, ValidatorBoundsHit boundsHit) { + if (isVariableNameBoundsAnalyzable(variableName)) { + _boundsHitByVariableName[variableName] + = boundsHit.merge(_boundsHitByVariableName[variableName]); + } + } + + std::string getBoundsHitLog() { + std::string result; + for (std::map::iterator i = _boundsHitByVariableName.begin(); + i != _boundsHitByVariableName.end(); + i++) { + result += "\"" + i->first + "\":"; + if (i->second.minHit) + result += " min-value-hit"; + if (i->second.maxHit) + result += " max-value-hit"; + result += "\n"; + } + return result; + } + + std::string getFeaturesLog() { + std::string result; + for (std::set::iterator i = _features.begin(); + i != _features.end(); + i++) { + result += "feature \"" + *i + "\":"; + if (_hitFeatures.count(*i)) + result += " hit"; + result += "\n"; + } + return result; + } + + void writeTestOverviewLog() { + if (!_testOverviewLogFileName.empty()) { + std::string fileName(_testOverviewLogFileName); + _testOverviewLogFileName = ""; + FILE *testOverviewLogFile = fopen(fileName.c_str(), "w"); + if (NULL == testOverviewLogFile) + __testlib_fail("Validator::writeTestOverviewLog: can't write test overview log to (" + fileName + ")"); + fprintf(testOverviewLogFile, "%s%s", getBoundsHitLog().c_str(), getFeaturesLog().c_str()); + if (fclose(testOverviewLogFile)) + __testlib_fail( + "Validator::writeTestOverviewLog: can't close test overview log file (" + fileName + ")"); + } + } + + void writeTestMarkup() { + if (!_testMarkupFileName.empty()) { + std::vector readChars = inf.getReadChars(); + if (!readChars.empty()) { + std::string markup(TEST_MARKUP_HEADER); + for (size_t i = 0; i < readChars.size(); i++) { + int c = readChars[i]; + if (i + 1 == readChars.size() && c == -1) + continue; + if (c <= 256) { + char cc = char(c); + if (cc == '\\' || cc == '!') + markup += '\\'; + markup += cc; + } else { + markup += TEST_CASE_OPEN_TAG; + markup += toString(c - 256); + markup += TEST_CASE_CLOSE_TAG; + } + } + FILE* f; + bool standard_file = false; + if (_testMarkupFileName == "stdout") + f = stdout, standard_file = true; + else if (_testMarkupFileName == "stderr") + f = stderr, standard_file = true; + else { + f = fopen(_testMarkupFileName.c_str(), "wb"); + if (NULL == f) + __testlib_fail("Validator::writeTestMarkup: can't write test markup to (" + _testMarkupFileName + ")"); + } + std::fprintf(f, "%s", markup.c_str()); + std::fflush(f); + if (!standard_file) + if (std::fclose(f)) + __testlib_fail("Validator::writeTestMarkup: can't close test markup file (" + _testCaseFileName + ")"); + } + } + } + + void writeTestCase() { + if (_testCase > 0) { + std::vector readChars = inf.getReadChars(); + if (!readChars.empty()) { + std::string content, testCaseContent; + bool matchedTestCase = false; + for (size_t i = 0; i < readChars.size(); i++) { + int c = readChars[i]; + if (i + 1 == readChars.size() && c == -1) + continue; + if (c <= 256) + content += char(c); + else { + if (matchedTestCase) { + testCaseContent = content; + matchedTestCase = false; + } + content = ""; + int testCase = c - 256; + if (testCase == _testCase) + matchedTestCase = true; + } + } + if (matchedTestCase) + testCaseContent = content; + + if (!testCaseContent.empty()) { + FILE* f; + bool standard_file = false; + if (_testCaseFileName.empty() || _testCaseFileName == "stdout") + f = stdout, standard_file = true; + else if (_testCaseFileName == "stderr") + f = stderr, standard_file = true; + else { + f = fopen(_testCaseFileName.c_str(), "wb"); + if (NULL == f) + __testlib_fail("Validator::writeTestCase: can't write test case to (" + _testCaseFileName + ")"); + } + std::fprintf(f, "%s", testCaseContent.c_str()); + std::fflush(f); + if (!standard_file) + if (std::fclose(f)) + __testlib_fail("Validator::writeTestCase: can't close test case file (" + _testCaseFileName + ")"); + } + } + } + } + + void addFeature(const std::string &feature) { + if (_features.count(feature)) + __testlib_fail("Feature " + feature + " registered twice."); + if (!isFeatureNameAnalyzable(feature)) + __testlib_fail("Feature name '" + feature + "' contains restricted characters."); + + _features.insert(feature); + } + + void feature(const std::string &feature) { + if (!isFeatureNameAnalyzable(feature)) + __testlib_fail("Feature name '" + feature + "' contains restricted characters."); + + if (!_features.count(feature)) + __testlib_fail("Feature " + feature + " didn't registered via addFeature(feature)."); + + _hitFeatures.insert(feature); + } +} validator; + +const std::string Validator::TEST_MARKUP_HEADER = "MU\xF3\x01"; +const std::string Validator::TEST_CASE_OPEN_TAG = "!c"; +const std::string Validator::TEST_CASE_CLOSE_TAG = ";"; + +struct TestlibFinalizeGuard { + static bool alive; + static bool registered; + + int quitCount, readEofCount; + + TestlibFinalizeGuard() : quitCount(0), readEofCount(0) { + // No operations. + } + + ~TestlibFinalizeGuard() { + bool _alive = alive; + alive = false; + + if (_alive) { + if (testlibMode == _checker && quitCount == 0) + __testlib_fail("Checker must end with quit or quitf call."); + + if (testlibMode == _validator && readEofCount == 0 && quitCount == 0) + __testlib_fail("Validator must end with readEof call."); + + /* opts */ + autoEnsureNoUnusedOpts(); + + if (!registered) + __testlib_fail("Call register-function in the first line of the main (registerTestlibCmd or other similar)"); + } + + if (__testlib_exitCode == 0) { + validator.writeTestOverviewLog(); + validator.writeTestMarkup(); + validator.writeTestCase(); + } + } + +private: + /* opts */ + void autoEnsureNoUnusedOpts(); +}; + +bool TestlibFinalizeGuard::alive = true; +bool TestlibFinalizeGuard::registered = false; +extern TestlibFinalizeGuard testlibFinalizeGuard; + +/* + * Call it to disable checks on finalization. + */ +void disableFinalizeGuard() { + TestlibFinalizeGuard::alive = false; +} + +/* Interactor streams. + */ +std::fstream tout; + +/* implementation + */ + +InStream::InStream() { + reader = NULL; + lastLine = -1; + opened = false; + name = ""; + mode = _input; + strict = false; + stdfile = false; + wordReserveSize = 4; + readManyIteration = NO_INDEX; + maxFileSize = 128 * 1024 * 1024; // 128MB. + maxTokenLength = 32 * 1024 * 1024; // 32MB. + maxMessageLength = 32000; +} + +InStream::InStream(const InStream &baseStream, std::string content) { + reader = new StringInputStreamReader(content); + lastLine = -1; + opened = true; + strict = baseStream.strict; + stdfile = false; + mode = baseStream.mode; + name = "based on " + baseStream.name; + readManyIteration = NO_INDEX; + maxFileSize = 128 * 1024 * 1024; // 128MB. + maxTokenLength = 32 * 1024 * 1024; // 32MB. + maxMessageLength = 32000; +} + +InStream::~InStream() { + if (NULL != reader) { + reader->close(); + delete reader; + reader = NULL; + } +} + +void InStream::setTestCase(int testCase) { + if (testlibMode != _validator || mode != _input || !stdfile || this != &inf) + __testlib_fail("InStream::setTestCase can be used only for inf in validator-mode." + " Actually, prefer setTestCase function instead of InStream member"); + reader->setTestCase(testCase); +} + +std::vector InStream::getReadChars() { + if (testlibMode != _validator || mode != _input || !stdfile || this != &inf) + __testlib_fail("InStream::getReadChars can be used only for inf in validator-mode."); + return reader == NULL ? std::vector() : reader->getReadChars(); +} + +void setTestCase(int testCase) { + static bool first_run = true; + static bool zero_based = false; + + if (first_run && testCase == 0) + zero_based = true; + + if (zero_based) + testCase++; + + __testlib_hasTestCase = true; + __testlib_testCase = testCase; + + if (testlibMode == _validator) + inf.setTestCase(testCase); + + first_run = false; +} + +#ifdef __GNUC__ +__attribute__((const)) +#endif +int resultExitCode(TResult r) { + if (r == _ok) + return OK_EXIT_CODE; + if (r == _wa) + return WA_EXIT_CODE; + if (r == _pe) + return PE_EXIT_CODE; + if (r == _fail) + return FAIL_EXIT_CODE; + if (r == _dirt) + return DIRT_EXIT_CODE; + if (r == _points) + return POINTS_EXIT_CODE; + if (r == _unexpected_eof) +#ifdef ENABLE_UNEXPECTED_EOF + return UNEXPECTED_EOF_EXIT_CODE; +#else + return PE_EXIT_CODE; +#endif + if (r >= _partially) + return PC_BASE_EXIT_CODE + (r - _partially); + return FAIL_EXIT_CODE; +} + +void InStream::textColor( +#if !(defined(ON_WINDOWS) && (!defined(_MSC_VER) || _MSC_VER > 1400)) && defined(__GNUC__) + __attribute__((unused)) +#endif + WORD color +) { +#if defined(ON_WINDOWS) && (!defined(_MSC_VER) || _MSC_VER > 1400) + HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE); + SetConsoleTextAttribute(handle, color); +#endif +#if !defined(ON_WINDOWS) && defined(__GNUC__) + if (isatty(2)) + { + switch (color) + { + case LightRed: + fprintf(stderr, "\033[1;31m"); + break; + case LightCyan: + fprintf(stderr, "\033[1;36m"); + break; + case LightGreen: + fprintf(stderr, "\033[1;32m"); + break; + case LightYellow: + fprintf(stderr, "\033[1;33m"); + break; + case LightGray: + default: + fprintf(stderr, "\033[0m"); + } + } +#endif +} + +#ifdef TESTLIB_THROW_EXIT_EXCEPTION_INSTEAD_OF_EXIT +class exit_exception: public std::exception { +private: + int exitCode; +public: + exit_exception(int exitCode): exitCode(exitCode) {} + int getExitCode() { return exitCode; } +}; +#endif + +NORETURN void halt(int exitCode) { +#ifdef FOOTER + InStream::textColor(InStream::LightGray); + std::fprintf(stderr, "Checker: \"%s\"\n", checkerName.c_str()); + std::fprintf(stderr, "Exit code: %d\n", exitCode); + InStream::textColor(InStream::LightGray); +#endif + __testlib_exitCode = exitCode; +#ifdef TESTLIB_THROW_EXIT_EXCEPTION_INSTEAD_OF_EXIT + throw exit_exception(exitCode); +#endif + std::exit(exitCode); +} + +static bool __testlib_shouldCheckDirt(TResult result) { + return result == _ok || result == _points || result >= _partially; +} + +static std::string __testlib_appendMessage(const std::string &message, const std::string &extra) { + int openPos = -1, closePos = -1; + for (size_t i = 0; i < message.length(); i++) { + if (message[i] == InStream::OPEN_BRACKET) { + if (openPos == -1) + openPos = int(i); + else + openPos = INT_MAX; + } + if (message[i] == InStream::CLOSE_BRACKET) { + if (closePos == -1) + closePos = int(i); + else + closePos = INT_MAX; + } + } + if (openPos != -1 && openPos != INT_MAX + && closePos != -1 && closePos != INT_MAX + && openPos < closePos) { + size_t index = message.find(extra, openPos); + if (index == std::string::npos || int(index) >= closePos) { + std::string result(message); + result.insert(closePos, ", " + extra); + return result; + } + return message; + } + + return message + " " + InStream::OPEN_BRACKET + extra + InStream::CLOSE_BRACKET; +} + +static std::string __testlib_toPrintableMessage(const std::string &message) { + int openPos = -1, closePos = -1; + for (size_t i = 0; i < message.length(); i++) { + if (message[i] == InStream::OPEN_BRACKET) { + if (openPos == -1) + openPos = int(i); + else + openPos = INT_MAX; + } + if (message[i] == InStream::CLOSE_BRACKET) { + if (closePos == -1) + closePos = int(i); + else + closePos = INT_MAX; + } + } + if (openPos != -1 && openPos != INT_MAX + && closePos != -1 && closePos != INT_MAX + && openPos < closePos) { + std::string result(message); + result[openPos] = '('; + result[closePos] = ')'; + return result; + } + + return message; +} + +NORETURN void InStream::quit(TResult result, const char *msg) { + if (TestlibFinalizeGuard::alive) + testlibFinalizeGuard.quitCount++; + + std::string message(msg); + message = trim(message); + + if (__testlib_hasTestCase) { + if (result != _ok) + message = __testlib_appendMessage(message, "test case " + vtos(__testlib_testCase)); + else { + if (__testlib_testCase == 1) + message = __testlib_appendMessage(message, vtos(__testlib_testCase) + " test case"); + else + message = __testlib_appendMessage(message, vtos(__testlib_testCase) + " test cases"); + } + } + + // You can change maxMessageLength. + // Example: 'inf.maxMessageLength = 1024 * 1024;'. + if (message.length() > maxMessageLength) { + std::string warn = "message length exceeds " + vtos(maxMessageLength) + + ", the message is truncated: "; + message = warn + message.substr(0, maxMessageLength - warn.length()); + } + +#ifndef ENABLE_UNEXPECTED_EOF + if (result == _unexpected_eof) + result = _pe; +#endif + + if (testlibMode == _scorer && result != _fail) + quits(_fail, "Scorer should return points only. Don't use a quit function."); + + if (mode != _output && result != _fail) { + if (mode == _input && testlibMode == _validator && lastLine != -1) + quits(_fail, __testlib_appendMessage(__testlib_appendMessage(message, name), "line " + vtos(lastLine))); + else + quits(_fail, __testlib_appendMessage(message, name)); + } + + std::FILE *resultFile; + std::string errorName; + + if (__testlib_shouldCheckDirt(result)) { + if (testlibMode != _interactor && !ouf.seekEof()) + quit(_dirt, "Extra information in the output file"); + } + + int pctype = result - _partially; + bool isPartial = false; + + switch (result) { + case _ok: + errorName = "ok "; + quitscrS(LightGreen, errorName); + break; + case _wa: + errorName = "wrong answer "; + quitscrS(LightRed, errorName); + break; + case _pe: + errorName = "wrong output format "; + quitscrS(LightRed, errorName); + break; + case _fail: + errorName = "FAIL "; + quitscrS(LightRed, errorName); + break; + case _dirt: + errorName = "wrong output format "; + quitscrS(LightCyan, errorName); + result = _pe; + break; + case _points: + errorName = "points "; + quitscrS(LightYellow, errorName); + break; + case _unexpected_eof: + errorName = "unexpected eof "; + quitscrS(LightCyan, errorName); + break; + default: + if (result >= _partially) { + errorName = format("partially correct (%d) ", pctype); + isPartial = true; + quitscrS(LightYellow, errorName); + } else + quit(_fail, "What is the code ??? "); + } + + if (resultName != "") { + resultFile = std::fopen(resultName.c_str(), "w"); + if (resultFile == NULL) { + resultName = ""; + quit(_fail, "Can not write to the result file"); + } + if (appesMode) { + std::fprintf(resultFile, ""); + if (isPartial) + std::fprintf(resultFile, "", + outcomes[(int) _partially].c_str(), pctype); + else { + if (result != _points) + std::fprintf(resultFile, "", outcomes[(int) result].c_str()); + else { + if (__testlib_points == std::numeric_limits::infinity()) + quit(_fail, "Expected points, but infinity found"); + std::string stringPoints = removeDoubleTrailingZeroes(format("%.10f", __testlib_points)); + std::fprintf(resultFile, "", + outcomes[(int) result].c_str(), stringPoints.c_str()); + } + } + xmlSafeWrite(resultFile, __testlib_toPrintableMessage(message).c_str()); + std::fprintf(resultFile, "\n"); + } else + std::fprintf(resultFile, "%s", __testlib_toPrintableMessage(message).c_str()); + if (NULL == resultFile || fclose(resultFile) != 0) { + resultName = ""; + quit(_fail, "Can not write to the result file"); + } + } + + quitscr(LightGray, __testlib_toPrintableMessage(message).c_str()); + std::fprintf(stderr, "\n"); + + inf.close(); + ouf.close(); + ans.close(); + if (tout.is_open()) + tout.close(); + + textColor(LightGray); + + if (resultName != "") + std::fprintf(stderr, "See file to check exit message\n"); + + halt(resultExitCode(result)); +} + +#ifdef __GNUC__ +__attribute__ ((format (printf, 3, 4))) +#endif +NORETURN void InStream::quitf(TResult result, const char *msg, ...) { + FMT_TO_RESULT(msg, msg, message); + InStream::quit(result, message.c_str()); +} + +#ifdef __GNUC__ +__attribute__ ((format (printf, 4, 5))) +#endif +void InStream::quitif(bool condition, TResult result, const char *msg, ...) { + if (condition) { + FMT_TO_RESULT(msg, msg, message); + InStream::quit(result, message.c_str()); + } +} + +NORETURN void InStream::quits(TResult result, std::string msg) { + InStream::quit(result, msg.c_str()); +} + +void InStream::xmlSafeWrite(std::FILE *file, const char *msg) { + size_t lmsg = strlen(msg); + for (size_t i = 0; i < lmsg; i++) { + if (msg[i] == '&') { + std::fprintf(file, "%s", "&"); + continue; + } + if (msg[i] == '<') { + std::fprintf(file, "%s", "<"); + continue; + } + if (msg[i] == '>') { + std::fprintf(file, "%s", ">"); + continue; + } + if (msg[i] == '"') { + std::fprintf(file, "%s", """); + continue; + } + if (0 <= msg[i] && msg[i] <= 31) { + std::fprintf(file, "%c", '.'); + continue; + } + std::fprintf(file, "%c", msg[i]); + } +} + +void InStream::quitscrS(WORD color, std::string msg) { + quitscr(color, msg.c_str()); +} + +void InStream::quitscr(WORD color, const char *msg) { + if (resultName == "") { + textColor(color); + std::fprintf(stderr, "%s", msg); + textColor(LightGray); + } +} + +void InStream::reset(std::FILE *file) { + if (opened && stdfile) + quit(_fail, "Can't reset standard handle"); + + if (opened) + close(); + + if (!stdfile && NULL == file) + if (NULL == (file = std::fopen(name.c_str(), "rb"))) { + if (mode == _output) + quits(_pe, std::string("Output file not found: \"") + name + "\""); + + if (mode == _answer) + quits(_fail, std::string("Answer file not found: \"") + name + "\""); + } + + if (NULL != file) { + opened = true; + __testlib_set_binary(file); + + if (stdfile) + reader = new FileInputStreamReader(file, name); + else + reader = new BufferedFileInputStreamReader(file, name); + } else { + opened = false; + reader = NULL; + } +} + +void InStream::init(std::string fileName, TMode mode) { + opened = false; + name = fileName; + stdfile = false; + this->mode = mode; + + std::ifstream stream; + stream.open(fileName.c_str(), std::ios::in); + if (stream.is_open()) { + std::streampos start = stream.tellg(); + stream.seekg(0, std::ios::end); + std::streampos end = stream.tellg(); + size_t fileSize = size_t(end - start); + stream.close(); + + // You can change maxFileSize. + // Example: 'inf.maxFileSize = 256 * 1024 * 1024;'. + if (fileSize > maxFileSize) + quitf(_pe, "File size exceeds %d bytes, size is %d", int(maxFileSize), int(fileSize)); + } + + reset(); +} + +void InStream::init(std::FILE *f, TMode mode) { + opened = false; + name = "untitled"; + this->mode = mode; + + if (f == stdin) + name = "stdin", stdfile = true; + if (f == stdout) + name = "stdout", stdfile = true; + if (f == stderr) + name = "stderr", stdfile = true; + + reset(f); +} + +void InStream::skipBom() { + const std::string utf8Bom = "\xEF\xBB\xBF"; + size_t index = 0; + while (index < utf8Bom.size() && curChar() == utf8Bom[index]) { + index++; + skipChar(); + } + if (index < utf8Bom.size()) { + while (index != 0) { + unreadChar(utf8Bom[index - 1]); + index--; + } + } +} + +char InStream::curChar() { + return char(reader->curChar()); +} + +char InStream::nextChar() { + return char(reader->nextChar()); +} + +char InStream::readChar() { + return nextChar(); +} + +char InStream::readChar(char c) { + lastLine = reader->getLine(); + char found = readChar(); + if (c != found) { + if (!isEoln(found)) + quit(_pe, ("Unexpected character '" + std::string(1, found) + "', but '" + std::string(1, c) + + "' expected").c_str()); + else + quit(_pe, ("Unexpected character " + ("#" + vtos(int(found))) + ", but '" + std::string(1, c) + + "' expected").c_str()); + } + return found; +} + +char InStream::readSpace() { + return readChar(' '); +} + +void InStream::unreadChar(char c) { + reader->unreadChar(c); +} + +void InStream::skipChar() { + reader->skipChar(); +} + +void InStream::skipBlanks() { + while (isBlanks(reader->curChar())) + reader->skipChar(); +} + +std::string InStream::readWord() { + readWordTo(_tmpReadToken); + return _tmpReadToken; +} + +void InStream::readWordTo(std::string &result) { + if (!strict) + skipBlanks(); + + lastLine = reader->getLine(); + int cur = reader->nextChar(); + + if (cur == EOFC) + quit(_unexpected_eof, "Unexpected end of file - token expected"); + + if (isBlanks(cur)) + quit(_pe, "Unexpected white-space - token expected"); + + result.clear(); + + while (!(isBlanks(cur) || cur == EOFC)) { + result += char(cur); + + // You can change maxTokenLength. + // Example: 'inf.maxTokenLength = 128 * 1024 * 1024;'. + if (result.length() > maxTokenLength) + quitf(_pe, "Length of token exceeds %d, token is '%s...'", int(maxTokenLength), + __testlib_part(result).c_str()); + + cur = reader->nextChar(); + } + + reader->unreadChar(cur); + + if (result.length() == 0) + quit(_unexpected_eof, "Unexpected end of file or white-space - token expected"); +} + +std::string InStream::readToken() { + return readWord(); +} + +void InStream::readTokenTo(std::string &result) { + readWordTo(result); +} + +static std::string __testlib_part(const std::string &s) { + std::string t; + for (size_t i = 0; i < s.length(); i++) + if (s[i] != '\0') + t += s[i]; + else + t += '~'; + if (t.length() <= 64) + return t; + else + return t.substr(0, 30) + "..." + t.substr(s.length() - 31, 31); +} + +#define __testlib_readMany(readMany, readOne, typeName, space) \ + if (size < 0) \ + quit(_fail, #readMany ": size should be non-negative."); \ + if (size > 100000000) \ + quit(_fail, #readMany ": size should be at most 100000000."); \ + \ + std::vector result(size); \ + readManyIteration = indexBase; \ + \ + for (int i = 0; i < size; i++) \ + { \ + result[i] = readOne; \ + readManyIteration++; \ + if (strict && space && i + 1 < size) \ + readSpace(); \ + } \ + \ + readManyIteration = NO_INDEX; \ + return result; \ + + +std::string InStream::readWord(const pattern &p, const std::string &variableName) { + readWordTo(_tmpReadToken); + if (!p.matches(_tmpReadToken)) { + if (readManyIteration == NO_INDEX) { + if (variableName.empty()) + quit(_wa, + ("Token \"" + __testlib_part(_tmpReadToken) + "\" doesn't correspond to pattern \"" + p.src() + + "\"").c_str()); + else + quit(_wa, ("Token parameter [name=" + variableName + "] equals to \"" + __testlib_part(_tmpReadToken) + + "\", doesn't correspond to pattern \"" + p.src() + "\"").c_str()); + } else { + if (variableName.empty()) + quit(_wa, ("Token element [index=" + vtos(readManyIteration) + "] equals to \"" + + __testlib_part(_tmpReadToken) + "\" doesn't correspond to pattern \"" + p.src() + + "\"").c_str()); + else + quit(_wa, ("Token element " + variableName + "[" + vtos(readManyIteration) + "] equals to \"" + + __testlib_part(_tmpReadToken) + "\", doesn't correspond to pattern \"" + p.src() + + "\"").c_str()); + } + } + return _tmpReadToken; +} + +std::vector +InStream::readWords(int size, const pattern &p, const std::string &variablesName, int indexBase) { + __testlib_readMany(readWords, readWord(p, variablesName), std::string, true); +} + +std::vector InStream::readWords(int size, int indexBase) { + __testlib_readMany(readWords, readWord(), std::string, true); +} + +std::string InStream::readWord(const std::string &ptrn, const std::string &variableName) { + return readWord(pattern(ptrn), variableName); +} + +std::vector +InStream::readWords(int size, const std::string &ptrn, const std::string &variablesName, int indexBase) { + pattern p(ptrn); + __testlib_readMany(readWords, readWord(p, variablesName), std::string, true); +} + +std::string InStream::readToken(const pattern &p, const std::string &variableName) { + return readWord(p, variableName); +} + +std::vector +InStream::readTokens(int size, const pattern &p, const std::string &variablesName, int indexBase) { + __testlib_readMany(readTokens, readToken(p, variablesName), std::string, true); +} + +std::vector InStream::readTokens(int size, int indexBase) { + __testlib_readMany(readTokens, readToken(), std::string, true); +} + +std::string InStream::readToken(const std::string &ptrn, const std::string &variableName) { + return readWord(ptrn, variableName); +} + +std::vector +InStream::readTokens(int size, const std::string &ptrn, const std::string &variablesName, int indexBase) { + pattern p(ptrn); + __testlib_readMany(readTokens, readWord(p, variablesName), std::string, true); +} + +void InStream::readWordTo(std::string &result, const pattern &p, const std::string &variableName) { + readWordTo(result); + if (!p.matches(result)) { + if (variableName.empty()) + quit(_wa, ("Token \"" + __testlib_part(result) + "\" doesn't correspond to pattern \"" + p.src() + + "\"").c_str()); + else + quit(_wa, ("Token parameter [name=" + variableName + "] equals to \"" + __testlib_part(result) + + "\", doesn't correspond to pattern \"" + p.src() + "\"").c_str()); + } +} + +void InStream::readWordTo(std::string &result, const std::string &ptrn, const std::string &variableName) { + return readWordTo(result, pattern(ptrn), variableName); +} + +void InStream::readTokenTo(std::string &result, const pattern &p, const std::string &variableName) { + return readWordTo(result, p, variableName); +} + +void InStream::readTokenTo(std::string &result, const std::string &ptrn, const std::string &variableName) { + return readWordTo(result, ptrn, variableName); +} + +#ifdef __GNUC__ +__attribute__((pure)) +#endif +static inline bool equals(long long integer, const char *s) { + if (integer == LLONG_MIN) + return strcmp(s, "-9223372036854775808") == 0; + + if (integer == 0LL) + return strcmp(s, "0") == 0; + + size_t length = strlen(s); + + if (length == 0) + return false; + + if (integer < 0 && s[0] != '-') + return false; + + if (integer < 0) + s++, length--, integer = -integer; + + if (length == 0) + return false; + + while (integer > 0) { + int digit = int(integer % 10); + + if (s[length - 1] != '0' + digit) + return false; + + length--; + integer /= 10; + } + + return length == 0; +} + +#ifdef __GNUC__ +__attribute__((pure)) +#endif +static inline bool equals(unsigned long long integer, const char *s) { + if (integer == ULLONG_MAX) + return strcmp(s, "18446744073709551615") == 0; + + if (integer == 0ULL) + return strcmp(s, "0") == 0; + + size_t length = strlen(s); + + if (length == 0) + return false; + + while (integer > 0) { + int digit = int(integer % 10); + + if (s[length - 1] != '0' + digit) + return false; + + length--; + integer /= 10; + } + + return length == 0; +} + +static inline double stringToDouble(InStream &in, const char *buffer) { + double retval; + + size_t length = strlen(buffer); + + int minusCount = 0; + int plusCount = 0; + int decimalPointCount = 0; + int digitCount = 0; + int eCount = 0; + + for (size_t i = 0; i < length; i++) { + if (('0' <= buffer[i] && buffer[i] <= '9') || buffer[i] == '.' + || buffer[i] == 'e' || buffer[i] == 'E' + || buffer[i] == '-' || buffer[i] == '+') { + if ('0' <= buffer[i] && buffer[i] <= '9') + digitCount++; + if (buffer[i] == 'e' || buffer[i] == 'E') + eCount++; + if (buffer[i] == '-') + minusCount++; + if (buffer[i] == '+') + plusCount++; + if (buffer[i] == '.') + decimalPointCount++; + } else + in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str()); + } + + // If for sure is not a number in standard notation or in e-notation. + if (digitCount == 0 || minusCount > 2 || plusCount > 2 || decimalPointCount > 1 || eCount > 1) + in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str()); + + char *suffix = new char[length + 1]; + std::memset(suffix, 0, length + 1); + int scanned = std::sscanf(buffer, "%lf%s", &retval, suffix); + bool empty = strlen(suffix) == 0; + delete[] suffix; + + if (scanned == 1 || (scanned == 2 && empty)) { + if (__testlib_isNaN(retval)) + in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str()); + return retval; + } else + in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str()); +} + +static inline double stringToDouble(InStream &in, const std::string& buffer) { + for (size_t i = 0; i < buffer.length(); i++) + if (buffer[i] == '\0') + in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found (it contains \\0)").c_str()); + return stringToDouble(in, buffer.c_str()); +} + +static inline double stringToStrictDouble(InStream &in, const char *buffer, + int minAfterPointDigitCount, int maxAfterPointDigitCount) { + if (minAfterPointDigitCount < 0) + in.quit(_fail, "stringToStrictDouble: minAfterPointDigitCount should be non-negative."); + + if (minAfterPointDigitCount > maxAfterPointDigitCount) + in.quit(_fail, + "stringToStrictDouble: minAfterPointDigitCount should be less or equal to maxAfterPointDigitCount."); + + double retval; + + size_t length = strlen(buffer); + + if (length == 0 || length > 1000) + in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str()); + + if (buffer[0] != '-' && (buffer[0] < '0' || buffer[0] > '9')) + in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str()); + + int pointPos = -1; + for (size_t i = 1; i + 1 < length; i++) { + if (buffer[i] == '.') { + if (pointPos > -1) + in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str()); + pointPos = int(i); + } + if (buffer[i] != '.' && (buffer[i] < '0' || buffer[i] > '9')) + in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str()); + } + + if (buffer[length - 1] < '0' || buffer[length - 1] > '9') + in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str()); + + int afterDigitsCount = (pointPos == -1 ? 0 : int(length) - pointPos - 1); + if (afterDigitsCount < minAfterPointDigitCount || afterDigitsCount > maxAfterPointDigitCount) + in.quit(_pe, ("Expected strict double with number of digits after point in range [" + + vtos(minAfterPointDigitCount) + + "," + + vtos(maxAfterPointDigitCount) + + "], but \"" + __testlib_part(buffer) + "\" found").c_str() + ); + + int firstDigitPos = -1; + for (size_t i = 0; i < length; i++) + if (buffer[i] >= '0' && buffer[i] <= '9') { + firstDigitPos = int(i); + break; + } + + if (firstDigitPos > 1 || firstDigitPos == -1) + in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str()); + + if (buffer[firstDigitPos] == '0' && firstDigitPos + 1 < int(length) + && buffer[firstDigitPos + 1] >= '0' && buffer[firstDigitPos + 1] <= '9') + in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str()); + + char *suffix = new char[length + 1]; + std::memset(suffix, 0, length + 1); + int scanned = std::sscanf(buffer, "%lf%s", &retval, suffix); + bool empty = strlen(suffix) == 0; + delete[] suffix; + + if (scanned == 1 || (scanned == 2 && empty)) { + if (__testlib_isNaN(retval) || __testlib_isInfinite(retval)) + in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str()); + if (buffer[0] == '-' && retval >= 0) + in.quit(_pe, ("Redundant minus in \"" + __testlib_part(buffer) + "\" found").c_str()); + return retval; + } else + in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str()); +} + +static inline double stringToStrictDouble(InStream &in, const std::string& buffer, + int minAfterPointDigitCount, int maxAfterPointDigitCount) { + for (size_t i = 0; i < buffer.length(); i++) + if (buffer[i] == '\0') + in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found (it contains \\0)").c_str()); + return stringToStrictDouble(in, buffer.c_str(), minAfterPointDigitCount, maxAfterPointDigitCount); +} + +static inline long long stringToLongLong(InStream &in, const char *buffer) { + if (strcmp(buffer, "-9223372036854775808") == 0) + return LLONG_MIN; + + bool minus = false; + size_t length = strlen(buffer); + + if (length > 1 && buffer[0] == '-') + minus = true; + + if (length > 20) + in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str()); + + long long retval = 0LL; + + int zeroes = 0; + bool processingZeroes = true; + + for (int i = (minus ? 1 : 0); i < int(length); i++) { + if (buffer[i] == '0' && processingZeroes) + zeroes++; + else + processingZeroes = false; + + if (buffer[i] < '0' || buffer[i] > '9') + in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str()); + retval = retval * 10 + (buffer[i] - '0'); + } + + if (retval < 0) + in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str()); + + if ((zeroes > 0 && (retval != 0 || minus)) || zeroes > 1) + in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str()); + + retval = (minus ? -retval : +retval); + + if (length < 19) + return retval; + + if (equals(retval, buffer)) + return retval; + else + in.quit(_pe, ("Expected int64, but \"" + __testlib_part(buffer) + "\" found").c_str()); +} + +static inline long long stringToLongLong(InStream &in, const std::string& buffer) { + for (size_t i = 0; i < buffer.length(); i++) + if (buffer[i] == '\0') + in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found (it contains \\0)").c_str()); + return stringToLongLong(in, buffer.c_str()); +} + +static inline unsigned long long stringToUnsignedLongLong(InStream &in, const char *buffer) { + size_t length = strlen(buffer); + + if (length > 20) + in.quit(_pe, ("Expected unsigned integer, but \"" + __testlib_part(buffer) + "\" found").c_str()); + if (length > 1 && buffer[0] == '0') + in.quit(_pe, ("Expected unsigned integer, but \"" + __testlib_part(buffer) + "\" found").c_str()); + + unsigned long long retval = 0LL; + for (int i = 0; i < int(length); i++) { + if (buffer[i] < '0' || buffer[i] > '9') + in.quit(_pe, ("Expected unsigned integer, but \"" + __testlib_part(buffer) + "\" found").c_str()); + retval = retval * 10 + (buffer[i] - '0'); + } + + if (length < 19) + return retval; + + if (length == 20 && strcmp(buffer, "18446744073709551615") > 0) + in.quit(_pe, ("Expected unsigned int64, but \"" + __testlib_part(buffer) + "\" found").c_str()); + + if (equals(retval, buffer)) + return retval; + else + in.quit(_pe, ("Expected unsigned int64, but \"" + __testlib_part(buffer) + "\" found").c_str()); +} + +static inline long long stringToUnsignedLongLong(InStream &in, const std::string& buffer) { + for (size_t i = 0; i < buffer.length(); i++) + if (buffer[i] == '\0') + in.quit(_pe, ("Expected unsigned integer, but \"" + __testlib_part(buffer) + "\" found (it contains \\0)").c_str()); + return stringToUnsignedLongLong(in, buffer.c_str()); +} + +int InStream::readInteger() { + if (!strict && seekEof()) + quit(_unexpected_eof, "Unexpected end of file - int32 expected"); + + readWordTo(_tmpReadToken); + + long long value = stringToLongLong(*this, _tmpReadToken); + if (value < INT_MIN || value > INT_MAX) + quit(_pe, ("Expected int32, but \"" + __testlib_part(_tmpReadToken) + "\" found").c_str()); + + return int(value); +} + +long long InStream::readLong() { + if (!strict && seekEof()) + quit(_unexpected_eof, "Unexpected end of file - int64 expected"); + + readWordTo(_tmpReadToken); + + return stringToLongLong(*this, _tmpReadToken); +} + +unsigned long long InStream::readUnsignedLong() { + if (!strict && seekEof()) + quit(_unexpected_eof, "Unexpected end of file - int64 expected"); + + readWordTo(_tmpReadToken); + + return stringToUnsignedLongLong(*this, _tmpReadToken); +} + +long long InStream::readLong(long long minv, long long maxv, const std::string &variableName) { + long long result = readLong(); + + if (result < minv || result > maxv) { + if (readManyIteration == NO_INDEX) { + if (variableName.empty()) + quit(_wa, ("Integer " + vtos(result) + " violates the range [" + toHumanReadableString(minv) + ", " + toHumanReadableString(maxv) + + "]").c_str()); + else + quit(_wa, ("Integer parameter [name=" + std::string(variableName) + "] equals to " + vtos(result) + + ", violates the range [" + toHumanReadableString(minv) + ", " + toHumanReadableString(maxv) + "]").c_str()); + } else { + if (variableName.empty()) + quit(_wa, ("Integer element [index=" + vtos(readManyIteration) + "] equals to " + vtos(result) + + ", violates the range [" + toHumanReadableString(minv) + ", " + toHumanReadableString(maxv) + "]").c_str()); + else + quit(_wa, + ("Integer element " + std::string(variableName) + "[" + vtos(readManyIteration) + "] equals to " + + vtos(result) + ", violates the range [" + toHumanReadableString(minv) + ", " + toHumanReadableString(maxv) + "]").c_str()); + } + } + + if (strict && !variableName.empty()) + validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result)); + + return result; +} + +std::vector +InStream::readLongs(int size, long long minv, long long maxv, const std::string &variablesName, int indexBase) { + __testlib_readMany(readLongs, readLong(minv, maxv, variablesName), long long, true) +} + +std::vector InStream::readLongs(int size, int indexBase) { + __testlib_readMany(readLongs, readLong(), long long, true) +} + +unsigned long long +InStream::readUnsignedLong(unsigned long long minv, unsigned long long maxv, const std::string &variableName) { + unsigned long long result = readUnsignedLong(); + + if (result < minv || result > maxv) { + if (readManyIteration == NO_INDEX) { + if (variableName.empty()) + quit(_wa, + ("Unsigned integer " + vtos(result) + " violates the range [" + toHumanReadableString(minv) + ", " + toHumanReadableString(maxv) + + "]").c_str()); + else + quit(_wa, + ("Unsigned integer parameter [name=" + std::string(variableName) + "] equals to " + vtos(result) + + ", violates the range [" + toHumanReadableString(minv) + ", " + toHumanReadableString(maxv) + "]").c_str()); + } else { + if (variableName.empty()) + quit(_wa, + ("Unsigned integer element [index=" + vtos(readManyIteration) + "] equals to " + vtos(result) + + ", violates the range [" + toHumanReadableString(minv) + ", " + toHumanReadableString(maxv) + "]").c_str()); + else + quit(_wa, ("Unsigned integer element " + std::string(variableName) + "[" + vtos(readManyIteration) + + "] equals to " + vtos(result) + ", violates the range [" + toHumanReadableString(minv) + ", " + toHumanReadableString(maxv) + + "]").c_str()); + } + } + + if (strict && !variableName.empty()) + validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result)); + + return result; +} + +std::vector InStream::readUnsignedLongs(int size, unsigned long long minv, unsigned long long maxv, + const std::string &variablesName, int indexBase) { + __testlib_readMany(readUnsignedLongs, readUnsignedLong(minv, maxv, variablesName), unsigned long long, true) +} + +std::vector InStream::readUnsignedLongs(int size, int indexBase) { + __testlib_readMany(readUnsignedLongs, readUnsignedLong(), unsigned long long, true) +} + +unsigned long long +InStream::readLong(unsigned long long minv, unsigned long long maxv, const std::string &variableName) { + return readUnsignedLong(minv, maxv, variableName); +} + +int InStream::readInt() { + return readInteger(); +} + +int InStream::readInt(int minv, int maxv, const std::string &variableName) { + int result = readInt(); + + if (result < minv || result > maxv) { + if (readManyIteration == NO_INDEX) { + if (variableName.empty()) + quit(_wa, ("Integer " + vtos(result) + " violates the range [" + toHumanReadableString(minv) + ", " + toHumanReadableString(maxv) + + "]").c_str()); + else + quit(_wa, ("Integer parameter [name=" + std::string(variableName) + "] equals to " + vtos(result) + + ", violates the range [" + toHumanReadableString(minv) + ", " + toHumanReadableString(maxv) + "]").c_str()); + } else { + if (variableName.empty()) + quit(_wa, ("Integer element [index=" + vtos(readManyIteration) + "] equals to " + vtos(result) + + ", violates the range [" + toHumanReadableString(minv) + ", " + toHumanReadableString(maxv) + "]").c_str()); + else + quit(_wa, + ("Integer element " + std::string(variableName) + "[" + vtos(readManyIteration) + "] equals to " + + vtos(result) + ", violates the range [" + toHumanReadableString(minv) + ", " + toHumanReadableString(maxv) + "]").c_str()); + } + } + + if (strict && !variableName.empty()) + validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result)); + + return result; +} + +int InStream::readInteger(int minv, int maxv, const std::string &variableName) { + return readInt(minv, maxv, variableName); +} + +std::vector InStream::readInts(int size, int minv, int maxv, const std::string &variablesName, int indexBase) { + __testlib_readMany(readInts, readInt(minv, maxv, variablesName), int, true) +} + +std::vector InStream::readInts(int size, int indexBase) { + __testlib_readMany(readInts, readInt(), int, true) +} + +std::vector InStream::readIntegers(int size, int minv, int maxv, const std::string &variablesName, int indexBase) { + __testlib_readMany(readIntegers, readInt(minv, maxv, variablesName), int, true) +} + +std::vector InStream::readIntegers(int size, int indexBase) { + __testlib_readMany(readIntegers, readInt(), int, true) +} + +double InStream::readReal() { + if (!strict && seekEof()) + quit(_unexpected_eof, "Unexpected end of file - double expected"); + + return stringToDouble(*this, readWord()); +} + +double InStream::readDouble() { + return readReal(); +} + +double InStream::readReal(double minv, double maxv, const std::string &variableName) { + double result = readReal(); + + if (result < minv || result > maxv) { + if (readManyIteration == NO_INDEX) { + if (variableName.empty()) + quit(_wa, ("Double " + vtos(result) + " violates the range [" + vtos(minv) + ", " + vtos(maxv) + + "]").c_str()); + else + quit(_wa, ("Double parameter [name=" + std::string(variableName) + "] equals to " + vtos(result) + + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str()); + } else { + if (variableName.empty()) + quit(_wa, ("Double element [index=" + vtos(readManyIteration) + "] equals to " + vtos(result) + + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str()); + else + quit(_wa, + ("Double element " + std::string(variableName) + "[" + vtos(readManyIteration) + "] equals to " + + vtos(result) + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str()); + } + } + + if (strict && !variableName.empty()) + validator.addBoundsHit(variableName, ValidatorBoundsHit( + doubleDelta(minv, result) < ValidatorBoundsHit::EPS, + doubleDelta(maxv, result) < ValidatorBoundsHit::EPS + )); + + return result; +} + +std::vector +InStream::readReals(int size, double minv, double maxv, const std::string &variablesName, int indexBase) { + __testlib_readMany(readReals, readReal(minv, maxv, variablesName), double, true) +} + +std::vector InStream::readReals(int size, int indexBase) { + __testlib_readMany(readReals, readReal(), double, true) +} + +double InStream::readDouble(double minv, double maxv, const std::string &variableName) { + return readReal(minv, maxv, variableName); +} + +std::vector +InStream::readDoubles(int size, double minv, double maxv, const std::string &variablesName, int indexBase) { + __testlib_readMany(readDoubles, readDouble(minv, maxv, variablesName), double, true) +} + +std::vector InStream::readDoubles(int size, int indexBase) { + __testlib_readMany(readDoubles, readDouble(), double, true) +} + +double InStream::readStrictReal(double minv, double maxv, + int minAfterPointDigitCount, int maxAfterPointDigitCount, + const std::string &variableName) { + if (!strict && seekEof()) + quit(_unexpected_eof, "Unexpected end of file - strict double expected"); + + double result = stringToStrictDouble(*this, readWord(), minAfterPointDigitCount, maxAfterPointDigitCount); + + if (result < minv || result > maxv) { + if (readManyIteration == NO_INDEX) { + if (variableName.empty()) + quit(_wa, ("Strict double " + vtos(result) + " violates the range [" + vtos(minv) + ", " + vtos(maxv) + + "]").c_str()); + else + quit(_wa, + ("Strict double parameter [name=" + std::string(variableName) + "] equals to " + vtos(result) + + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str()); + } else { + if (variableName.empty()) + quit(_wa, ("Strict double element [index=" + vtos(readManyIteration) + "] equals to " + vtos(result) + + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str()); + else + quit(_wa, ("Strict double element " + std::string(variableName) + "[" + vtos(readManyIteration) + + "] equals to " + vtos(result) + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + + "]").c_str()); + } + } + + if (strict && !variableName.empty()) + validator.addBoundsHit(variableName, ValidatorBoundsHit( + doubleDelta(minv, result) < ValidatorBoundsHit::EPS, + doubleDelta(maxv, result) < ValidatorBoundsHit::EPS + )); + + return result; +} + +std::vector InStream::readStrictReals(int size, double minv, double maxv, + int minAfterPointDigitCount, int maxAfterPointDigitCount, + const std::string &variablesName, int indexBase) { + __testlib_readMany(readStrictReals, + readStrictReal(minv, maxv, minAfterPointDigitCount, maxAfterPointDigitCount, variablesName), + double, true) +} + +double InStream::readStrictDouble(double minv, double maxv, + int minAfterPointDigitCount, int maxAfterPointDigitCount, + const std::string &variableName) { + return readStrictReal(minv, maxv, + minAfterPointDigitCount, maxAfterPointDigitCount, + variableName); +} + +std::vector InStream::readStrictDoubles(int size, double minv, double maxv, + int minAfterPointDigitCount, int maxAfterPointDigitCount, + const std::string &variablesName, int indexBase) { + __testlib_readMany(readStrictDoubles, + readStrictDouble(minv, maxv, minAfterPointDigitCount, maxAfterPointDigitCount, variablesName), + double, true) +} + +bool InStream::eof() { + if (!strict && NULL == reader) + return true; + + return reader->eof(); +} + +bool InStream::seekEof() { + if (!strict && NULL == reader) + return true; + skipBlanks(); + return eof(); +} + +bool InStream::eoln() { + if (!strict && NULL == reader) + return true; + + int c = reader->nextChar(); + + if (!strict) { + if (c == EOFC) + return true; + + if (c == CR) { + c = reader->nextChar(); + + if (c != LF) { + reader->unreadChar(c); + reader->unreadChar(CR); + return false; + } else + return true; + } + + if (c == LF) + return true; + + reader->unreadChar(c); + return false; + } else { + bool returnCr = false; + +#if (defined(ON_WINDOWS) && !defined(FOR_LINUX)) || defined(FOR_WINDOWS) + if (c != CR) { + reader->unreadChar(c); + return false; + } else { + if (!returnCr) + returnCr = true; + c = reader->nextChar(); + } +#endif + if (c != LF) { + reader->unreadChar(c); + if (returnCr) + reader->unreadChar(CR); + return false; + } + + return true; + } +} + +void InStream::readEoln() { + lastLine = reader->getLine(); + if (!eoln()) + quit(_pe, "Expected EOLN"); +} + +void InStream::readEof() { + lastLine = reader->getLine(); + if (!eof()) + quit(_pe, "Expected EOF"); + + if (TestlibFinalizeGuard::alive && this == &inf) + testlibFinalizeGuard.readEofCount++; +} + +bool InStream::seekEoln() { + if (!strict && NULL == reader) + return true; + + int cur; + do { + cur = reader->nextChar(); + } while (cur == SPACE || cur == TAB); + + reader->unreadChar(cur); + return eoln(); +} + +void InStream::nextLine() { + readLine(); +} + +void InStream::readStringTo(std::string &result) { + if (NULL == reader) + quit(_pe, "Expected line"); + + result.clear(); + + for (;;) { + int cur = reader->curChar(); + + if (cur == LF || cur == EOFC) + break; + + if (cur == CR) { + cur = reader->nextChar(); + if (reader->curChar() == LF) { + reader->unreadChar(cur); + break; + } + } + + lastLine = reader->getLine(); + result += char(reader->nextChar()); + } + + if (strict) + readEoln(); + else + eoln(); +} + +std::string InStream::readString() { + readStringTo(_tmpReadToken); + return _tmpReadToken; +} + +std::vector InStream::readStrings(int size, int indexBase) { + __testlib_readMany(readStrings, readString(), std::string, false) +} + +void InStream::readStringTo(std::string &result, const pattern &p, const std::string &variableName) { + readStringTo(result); + if (!p.matches(result)) { + if (readManyIteration == NO_INDEX) { + if (variableName.empty()) + quit(_wa, ("Line \"" + __testlib_part(result) + "\" doesn't correspond to pattern \"" + p.src() + + "\"").c_str()); + else + quit(_wa, ("Line [name=" + variableName + "] equals to \"" + __testlib_part(result) + + "\", doesn't correspond to pattern \"" + p.src() + "\"").c_str()); + } else { + if (variableName.empty()) + quit(_wa, + ("Line element [index=" + vtos(readManyIteration) + "] equals to \"" + __testlib_part(result) + + "\" doesn't correspond to pattern \"" + p.src() + "\"").c_str()); + else + quit(_wa, + ("Line element " + std::string(variableName) + "[" + vtos(readManyIteration) + "] equals to \"" + + __testlib_part(result) + "\", doesn't correspond to pattern \"" + p.src() + "\"").c_str()); + } + } +} + +void InStream::readStringTo(std::string &result, const std::string &ptrn, const std::string &variableName) { + readStringTo(result, pattern(ptrn), variableName); +} + +std::string InStream::readString(const pattern &p, const std::string &variableName) { + readStringTo(_tmpReadToken, p, variableName); + return _tmpReadToken; +} + +std::vector +InStream::readStrings(int size, const pattern &p, const std::string &variablesName, int indexBase) { + __testlib_readMany(readStrings, readString(p, variablesName), std::string, false) +} + +std::string InStream::readString(const std::string &ptrn, const std::string &variableName) { + readStringTo(_tmpReadToken, ptrn, variableName); + return _tmpReadToken; +} + +std::vector +InStream::readStrings(int size, const std::string &ptrn, const std::string &variablesName, int indexBase) { + pattern p(ptrn); + __testlib_readMany(readStrings, readString(p, variablesName), std::string, false) +} + +void InStream::readLineTo(std::string &result) { + readStringTo(result); +} + +std::string InStream::readLine() { + return readString(); +} + +std::vector InStream::readLines(int size, int indexBase) { + __testlib_readMany(readLines, readString(), std::string, false) +} + +void InStream::readLineTo(std::string &result, const pattern &p, const std::string &variableName) { + readStringTo(result, p, variableName); +} + +void InStream::readLineTo(std::string &result, const std::string &ptrn, const std::string &variableName) { + readStringTo(result, ptrn, variableName); +} + +std::string InStream::readLine(const pattern &p, const std::string &variableName) { + return readString(p, variableName); +} + +std::vector +InStream::readLines(int size, const pattern &p, const std::string &variablesName, int indexBase) { + __testlib_readMany(readLines, readString(p, variablesName), std::string, false) +} + +std::string InStream::readLine(const std::string &ptrn, const std::string &variableName) { + return readString(ptrn, variableName); +} + +std::vector +InStream::readLines(int size, const std::string &ptrn, const std::string &variablesName, int indexBase) { + pattern p(ptrn); + __testlib_readMany(readLines, readString(p, variablesName), std::string, false) +} + +#ifdef __GNUC__ +__attribute__ ((format (printf, 3, 4))) +#endif +void InStream::ensuref(bool cond, const char *format, ...) { + if (!cond) { + FMT_TO_RESULT(format, format, message); + this->__testlib_ensure(cond, message); + } +} + +void InStream::__testlib_ensure(bool cond, std::string message) { + if (!cond) + this->quit(_wa, message.c_str()); +} + +void InStream::close() { + if (NULL != reader) { + reader->close(); + delete reader; + reader = NULL; + } + + opened = false; +} + +NORETURN void quit(TResult result, const std::string &msg) { + ouf.quit(result, msg.c_str()); +} + +NORETURN void quit(TResult result, const char *msg) { + ouf.quit(result, msg); +} + +NORETURN void __testlib_quitp(double points, const char *message) { + __testlib_points = points; + std::string stringPoints = removeDoubleTrailingZeroes(format("%.10f", points)); + + std::string quitMessage; + if (NULL == message || 0 == strlen(message)) + quitMessage = stringPoints; + else + quitMessage = stringPoints + " " + message; + + quit(_points, quitMessage.c_str()); +} + +NORETURN void __testlib_quitp(int points, const char *message) { + __testlib_points = points; + std::string stringPoints = format("%d", points); + + std::string quitMessage; + if (NULL == message || 0 == strlen(message)) + quitMessage = stringPoints; + else + quitMessage = stringPoints + " " + message; + + quit(_points, quitMessage.c_str()); +} + +NORETURN void quitp(float points, const std::string &message = "") { + __testlib_quitp(double(points), message.c_str()); +} + +NORETURN void quitp(double points, const std::string &message = "") { + __testlib_quitp(points, message.c_str()); +} + +NORETURN void quitp(long double points, const std::string &message = "") { + __testlib_quitp(double(points), message.c_str()); +} + +NORETURN void quitp(int points, const std::string &message = "") { + __testlib_quitp(points, message.c_str()); +} + +NORETURN void quitpi(const std::string &points_info, const std::string &message = "") { + if (points_info.find(' ') != std::string::npos) + quit(_fail, "Parameter 'points_info' can't contain spaces"); + if (message.empty()) + quit(_points, ("points_info=" + points_info).c_str()); + else + quit(_points, ("points_info=" + points_info + " " + message).c_str()); +} + +template +#ifdef __GNUC__ +__attribute__ ((format (printf, 2, 3))) +#endif +NORETURN void quitp(F points, const char *format, ...) { + FMT_TO_RESULT(format, format, message); + quitp(points, message); +} + +#ifdef __GNUC__ +__attribute__ ((format (printf, 2, 3))) +#endif +NORETURN void quitf(TResult result, const char *format, ...) { + FMT_TO_RESULT(format, format, message); + quit(result, message); +} + +#ifdef __GNUC__ +__attribute__ ((format (printf, 3, 4))) +#endif +void quitif(bool condition, TResult result, const char *format, ...) { + if (condition) { + FMT_TO_RESULT(format, format, message); + quit(result, message); + } +} + +NORETURN void __testlib_help() { + InStream::textColor(InStream::LightCyan); + std::fprintf(stderr, "TESTLIB %s, https://github.com/MikeMirzayanov/testlib/ ", VERSION); + std::fprintf(stderr, "by Mike Mirzayanov, copyright(c) 2005-2020\n"); + std::fprintf(stderr, "Checker name: \"%s\"\n", checkerName.c_str()); + InStream::textColor(InStream::LightGray); + + std::fprintf(stderr, "\n"); + std::fprintf(stderr, "Latest features: \n"); + for (size_t i = 0; i < sizeof(latestFeatures) / sizeof(char *); i++) { + std::fprintf(stderr, "*) %s\n", latestFeatures[i]); + } + std::fprintf(stderr, "\n"); + + std::fprintf(stderr, "Program must be run with the following arguments: \n"); + std::fprintf(stderr, " [--testset testset] [--group group] [ [<-appes>]]\n\n"); + + __testlib_exitCode = FAIL_EXIT_CODE; + std::exit(FAIL_EXIT_CODE); +} + +static void __testlib_ensuresPreconditions() { + // testlib assumes: sizeof(int) = 4. + __TESTLIB_STATIC_ASSERT(sizeof(int) == 4); + + // testlib assumes: INT_MAX == 2147483647. + __TESTLIB_STATIC_ASSERT(INT_MAX == 2147483647); + + // testlib assumes: sizeof(long long) = 8. + __TESTLIB_STATIC_ASSERT(sizeof(long long) == 8); + + // testlib assumes: sizeof(double) = 8. + __TESTLIB_STATIC_ASSERT(sizeof(double) == 8); + + // testlib assumes: no -ffast-math. + if (!__testlib_isNaN(+__testlib_nan())) + quit(_fail, "Function __testlib_isNaN is not working correctly: possible reason is '-ffast-math'"); + if (!__testlib_isNaN(-__testlib_nan())) + quit(_fail, "Function __testlib_isNaN is not working correctly: possible reason is '-ffast-math'"); +} + +std::string __testlib_testset; + +std::string getTestset() { + return __testlib_testset; +} + +std::string __testlib_group; + +std::string getGroup() { + return __testlib_group; +} + +static void __testlib_set_testset_and_group(int argc, char* argv[]) { + for (int i = 1; i < argc; i++) { + if (!strcmp("--testset", argv[i])) { + if (i + 1 < argc && strlen(argv[i + 1]) > 0) + __testlib_testset = argv[++i]; + else + quit(_fail, std::string("Expected non-empty testset after --testset command line parameter")); + } else if (!strcmp("--group", argv[i])) { + if (i + 1 < argc) + __testlib_group = argv[++i]; + else + quit(_fail, std::string("Expected group after --group command line parameter")); + } + } +} + +void registerGen(int argc, char *argv[], int randomGeneratorVersion) { + if (randomGeneratorVersion < 0 || randomGeneratorVersion > 1) + quitf(_fail, "Random generator version is expected to be 0 or 1."); + random_t::version = randomGeneratorVersion; + + __testlib_ensuresPreconditions(); + TestlibFinalizeGuard::registered = true; + + testlibMode = _generator; + __testlib_set_binary(stdin); + rnd.setSeed(argc, argv); + +#if __cplusplus > 199711L || defined(_MSC_VER) + prepareOpts(argc, argv); +#endif +} + +#ifdef USE_RND_AS_BEFORE_087 +void registerGen(int argc, char* argv[]) +{ + registerGen(argc, argv, 0); +} +#else +#ifdef __GNUC__ +#if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 4)) +__attribute__ ((deprecated("Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1)." +" The third parameter stands for the random generator version." +" If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0)." +" Version 1 has been released on Spring, 2013. Use it to write new generators."))) +#else +__attribute__ ((deprecated)) +#endif +#endif +#ifdef _MSC_VER +__declspec(deprecated("Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1)." + " The third parameter stands for the random generator version." + " If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0)." + " Version 1 has been released on Spring, 2013. Use it to write new generators.")) +#endif +void registerGen(int argc, char *argv[]) { + std::fprintf(stderr, "Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1)." + " The third parameter stands for the random generator version." + " If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0)." + " Version 1 has been released on Spring, 2013. Use it to write new generators.\n\n"); + registerGen(argc, argv, 0); +} +#endif + +void registerInteraction(int argc, char *argv[]) { + __testlib_ensuresPreconditions(); + __testlib_set_testset_and_group(argc, argv); + TestlibFinalizeGuard::registered = true; + + testlibMode = _interactor; + __testlib_set_binary(stdin); + + if (argc > 1 && !strcmp("--help", argv[1])) + __testlib_help(); + + if (argc < 3 || argc > 6) { + quit(_fail, std::string("Program must be run with the following arguments: ") + + std::string(" [ [ [<-appes>]]]") + + "\nUse \"--help\" to get help information"); + } + + if (argc <= 4) { + resultName = ""; + appesMode = false; + } + +#ifndef EJUDGE + if (argc == 5) { + resultName = argv[4]; + appesMode = false; + } + + if (argc == 6) { + if (strcmp("-APPES", argv[5]) && strcmp("-appes", argv[5])) { + quit(_fail, std::string("Program must be run with the following arguments: ") + + " [ [<-appes>]]"); + } else { + resultName = argv[4]; + appesMode = true; + } + } +#endif + + inf.init(argv[1], _input); + + tout.open(argv[2], std::ios_base::out); + if (tout.fail() || !tout.is_open()) + quit(_fail, std::string("Can not write to the test-output-file '") + argv[2] + std::string("'")); + + ouf.init(stdin, _output); + + if (argc >= 4) + ans.init(argv[3], _answer); + else + ans.name = "unopened answer stream"; +} + +void registerValidation() { + __testlib_ensuresPreconditions(); + TestlibFinalizeGuard::registered = true; + + testlibMode = _validator; + + __testlib_set_binary(stdin); + __testlib_set_binary(stdout); + __testlib_set_binary(stderr); + + inf.init(stdin, _input); + inf.strict = true; +} + +void registerValidation(int argc, char *argv[]) { + registerValidation(); + __testlib_set_testset_and_group(argc, argv); + + validator.initialize(); + TestlibFinalizeGuard::registered = true; + + std::string comment = "Validator must be run with the following arguments:" + " [--testset testset]" + " [--group group]" + " [--testOverviewLogFileName fileName]" + " [--testMarkupFileName fileName]" + " [--testCase testCase]" + " [--testCaseFileName fileName]" + ; + + for (int i = 1; i < argc; i++) { + if (!strcmp("--testset", argv[i])) { + if (i + 1 < argc && strlen(argv[i + 1]) > 0) + validator.setTestset(argv[++i]); + else + quit(_fail, comment); + } + if (!strcmp("--group", argv[i])) { + if (i + 1 < argc) + validator.setGroup(argv[++i]); + else + quit(_fail, comment); + } + if (!strcmp("--testOverviewLogFileName", argv[i])) { + if (i + 1 < argc) + validator.setTestOverviewLogFileName(argv[++i]); + else + quit(_fail, comment); + } + if (!strcmp("--testMarkupFileName", argv[i])) { + if (i + 1 < argc) + validator.setTestMarkupFileName(argv[++i]); + else + quit(_fail, comment); + } + if (!strcmp("--testCase", argv[i])) { + if (i + 1 < argc) { + long long testCase = stringToLongLong(inf, argv[++i]); + if (testCase < 1 || testCase >= __TESTLIB_MAX_TEST_CASE) + quit(_fail, format("Argument testCase should be between 1 and %d, but ", __TESTLIB_MAX_TEST_CASE) + + toString(testCase) + " found"); + validator.setTestCase(int(testCase)); + } else + quit(_fail, comment); + } + if (!strcmp("--testCaseFileName", argv[i])) { + if (i + 1 < argc) { + validator.setTestCaseFileName(argv[++i]); + } else + quit(_fail, comment); + } + } +} + +void addFeature(const std::string &feature) { + if (testlibMode != _validator) + quit(_fail, "Features are supported in validators only."); + validator.addFeature(feature); +} + +void feature(const std::string &feature) { + if (testlibMode != _validator) + quit(_fail, "Features are supported in validators only."); + validator.feature(feature); +} + +class Checker { +private: + bool _initialized; + std::string _testset; + std::string _group; + +public: + Checker() : _initialized(false), _testset("tests"), _group() { + } + + void initialize() { + _initialized = true; + } + + std::string testset() const { + if (!_initialized) + __testlib_fail("Checker should be initialized with registerTestlibCmd(argc, argv) instead of registerTestlibCmd() to support checker.testset()"); + return _testset; + } + + std::string group() const { + if (!_initialized) + __testlib_fail("Checker should be initialized with registerTestlibCmd(argc, argv) instead of registerTestlibCmd() to support checker.group()"); + return _group; + } + + void setTestset(const char *const testset) { + _testset = testset; + } + + void setGroup(const char *const group) { + _group = group; + } +} checker; + +void registerTestlibCmd(int argc, char *argv[]) { + __testlib_ensuresPreconditions(); + __testlib_set_testset_and_group(argc, argv); + TestlibFinalizeGuard::registered = true; + + testlibMode = _checker; + __testlib_set_binary(stdin); + + std::vector args(1, argv[0]); + checker.initialize(); + + for (int i = 1; i < argc; i++) { + if (!strcmp("--testset", argv[i])) { + if (i + 1 < argc && strlen(argv[i + 1]) > 0) + checker.setTestset(argv[++i]); + else + quit(_fail, std::string("Expected testset after --testset command line parameter")); + } else if (!strcmp("--group", argv[i])) { + if (i + 1 < argc) + checker.setGroup(argv[++i]); + else + quit(_fail, std::string("Expected group after --group command line parameter")); + } else + args.push_back(argv[i]); + } + + argc = int(args.size()); + if (argc > 1 && "--help" == args[1]) + __testlib_help(); + + if (argc < 4 || argc > 6) { + quit(_fail, std::string("Program must be run with the following arguments: ") + + std::string("[--testset testset] [--group group] [ [<-appes>]]") + + "\nUse \"--help\" to get help information"); + } + + if (argc == 4) { + resultName = ""; + appesMode = false; + } + + if (argc == 5) { + resultName = args[4]; + appesMode = false; + } + + if (argc == 6) { + if ("-APPES" != args[5] && "-appes" != args[5]) { + quit(_fail, std::string("Program must be run with the following arguments: ") + + " [ [<-appes>]]"); + } else { + resultName = args[4]; + appesMode = true; + } + } + + inf.init(args[1], _input); + ouf.init(args[2], _output); + ouf.skipBom(); + ans.init(args[3], _answer); +} + +void registerTestlib(int argc, ...) { + if (argc < 3 || argc > 5) + quit(_fail, std::string("Program must be run with the following arguments: ") + + " [ [<-appes>]]"); + + char **argv = new char *[argc + 1]; + + va_list ap; + va_start(ap, argc); + argv[0] = NULL; + for (int i = 0; i < argc; i++) { + argv[i + 1] = va_arg(ap, char*); + } + va_end(ap); + + registerTestlibCmd(argc + 1, argv); + delete[] argv; +} + +static inline void __testlib_ensure(bool cond, const std::string &msg) { + if (!cond) + quit(_fail, msg.c_str()); +} + +#ifdef __GNUC__ +__attribute__((unused)) +#endif +static inline void __testlib_ensure(bool cond, const char *msg) { + if (!cond) + quit(_fail, msg); +} + +#define ensure(cond) __testlib_ensure(cond, "Condition failed: \"" #cond "\"") +#define STRINGIZE_DETAIL(x) #x +#define STRINGIZE(x) STRINGIZE_DETAIL(x) +#define ensure_ext(cond) __testlib_ensure(cond, "Line " STRINGIZE(__LINE__) ": Condition failed: \"" #cond "\"") + +#ifdef __GNUC__ +__attribute__ ((format (printf, 2, 3))) +#endif +inline void ensuref(bool cond, const char *format, ...) { + if (!cond) { + FMT_TO_RESULT(format, format, message); + __testlib_ensure(cond, message); + } +} + +NORETURN static void __testlib_fail(const std::string &message) { + quitf(_fail, "%s", message.c_str()); +} + +#ifdef __GNUC__ +__attribute__ ((format (printf, 1, 2))) +#endif +void setName(const char *format, ...) { + FMT_TO_RESULT(format, format, name); + checkerName = name; +} + +/* + * Do not use random_shuffle, because it will produce different result + * for different C++ compilers. + * + * This implementation uses testlib random_t to produce random numbers, so + * it is stable. + */ +template +void shuffle(_RandomAccessIter __first, _RandomAccessIter __last) { + if (__first == __last) return; + for (_RandomAccessIter __i = __first + 1; __i != __last; ++__i) + std::iter_swap(__i, __first + rnd.next(int(__i - __first) + 1)); +} + + +template +#if defined(__GNUC__) && !defined(__clang__) +__attribute__ ((error("Don't use random_shuffle(), use shuffle() instead"))) +#endif +void random_shuffle(_RandomAccessIter, _RandomAccessIter) { + quitf(_fail, "Don't use random_shuffle(), use shuffle() instead"); +} + +#ifdef __GLIBC__ +# define RAND_THROW_STATEMENT throw() +#else +# define RAND_THROW_STATEMENT +#endif + +#if defined(__GNUC__) && !defined(__clang__) + +__attribute__ ((error("Don't use rand(), use rnd.next() instead"))) +#endif +#ifdef _MSC_VER +# pragma warning( disable : 4273 ) +#endif +int rand() RAND_THROW_STATEMENT +{ + quitf(_fail, "Don't use rand(), use rnd.next() instead"); + + /* This line never runs. */ + //throw "Don't use rand(), use rnd.next() instead"; +} + +#if defined(__GNUC__) && !defined(__clang__) + +__attribute__ ((error("Don't use srand(), you should use " +"'registerGen(argc, argv, 1);' to initialize generator seed " +"by hash code of the command line params. The third parameter " +"is randomGeneratorVersion (currently the latest is 1)."))) +#endif +#ifdef _MSC_VER +# pragma warning( disable : 4273 ) +#endif +void srand(unsigned int seed) RAND_THROW_STATEMENT +{ + quitf(_fail, "Don't use srand(), you should use " + "'registerGen(argc, argv, 1);' to initialize generator seed " + "by hash code of the command line params. The third parameter " + "is randomGeneratorVersion (currently the latest is 1) [ignored seed=%u].", seed); +} + +void startTest(int test) { + const std::string testFileName = vtos(test); + if (NULL == freopen(testFileName.c_str(), "wt", stdout)) + __testlib_fail("Unable to write file '" + testFileName + "'"); +} + +inline std::string upperCase(std::string s) { + for (size_t i = 0; i < s.length(); i++) + if ('a' <= s[i] && s[i] <= 'z') + s[i] = char(s[i] - 'a' + 'A'); + return s; +} + +inline std::string lowerCase(std::string s) { + for (size_t i = 0; i < s.length(); i++) + if ('A' <= s[i] && s[i] <= 'Z') + s[i] = char(s[i] - 'A' + 'a'); + return s; +} + +inline std::string compress(const std::string &s) { + return __testlib_part(s); +} + +inline std::string englishEnding(int x) { + x %= 100; + if (x / 10 == 1) + return "th"; + if (x % 10 == 1) + return "st"; + if (x % 10 == 2) + return "nd"; + if (x % 10 == 3) + return "rd"; + return "th"; +} + +template +std::string join(_ForwardIterator first, _ForwardIterator last, _Separator separator) { + std::stringstream ss; + bool repeated = false; + for (_ForwardIterator i = first; i != last; i++) { + if (repeated) + ss << separator; + else + repeated = true; + ss << *i; + } + return ss.str(); +} + +template +std::string join(_ForwardIterator first, _ForwardIterator last) { + return join(first, last, ' '); +} + +template +std::string join(const _Collection &collection, _Separator separator) { + return join(collection.begin(), collection.end(), separator); +} + +template +std::string join(const _Collection &collection) { + return join(collection, ' '); +} + +/** + * Splits string s by character separator returning exactly k+1 items, + * where k is the number of separator occurrences. + */ +std::vector split(const std::string &s, char separator) { + std::vector result; + std::string item; + for (size_t i = 0; i < s.length(); i++) + if (s[i] == separator) { + result.push_back(item); + item = ""; + } else + item += s[i]; + result.push_back(item); + return result; +} + +/** + * Splits string s by character separators returning exactly k+1 items, + * where k is the number of separator occurrences. + */ +std::vector split(const std::string &s, const std::string &separators) { + if (separators.empty()) + return std::vector(1, s); + + std::vector isSeparator(256); + for (size_t i = 0; i < separators.size(); i++) + isSeparator[(unsigned char) (separators[i])] = true; + + std::vector result; + std::string item; + for (size_t i = 0; i < s.length(); i++) + if (isSeparator[(unsigned char) (s[i])]) { + result.push_back(item); + item = ""; + } else + item += s[i]; + result.push_back(item); + return result; +} + +/** + * Splits string s by character separator returning non-empty items. + */ +std::vector tokenize(const std::string &s, char separator) { + std::vector result; + std::string item; + for (size_t i = 0; i < s.length(); i++) + if (s[i] == separator) { + if (!item.empty()) + result.push_back(item); + item = ""; + } else + item += s[i]; + if (!item.empty()) + result.push_back(item); + return result; +} + +/** + * Splits string s by character separators returning non-empty items. + */ +std::vector tokenize(const std::string &s, const std::string &separators) { + if (separators.empty()) + return std::vector(1, s); + + std::vector isSeparator(256); + for (size_t i = 0; i < separators.size(); i++) + isSeparator[(unsigned char) (separators[i])] = true; + + std::vector result; + std::string item; + for (size_t i = 0; i < s.length(); i++) + if (isSeparator[(unsigned char) (s[i])]) { + if (!item.empty()) + result.push_back(item); + item = ""; + } else + item += s[i]; + + if (!item.empty()) + result.push_back(item); + + return result; +} + +NORETURN void __testlib_expectedButFound(TResult result, std::string expected, std::string found, const char *prepend) { + std::string message; + if (strlen(prepend) != 0) + message = format("%s: expected '%s', but found '%s'", + compress(prepend).c_str(), compress(expected).c_str(), compress(found).c_str()); + else + message = format("expected '%s', but found '%s'", + compress(expected).c_str(), compress(found).c_str()); + quit(result, message); +} + +NORETURN void __testlib_expectedButFound(TResult result, double expected, double found, const char *prepend) { + std::string expectedString = removeDoubleTrailingZeroes(format("%.12f", expected)); + std::string foundString = removeDoubleTrailingZeroes(format("%.12f", found)); + __testlib_expectedButFound(result, expectedString, foundString, prepend); +} + +template +#ifdef __GNUC__ +__attribute__ ((format (printf, 4, 5))) +#endif +NORETURN void expectedButFound(TResult result, T expected, T found, const char *prependFormat = "", ...) { + FMT_TO_RESULT(prependFormat, prependFormat, prepend); + std::string expectedString = vtos(expected); + std::string foundString = vtos(found); + __testlib_expectedButFound(result, expectedString, foundString, prepend.c_str()); +} + +template<> +#ifdef __GNUC__ +__attribute__ ((format (printf, 4, 5))) +#endif +NORETURN void +expectedButFound(TResult result, std::string expected, std::string found, const char *prependFormat, ...) { + FMT_TO_RESULT(prependFormat, prependFormat, prepend); + __testlib_expectedButFound(result, expected, found, prepend.c_str()); +} + +template<> +#ifdef __GNUC__ +__attribute__ ((format (printf, 4, 5))) +#endif +NORETURN void expectedButFound(TResult result, double expected, double found, const char *prependFormat, ...) { + FMT_TO_RESULT(prependFormat, prependFormat, prepend); + std::string expectedString = removeDoubleTrailingZeroes(format("%.12f", expected)); + std::string foundString = removeDoubleTrailingZeroes(format("%.12f", found)); + __testlib_expectedButFound(result, expectedString, foundString, prepend.c_str()); +} + +template<> +#ifdef __GNUC__ +__attribute__ ((format (printf, 4, 5))) +#endif +NORETURN void +expectedButFound(TResult result, const char *expected, const char *found, const char *prependFormat, + ...) { + FMT_TO_RESULT(prependFormat, prependFormat, prepend); + __testlib_expectedButFound(result, std::string(expected), std::string(found), prepend.c_str()); +} + +template<> +#ifdef __GNUC__ +__attribute__ ((format (printf, 4, 5))) +#endif +NORETURN void expectedButFound(TResult result, float expected, float found, const char *prependFormat, ...) { + FMT_TO_RESULT(prependFormat, prependFormat, prepend); + __testlib_expectedButFound(result, double(expected), double(found), prepend.c_str()); +} + +template<> +#ifdef __GNUC__ +__attribute__ ((format (printf, 4, 5))) +#endif +NORETURN void +expectedButFound(TResult result, long double expected, long double found, const char *prependFormat, ...) { + FMT_TO_RESULT(prependFormat, prependFormat, prepend); + __testlib_expectedButFound(result, double(expected), double(found), prepend.c_str()); +} + +#if __cplusplus > 199711L || defined(_MSC_VER) +template +struct is_iterable { + template + static char test(typename U::iterator *x); + + template + static long test(U *x); + + static const bool value = sizeof(test(0)) == 1; +}; + +template +struct __testlib_enable_if { +}; + +template +struct __testlib_enable_if { + typedef T type; +}; + +template +typename __testlib_enable_if::value, void>::type __testlib_print_one(const T &t) { + std::cout << t; +} + +template +typename __testlib_enable_if::value, void>::type __testlib_print_one(const T &t) { + bool first = true; + for (typename T::const_iterator i = t.begin(); i != t.end(); i++) { + if (first) + first = false; + else + std::cout << " "; + std::cout << *i; + } +} + +template<> +typename __testlib_enable_if::value, void>::type +__testlib_print_one(const std::string &t) { + std::cout << t; +} + +template +void __println_range(A begin, B end) { + bool first = true; + for (B i = B(begin); i != end; i++) { + if (first) + first = false; + else + std::cout << " "; + __testlib_print_one(*i); + } + std::cout << std::endl; +} + +template +struct is_iterator { + static T makeT(); + + typedef void *twoptrs[2]; + + static twoptrs &test(...); + + template + static typename R::iterator_category *test(R); + + template + static void *test(R *); + + static const bool value = sizeof(test(makeT())) == sizeof(void *); +}; + +template +struct is_iterator::value>::type> { + static const bool value = false; +}; + +template +typename __testlib_enable_if::value, void>::type println(const A &a, const B &b) { + __testlib_print_one(a); + std::cout << " "; + __testlib_print_one(b); + std::cout << std::endl; +} + +template +typename __testlib_enable_if::value, void>::type println(const A &a, const B &b) { + __println_range(a, b); +} + +template +void println(const A *a, const A *b) { + __println_range(a, b); +} + +template<> +void println(const char *a, const char *b) { + __testlib_print_one(a); + std::cout << " "; + __testlib_print_one(b); + std::cout << std::endl; +} + +template +void println(const T &x) { + __testlib_print_one(x); + std::cout << std::endl; +} + +template +void println(const A &a, const B &b, const C &c) { + __testlib_print_one(a); + std::cout << " "; + __testlib_print_one(b); + std::cout << " "; + __testlib_print_one(c); + std::cout << std::endl; +} + +template +void println(const A &a, const B &b, const C &c, const D &d) { + __testlib_print_one(a); + std::cout << " "; + __testlib_print_one(b); + std::cout << " "; + __testlib_print_one(c); + std::cout << " "; + __testlib_print_one(d); + std::cout << std::endl; +} + +template +void println(const A &a, const B &b, const C &c, const D &d, const E &e) { + __testlib_print_one(a); + std::cout << " "; + __testlib_print_one(b); + std::cout << " "; + __testlib_print_one(c); + std::cout << " "; + __testlib_print_one(d); + std::cout << " "; + __testlib_print_one(e); + std::cout << std::endl; +} + +template +void println(const A &a, const B &b, const C &c, const D &d, const E &e, const F &f) { + __testlib_print_one(a); + std::cout << " "; + __testlib_print_one(b); + std::cout << " "; + __testlib_print_one(c); + std::cout << " "; + __testlib_print_one(d); + std::cout << " "; + __testlib_print_one(e); + std::cout << " "; + __testlib_print_one(f); + std::cout << std::endl; +} + +template +void println(const A &a, const B &b, const C &c, const D &d, const E &e, const F &f, const G &g) { + __testlib_print_one(a); + std::cout << " "; + __testlib_print_one(b); + std::cout << " "; + __testlib_print_one(c); + std::cout << " "; + __testlib_print_one(d); + std::cout << " "; + __testlib_print_one(e); + std::cout << " "; + __testlib_print_one(f); + std::cout << " "; + __testlib_print_one(g); + std::cout << std::endl; +} + +/* opts */ + +/** + * A struct for a singular testlib opt, containing the raw string value, + * and a boolean value for marking whether the opt is used. + */ +struct TestlibOpt { + std::string value; + bool used; + + TestlibOpt() : value(), used(false) {} +}; + +/** + * Get the type of opt based on the number of `-` at the beginning and the + * _validity_ of the key name. + * + * A valid key name must start with an alphabetical character. + * + * Returns: 1 if s has one `-` at the beginning, that is, "-keyName". + * 2 if s has two `-` at the beginning, that is, "--keyName". + * 0 otherwise. That is, if s has no `-` at the beginning, or has more + * than 2 at the beginning ("---keyName", "----keyName", ...), or the + * keyName is invalid (the first character is not an alphabetical + * character). + */ +size_t getOptType(char *s) { + if (!s || strlen(s) <= 1) + return 0; + + if (s[0] == '-') { + if (isalpha(s[1])) + return 1; + else if (s[1] == '-') + return isalpha(s[2]) ? 2 : 0; + } + + return 0; +} + +/** + * Parse the opt at a given index, and put it into the opts maps. + * + * An opt can has the following form: + * 1) -keyName=value or --keyName=value (ex. -n=10 --test-count=20) + * 2) -keyName value or --keyName value (ex. -n 10 --test-count 20) + * 3) -kNumval or --kNumval (ex. -n10 --t20) + * 4) -boolProperty or --boolProperty (ex. -sorted --tree-only) + * + * Only the second form consumes 2 arguments. The other consumes only 1 + * argument. + * + * In the third form, the key is a single character, and after the key is the + * value. The value _should_ be a number. + * + * In the forth form, the value is true. + * + * Params: + * - argc and argv: the number of command line arguments and the command line + * arguments themselves. + * - index: the starting index of the opts. + * - opts: the map containing the resulting opt. + * + * Returns: the number of consumed arguments to parse the opt. + * 0 if there is no arguments to parse. + * + * Algorithm details: + * TODO. Please refer to the implementation to see how the code handles the 3rd and 4th forms separately. + */ +size_t parseOpt(size_t argc, char *argv[], size_t index, std::map &opts) { + if (index >= argc) + return 0; + + size_t type = getOptType(argv[index]), inc = 1; + if (type > 0) { + std::string key(argv[index] + type), val; + size_t sep = key.find('='); + if (sep != std::string::npos) { + val = key.substr(sep + 1); + key = key.substr(0, sep); + } else { + if (index + 1 < argc && getOptType(argv[index + 1]) == 0) { + val = argv[index + 1]; + inc = 2; + } else { + if (key.length() > 1 && isdigit(key[1])) { + val = key.substr(1); + key = key.substr(0, 1); + } else { + val = "true"; + } + } + } + opts[key].value = val; + } else { + return inc; + } + + return inc; +} + +/** + * Global list containing all the arguments in the order given in the command line. + */ +std::vector __testlib_argv; + +/** + * Global dictionary containing all the parsed opts. + */ +std::map __testlib_opts; + +/** + * Whether automatic no unused opts ensurement should be done. This flag will + * be turned on when `has_opt` or `opt(key, default_value)` is called. + * + * The automatic ensurement can be suppressed when + * __testlib_ensureNoUnusedOptsSuppressed is true. + */ +bool __testlib_ensureNoUnusedOptsFlag = false; + +/** + * Suppress no unused opts automatic ensurement. Can be set to true with + * `suppressEnsureNoUnusedOpts()`. + */ +bool __testlib_ensureNoUnusedOptsSuppressed = false; + +/** + * Parse command line arguments into opts. + * The results are stored into __testlib_argv and __testlib_opts. + */ +void prepareOpts(int argc, char *argv[]) { + if (argc <= 0) + __testlib_fail("Opts: expected argc>=0 but found " + toString(argc)); + size_t n = static_cast(argc); // NOLINT(hicpp-use-auto,modernize-use-auto) + __testlib_opts = std::map(); + for (size_t index = 1; index < n; index += parseOpt(n, argv, index, __testlib_opts)); + __testlib_argv = std::vector(n); + for (size_t index = 0; index < n; index++) + __testlib_argv[index] = argv[index]; +} + +/** + * An utility function to get the argument with a given index. This function + * also print a readable message when no arguments are found. + */ +std::string __testlib_indexToArgv(int index) { + if (index < 0 || index >= int(__testlib_argv.size())) + __testlib_fail("Opts: index '" + toString(index) + "' is out of range [0," + + toString(__testlib_argv.size()) + ")"); + return __testlib_argv[size_t(index)]; +} + +/** + * An utility function to get the opt with a given key . This function + * also print a readable message when no opts are found. + */ +std::string __testlib_keyToOpts(const std::string &key) { + auto it = __testlib_opts.find(key); + if (it == __testlib_opts.end()) + __testlib_fail("Opts: unknown key '" + compress(key) + "'"); + it->second.used = true; + return it->second.value; +} + +template +T optValueToIntegral(const std::string &s, bool nonnegative); + +long double optValueToLongDouble(const std::string &s); + +std::string parseExponentialOptValue(const std::string &s) { + size_t pos = std::string::npos; + for (size_t i = 0; i < s.length(); i++) + if (s[i] == 'e' || s[i] == 'E') { + if (pos != std::string::npos) + __testlib_fail("Opts: expected typical exponential notation but '" + compress(s) + "' found"); + pos = i; + } + if (pos == std::string::npos) + return s; + std::string e = s.substr(pos + 1); + if (!e.empty() && e[0] == '+') + e = e.substr(1); + if (e.empty()) + __testlib_fail("Opts: expected typical exponential notation but '" + compress(s) + "' found"); + if (e.length() > 20) + __testlib_fail("Opts: expected typical exponential notation but '" + compress(s) + "' found"); + int ne = optValueToIntegral(e, false); + std::string num = s.substr(0, pos); + if (num.length() > 20) + __testlib_fail("Opts: expected typical exponential notation but '" + compress(s) + "' found"); + if (!num.empty() && num[0] == '+') + num = num.substr(1); + optValueToLongDouble(num); + bool minus = false; + if (num[0] == '-') { + minus = true; + num = num.substr(1); + } + for (int i = 0; i < +ne; i++) { + size_t sep = num.find('.'); + if (sep == std::string::npos) + num += '0'; + else { + if (sep + 1 == num.length()) + num[sep] = '0'; + else + std::swap(num[sep], num[sep + 1]); + } + } + for (int i = 0; i < -ne; i++) { + size_t sep = num.find('.'); + if (sep == std::string::npos) + num.insert(num.begin() + int(num.length()) - 1, '.'); + else { + if (sep == 0) + num.insert(num.begin() + 1, '0'); + else + std::swap(num[sep - 1], num[sep]); + } + } + while (!num.empty() && num[0] == '0') + num = num.substr(1); + while (num.find('.') != std::string::npos && num.back() == '0') + num = num.substr(0, num.length() - 1); + if (!num.empty() && num.back() == '.') + num = num.substr(0, num.length() - 1); + if ((!num.empty() && num[0] == '.') || num.empty()) + num.insert(num.begin(), '0'); + return (minus ? "-" : "") + num; +} + +template +T optValueToIntegral(const std::string &s_, bool nonnegative) { + std::string s(parseExponentialOptValue(s_)); + if (s.empty()) + __testlib_fail("Opts: expected integer but '" + compress(s_) + "' found"); + T value = 0; + long double about = 0.0; + signed char sign = +1; + size_t pos = 0; + if (s[pos] == '-') { + if (nonnegative) + __testlib_fail("Opts: expected non-negative integer but '" + compress(s_) + "' found"); + sign = -1; + pos++; + } + for (size_t i = pos; i < s.length(); i++) { + if (s[i] < '0' || s[i] > '9') + __testlib_fail("Opts: expected integer but '" + compress(s_) + "' found"); + value = value * 10 + s[i] - '0'; + about = about * 10 + s[i] - '0'; + } + value *= sign; + about *= sign; + if (fabsl(value - about) > 0.1) + __testlib_fail("Opts: integer overflow: expected integer but '" + compress(s_) + "' found"); + return value; +} + +long double optValueToLongDouble(const std::string &s_) { + std::string s(parseExponentialOptValue(s_)); + if (s.empty()) + __testlib_fail("Opts: expected float number but '" + compress(s_) + "' found"); + long double value = 0.0; + signed char sign = +1; + size_t pos = 0; + if (s[pos] == '-') { + sign = -1; + pos++; + } + bool period = false; + long double mul = 1.0; + for (size_t i = pos; i < s.length(); i++) { + if (s[i] == '.') { + if (period) + __testlib_fail("Opts: expected float number but '" + compress(s_) + "' found"); + else { + period = true; + continue; + } + } + if (period) + mul *= 10.0; + if (s[i] < '0' || s[i] > '9') + __testlib_fail("Opts: expected float number but '" + compress(s_) + "' found"); + if (period) + value += (s[i] - '0') / mul; + else + value = value * 10 + s[i] - '0'; + } + value *= sign; + return value; +} + +/** + * Return true if there is an opt with a given key. + * + * By calling this function, automatic ensurement for no unused opts will be + * done when the program is finalized. Call suppressEnsureNoUnusedOpts() to + * turn it off. + */ +bool has_opt(const std::string &key) { + __testlib_ensureNoUnusedOptsFlag = true; + return __testlib_opts.count(key) != 0; +} + +/* About the following part for opt with 2 and 3 arguments. + * + * To parse the argv/opts correctly for a give type (integer, floating point or + * string), some meta programming must be done to determine the type of + * the type, and use the correct parsing function accordingly. + * + * The pseudo algorithm for determining the type of T and parse it accordingly + * is as follows: + * + * if (T is integral type) { + * if (T is unsigned) { + * parse the argv/opt as an **unsigned integer** of type T. + * } else { + * parse the argv/opt as an **signed integer** of type T. + * } else { + * if (T is floating point type) { + * parse the argv/opt as an **floating point** of type T. + * } else { + * // T should be std::string + * just the raw content of the argv/opts. + * } + * } + * + * To help with meta programming, some `opt` function with 2 or 3 arguments are + * defined. + * + * Opt with 3 arguments: T opt(true/false is_integral, true/false is_unsigned, index/key) + * + * + The first argument is for determining whether the type T is an integral + * type. That is, the result of std::is_integral() should be passed to + * this argument. When false, the type _should_ be either floating point or a + * std::string. + * + * + The second argument is for determining whether the signedness of the type + * T (if it is unsigned or signed). That is, the result of + * std::is_unsigned() should be passed to this argument. This argument can + * be ignored if the first one is false, because it only applies to integer. + * + * Opt with 2 arguments: T opt(true/false is_floating_point, index/key) + * + The first argument is for determining whether the type T is a floating + * point type. That is, the result of std::is_floating_point() should be + * passed to this argument. When false, the type _should_ be a std::string. + */ + +template +T opt(std::false_type is_floating_point, int index); + +template<> +std::string opt(std::false_type /*is_floating_point*/, int index) { + return __testlib_indexToArgv(index); +} + +template +T opt(std::true_type /*is_floating_point*/, int index) { + return T(optValueToLongDouble(__testlib_indexToArgv(index))); +} + +template +T opt(std::false_type /*is_integral*/, U /*is_unsigned*/, int index) { + return opt(std::is_floating_point(), index); +} + +template +T opt(std::true_type /*is_integral*/, std::false_type /*is_unsigned*/, int index) { + return optValueToIntegral(__testlib_indexToArgv(index), false); +} + +template +T opt(std::true_type /*is_integral*/, std::true_type /*is_unsigned*/, int index) { + return optValueToIntegral(__testlib_indexToArgv(index), true); +} + +template<> +bool opt(std::true_type /*is_integral*/, std::true_type /*is_unsigned*/, int index) { + std::string value = __testlib_indexToArgv(index); + if (value == "true" || value == "1") + return true; + if (value == "false" || value == "0") + return false; + __testlib_fail("Opts: opt by index '" + toString(index) + "': expected bool true/false or 0/1 but '" + + compress(value) + "' found"); +} + +/** + * Return the parsed argv by a given index. + */ +template +T opt(int index) { + return opt(std::is_integral(), std::is_unsigned(), index); +} + +/** + * Return the raw string value of an argv by a given index. + */ +std::string opt(int index) { + return opt(index); +} + +/** + * Return the parsed argv by a given index. If the index is bigger than + * the number of argv, return the given default_value. + */ +template +T opt(int index, const T &default_value) { + if (index >= int(__testlib_argv.size())) { + return default_value; + } + return opt(index); +} + +/** + * Return the raw string value of an argv by a given index. If the index is + * bigger than the number of argv, return the given default_value. + */ +std::string opt(int index, const std::string &default_value) { + return opt(index, default_value); +} + +template +T opt(std::false_type is_floating_point, const std::string &key); + +template<> +std::string opt(std::false_type /*is_floating_point*/, const std::string &key) { + return __testlib_keyToOpts(key); +} + +template +T opt(std::true_type /*is_integral*/, const std::string &key) { + return T(optValueToLongDouble(__testlib_keyToOpts(key))); +} + +template +T opt(std::false_type /*is_integral*/, U, const std::string &key) { + return opt(std::is_floating_point(), key); +} + +template +T opt(std::true_type /*is_integral*/, std::false_type /*is_unsigned*/, const std::string &key) { + return optValueToIntegral(__testlib_keyToOpts(key), false); +} + +template +T opt(std::true_type /*is_integral*/, std::true_type /*is_unsigned*/, const std::string &key) { + return optValueToIntegral(__testlib_keyToOpts(key), true); +} + +template<> +bool opt(std::true_type /*is_integral*/, std::true_type /*is_unsigned*/, const std::string &key) { + if (!has_opt(key)) + return false; + std::string value = __testlib_keyToOpts(key); + if (value == "true" || value == "1") + return true; + if (value == "false" || value == "0") + return false; + __testlib_fail("Opts: key '" + compress(key) + "': expected bool true/false or 0/1 but '" + + compress(value) + "' found"); +} + +/** + * Return the parsed opt by a given key. + */ +template +T opt(const std::string &key) { + return opt(std::is_integral(), std::is_unsigned(), key); +} + +/** + * Return the raw string value of an opt by a given key + */ +std::string opt(const std::string &key) { + return opt(key); +} + +/* Scorer started. */ + +enum TestResultVerdict { + SKIPPED, + OK, + WRONG_ANSWER, + RUNTIME_ERROR, + TIME_LIMIT_EXCEEDED, + IDLENESS_LIMIT_EXCEEDED, + MEMORY_LIMIT_EXCEEDED, + COMPILATION_ERROR, + CRASHED, + FAILED +}; + +std::string serializeVerdict(TestResultVerdict verdict) { + switch (verdict) { + case SKIPPED: return "SKIPPED"; + case OK: return "OK"; + case WRONG_ANSWER: return "WRONG_ANSWER"; + case RUNTIME_ERROR: return "RUNTIME_ERROR"; + case TIME_LIMIT_EXCEEDED: return "TIME_LIMIT_EXCEEDED"; + case IDLENESS_LIMIT_EXCEEDED: return "IDLENESS_LIMIT_EXCEEDED"; + case MEMORY_LIMIT_EXCEEDED: return "MEMORY_LIMIT_EXCEEDED"; + case COMPILATION_ERROR: return "COMPILATION_ERROR"; + case CRASHED: return "CRASHED"; + case FAILED: return "FAILED"; + } + throw "Unexpected verdict"; +} + +TestResultVerdict deserializeTestResultVerdict(std::string s) { + if (s == "SKIPPED") + return SKIPPED; + else if (s == "OK") + return OK; + else if (s == "WRONG_ANSWER") + return WRONG_ANSWER; + else if (s == "RUNTIME_ERROR") + return RUNTIME_ERROR; + else if (s == "TIME_LIMIT_EXCEEDED") + return TIME_LIMIT_EXCEEDED; + else if (s == "IDLENESS_LIMIT_EXCEEDED") + return IDLENESS_LIMIT_EXCEEDED; + else if (s == "MEMORY_LIMIT_EXCEEDED") + return MEMORY_LIMIT_EXCEEDED; + else if (s == "COMPILATION_ERROR") + return COMPILATION_ERROR; + else if (s == "CRASHED") + return CRASHED; + else if (s == "FAILED") + return FAILED; + ensuref(false, "Unexpected serialized TestResultVerdict"); + // No return actually. + return FAILED; +} + +struct TestResult { + int testIndex; + std::string testset; + std::string group; + TestResultVerdict verdict; + double points; + long long timeConsumed; + long long memoryConsumed; + std::string input; + std::string output; + std::string answer; + int exitCode; + std::string checkerComment; +}; + +std::string serializePoints(double points) { + if (std::isnan(points)) + return ""; + else { + char c[64]; + snprintf(c, 64, "%.03lf", points); + return c; + } +} + +double deserializePoints(std::string s) { + if (s.empty()) + return std::numeric_limits::quiet_NaN(); + else { + double result; + ensuref(sscanf(s.c_str(), "%lf", &result) == 1, "Invalid serialized points"); + return result; + } +} + +std::string escapeTestResultString(std::string s) { + std::string result; + for (size_t i = 0; i < s.length(); i++) { + if (s[i] == '\r') + continue; + if (s[i] == '\n') { + result += "\\n"; + continue; + } + if (s[i] == '\\' || s[i] == ';') + result += '\\'; + result += s[i]; + } + return result; +} + +std::string unescapeTestResultString(std::string s) { + std::string result; + for (size_t i = 0; i < s.length(); i++) { + if (s[i] == '\\' && i + 1 < s.length()) { + if (s[i + 1] == 'n') { + result += '\n'; + i++; + continue; + } else if (s[i + 1] == ';' || s[i + 1] == '\\') { + result += s[i + 1]; + i++; + continue; + } + } + result += s[i]; + } + return result; +} + +std::string serializeTestResult(TestResult tr) { + std::string result; + result += std::to_string(tr.testIndex); + result += ";"; + result += escapeTestResultString(tr.testset); + result += ";"; + result += escapeTestResultString(tr.group); + result += ";"; + result += serializeVerdict(tr.verdict); + result += ";"; + result += serializePoints(tr.points); + result += ";"; + result += std::to_string(tr.timeConsumed); + result += ";"; + result += std::to_string(tr.memoryConsumed); + result += ";"; + result += escapeTestResultString(tr.input); + result += ";"; + result += escapeTestResultString(tr.output); + result += ";"; + result += escapeTestResultString(tr.answer); + result += ";"; + result += std::to_string(tr.exitCode); + result += ";"; + result += escapeTestResultString(tr.checkerComment); + return result; +} + +TestResult deserializeTestResult(std::string s) { + std::vector items; + std::string t; + for (size_t i = 0; i < s.length(); i++) { + if (s[i] == '\\') { + t += s[i]; + if (i + 1 < s.length()) + t += s[i + 1]; + i++; + continue; + } else { + if (s[i] == ';') { + items.push_back(t); + t = ""; + } else + t += s[i]; + } + } + items.push_back(t); + + ensuref(items.size() == 12, "Invalid TestResult serialization: expected exactly 12 items"); + + TestResult tr; + size_t pos = 0; + tr.testIndex = stoi(items[pos++]); + tr.testset = unescapeTestResultString(items[pos++]); + tr.group = unescapeTestResultString(items[pos++]); + tr.verdict = deserializeTestResultVerdict(items[pos++]); + tr.points = deserializePoints(items[pos++]); + tr.timeConsumed = stoll(items[pos++]); + tr.memoryConsumed = stoll(items[pos++]); + tr.input = unescapeTestResultString(items[pos++]); + tr.output = unescapeTestResultString(items[pos++]); + tr.answer = unescapeTestResultString(items[pos++]); + tr.exitCode = stoi(items[pos++]); + tr.checkerComment = unescapeTestResultString(items[pos++]); + + return tr; +} + +std::vector readTestResults(std::string fileName) { + std::ifstream stream; + stream.open(fileName.c_str(), std::ios::in); + ensuref(stream.is_open(), "Can't read test results file '%s'", fileName.c_str()); + std::vector result; + std::string line; + while (getline(stream, line)) + if (!line.empty()) + result.push_back(deserializeTestResult(line)); + stream.close(); + return result; +} + +std::function)> __testlib_scorer; + +struct TestlibScorerGuard { + ~TestlibScorerGuard() { + if (testlibMode == _scorer) { + std::vector testResults; + while (!inf.eof()) { + std::string line = inf.readLine(); + if (!line.empty()) + testResults.push_back(deserializeTestResult(line)); + } + inf.readEof(); + printf("%.3f\n", __testlib_scorer(testResults)); + } + } +} __testlib_scorer_guard; + +void registerScorer(int argc, char *argv[], std::function)> scorer) { + /* Suppress unused. */ + (void)(argc), (void)(argv); + + __testlib_ensuresPreconditions(); + + testlibMode = _scorer; + __testlib_set_binary(stdin); + + inf.init(stdin, _input); + inf.strict = false; + + __testlib_scorer = scorer; +} + +/* Scorer ended. */ + +/** + * Return the parsed opt by a given key. If no opts with the given key are + * found, return the given default_value. + * + * By calling this function, automatic ensurement for no unused opts will be + * done when the program is finalized. Call suppressEnsureNoUnusedOpts() to + * turn it off. + */ +template +T opt(const std::string &key, const T &default_value) { + if (!has_opt(key)) { + return default_value; + } + return opt(key); +} + +/** + * Return the raw string value of an opt by a given key. If no opts with the + * given key are found, return the given default_value. + * + * By calling this function, automatic ensurement for no unused opts will be + * done when the program is finalized. Call suppressEnsureNoUnusedOpts() to + * turn it off. + */ +std::string opt(const std::string &key, const std::string &default_value) { + return opt(key, default_value); +} + +/** + * Check if all opts are used. If not, __testlib_fail is called. + * Should be used after calling all opt() function calls. + * + * This function is useful when opt() with default_value for checking typos + * in the opt's key. + */ +void ensureNoUnusedOpts() { + for (const auto &opt: __testlib_opts) { + if (!opt.second.used) { + __testlib_fail(format("Opts: unused key '%s'", compress(opt.first).c_str())); + } + } +} + +void suppressEnsureNoUnusedOpts() { + __testlib_ensureNoUnusedOptsSuppressed = true; +} + +void TestlibFinalizeGuard::autoEnsureNoUnusedOpts() { + if (__testlib_ensureNoUnusedOptsFlag && !__testlib_ensureNoUnusedOptsSuppressed) { + ensureNoUnusedOpts(); + } +} + +TestlibFinalizeGuard testlibFinalizeGuard; + +#endif +#endif diff --git a/tests/run.sh b/tests/run.sh new file mode 100755 index 00000000..4ae02a0a --- /dev/null +++ b/tests/run.sh @@ -0,0 +1,273 @@ +#!/bin/bash +set -e -o pipefail + +echo "Checking installed Java" +java -version + +TESTS_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd) +export TESTS_DIR="$TESTS_DIR" + +export RED='\033[0;31m' +export CYAN='\033[1;36m' +export BLUE='\033[1;34m' +export YELLOW='\033[1;33m' +export GREEN='\033[1;32m' +export NC='\033[0m' + +ARGS_CPP="" +ARGS_VALID_CPP_STANDARDS=",11,14,17,20,23," +ARGS_CPP_STANDARDS="," +ARGS_CPP_VERSIONS="," +ARGS_TESTS="," +ARGS_CPP_BITS="" + +MSVC_INCLUDE_YEAR="2022" +WINKIT_INCLUDE_VERSION="10.0.19041.0" + +for arg in "$@"; do + if [[ "$arg" == test-* ]]; then + ARGS_TESTS="${ARGS_TESTS}${arg}," + continue + fi + if [[ "$arg" == "32" || "$arg" == "64" ]]; then + if [[ -n "$ARGS_CPP_BITS" ]]; then + echo Expected at most one bits-argument: 32 or 64 + exit 1 + fi + ARGS_CPP_BITS="$arg" + continue + fi + if [[ "$ARGS_VALID_CPP_STANDARDS" == *,$arg,* ]]; then + ARGS_CPP_STANDARDS="$ARGS_CPP_STANDARDS$arg," + else + if [[ "$arg" == v* ]]; then + ARGS_CPP_VERSIONS="$ARGS_CPP_VERSIONS${arg:1}," + else + if [[ -n "$ARGS_CPP" ]]; then + echo Expected just one non-version argument: g++, clang++ or msvc, but found "$ARGS_CPP" and "$arg" + exit 1 + fi + if [[ ! "$arg" == "g++" && ! "$arg" == "clang++" && ! "$arg" == "msvc" ]]; then + echo Expected just one non-version argument: g++, clang++ or msvc, but "$arg" found + exit 1 + fi + ARGS_CPP="$arg" + fi + fi +done + +if [[ ! "$ARGS_TESTS" == "," ]]; then + echo [INFO] Filter tests: ${ARGS_TESTS:1:${#ARGS_TESTS}-2} +fi + +if [[ ! "$ARGS_CPP" == "" ]]; then + echo [INFO] Filter CPP: "$ARGS_CPP" +fi + +if [[ ! "$ARGS_CPP_STANDARDS" == "," ]]; then + echo [INFO] Filter standards: ${ARGS_CPP_STANDARDS:1:${#ARGS_CPP_STANDARDS}-2} +fi + +if [[ ! "$ARGS_CPP_VERSIONS" == "," ]]; then + echo [INFO] Filter versions: ${ARGS_CPP_VERSIONS:1:${#ARGS_CPP_VERSIONS}-2} +fi + +if [[ ! "$ARGS_CPP_BITS" == "" ]]; then + echo [INFO] Filter target arch.: "$ARGS_CPP_BITS" +fi + +COMPILERS=('clang++' 'g++') +if [[ ! "$ARGS_CPP" == "" ]]; then + if [[ "$ARGS_CPP" == "msvc" ]]; then + COMPILERS=() + else + COMPILERS=("$ARGS_CPP") + fi +fi +echo "" +echo GNU-like compilers: +printf ' %s\n' "${COMPILERS[@]}" + +CPP_STANDARDS=() +MSVC_CPP_STANDARDS=() +for v in 11 14 17 20 23; do + if [[ "$ARGS_CPP_STANDARDS" == "," || "$ARGS_CPP_STANDARDS" == *,$v,* ]]; then + CPP_STANDARDS+=("--std=c++$v") + MSVC_CPP_STANDARDS+=("-std:c++$v") + fi +done +echo "" +echo Standards: +printf ' %s\n' "${CPP_STANDARDS[@]}" + +uname_output="$(uname -s)" +case "${uname_output}" in +Linux*) machine=Linux ;; +Darwin*) machine=Mac ;; +CYGWIN*) machine=Windows ;; +MINGW*) machine=Windows ;; +MSYS*) machine=Windows ;; +*) echo "Unknown system '${uname_output}'" && exit 1 ;; +esac +export MACHINE="$machine" + +#if [[ "$machine" == "Windows" && ("$ARGS_CPP" == "" || "$ARGS_CPP" == "clang++") ]]; then +# for f in msvc-${MSVC_INCLUDE_YEAR}-include windows-kit-${WINKIT_INCLUDE_VERSION}-include; do +# rm -rf "${TESTS_DIR:?}"/lib/$f && mkdir -p "$TESTS_DIR"/lib/$f +# 7z x -o"${TESTS_DIR:?}"/lib/$f "$TESTS_DIR"/lib/$f.7z +# done +#fi + +run_tests() { + export INVOCATION_ID=$RANDOM + export CPP="$1" + export CPP_STANDARD="$2" + + echo -e Running tests \("${CYAN}""$CPP"@"$CPP_STANDARD""${NC}"\) + echo "" + + for test_dir in "$TESTS_DIR"/*/; do + test=$(basename "$test_dir") + if [[ $test == test-* ]]; then + if [[ "$ARGS_TESTS" == "," || "$ARGS_TESTS" == *,$test,* ]]; then + echo -e Running "${BLUE}${test}${NC}" \("$CPP"@"$CPP_STANDARD"\) + export TEST_DIR="$test_dir" + export CPP_INCLUDE_DIR=${TESTS_DIR}/.. + export CPP_OPTS="" + if [[ -n "$ARGS_CPP_BITS" ]]; then + export CPP_OPTS="-m$ARGS_CPP_BITS" + fi + pushd "$test_dir" 1>/dev/null 2>&1 + bash "${test_dir}run.sh" + echo -e Done "${BLUE}$test${NC}" \("${CYAN}""$CPP"@"$CPP_STANDARD""${NC}"\) + echo "" + popd 1>&2 1>/dev/null 2>&1 + fi + fi + done + + rm -rf "$TESTS_DIR"/tester-lcmp + echo -e Done all tests \("${CYAN}""$CPP"@"$CPP_STANDARD""${NC}"\) + echo "" +} + +VALGRIND="" +valgrind_output=$(valgrind 2>&1 || true) +if [[ $valgrind_output == *"--help"* ]]; then + VALGRIND="valgrind -q" + echo Valgrind mode is ON +else + echo Valgrind mode is OFF +fi +export VALGRIND="$VALGRIND" + +done="" +if [[ "$machine" == "Windows" && ("$ARGS_CPP" == "" || "$ARGS_CPP" == "msvc") ]]; then + VS_RELEASES=("Professional" "Enterprise" "Community") + PROGRAM_FILES=("${PROGRAMFILES}" "${PROGRAMFILES} (x86)") + + for vs_release in "${VS_RELEASES[@]}"; do + for program_files in "${PROGRAM_FILES[@]}"; do + for ((version = 2000; version <= 2100; version++)); do + vs_dir="$program_files\\Microsoft Visual Studio\\$version\\$vs_release\\VC\\Auxiliary\\Build" + if [[ -d $vs_dir ]]; then + for bits in 32 64; do + vcvars_bat_file="$vs_dir\\vcvars$bits.bat" + if [[ -f $vcvars_bat_file ]]; then + echo "Compiler Visual Studio $version ($vs_release-$bits) has been found" + echo call \""$vcvars_bat_file"\" >do-vcvars.bat + echo "bash -c export > vcvars.env" >>do-vcvars.bat + python file-runner.py do-vcvars.bat + grep -v -E "(\(.*=)|(\!.*=)|([A-Z]\-[A-Z].*=)" vcvars_filtered.env + source vcvars_filtered.env + rm -f do-vcvars.bat vcvars.env vcvars_filtered.env + for cpp_standard in "${MSVC_CPP_STANDARDS[@]}"; do + touch empty_file.cpp + cpp_output=$(cl.exe "$cpp_standard" empty_file.cpp 2>&1 || true) + rm -f empty_file.* + if [[ ! $cpp_output == *"unknown"* ]]; then + echo Testing msvc-"$version"-$bits@"$cpp_standard" + run_tests "cl.exe" "$cpp_standard" + if [[ ! "$done" == "" ]]; then + done="$done, " + fi + done="${done}msvc-$version-$bits@$cpp_standard" + fi + done + fi + done + fi + done + done + done +fi + +# Find /c/Programs/*/bin/g++ in case of Windows and no ARGS_CPP +if [[ "$MACHINE" == "Windows" && "$ARGS_CPP" == "" ]]; then + for d in /c/Programs/*/; do + dir="${d}bin" + OLD_PATH="$PATH" + export PATH="$dir":$PATH + gpp="${d}bin/g++.exe" + gpp_output=$($gpp 2>&1 || true) + if [[ $gpp_output == *"no input files"* ]]; then + for gpp_standard in "${CPP_STANDARDS[@]}"; do + touch empty_file.cpp + gpp_output=$($gpp "$gpp_standard" empty_file.cpp 2>&1 || true) + if [[ ! $gpp_output == *"unrecognized"* && ! $gpp_output == *"standard"* ]]; then + run_tests "$gpp" "$gpp_standard" + if [[ ! "$done" == "" ]]; then + done="$done, " + fi + done="$done$gpp@$gpp_standard" + fi + rm -f empty_file.* + done + fi + export PATH="$OLD_PATH" + done +fi + +for compiler in "${COMPILERS[@]}"; do + for version in 0 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20; do + if [[ "$ARGS_CPP_VERSIONS" == "," || "$ARGS_CPP_VERSIONS" == *,$version,* ]]; then + cpp="$compiler-$version" + if [[ "$version" == 0 ]]; then + cpp="$compiler" + fi + cpp_output=$($cpp 2>&1 || true) + if [[ $cpp_output == *"no input files"* ]]; then + echo "Compiler '$cpp' has been found" + for cpp_standard in "${CPP_STANDARDS[@]}"; do + touch empty_file.cpp + cpp_output=$($cpp "$cpp_standard" empty_file.cpp 2>&1 || true) + if [[ ! $cpp_output == *"unrecognized"* && ! $cpp_output == *"standard"* ]]; then + if [[ "$machine" == "Windows" && "$cpp" == "clang++" && "$cpp_standard" == "--std=c++11" ]]; then + echo Ignore "$cpp" "$cpp_standard" on $machine + continue + fi + run_tests "$cpp" "$cpp_standard" + if [[ ! "$done" == "" ]]; then + done="$done, " + fi + done="$done$cpp@$cpp_standard" + fi + rm -f empty_file.* + done + fi + fi + done +done + +#if [[ "$machine" == "Windows" ]]; then +# for f in msvc-${MSVC_INCLUDE_YEAR}-include windows-kit-${WINKIT_INCLUDE_VERSION}-include; do +# rm -rf "${TESTS_DIR:?}"/lib/$f +# done +#fi + +if [[ -z "$done" ]]; then + echo -e "${RED}[ERROR]${NC} No compilers found\n" + exit 1 +fi + +echo -e "${GREEN}Successfully tested on${NC}: $done\n" diff --git a/tests/scripts/compile b/tests/scripts/compile new file mode 100644 index 00000000..11357b7d --- /dev/null +++ b/tests/scripts/compile @@ -0,0 +1,75 @@ +#!/bin/bash +set -eo pipefail + +SUCCESS_TXT="${GREEN}[SUCCESS]${NC}" + +src_file=$1 +exe_file=$(basename "${src_file%.*}") + +if [[ -z "$MACHINE" ]]; then + echo "Must provide MACHINE for compile" + exit 1 +fi + +if [[ "$MACHINE" == "Windows" ]]; then + exe_file=$(basename "${src_file%.*}".exe) +fi + +if [[ -z "$src_file" ]]; then + echo "Must provide \$1 for compile" + exit 1 +fi + +if [[ -z "$CPP_INCLUDE_DIR" ]]; then + echo "Must provide CPP_INCLUDE_DIR in environment" + exit 1 +fi + +if [[ -z "$CPP" ]]; then + echo "Must provide CPP in environment" + exit 1 +fi + +rm -f "$exe_file" + +EXTRA_ARGS="" + +if [[ -z "${TESTLIB_COMPILER_OPTIMIZATION_OPT}" ]]; then + if [[ "$2" == "--check-only" ]]; then + if [[ "$CPP" == "cl.exe" ]]; then + OPTIMIZATION="d" + else + OPTIMIZATION="0" + fi + else + OPTIMIZATION="2" + fi +else + OPTIMIZATION="${TESTLIB_COMPILER_OPTIMIZATION_OPT}" +fi + +if [[ "$CPP" == "cl.exe" ]]; then + echo "Compiling $src_file, running:" "$CPP" "$CPP_STANDARD" "-F268435456" "-EHsc" "-O${OPTIMIZATION}" -I"${CPP_INCLUDE_DIR}" -Fe"$exe_file" "$src_file" + "$CPP" "$CPP_STANDARD" "-F268435456" "-EHsc" "-O${OPTIMIZATION}" -I"${CPP_INCLUDE_DIR}" -Fe"$exe_file" "$src_file" +else + "$CPP" --version + dir=$(dirname "$CPP") + if [[ "$dir" == *"/bin" ]] || [[ "$MACHINE" == "Windows" ]]; then + EXTRA_ARGS="${EXTRA_ARGS} -static" + fi + echo "Compiling $src_file, running:" "$CPP" "$CPP_OPTS" "$CPP_STANDARD" -Wpedantic -Werror -I"${CPP_INCLUDE_DIR}""$EXTRA_ARGS" -o"$exe_file" "-O${OPTIMIZATION}" "$src_file" + eval "$CPP" "$CPP_OPTS" "$CPP_STANDARD" -Wpedantic -Werror -I"${CPP_INCLUDE_DIR}""$EXTRA_ARGS" -o"$exe_file" "-O${OPTIMIZATION}" "$src_file" +fi + +rm -f ./*.o ./*.obj + +if [ ! -f "$exe_file" ]; then + echo "Compilation failed: file $exe_file not found" + exit 1 +fi + +echo -e "${SUCCESS_TXT} $src_file compiled\n" + +if [[ "$2" == "--check-only" ]]; then + rm -rf "$exe_file" +fi diff --git a/tests/scripts/test-ref b/tests/scripts/test-ref new file mode 100644 index 00000000..2eff6c34 --- /dev/null +++ b/tests/scripts/test-ref @@ -0,0 +1,116 @@ +#!/bin/bash +set -eo pipefail + +FAILED_TXT="${RED}[FAILED]${NC}" +SUCCESS_TXT="${GREEN}[SUCCESS]${NC}" + +# Check $TESTS_DIR is given +if [[ -z "$TESTS_DIR" ]]; then + echo "Must provide \$TESTS_DIR env variable" + exit 1 +fi + +# Check $INVOCATION_ID is given: we use it as cache key to be sure compiled tester-lcmp is actual (see file $TESTS_DIR/tester-lcmp/tester-lcmp.$INVOCATION_ID) +if [[ -z "$INVOCATION_ID" ]]; then + echo "Must provide \$INVOCATION_ID env variable" + exit 1 +fi + +mkdir -p "$TESTS_DIR"/tester-lcmp + +# If compiled tester-lcmp is not actual +if [ ! -f "$TESTS_DIR"/tester-lcmp/tester-lcmp."$INVOCATION_ID" ]; then + # Clear + rm -f "$TESTS_DIR"/tester-lcmp/* + + # Compile it + CPP_INCLUDE_DIR_=$CPP_INCLUDE_DIR + export CPP_INCLUDE_DIR=$TESTS_DIR/lib + bash "$TESTS_DIR"/scripts/compile "$TESTS_DIR"/src/tester-lcmp.cpp + export CPP_INCLUDE_DIR=$CPP_INCLUDE_DIR_ + + # Move from current dir to /tester-lcmp + if [ ! -d ./tester-lcmp ]; then + mv -f ./tester-lcmp "$TESTS_DIR"/tester-lcmp + else + mv -f ./tester-lcmp.exe "$TESTS_DIR"/tester-lcmp + fi + + # Create file to inform that it was compiled to this $INVOCATION_ID + touch "$TESTS_DIR"/tester-lcmp/tester-lcmp."$INVOCATION_ID" +fi + +# First argument as a subdirectory in ./refs +ref_dir=$1 +if [[ -z "$ref_dir" ]]; then + echo "Must provide \$1 for test-ref" + exit 1 +fi + +refs=refs/$1 + +shift 1 + +# Check if we don't have invocation reference files +if [ ! -d "$refs" ]; then + if [[ "$TEST_REF_FORBID_GEN_REFS" == "true" ]]; then + echo "You forgot to run push ref files for invocation: ""$*""" + echo "Run test locally, it will produce ref files and push it into the repo" + exit 1 + fi + # Create them + mkdir -p "$refs" + echo Generating tester refs: "$*" + exit_code=0 + # shellcheck disable=SC2048 + $* 1>"$refs"/stdout 2>"$refs"/stderr || exit_code=$? + echo $exit_code >"$refs"/exit_code + echo -e "${SUCCESS_TXT} generated execution reference files (exit code: $exit_code)\n" +else + # Do invocation + echo Testing refs: "$*" + exit_code=0 + # shellcheck disable=SC2048 + $* 1>"$refs"/stdout.aux 2>"$refs"/stderr.aux || exit_code=$? + stdout_size=$(wc -c < "$refs"/stdout.aux) + stderr_size=$(wc -c < "$refs"/stderr.aux) + echo "Program exit code: $exit_code, stdout size: $stdout_size bytes, stderr size: $stderr_size bytes" + echo $exit_code >"$refs"/exit_code.aux + + # Check exit code is the same + tester_lcmp_exit_code=0 + "$TESTS_DIR"/tester-lcmp/tester-lcmp "$TESTS_DIR"/tester-lcmp/tester-lcmp."$INVOCATION_ID" "$refs"/exit_code.aux "$refs"/exit_code 2>tester-lcmp.out || tester_lcmp_exit_code=$? + if [[ ! "$tester_lcmp_exit_code" == "0" ]]; then + echo -e "${FAILED_TXT} exit_code mismatched: found $(cat < "$refs"/exit_code.aux) but expected $(cat "$refs"/exit_code)\n" + cat tester-lcmp.out + rm -f tester-lcmp.out + rm -f "$refs"/*.aux + exit 1 + fi + echo $exit_code >"$refs"/exit_code.aux + + # Check stdout is the same + "$TESTS_DIR"/tester-lcmp/tester-lcmp "$TESTS_DIR"/tester-lcmp/tester-lcmp."$INVOCATION_ID" "$refs"/stdout.aux "$refs"/stdout 2>tester-lcmp.out || tester_lcmp_exit_code=$? + if [[ ! "$tester_lcmp_exit_code" == "0" ]]; then + echo -e "${FAILED_TXT} stdout mismatched\n" + cat tester-lcmp.out + rm -f tester-lcmp.out + rm -f "$refs"/*.aux + exit 1 + fi + + # Check stderr is the same + "$TESTS_DIR"/tester-lcmp/tester-lcmp "$TESTS_DIR"/tester-lcmp/tester-lcmp."$INVOCATION_ID" "$refs"/stderr.aux "$refs"/stderr 2>tester-lcmp.out || tester_lcmp_exit_code=$? + if [[ ! "$tester_lcmp_exit_code" == "0" ]]; then + echo -e "${FAILED_TXT} stderr mismatched\n" + cat tester-lcmp.out + rm -f tester-lcmp.out + rm -f "$refs"/*.aux + exit 1 + fi + + # Invocation is the same! + echo -e "${SUCCESS_TXT} execution matched with reference (exit code: $exit_code)\n" + rm -f tester-lcmp.out + rm -f "$refs"/*.aux +fi diff --git a/tests/src/tester-lcmp.cpp b/tests/src/tester-lcmp.cpp new file mode 100644 index 00000000..1e3ace42 --- /dev/null +++ b/tests/src/tester-lcmp.cpp @@ -0,0 +1,54 @@ +#include "testlib.h" +#include +#include +#include + +using namespace std; + +bool compareWords(string a, string b) +{ + vector va, vb; + stringstream sa; + + sa << a; + string cur; + while (sa >> cur) + va.push_back(cur); + + stringstream sb; + sb << b; + while (sb >> cur) + vb.push_back(cur); + + return (va == vb); +} + +int main(int argc, char * argv[]) +{ + setName("compare files as sequence of tokens in lines"); + registerTestlibCmd(argc, argv); + + std::string strAnswer; + + int n = 0; + while (!ans.eof()) + { + std::string j = ans.readString(); + + if (j == "" && ans.eof()) + break; + + std::string p = ouf.readString(); + strAnswer = p; + + n++; + + if (!compareWords(j, p)) + quitf(_wa, "%d%s lines differ - expected: '%s', found: '%s'", n, englishEnding(n).c_str(), compress(j).c_str(), compress(p).c_str()); + } + + if (n == 1) + quitf(_ok, "single line: '%s'", compress(strAnswer).c_str()); + + quitf(_ok, "%d lines", n); +} diff --git a/tests/t.bat b/tests/t.bat new file mode 100755 index 00000000..c3d3f25c --- /dev/null +++ b/tests/t.bat @@ -0,0 +1,2 @@ +rem Shortcut to run `run.sh g++ 11 v0 %*` +bash "%~dp0\t.sh" %* diff --git a/tests/t.sh b/tests/t.sh new file mode 100755 index 00000000..fbc6694d --- /dev/null +++ b/tests/t.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -eo pipefail + +# Shortcut to run `run.sh g++ 11 v0 $*` +TESTS_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd) +bash $TESTS_DIR/run.sh g++ 11 v0 $* diff --git a/tests/test-000_compile-all-cpp/run.sh b/tests/test-000_compile-all-cpp/run.sh new file mode 100644 index 00000000..905685f0 --- /dev/null +++ b/tests/test-000_compile-all-cpp/run.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eo pipefail + +( + IFS=' +' + for f in $(find "$TESTS_DIR"/.. -name "*.cpp"); do + if [[ ! "$f" == *../tests/* ]]; then + bash ../scripts/compile "$f" --check-only + fi + done +) diff --git a/tests/test-001_run-sval-case-nval/files/unix/case-nval/input.01 b/tests/test-001_run-sval-case-nval/files/unix/case-nval/input.01 new file mode 100644 index 00000000..e8183f05 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/unix/case-nval/input.01 @@ -0,0 +1,3 @@ +1 +1 +1 diff --git a/tests/test-001_run-sval-case-nval/files/unix/case-nval/input.02 b/tests/test-001_run-sval-case-nval/files/unix/case-nval/input.02 new file mode 100644 index 00000000..934d65d8 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/unix/case-nval/input.02 @@ -0,0 +1,3 @@ +1 +4 +1000 100 -100 -1000 diff --git a/tests/test-001_run-sval-case-nval/files/unix/case-nval/input.03 b/tests/test-001_run-sval-case-nval/files/unix/case-nval/input.03 new file mode 100644 index 00000000..9f3c7c92 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/unix/case-nval/input.03 @@ -0,0 +1,7 @@ +3 +4 +1000 100 -100 -1000 +5 +3 1 4 2 5 +11 +1 2 3 4 5 6 7 8 9 10 11 diff --git a/tests/test-001_run-sval-case-nval/files/unix/case-nval/input.04 b/tests/test-001_run-sval-case-nval/files/unix/case-nval/input.04 new file mode 100644 index 00000000..b0909408 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/unix/case-nval/input.04 @@ -0,0 +1,8 @@ +3 +4 +1000 100 -100 -1000 + +5 +3 1 4 2 5 +11 +1 2 3 4 5 6 7 8 9 10 11 diff --git a/tests/test-001_run-sval-case-nval/files/unix/case-nval/input.05 b/tests/test-001_run-sval-case-nval/files/unix/case-nval/input.05 new file mode 100644 index 00000000..b43aaa9c --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/unix/case-nval/input.05 @@ -0,0 +1,7 @@ +3 +4 +1000 100 -100 -1000 +5 +3 1 4 2 1001 +11 +1 2 3 4 5 6 7 8 9 10 11 diff --git a/tests/test-001_run-sval-case-nval/files/unix/case-nval/input.06 b/tests/test-001_run-sval-case-nval/files/unix/case-nval/input.06 new file mode 100644 index 00000000..97791722 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/unix/case-nval/input.06 @@ -0,0 +1,7 @@ +3 +4 +1000 100 -100 -1000 +5 +3 1 4 2 1001 +11 + diff --git a/tests/test-001_run-sval-case-nval/files/unix/case-string-zb/input.01 b/tests/test-001_run-sval-case-nval/files/unix/case-string-zb/input.01 new file mode 100644 index 00000000..dd96e0e0 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/unix/case-string-zb/input.01 @@ -0,0 +1,4 @@ +3 +!\\!\\!!!\!!\\!\!!!\\\\\!!\!\\!! +!c!c\c\c!c\!cc\\\!!!c!c\c! +\c\c\ccc!\!\c!!!\c!\c!\!\c!\!\c!\!c\!\!\c!\!c\!\c!\c!\c!!\!c!\c!\!\c\\c!!!\c!\c\!c\!\c!\c!\c!\c!\!c! diff --git a/tests/test-001_run-sval-case-nval/files/unix/sval/input.01 b/tests/test-001_run-sval-case-nval/files/unix/sval/input.01 new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/files/unix/sval/input.02 b/tests/test-001_run-sval-case-nval/files/unix/sval/input.02 new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/unix/sval/input.02 @@ -0,0 +1 @@ + diff --git a/tests/test-001_run-sval-case-nval/files/unix/sval/input.03 b/tests/test-001_run-sval-case-nval/files/unix/sval/input.03 new file mode 100644 index 00000000..78981922 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/unix/sval/input.03 @@ -0,0 +1 @@ +a diff --git a/tests/test-001_run-sval-case-nval/files/unix/sval/input.04 b/tests/test-001_run-sval-case-nval/files/unix/sval/input.04 new file mode 100644 index 00000000..95e76ee2 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/unix/sval/input.04 @@ -0,0 +1 @@ +abacabazwetyuiop diff --git a/tests/test-001_run-sval-case-nval/files/unix/sval/input.05 b/tests/test-001_run-sval-case-nval/files/unix/sval/input.05 new file mode 100644 index 00000000..16159be7 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/unix/sval/input.05 @@ -0,0 +1 @@ +abacabazwetyuiopasdfghjklxcvbnmegeeekdddabacabazwetyuiopasdfghjklxcvbnmegeeekdddabacabazwetyuiopasda diff --git a/tests/test-001_run-sval-case-nval/files/unix/sval/input.06 b/tests/test-001_run-sval-case-nval/files/unix/sval/input.06 new file mode 100644 index 00000000..d716ff76 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/unix/sval/input.06 @@ -0,0 +1 @@ +asbacabazwetyuiopasdfghjklxcvbnmegeeekdddabacabazwetyuiopasdfghjklxcvbnmegeeekdddabacabazwetyuiopasda diff --git a/tests/test-001_run-sval-case-nval/files/unix/sval/input.07 b/tests/test-001_run-sval-case-nval/files/unix/sval/input.07 new file mode 100644 index 00000000..01099aa0 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/unix/sval/input.07 @@ -0,0 +1 @@ +asbacabazwetyuiopasdfghjklxcvbnmegeeekdddabacabazwetyuiopasdfghjklxcvbnmegeeekdddabacabazwetyuiopa.a diff --git a/tests/test-001_run-sval-case-nval/files/unix/sval/input.08 b/tests/test-001_run-sval-case-nval/files/unix/sval/input.08 new file mode 100644 index 00000000..7507080a --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/unix/sval/input.08 @@ -0,0 +1 @@ +abacabazwetyuiopasdfghjklxcvbnmegeeekdddabacabazwetyuiopasdfghjklxcvbnmegeeekdddabacabazwetyuiopasda diff --git a/tests/test-001_run-sval-case-nval/files/unix/sval/input.09 b/tests/test-001_run-sval-case-nval/files/unix/sval/input.09 new file mode 100644 index 00000000..a1cd2d23 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/unix/sval/input.09 @@ -0,0 +1 @@ +abacabazwetyuiopasdfghjklxcvbnmegeeekdddabacabazwetyuiopasdfghjklxcvbnmegeeekdddabacabazwetyuiopasda \ No newline at end of file diff --git a/tests/test-001_run-sval-case-nval/files/unix/sval/input.10 b/tests/test-001_run-sval-case-nval/files/unix/sval/input.10 new file mode 100644 index 00000000..5300c7ce --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/unix/sval/input.10 @@ -0,0 +1 @@ + abcabazwetyuiopasdfghjklxcvbnmegeeekdddabacabazwetyuiopasdfghjklxcvbnmegeeekdddabacabazwetyuiopasda diff --git a/tests/test-001_run-sval-case-nval/files/win/case-nval/input.01 b/tests/test-001_run-sval-case-nval/files/win/case-nval/input.01 new file mode 100644 index 00000000..d1e54069 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/win/case-nval/input.01 @@ -0,0 +1,3 @@ +1 +1 +1 diff --git a/tests/test-001_run-sval-case-nval/files/win/case-nval/input.02 b/tests/test-001_run-sval-case-nval/files/win/case-nval/input.02 new file mode 100644 index 00000000..9ccda0fa --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/win/case-nval/input.02 @@ -0,0 +1,3 @@ +1 +4 +1000 100 -100 -1000 diff --git a/tests/test-001_run-sval-case-nval/files/win/case-nval/input.03 b/tests/test-001_run-sval-case-nval/files/win/case-nval/input.03 new file mode 100644 index 00000000..c3e61a80 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/win/case-nval/input.03 @@ -0,0 +1,7 @@ +3 +4 +1000 100 -100 -1000 +5 +3 1 4 2 5 +11 +1 2 3 4 5 6 7 8 9 10 11 diff --git a/tests/test-001_run-sval-case-nval/files/win/case-nval/input.04 b/tests/test-001_run-sval-case-nval/files/win/case-nval/input.04 new file mode 100644 index 00000000..519165e7 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/win/case-nval/input.04 @@ -0,0 +1,8 @@ +3 +4 +1000 100 -100 -1000 + +5 +3 1 4 2 5 +11 +1 2 3 4 5 6 7 8 9 10 11 diff --git a/tests/test-001_run-sval-case-nval/files/win/case-nval/input.05 b/tests/test-001_run-sval-case-nval/files/win/case-nval/input.05 new file mode 100644 index 00000000..6ad26c9f --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/win/case-nval/input.05 @@ -0,0 +1,7 @@ +3 +4 +1000 100 -100 -1000 +5 +3 1 4 2 1001 +11 +1 2 3 4 5 6 7 8 9 10 11 diff --git a/tests/test-001_run-sval-case-nval/files/win/case-nval/input.06 b/tests/test-001_run-sval-case-nval/files/win/case-nval/input.06 new file mode 100644 index 00000000..d43e8e51 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/win/case-nval/input.06 @@ -0,0 +1,7 @@ +3 +4 +1000 100 -100 -1000 +5 +3 1 4 2 1001 +11 + diff --git a/tests/test-001_run-sval-case-nval/files/win/case-string-zb/input.01 b/tests/test-001_run-sval-case-nval/files/win/case-string-zb/input.01 new file mode 100644 index 00000000..da55c369 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/win/case-string-zb/input.01 @@ -0,0 +1,4 @@ +3 +!\\!\\!!!\!!\\!\!!!\\\\\!!\!\\!! +!c!c\c\c!c\!cc\\\!!!c!c\c! +\c\c\ccc!\!\c!!!\c!\c!\!\c!\!\c!\!c\!\!\c!\!c\!\c!\c!\c!!\!c!\c!\!\c\\c!!!\c!\c\!c\!\c!\c!\c!\c!\!c! diff --git a/tests/test-001_run-sval-case-nval/files/win/sval/input.01 b/tests/test-001_run-sval-case-nval/files/win/sval/input.01 new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/files/win/sval/input.02 b/tests/test-001_run-sval-case-nval/files/win/sval/input.02 new file mode 100644 index 00000000..d3f5a12f --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/win/sval/input.02 @@ -0,0 +1 @@ + diff --git a/tests/test-001_run-sval-case-nval/files/win/sval/input.03 b/tests/test-001_run-sval-case-nval/files/win/sval/input.03 new file mode 100644 index 00000000..533790e5 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/win/sval/input.03 @@ -0,0 +1 @@ +a diff --git a/tests/test-001_run-sval-case-nval/files/win/sval/input.04 b/tests/test-001_run-sval-case-nval/files/win/sval/input.04 new file mode 100644 index 00000000..1105b609 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/win/sval/input.04 @@ -0,0 +1 @@ +abacabazwetyuiop diff --git a/tests/test-001_run-sval-case-nval/files/win/sval/input.05 b/tests/test-001_run-sval-case-nval/files/win/sval/input.05 new file mode 100644 index 00000000..7507080a --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/win/sval/input.05 @@ -0,0 +1 @@ +abacabazwetyuiopasdfghjklxcvbnmegeeekdddabacabazwetyuiopasdfghjklxcvbnmegeeekdddabacabazwetyuiopasda diff --git a/tests/test-001_run-sval-case-nval/files/win/sval/input.06 b/tests/test-001_run-sval-case-nval/files/win/sval/input.06 new file mode 100644 index 00000000..e9bded3e --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/win/sval/input.06 @@ -0,0 +1 @@ +asbacabazwetyuiopasdfghjklxcvbnmegeeekdddabacabazwetyuiopasdfghjklxcvbnmegeeekdddabacabazwetyuiopasda diff --git a/tests/test-001_run-sval-case-nval/files/win/sval/input.07 b/tests/test-001_run-sval-case-nval/files/win/sval/input.07 new file mode 100644 index 00000000..8a50dc8b --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/win/sval/input.07 @@ -0,0 +1 @@ +asbacabazwetyuiopasdfghjklxcvbnmegeeekdddabacabazwetyuiopasdfghjklxcvbnmegeeekdddabacabazwetyuiopa.a diff --git a/tests/test-001_run-sval-case-nval/files/win/sval/input.08 b/tests/test-001_run-sval-case-nval/files/win/sval/input.08 new file mode 100644 index 00000000..16159be7 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/win/sval/input.08 @@ -0,0 +1 @@ +abacabazwetyuiopasdfghjklxcvbnmegeeekdddabacabazwetyuiopasdfghjklxcvbnmegeeekdddabacabazwetyuiopasda diff --git a/tests/test-001_run-sval-case-nval/files/win/sval/input.09 b/tests/test-001_run-sval-case-nval/files/win/sval/input.09 new file mode 100644 index 00000000..a1cd2d23 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/win/sval/input.09 @@ -0,0 +1 @@ +abacabazwetyuiopasdfghjklxcvbnmegeeekdddabacabazwetyuiopasdfghjklxcvbnmegeeekdddabacabazwetyuiopasda \ No newline at end of file diff --git a/tests/test-001_run-sval-case-nval/files/win/sval/input.10 b/tests/test-001_run-sval-case-nval/files/win/sval/input.10 new file mode 100644 index 00000000..1e0404a4 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/files/win/sval/input.10 @@ -0,0 +1 @@ + abcabazwetyuiopasdfghjklxcvbnmegeeekdddabacabazwetyuiopasdfghjklxcvbnmegeeekdddabacabazwetyuiopasda diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-1/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-1/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-1/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-1/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-1/stderr new file mode 100644 index 00000000..70411481 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-1/stderr @@ -0,0 +1,3 @@ +MUó1 +!c1;1 +1 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-1/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-1/stdout new file mode 100644 index 00000000..3abe0596 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-1/stdout @@ -0,0 +1,2 @@ +1 +1 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-2/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-2/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-2/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-2/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-2/stderr new file mode 100644 index 00000000..70411481 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-2/stderr @@ -0,0 +1,3 @@ +MUó1 +!c1;1 +1 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-2/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-2/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-3-stderr/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-3-stderr/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-3-stderr/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-3-stderr/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-3-stderr/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-3-stderr/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-3-stderr/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-3/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-3/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-3/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-3/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-3/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-3/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-3/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-4/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-4/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-4/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-4/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-4/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-4/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01-4/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01/stderr new file mode 100644 index 00000000..70411481 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01/stderr @@ -0,0 +1,3 @@ +MUó1 +!c1;1 +1 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.01/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-1/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-1/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-1/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-1/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-1/stderr new file mode 100644 index 00000000..7798b760 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-1/stderr @@ -0,0 +1,3 @@ +MUó1 +!c1;4 +1000 100 -100 -1000 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-1/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-1/stdout new file mode 100644 index 00000000..1ba8b0a4 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-1/stdout @@ -0,0 +1,2 @@ +4 +1000 100 -100 -1000 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-2/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-2/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-2/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-2/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-2/stderr new file mode 100644 index 00000000..7798b760 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-2/stderr @@ -0,0 +1,3 @@ +MUó1 +!c1;4 +1000 100 -100 -1000 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-2/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-2/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-3-stderr/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-3-stderr/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-3-stderr/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-3-stderr/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-3-stderr/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-3-stderr/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-3-stderr/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-3/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-3/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-3/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-3/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-3/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-3/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-3/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-4/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-4/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-4/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-4/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-4/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-4/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02-4/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02/stderr new file mode 100644 index 00000000..7798b760 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02/stderr @@ -0,0 +1,3 @@ +MUó1 +!c1;4 +1000 100 -100 -1000 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.02/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-1/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-1/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-1/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-1/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-1/stderr new file mode 100644 index 00000000..9f07f38e --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-1/stderr @@ -0,0 +1,7 @@ +MUó3 +!c1;4 +1000 100 -100 -1000 +!c2;5 +3 1 4 2 5 +!c3;11 +1 2 3 4 5 6 7 8 9 10 11 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-1/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-1/stdout new file mode 100644 index 00000000..1ba8b0a4 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-1/stdout @@ -0,0 +1,2 @@ +4 +1000 100 -100 -1000 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-2/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-2/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-2/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-2/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-2/stderr new file mode 100644 index 00000000..9f07f38e --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-2/stderr @@ -0,0 +1,7 @@ +MUó3 +!c1;4 +1000 100 -100 -1000 +!c2;5 +3 1 4 2 5 +!c3;11 +1 2 3 4 5 6 7 8 9 10 11 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-2/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-2/stdout new file mode 100644 index 00000000..abd45077 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-2/stdout @@ -0,0 +1,2 @@ +5 +3 1 4 2 5 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-3-stderr/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-3-stderr/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-3-stderr/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-3-stderr/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-3-stderr/stderr new file mode 100644 index 00000000..605fbb0e --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-3-stderr/stderr @@ -0,0 +1,2 @@ +11 +1 2 3 4 5 6 7 8 9 10 11 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-3-stderr/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-3-stderr/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-3/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-3/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-3/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-3/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-3/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-3/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-3/stdout new file mode 100644 index 00000000..605fbb0e --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-3/stdout @@ -0,0 +1,2 @@ +11 +1 2 3 4 5 6 7 8 9 10 11 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-4/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-4/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-4/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-4/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-4/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-4/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03-4/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03/stderr new file mode 100644 index 00000000..9f07f38e --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03/stderr @@ -0,0 +1,7 @@ +MUó3 +!c1;4 +1000 100 -100 -1000 +!c2;5 +3 1 4 2 5 +!c3;11 +1 2 3 4 5 6 7 8 9 10 11 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.03/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-1/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-1/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-1/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-1/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-1/stderr new file mode 100644 index 00000000..a322258f --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-1/stderr @@ -0,0 +1 @@ +FAIL Unexpected white-space - token expected (test case 2, stdin, line 4) diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-1/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-1/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-2/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-2/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-2/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-2/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-2/stderr new file mode 100644 index 00000000..a322258f --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-2/stderr @@ -0,0 +1 @@ +FAIL Unexpected white-space - token expected (test case 2, stdin, line 4) diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-2/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-2/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-3-stderr/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-3-stderr/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-3-stderr/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-3-stderr/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-3-stderr/stderr new file mode 100644 index 00000000..a322258f --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-3-stderr/stderr @@ -0,0 +1 @@ +FAIL Unexpected white-space - token expected (test case 2, stdin, line 4) diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-3-stderr/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-3-stderr/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-3/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-3/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-3/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-3/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-3/stderr new file mode 100644 index 00000000..a322258f --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-3/stderr @@ -0,0 +1 @@ +FAIL Unexpected white-space - token expected (test case 2, stdin, line 4) diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-3/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-3/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-4/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-4/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-4/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-4/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-4/stderr new file mode 100644 index 00000000..a322258f --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-4/stderr @@ -0,0 +1 @@ +FAIL Unexpected white-space - token expected (test case 2, stdin, line 4) diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-4/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04-4/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04/stderr new file mode 100644 index 00000000..a322258f --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04/stderr @@ -0,0 +1 @@ +FAIL Unexpected white-space - token expected (test case 2, stdin, line 4) diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.04/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-1/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-1/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-1/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-1/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-1/stderr new file mode 100644 index 00000000..57986dcb --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-1/stderr @@ -0,0 +1 @@ +FAIL Integer element a[5] equals to 1001, violates the range [-1000, 1000] (test case 2, stdin, line 5) diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-1/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-1/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-2/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-2/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-2/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-2/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-2/stderr new file mode 100644 index 00000000..57986dcb --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-2/stderr @@ -0,0 +1 @@ +FAIL Integer element a[5] equals to 1001, violates the range [-1000, 1000] (test case 2, stdin, line 5) diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-2/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-2/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-3-stderr/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-3-stderr/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-3-stderr/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-3-stderr/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-3-stderr/stderr new file mode 100644 index 00000000..57986dcb --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-3-stderr/stderr @@ -0,0 +1 @@ +FAIL Integer element a[5] equals to 1001, violates the range [-1000, 1000] (test case 2, stdin, line 5) diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-3-stderr/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-3-stderr/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-3/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-3/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-3/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-3/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-3/stderr new file mode 100644 index 00000000..57986dcb --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-3/stderr @@ -0,0 +1 @@ +FAIL Integer element a[5] equals to 1001, violates the range [-1000, 1000] (test case 2, stdin, line 5) diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-3/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-3/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-4/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-4/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-4/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-4/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-4/stderr new file mode 100644 index 00000000..57986dcb --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-4/stderr @@ -0,0 +1 @@ +FAIL Integer element a[5] equals to 1001, violates the range [-1000, 1000] (test case 2, stdin, line 5) diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-4/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05-4/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05/stderr new file mode 100644 index 00000000..57986dcb --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05/stderr @@ -0,0 +1 @@ +FAIL Integer element a[5] equals to 1001, violates the range [-1000, 1000] (test case 2, stdin, line 5) diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.05/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-1/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-1/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-1/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-1/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-1/stderr new file mode 100644 index 00000000..57986dcb --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-1/stderr @@ -0,0 +1 @@ +FAIL Integer element a[5] equals to 1001, violates the range [-1000, 1000] (test case 2, stdin, line 5) diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-1/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-1/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-2/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-2/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-2/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-2/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-2/stderr new file mode 100644 index 00000000..57986dcb --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-2/stderr @@ -0,0 +1 @@ +FAIL Integer element a[5] equals to 1001, violates the range [-1000, 1000] (test case 2, stdin, line 5) diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-2/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-2/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-3-stderr/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-3-stderr/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-3-stderr/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-3-stderr/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-3-stderr/stderr new file mode 100644 index 00000000..57986dcb --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-3-stderr/stderr @@ -0,0 +1 @@ +FAIL Integer element a[5] equals to 1001, violates the range [-1000, 1000] (test case 2, stdin, line 5) diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-3-stderr/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-3-stderr/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-3/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-3/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-3/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-3/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-3/stderr new file mode 100644 index 00000000..57986dcb --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-3/stderr @@ -0,0 +1 @@ +FAIL Integer element a[5] equals to 1001, violates the range [-1000, 1000] (test case 2, stdin, line 5) diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-3/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-3/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-4/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-4/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-4/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-4/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-4/stderr new file mode 100644 index 00000000..57986dcb --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-4/stderr @@ -0,0 +1 @@ +FAIL Integer element a[5] equals to 1001, violates the range [-1000, 1000] (test case 2, stdin, line 5) diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-4/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06-4/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06/stderr new file mode 100644 index 00000000..57986dcb --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06/stderr @@ -0,0 +1 @@ +FAIL Integer element a[5] equals to 1001, violates the range [-1000, 1000] (test case 2, stdin, line 5) diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-nval-input.06/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-1/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-1/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-1/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-1/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-1/stderr new file mode 100644 index 00000000..7209edb5 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-1/stderr @@ -0,0 +1,4 @@ +MUó3 +!c1;\!\\\\\!\\\\\!\!\!\\\!\!\\\\\!\\\!\!\!\\\\\\\\\\\!\!\\\!\\\\\!\! +!c2;\!c\!c\\c\\c\!c\\\!cc\\\\\\\!\!\!c\!c\\c\! +!c3;\\c\\c\\ccc\!\\\!\\c\!\!\!\\c\!\\c\!\\\!\\c\!\\\!\\c\!\\\!c\\\!\\\!\\c\!\\\!c\\\!\\c\!\\c\!\\c\!\!\\\!c\!\\c\!\\\!\\c\\\\c\!\!\!\\c\!\\c\\\!c\\\!\\c\!\\c\!\\c\!\\c\!\\\!c\! diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-1/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-1/stdout new file mode 100644 index 00000000..74f17048 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-1/stdout @@ -0,0 +1 @@ +!\\!\\!!!\!!\\!\!!!\\\\\!!\!\\!! diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-2/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-2/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-2/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-2/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-2/stderr new file mode 100644 index 00000000..7209edb5 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-2/stderr @@ -0,0 +1,4 @@ +MUó3 +!c1;\!\\\\\!\\\\\!\!\!\\\!\!\\\\\!\\\!\!\!\\\\\\\\\\\!\!\\\!\\\\\!\! +!c2;\!c\!c\\c\\c\!c\\\!cc\\\\\\\!\!\!c\!c\\c\! +!c3;\\c\\c\\ccc\!\\\!\\c\!\!\!\\c\!\\c\!\\\!\\c\!\\\!\\c\!\\\!c\\\!\\\!\\c\!\\\!c\\\!\\c\!\\c\!\\c\!\!\\\!c\!\\c\!\\\!\\c\\\\c\!\!\!\\c\!\\c\\\!c\\\!\\c\!\\c\!\\c\!\\c\!\\\!c\! diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-2/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-2/stdout new file mode 100644 index 00000000..2848144a --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-2/stdout @@ -0,0 +1 @@ +!c!c\c\c!c\!cc\\\!!!c!c\c! diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-3-stderr/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-3-stderr/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-3-stderr/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-3-stderr/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-3-stderr/stderr new file mode 100644 index 00000000..a007e7bc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-3-stderr/stderr @@ -0,0 +1 @@ +\c\c\ccc!\!\c!!!\c!\c!\!\c!\!\c!\!c\!\!\c!\!c\!\c!\c!\c!!\!c!\c!\!\c\\c!!!\c!\c\!c\!\c!\c!\c!\c!\!c! diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-3-stderr/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-3-stderr/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-3/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-3/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-3/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-3/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-3/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-3/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-3/stdout new file mode 100644 index 00000000..a007e7bc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-3/stdout @@ -0,0 +1 @@ +\c\c\ccc!\!\c!!!\c!\c!\!\c!\!\c!\!c\!\!\c!\!c\!\c!\c!\c!!\!c!\c!\!\c\\c!!!\c!\c\!c\!\c!\c!\c!\c!\!c! diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-4/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-4/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-4/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-4/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-4/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-4/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01-4/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01/exit_code b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01/stderr b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01/stderr new file mode 100644 index 00000000..7209edb5 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01/stderr @@ -0,0 +1,4 @@ +MUó3 +!c1;\!\\\\\!\\\\\!\!\!\\\!\!\\\\\!\\\!\!\!\\\\\\\\\\\!\!\\\!\\\\\!\! +!c2;\!c\!c\\c\\c\!c\\\!cc\\\\\\\!\!\!c\!c\\c\! +!c3;\\c\\c\\ccc\!\\\!\\c\!\!\!\\c\!\\c\!\\\!\\c\!\\\!\\c\!\\\!c\\\!\\\!\\c\!\\\!c\\\!\\c\!\\c\!\\c\!\!\\\!c\!\\c\!\\\!\\c\\\\c\!\!\!\\c\!\\c\\\!c\\\!\\c\!\\c\!\\c\!\\c\!\\\!c\! diff --git a/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01/stdout b/tests/test-001_run-sval-case-nval/refs/r-case-string-zb-input.01/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.01/exit_code b/tests/test-001_run-sval-case-nval/refs/r-sval-input.01/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-sval-input.01/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.01/stderr b/tests/test-001_run-sval-case-nval/refs/r-sval-input.01/stderr new file mode 100644 index 00000000..6851dab2 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-sval-input.01/stderr @@ -0,0 +1 @@ +FAIL Unexpected end of file - token expected (stdin, line 1) diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.01/stdout b/tests/test-001_run-sval-case-nval/refs/r-sval-input.01/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.02/exit_code b/tests/test-001_run-sval-case-nval/refs/r-sval-input.02/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-sval-input.02/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.02/stderr b/tests/test-001_run-sval-case-nval/refs/r-sval-input.02/stderr new file mode 100644 index 00000000..4afa0661 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-sval-input.02/stderr @@ -0,0 +1 @@ +FAIL Unexpected white-space - token expected (stdin, line 1) diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.02/stdout b/tests/test-001_run-sval-case-nval/refs/r-sval-input.02/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.03/exit_code b/tests/test-001_run-sval-case-nval/refs/r-sval-input.03/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-sval-input.03/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.03/stderr b/tests/test-001_run-sval-case-nval/refs/r-sval-input.03/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.03/stdout b/tests/test-001_run-sval-case-nval/refs/r-sval-input.03/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.04/exit_code b/tests/test-001_run-sval-case-nval/refs/r-sval-input.04/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-sval-input.04/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.04/stderr b/tests/test-001_run-sval-case-nval/refs/r-sval-input.04/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.04/stdout b/tests/test-001_run-sval-case-nval/refs/r-sval-input.04/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.05/exit_code b/tests/test-001_run-sval-case-nval/refs/r-sval-input.05/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-sval-input.05/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.05/stderr b/tests/test-001_run-sval-case-nval/refs/r-sval-input.05/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.05/stdout b/tests/test-001_run-sval-case-nval/refs/r-sval-input.05/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.06/exit_code b/tests/test-001_run-sval-case-nval/refs/r-sval-input.06/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-sval-input.06/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.06/stderr b/tests/test-001_run-sval-case-nval/refs/r-sval-input.06/stderr new file mode 100644 index 00000000..e3854ade --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-sval-input.06/stderr @@ -0,0 +1 @@ +FAIL Token parameter [name=s] equals to "asbacabazwetyuiopasdfghjklxcvb...nmegeeekdddabacabazwetyuiopasda", doesn't correspond to pattern "[a-z]{1,100}" (stdin, line 1) diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.06/stdout b/tests/test-001_run-sval-case-nval/refs/r-sval-input.06/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.07/exit_code b/tests/test-001_run-sval-case-nval/refs/r-sval-input.07/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-sval-input.07/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.07/stderr b/tests/test-001_run-sval-case-nval/refs/r-sval-input.07/stderr new file mode 100644 index 00000000..4a9f2f30 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-sval-input.07/stderr @@ -0,0 +1 @@ +FAIL Token parameter [name=s] equals to "asbacabazwetyuiopasdfghjklxcvb...bnmegeeekdddabacabazwetyuiopa.a", doesn't correspond to pattern "[a-z]{1,100}" (stdin, line 1) diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.07/stdout b/tests/test-001_run-sval-case-nval/refs/r-sval-input.07/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.08/exit_code b/tests/test-001_run-sval-case-nval/refs/r-sval-input.08/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-sval-input.08/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.08/stderr b/tests/test-001_run-sval-case-nval/refs/r-sval-input.08/stderr new file mode 100644 index 00000000..1ffb52d1 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-sval-input.08/stderr @@ -0,0 +1 @@ +FAIL Expected EOLN (stdin, line 1) diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.08/stdout b/tests/test-001_run-sval-case-nval/refs/r-sval-input.08/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.09/exit_code b/tests/test-001_run-sval-case-nval/refs/r-sval-input.09/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-sval-input.09/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.09/stderr b/tests/test-001_run-sval-case-nval/refs/r-sval-input.09/stderr new file mode 100644 index 00000000..1ffb52d1 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-sval-input.09/stderr @@ -0,0 +1 @@ +FAIL Expected EOLN (stdin, line 1) diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.09/stdout b/tests/test-001_run-sval-case-nval/refs/r-sval-input.09/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.10/exit_code b/tests/test-001_run-sval-case-nval/refs/r-sval-input.10/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-sval-input.10/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.10/stderr b/tests/test-001_run-sval-case-nval/refs/r-sval-input.10/stderr new file mode 100644 index 00000000..4afa0661 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/refs/r-sval-input.10/stderr @@ -0,0 +1 @@ +FAIL Unexpected white-space - token expected (stdin, line 1) diff --git a/tests/test-001_run-sval-case-nval/refs/r-sval-input.10/stdout b/tests/test-001_run-sval-case-nval/refs/r-sval-input.10/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-001_run-sval-case-nval/run.sh b/tests/test-001_run-sval-case-nval/run.sh new file mode 100644 index 00000000..18a71879 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/run.sh @@ -0,0 +1,41 @@ +#!/bin/bash +set -eo pipefail + +os="unix" +if [[ "$MACHINE" == "Windows" ]]; then + os="win" +fi + +bash ../scripts/compile src/case-nval.cpp +for i in files/"$os"/case-nval/*; do + j=$(basename $i) + bash ../scripts/test-ref r-case-nval-$j "$VALGRIND" ./case-nval --testMarkupFileName stderr <$i + for t in 1 2; do + bash ../scripts/test-ref r-case-nval-$j-$t "$VALGRIND" ./case-nval --testMarkupFileName stderr --testCase "${t}" <$i + done + bash ../scripts/test-ref r-case-nval-$j-3 "$VALGRIND" ./case-nval --testCase "3" <$i + bash ../scripts/test-ref r-case-nval-$j-3-stderr "$VALGRIND" ./case-nval --testCase "3" --testCaseFileName stderr <$i + bash ../scripts/test-ref r-case-nval-$j-4 "$VALGRIND" ./case-nval --testCase "4" --testCaseFileName stderr <$i +done +rm -f case-nval case-nval.exe + +bash ../scripts/compile src/case-string-zb.cpp +for i in files/"$os"/case-string-zb/*; do + j=$(basename $i) + bash ../scripts/test-ref r-case-string-zb-$j "$VALGRIND" ./case-string-zb --testMarkupFileName stderr <$i + for t in 1 2; do + bash ../scripts/test-ref r-case-string-zb-$j-$t "$VALGRIND" ./case-string-zb --testMarkupFileName stderr --testCase "${t}" <$i + done + bash ../scripts/test-ref r-case-string-zb-$j-3 "$VALGRIND" ./case-string-zb --testCase "3" <$i + bash ../scripts/test-ref r-case-string-zb-$j-3-stderr "$VALGRIND" ./case-string-zb --testCase "3" --testCaseFileName stderr <$i + bash ../scripts/test-ref r-case-string-zb-$j-4 "$VALGRIND" ./case-string-zb --testCase "4" --testCaseFileName stderr <$i +done +rm -f case-string-zb case-string-zb.exe + +bash ../scripts/compile src/sval.cpp +for i in files/"$os"/sval/*; do + j=$(basename $i) + echo "test-ref r-sval-$j ""$VALGRIND"" ./sval < files/$os/sval/input.$i" + bash ../scripts/test-ref r-sval-$j "$VALGRIND" ./sval <$i +done +rm -f sval sval.exe diff --git a/tests/test-001_run-sval-case-nval/src/case-nval.cpp b/tests/test-001_run-sval-case-nval/src/case-nval.cpp new file mode 100644 index 00000000..928b49c7 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/src/case-nval.cpp @@ -0,0 +1,27 @@ +/** + * Validates t (1 <= t <= 10) test cases. + * The first line contains the integer between 1 and 10^4, inclusive. + * The second line should contains space-separated sequence of integers between -1000 and 1000, inclusive. + * Also validates that file ends with EOLN and EOF. + */ + +#include "testlib.h" + +using namespace std; + +int main(int argc, char *argv[]) { + registerValidation(argc, argv); + + int testCaseCount = inf.readInt(1, 10, "t"); + inf.readEoln(); + + for (int testCase = 1; testCase <= testCaseCount; testCase++) { + setTestCase(testCase); + int n = inf.readInt(1, 10000, "n"); + inf.readEoln(); + inf.readInts(n, -1000, 1000, "a"); + inf.readEoln(); + } + + inf.readEof(); +} diff --git a/tests/test-001_run-sval-case-nval/src/case-string-zb.cpp b/tests/test-001_run-sval-case-nval/src/case-string-zb.cpp new file mode 100644 index 00000000..62835270 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/src/case-string-zb.cpp @@ -0,0 +1,17 @@ +#include "testlib.h" + +using namespace std; + +int main(int argc, char *argv[]) { + registerValidation(argc, argv); + + int testCaseCount = inf.readInt(1, 10, "t"); + inf.readEoln(); + + for (int testCase = 1; testCase <= testCaseCount; testCase++) { + setTestCase(testCase - 1); + inf.readLine("[\\\\!a-z]{1,100}"); + } + + inf.readEof(); +} diff --git a/tests/test-001_run-sval-case-nval/src/sval.cpp b/tests/test-001_run-sval-case-nval/src/sval.cpp new file mode 100644 index 00000000..6e59d1e9 --- /dev/null +++ b/tests/test-001_run-sval-case-nval/src/sval.cpp @@ -0,0 +1,18 @@ +/** + * Validates that the input contains the only token token. + * This token can contain only lowercase latin letters a-z. The length should be between 1 and 100, inclusive. + * Also validates that file ends with EOLN and EOF. + */ + +#include "testlib.h" + +using namespace std; + +int main(int argc, char* argv[]) +{ + registerValidation(argc, argv); + + inf.readToken("[a-z]{1,100}", "s"); + inf.readEoln(); + inf.readEof(); +} diff --git a/tests/test-002_run-fcmp-wcmp/files/answer.01 b/tests/test-002_run-fcmp-wcmp/files/answer.01 new file mode 100644 index 00000000..9a20c784 --- /dev/null +++ b/tests/test-002_run-fcmp-wcmp/files/answer.01 @@ -0,0 +1 @@ +abc 01 \%test!$ diff --git a/tests/test-002_run-fcmp-wcmp/files/input.01 b/tests/test-002_run-fcmp-wcmp/files/input.01 new file mode 100644 index 00000000..b61b7c26 --- /dev/null +++ b/tests/test-002_run-fcmp-wcmp/files/input.01 @@ -0,0 +1 @@ +1 2 3 4 5 6 diff --git a/tests/test-002_run-fcmp-wcmp/files/output.01 b/tests/test-002_run-fcmp-wcmp/files/output.01 new file mode 100644 index 00000000..edeb335f --- /dev/null +++ b/tests/test-002_run-fcmp-wcmp/files/output.01 @@ -0,0 +1,3 @@ +abc 01 \%test!$ + +me diff --git a/tests/test-002_run-fcmp-wcmp/files/output.01.bom b/tests/test-002_run-fcmp-wcmp/files/output.01.bom new file mode 100644 index 00000000..7185e986 --- /dev/null +++ b/tests/test-002_run-fcmp-wcmp/files/output.01.bom @@ -0,0 +1,3 @@ +abc 01 \%test!$ + +me diff --git a/tests/test-002_run-fcmp-wcmp/refs/r1/exit_code b/tests/test-002_run-fcmp-wcmp/refs/r1/exit_code new file mode 100644 index 00000000..d00491fd --- /dev/null +++ b/tests/test-002_run-fcmp-wcmp/refs/r1/exit_code @@ -0,0 +1 @@ +1 diff --git a/tests/test-002_run-fcmp-wcmp/refs/r1/stderr b/tests/test-002_run-fcmp-wcmp/refs/r1/stderr new file mode 100644 index 00000000..eea869ac --- /dev/null +++ b/tests/test-002_run-fcmp-wcmp/refs/r1/stderr @@ -0,0 +1 @@ +wrong answer Participant output contains extra tokens diff --git a/tests/test-002_run-fcmp-wcmp/refs/r1/stdout b/tests/test-002_run-fcmp-wcmp/refs/r1/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-002_run-fcmp-wcmp/refs/r2/exit_code b/tests/test-002_run-fcmp-wcmp/refs/r2/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-002_run-fcmp-wcmp/refs/r2/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-002_run-fcmp-wcmp/refs/r2/stderr b/tests/test-002_run-fcmp-wcmp/refs/r2/stderr new file mode 100644 index 00000000..06a60bb2 --- /dev/null +++ b/tests/test-002_run-fcmp-wcmp/refs/r2/stderr @@ -0,0 +1 @@ +ok 4 tokens diff --git a/tests/test-002_run-fcmp-wcmp/refs/r2/stdout b/tests/test-002_run-fcmp-wcmp/refs/r2/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-002_run-fcmp-wcmp/refs/r3/exit_code b/tests/test-002_run-fcmp-wcmp/refs/r3/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-002_run-fcmp-wcmp/refs/r3/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-002_run-fcmp-wcmp/refs/r3/stderr b/tests/test-002_run-fcmp-wcmp/refs/r3/stderr new file mode 100644 index 00000000..f108b2c7 --- /dev/null +++ b/tests/test-002_run-fcmp-wcmp/refs/r3/stderr @@ -0,0 +1 @@ +FAIL Answer file not found: "files/answer2.01" diff --git a/tests/test-002_run-fcmp-wcmp/refs/r3/stdout b/tests/test-002_run-fcmp-wcmp/refs/r3/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-002_run-fcmp-wcmp/refs/r4/exit_code b/tests/test-002_run-fcmp-wcmp/refs/r4/exit_code new file mode 100644 index 00000000..0cfbf088 --- /dev/null +++ b/tests/test-002_run-fcmp-wcmp/refs/r4/exit_code @@ -0,0 +1 @@ +2 diff --git a/tests/test-002_run-fcmp-wcmp/refs/r4/stderr b/tests/test-002_run-fcmp-wcmp/refs/r4/stderr new file mode 100644 index 00000000..f4f4b37a --- /dev/null +++ b/tests/test-002_run-fcmp-wcmp/refs/r4/stderr @@ -0,0 +1 @@ +wrong output format Extra information in the output file diff --git a/tests/test-002_run-fcmp-wcmp/refs/r4/stdout b/tests/test-002_run-fcmp-wcmp/refs/r4/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-002_run-fcmp-wcmp/refs/r5/exit_code b/tests/test-002_run-fcmp-wcmp/refs/r5/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-002_run-fcmp-wcmp/refs/r5/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-002_run-fcmp-wcmp/refs/r5/stderr b/tests/test-002_run-fcmp-wcmp/refs/r5/stderr new file mode 100644 index 00000000..f73e0a94 --- /dev/null +++ b/tests/test-002_run-fcmp-wcmp/refs/r5/stderr @@ -0,0 +1 @@ +ok 3 lines diff --git a/tests/test-002_run-fcmp-wcmp/refs/r5/stdout b/tests/test-002_run-fcmp-wcmp/refs/r5/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-002_run-fcmp-wcmp/refs/r6/exit_code b/tests/test-002_run-fcmp-wcmp/refs/r6/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-002_run-fcmp-wcmp/refs/r6/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-002_run-fcmp-wcmp/refs/r6/stderr b/tests/test-002_run-fcmp-wcmp/refs/r6/stderr new file mode 100644 index 00000000..f108b2c7 --- /dev/null +++ b/tests/test-002_run-fcmp-wcmp/refs/r6/stderr @@ -0,0 +1 @@ +FAIL Answer file not found: "files/answer2.01" diff --git a/tests/test-002_run-fcmp-wcmp/refs/r6/stdout b/tests/test-002_run-fcmp-wcmp/refs/r6/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-002_run-fcmp-wcmp/run.sh b/tests/test-002_run-fcmp-wcmp/run.sh new file mode 100644 index 00000000..1c311ce0 --- /dev/null +++ b/tests/test-002_run-fcmp-wcmp/run.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -eo pipefail + +bash ../scripts/compile src/wcmp.cpp +bash ../scripts/test-ref r1 "$VALGRIND" ./wcmp files/input.01 files/output.01 files/answer.01 +bash ../scripts/test-ref r2 "$VALGRIND" ./wcmp files/input.01 files/output.01 files/output.01 +bash ../scripts/test-ref r3 "$VALGRIND" ./wcmp files/input.01 files/output.01 files/answer2.01 + +# BOM shouldn't change refs +bash ../scripts/test-ref r1 "$VALGRIND" ./wcmp files/input.01 files/output.01.bom files/answer.01 +bash ../scripts/test-ref r2 "$VALGRIND" ./wcmp files/input.01 files/output.01.bom files/output.01 +bash ../scripts/test-ref r3 "$VALGRIND" ./wcmp files/input.01 files/output.01.bom files/answer2.01 +rm -f wcmp wcmp.exe + +bash ../scripts/compile src/fcmp.cpp +bash ../scripts/test-ref r4 "$VALGRIND" ./fcmp files/input.01 files/output.01 files/answer.01 +bash ../scripts/test-ref r5 "$VALGRIND" ./fcmp files/input.01 files/output.01 files/output.01 +bash ../scripts/test-ref r6 "$VALGRIND" ./fcmp files/input.01 files/output.01 files/answer2.01 +rm -f fcmp fcmp.exe diff --git a/tests/test-002_run-fcmp-wcmp/src/fcmp.cpp b/tests/test-002_run-fcmp-wcmp/src/fcmp.cpp new file mode 100644 index 00000000..9bf2c339 --- /dev/null +++ b/tests/test-002_run-fcmp-wcmp/src/fcmp.cpp @@ -0,0 +1,36 @@ +#include "testlib.h" +#include +#include +#include + +using namespace std; + +int main(int argc, char * argv[]) +{ + setName("compare files as sequence of lines"); + registerTestlibCmd(argc, argv); + + std::string strAnswer; + + int n = 0; + while (!ans.eof()) + { + std::string j = ans.readString(); + + if (j == "" && ans.eof()) + break; + + strAnswer = j; + std::string p = ouf.readString(); + + n++; + + if (j != p) + quitf(_wa, "%d%s lines differ - expected: '%s', found: '%s'", n, englishEnding(n).c_str(), compress(j).c_str(), compress(p).c_str()); + } + + if (n == 1) + quitf(_ok, "single line: '%s'", compress(strAnswer).c_str()); + + quitf(_ok, "%d lines", n); +} diff --git a/tests/test-002_run-fcmp-wcmp/src/wcmp.cpp b/tests/test-002_run-fcmp-wcmp/src/wcmp.cpp new file mode 100644 index 00000000..fe4ae5e4 --- /dev/null +++ b/tests/test-002_run-fcmp-wcmp/src/wcmp.cpp @@ -0,0 +1,38 @@ +#include "testlib.h" + +using namespace std; + +int main(int argc, char * argv[]) +{ + setName("compare sequences of tokens"); + registerTestlibCmd(argc, argv); + + int n = 0; + string j, p; + + while (!ans.seekEof() && !ouf.seekEof()) + { + n++; + + ans.readWordTo(j); + ouf.readWordTo(p); + + if (j != p) + quitf(_wa, "%d%s words differ - expected: '%s', found: '%s'", n, englishEnding(n).c_str(), compress(j).c_str(), compress(p).c_str()); + } + + if (ans.seekEof() && ouf.seekEof()) + { + if (n == 1) + quitf(_ok, "\"%s\"", compress(j).c_str()); + else + quitf(_ok, "%d tokens", n); + } + else + { + if (ans.seekEof()) + quitf(_wa, "Participant output contains extra tokens"); + else + quitf(_wa, "Unexpected EOF in the participants output"); + } +} diff --git a/tests/test-003_run-rnd/refs/r1/exit_code b/tests/test-003_run-rnd/refs/r1/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-003_run-rnd/refs/r1/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-003_run-rnd/refs/r1/stderr b/tests/test-003_run-rnd/refs/r1/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-003_run-rnd/refs/r1/stdout b/tests/test-003_run-rnd/refs/r1/stdout new file mode 100644 index 00000000..0cba9c36 --- /dev/null +++ b/tests/test-003_run-rnd/refs/r1/stdout @@ -0,0 +1,68 @@ +10 +8 10 +4 5 +2 7 +9 1 +8 7 +9 6 +10 5 +6 4 +3 2 +vutwaahqooeqoxzxwetlpecqiwgdbogiqqulttysyohwhzxzphvsfmnplizxoebzcvvfyppqbhxjksuzepuezqqzxlfmdanoeaoq +3.0177 +71836424476711 +7548514365797 +763523 +467326 +961 +9 3 1 7 0 4 6 8 5 2 + + +9 2 6 10 1 4 3 5 8 7 +81 19 73 27 64 82 68 28 67 88 + +10 6 13 5 5 11 18 4 22 6 + +0 +238 +844 +933 +980 +96952 +99843 +277.6710 +1652.0276 +1871.0491 +1771.8652 +521.1956 +461.5447 +1631 +828 +761 +266 +804 +409 +1085 +1837 +1834 +557 +119 +62 +1880 +1973 +1850 +2116 +441 +e +a +c +f +e +d +b +f +c +f +f +b +b diff --git a/tests/test-003_run-rnd/refs/r2/exit_code b/tests/test-003_run-rnd/refs/r2/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-003_run-rnd/refs/r2/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-003_run-rnd/refs/r2/stderr b/tests/test-003_run-rnd/refs/r2/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-003_run-rnd/refs/r2/stdout b/tests/test-003_run-rnd/refs/r2/stdout new file mode 100644 index 00000000..4c3500de --- /dev/null +++ b/tests/test-003_run-rnd/refs/r2/stdout @@ -0,0 +1,158 @@ +100 +7 33 +27 40 +97 43 +12 95 +89 36 +50 19 +34 14 +13 58 +94 78 +90 96 +91 51 +54 57 +69 86 +18 9 +20 88 +76 43 +100 85 +93 55 +35 42 +23 88 +54 44 +46 23 +17 62 +77 47 +73 25 +27 79 +79 30 +92 11 +77 61 +34 83 +21 76 +80 83 +67 40 +72 29 +8 22 +32 63 +20 75 +66 92 +55 74 +35 49 +91 21 +26 96 +10 24 +24 97 +39 33 +42 45 +70 53 +37 52 +49 86 +36 78 +85 61 +63 64 +87 5 +90 4 +5 60 +72 84 +62 100 +51 50 +74 48 +19 94 +81 98 +65 2 +1 16 +75 8 +32 6 +64 30 +29 59 +15 11 +80 93 +58 28 +87 95 +71 10 +57 31 +38 39 +71 68 +65 4 +89 9 +3 41 +18 82 +46 84 +45 3 +52 99 +16 98 +37 25 +14 38 +17 67 +69 47 +70 68 +13 48 +81 56 +59 7 +22 44 +60 15 +73 2 +6 31 +99 12 +28 53 +82 26 +41 56 +clizwkchataumicxkohcrpqnyrjyzbjvsypznpembvkkkbyzvzckcmhbjbuopfbwbkntswhwsdfzabjghjkjftogziikipdkajdm +2.5026 +48691624799250 +6036792742366 +594248 +269230 +1156 +7 3 5 2 6 9 0 1 8 4 + + +3 7 5 1 2 10 6 4 8 9 +36 28 78 94 72 40 23 95 82 19 + +5 22 4 31 3 11 4 9 7 4 + +0 +896 +650 +989 +860 +99644 +98400 +373.3556 +109.6260 +1999.1647 +1871.5326 +311.6935 +562.6932 +638 +730 +52 +334 +62 +983 +1686 +1538 +1911 +71 +259 +445 +1363 +1897 +1175 +3249 +3481 +e +d +c +f +d +a +a +e +e +f +f +d +c diff --git a/tests/test-003_run-rnd/run.sh b/tests/test-003_run-rnd/run.sh new file mode 100644 index 00000000..362f5c3e --- /dev/null +++ b/tests/test-003_run-rnd/run.sh @@ -0,0 +1,7 @@ +#!/bin/bash +set -eo pipefail + +bash ../scripts/compile src/gen.cpp +bash ../scripts/test-ref r1 $VALGRIND ./gen 10 100 +bash ../scripts/test-ref r2 $VALGRIND ./gen 100 1000 +rm -f gen gen.exe diff --git a/tests/test-003_run-rnd/src/gen.cpp b/tests/test-003_run-rnd/src/gen.cpp new file mode 100644 index 00000000..9e9f839a --- /dev/null +++ b/tests/test-003_run-rnd/src/gen.cpp @@ -0,0 +1,171 @@ +#include "testlib.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define forn(i, n) for (int i = 0; i < int(n); i++) + +using namespace std; + +int main(int argc, char* argv[]) +{ + registerGen(argc, argv, 1); + + int n = opt(1); + int t = opt(2); + + vector p(n); + forn(i, n) + if (i > 0) + p[i] = rnd.wnext(i, t); + + println(n); + vector perm(n); + forn(i, n) + perm[i] = i; + shuffle(perm.begin() + 1, perm.end()); + vector > edges; + + for (int i = 1; i < n; i++) + if (rnd.next(2)) + edges.push_back(make_pair(perm[i], perm[p[i]])); + else + edges.push_back(make_pair(perm[p[i]], perm[i])); + + shuffle(edges.begin(), edges.end()); + + for (int i = 0; i + 1 < n; i++) + println(edges[i].first + 1, edges[i].second + 1); + + println(rnd.next("[a-z]{100}")); + printf("%.04f\n", rnd.next(3.1415)); + + { + long long LL = 12345678901234LL; + long long LR = 82345678901234LL; + println(rnd.next(LL, LR)); + } + + { + unsigned long long LL = 1345678901234ULL; + unsigned long long LR = 8345678901234ULL; + println(rnd.next(LL, LR)); + } + + { + unsigned long LL = 134567UL; + unsigned long LR = 834567UL; + println(rnd.next(LL, LR)); + } + + { + int LL = 134567; + int LR = 834567; + println(rnd.next(LL, LR)); + } + + vector a; + forn(i, 100) + a.push_back(i * i); + println(rnd.any(a)); + println(rnd.perm(10)); + println(rnd.perm(0)); + println(rnd.perm(0, 1)); + println(rnd.perm(10, 1)); + println(rnd.distinct(10, 15, 100)); + println(rnd.distinct(0, 15, 100)); + println(rnd.partition(10, 100, 3)); + println(rnd.partition(0, 0, 10)); + println(rnd.partition(1, 0, 0)); + println(rnd.wnext(1000, 2)); + println(rnd.wnext(1000LL, 2LL)); + println(rnd.wnext(1000, 20)); + println(rnd.wnext(1000LL, 20LL)); + println(rnd.wnext(100000, 200)); + println(rnd.wnext(100000LL, 200LL)); + + std::cout << std::fixed << std::setprecision(4) << rnd.next((float) 42.0, (float) 2011.1109) << std::endl; + std::cout << std::fixed << std::setprecision(4) << rnd.next((double) 42.0, (double) 2011.1109) << std::endl; + std::cout << std::fixed << std::setprecision(4) << rnd.wnext((float) 42.0, (float) 2011.1109, 5) << std::endl; + std::cout << std::fixed << std::setprecision(4) << rnd.wnext((double) 42.0, (double) 2011.1109, 5) << std::endl; + std::cout << std::fixed << std::setprecision(4) << rnd.wnext((float) 42.0, (float) 2011.1109, -7) << std::endl; + std::cout << std::fixed << std::setprecision(4) << rnd.wnext((double) 42.0, (double) 2011.1109, -7) << std::endl; + + std::cout << rnd.next((unsigned long long) 42, (unsigned long long) 2011) << std::endl; + std::cout << rnd.next((unsigned int) 42, (unsigned int) 2011) << std::endl; + std::cout << rnd.next((unsigned short) 42, (unsigned short) 2011) << std::endl; + + std::cout << rnd.wnext((unsigned long long) 42, (unsigned long long) 2011, -3) << std::endl; + std::cout << rnd.wnext((unsigned int) 42, (unsigned int) 2011, -3) << std::endl; + std::cout << rnd.wnext((unsigned short) 42, (unsigned short) 2011, -3) << std::endl; + std::cout << rnd.wnext((unsigned long long) 42, (unsigned long long) 2011, 3) << std::endl; + std::cout << rnd.wnext((unsigned int) 42, (unsigned int) 2011, 3) << std::endl; + std::cout << rnd.wnext((unsigned short) 42, (unsigned short) 2011, 3) << std::endl; + + std::cout << rnd.wnext((signed long long) 42, (signed long long) 2011, -5) << std::endl; + std::cout << rnd.wnext((signed int) 42, (signed int) 2011, -5) << std::endl; + std::cout << rnd.wnext((signed short) 42, (signed short) 2011, -5) << std::endl; + std::cout << rnd.wnext((signed long long) 42, (signed long long) 2011, 4) << std::endl; + std::cout << rnd.wnext((signed int) 42, (signed int) 2011, 4) << std::endl; + std::cout << rnd.wnext((signed short) 42, (signed short) 2011, 4) << std::endl; + + println(rnd.wany(a, 1)); + println(rnd.wany(a, -1)); + + set b; + b.insert("a"); b.insert("b"); b.insert("c"); b.insert("d"); b.insert("e"); b.insert("f"); b.insert("g"); + println(rnd.any(b)); + + { + std::set string_set; + string_set.insert("a"); + string_set.insert("b"); + string_set.insert("c"); + string_set.insert("d"); + string_set.insert("e"); + string_set.insert("f"); + + std::cout << rnd.any(string_set) << std::endl; + std::cout << rnd.any(string_set.begin(), string_set.end()) << std::endl; + std::cout << rnd.wany(string_set, 1) << std::endl; + std::cout << rnd.wany(string_set.begin(), string_set.end(), 1) << std::endl; + std::cout << rnd.wany(string_set, -1) << std::endl; + std::cout << rnd.wany(string_set.begin(), string_set.end(), -1) << std::endl; + } + + { + std::multiset string_multiset; + string_multiset.insert("a"); + string_multiset.insert("b"); string_multiset.insert("b"); + string_multiset.insert("c"); string_multiset.insert("c"); string_multiset.insert("c"); + string_multiset.insert("d"); + string_multiset.insert("e"); string_multiset.insert("e"); string_multiset.insert("e"); + string_multiset.insert("f"); string_multiset.insert("f"); string_multiset.insert("f"); string_multiset.insert("f"); + + std::cout << rnd.any(string_multiset) << std::endl; + std::cout << rnd.any(string_multiset.begin(), string_multiset.end()) << std::endl; + std::cout << rnd.wany(string_multiset, 2) << std::endl; + std::cout << rnd.wany(string_multiset.begin(), string_multiset.end(), 1) << std::endl; + std::cout << rnd.wany(string_multiset, -1) << std::endl; + std::cout << rnd.wany(string_multiset.begin(), string_multiset.end(), -2) << std::endl; + } +} diff --git a/tests/test-004_use-test.h/refs/r1/exit_code b/tests/test-004_use-test.h/refs/r1/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-004_use-test.h/refs/r1/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-004_use-test.h/refs/r1/stderr b/tests/test-004_use-test.h/refs/r1/stderr new file mode 100644 index 00000000..c9169b9a --- /dev/null +++ b/tests/test-004_use-test.h/refs/r1/stderr @@ -0,0 +1,53 @@ +FAIL Opts: index '1' is out of range [0,1) +FAIL Opts: integer overflow: expected integer but '3e6' found +FAIL Opts: index '-1' is out of range [0,14) +FAIL Opts: opt by index '2': expected bool true/false or 0/1 but '-2147483648' found +FAIL Opts: expected integer but '-f1' found +FAIL Opts: index '14' is out of range [0,14) +FAIL Opts: expected non-negative integer but '-2147483648' found +FAIL Opts: unknown key 'test-count' +FAIL Opts: unknown key 'sum-n' +FAIL Opts: unused key 'min-val' +FAIL Opts: unused key 'max-val' +FAIL Opts: unused key 'min-length' +FAIL Opts: unused key 'bias-value' +FAIL Unexpected end of file - token expected (based on ) +FAIL Unexpected end of file - token expected (based on ) +FAIL Integer parameter [name=n] equals to 1, violates the range [0, 0] (based on ) +FAIL Token parameter [name=n] equals to "abacaba", doesn't correspond to pattern "[abc]{6}" (based on ) +FAIL Token parameter [name=n] equals to "abacab", doesn't correspond to pattern "a|test|abacaba|ok|abac" (based on ) +FAIL Token parameter [name=n] equals to "abacabaa", doesn't correspond to pattern "a|test|abacaba|ok|abac" (based on ) +FAIL Token parameter [name=n] equals to "abacaba!", doesn't correspond to pattern "a|test|abacaba|ok|abac" (based on ) +FAIL Integer element a[4] equals to 4, violates the range [1, 3] (based on ) +FAIL Expected integer, but "" found () +FAIL Expected integer, but "-" found () +FAIL Expected integer, but "+" found () +FAIL Expected integer, but "00" found () +FAIL Expected integer, but "0123" found () +FAIL Expected integer, but "+123" found () +FAIL Expected integer, but "09223372036854775807" found () +FAIL Expected integer, but "9223372036854775808" found () +FAIL Expected integer, but "-09223372036854775808" found () +FAIL Expected integer, but "-9223372036854775809" found () +FAIL Expected integer, but "1 " found () +FAIL Expected integer, but " 1" found () +FAIL Expected integer, but "1 2" found () +FAIL Expected integer, but "-0" found () +FAIL Expected integer, but "--0" found () +FAIL Expected integer, but "123-" found () +FAIL Expected unsigned integer, but "" found () +FAIL Expected unsigned integer, but "-" found () +FAIL Expected unsigned integer, but "-1" found () +FAIL Expected unsigned integer, but "+" found () +FAIL Expected unsigned integer, but "00" found () +FAIL Expected unsigned integer, but "0123" found () +FAIL Expected unsigned integer, but "+123" found () +FAIL Expected unsigned integer, but "18446744073709551616" found () +FAIL Expected unsigned integer, but "18446744073709551617" found () +FAIL Expected unsigned integer, but "36893488147419103232" found () +FAIL Expected unsigned integer, but "1 " found () +FAIL Expected unsigned integer, but " 1" found () +FAIL Expected unsigned integer, but "1 2" found () +FAIL Expected unsigned integer, but "-0" found () +FAIL Expected unsigned integer, but "--0" found () +FAIL Expected unsigned integer, but "-00" found () diff --git a/tests/test-004_use-test.h/refs/r1/stdout b/tests/test-004_use-test.h/refs/r1/stdout new file mode 100644 index 00000000..e935d06c --- /dev/null +++ b/tests/test-004_use-test.h/refs/r1/stdout @@ -0,0 +1,10 @@ +Running test 'join' OK +Running test 'split' OK +Running test 'tokenize' OK +Running test 'opts' OK +Running test 'instream' OK +Running test 'pattern' OK +Running test 'stringToLongLong' OK +Running test 'stringToUnsignedLongLong' OK + +SUCCESS 8 tests passed. diff --git a/tests/test-004_use-test.h/run.sh b/tests/test-004_use-test.h/run.sh new file mode 100644 index 00000000..6e8c176e --- /dev/null +++ b/tests/test-004_use-test.h/run.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -eo pipefail + +bash ../scripts/compile test.cpp +bash ../scripts/test-ref r1 "$VALGRIND" ./test +rm -f test test.exe diff --git a/tests/test-004_use-test.h/test.cpp b/tests/test-004_use-test.h/test.cpp new file mode 100644 index 00000000..9c7c916d --- /dev/null +++ b/tests/test-004_use-test.h/test.cpp @@ -0,0 +1,20 @@ +#define TESTLIB_THROW_EXIT_EXCEPTION_INSTEAD_OF_EXIT + +#include "testlib.h" +#include "test.h" + +using namespace std; + +#include "tests/test-join.cpp" +#include "tests/test-split.cpp" +#include "tests/test-tokenize.cpp" +#include "tests/test-opts.cpp" +#include "tests/test-instream.cpp" +#include "tests/test-pattern.cpp" +#include "tests/test-stringToLongLong.cpp" +#include "tests/test-stringToUnsignedLongLong.cpp" + +int main() { + disableFinalizeGuard(); + run_tests(); +} diff --git a/tests/test-004_use-test.h/test.h b/tests/test-004_use-test.h/test.h new file mode 100644 index 00000000..b510108c --- /dev/null +++ b/tests/test-004_use-test.h/test.h @@ -0,0 +1,79 @@ +#ifndef _TEST_H_ +#define _TEST_H_ + +#include +#include +#include +#include +#include +#include + +struct test { + std::string name; + std::function f; +}; + +std::vector tests; + +struct test_holder { + test_holder(const test& t) { + tests.push_back(t); + } +}; + +#define TEST(f) \ + void test_##f(); \ + test test_item##f = {#f, test_##f}; \ + test_holder test_holder##f(test_item##f); \ + void test_##f() \ + +#ifdef _MSC_VER +# define TEST_NORETURN __declspec(noreturn) +#elif defined __GNUC__ +# define TEST_NORETURN __attribute__ ((noreturn)) +#else +# define TEST_NORETURN +#endif + +TEST_NORETURN void error(std::string message) { + std::cout << "ERROR: " << message << std::endl; + exit(1); +} + +void ensure_exit(int exit_code, std::function f) { + try { + f(); + } catch (exit_exception& e) { + if (e.getExitCode() != exit_code) { + error("Expected exit code " + std::to_string(exit_code) + " but found " + std::to_string(e.getExitCode())); + } else + return; + } catch (...) { + error("Expected exit_exception, but got other exception"); + } + error("Expected exit_exception, but not exception got"); +} + +void run_tests() { + for (const auto& t: tests) { + std::string title = "Running test '" + t.name + "'"; + while (title.length() < 100) + title += ' '; + std::cout << title; + + try { + t.f(); + } catch (exit_exception& e) { + error("Teslib exited with code " + std::to_string(e.getExitCode())); + } catch (...) { + error("Unexpected exception"); + std::exit(1); + } + + std::cout << "OK" << std::endl; + } + + std::cout << std::endl << "SUCCESS " << tests.size() << " tests passed." << std::endl; +} + +#endif diff --git a/tests/test-004_use-test.h/tests/test-instream.cpp b/tests/test-004_use-test.h/tests/test-instream.cpp new file mode 100644 index 00000000..dcdd785c --- /dev/null +++ b/tests/test-004_use-test.h/tests/test-instream.cpp @@ -0,0 +1,55 @@ +TEST(instream) { + { + InStream s(inf, "this 100500 the test 123\n\n"); + ensure(s.readWord() == "this"); + ensure(s.readInt() == 100500); + ensure(s.readToken() == "the"); + ensure(s.readLine() == " test 123"); + ensure(s.readLine() == ""); + ensure(s.eof()); + ensure_exit(3, [&](){s.readWord();}); + } + { + ensure_exit(3, [](){InStream(inf, "").readWord();}); + } + { + InStream s(inf, "3\n10 20 30\n"); + ensure(s.readInt(1, 3, "n") == 3); + ensure(s.readInts(3, 10, 30, "a") == vector({10, 20, 30})); + } + { + ensure_exit(3, [](){InStream(inf, "1").readInt(0, 0, "n");}); + ensure_exit(3, [](){InStream(inf, "abacaba").readToken("[abc]{6}", "n");}); + ensure(InStream(inf, "abacaba").readToken("[abc]{7}", "s") == "abacaba"); + ensure(InStream(inf, "abacaba").readToken("a|test|abacaba|ok|abac", "s") == "abacaba"); + ensure_exit(3, [](){InStream(inf, "abacab").readToken("a|test|abacaba|ok|abac", "n");}); + ensure_exit(3, [](){InStream(inf, "abacabaa").readToken("a|test|abacaba|ok|abac", "n");}); + ensure_exit(3, [](){InStream(inf, "abacaba!").readToken("a|test|abacaba|ok|abac", "n");}); + InStream(inf, "1 2 3 4 1").readInts(5, 1, 4, "a"); + ensure_exit(3, [](){InStream(inf, "1 2 3 4 1").readInts(5, 1, 3, "a");}); + { + string result; + InStream(inf, "\t\t100500\t").readTokenTo(result, "[0-9]{1,6}", "n"); + ensure(result == "100500"); + } + } + { + InStream s(inf, "\xEF\xBB\xBF" "content"); + s.skipBom(); + ensure(s.readWord() == "content"); + ensure(s.eof()); + } + { + InStream s(inf, "content"); + s.skipBom(); + ensure(s.readWord() == "content"); + ensure(s.eof()); + } + { + InStream s(inf, "\xEF" "content"); + s.skipBom(); + ensure(s.readChar() == '\xEF'); + ensure(s.readWord() == "content"); + ensure(s.eof()); + } +} diff --git a/tests/test-004_use-test.h/tests/test-join.cpp b/tests/test-004_use-test.h/tests/test-join.cpp new file mode 100644 index 00000000..45965c8f --- /dev/null +++ b/tests/test-004_use-test.h/tests/test-join.cpp @@ -0,0 +1,8 @@ +TEST(join) { + ensure(join(vector({LLONG_MIN, 2, LLONG_MAX})) == "-9223372036854775808 2 9223372036854775807"); + ensure(join(vector({LLONG_MIN, 2, LLONG_MAX}), ',') == "-9223372036854775808,2,9223372036854775807"); + ensure(join(vector()) == ""); + ensure(join(vector({"ok"})) == "ok"); + ensure(join(vector({"ok", "ok", "ok", "ok"})) == "ok ok ok ok"); + ensure(join(vector({"ok", "test"})) == "ok test"); +} diff --git a/tests/test-004_use-test.h/tests/test-opts.cpp b/tests/test-004_use-test.h/tests/test-opts.cpp new file mode 100644 index 00000000..6f4ae02e --- /dev/null +++ b/tests/test-004_use-test.h/tests/test-opts.cpp @@ -0,0 +1,126 @@ +TEST(opts) { + suppressEnsureNoUnusedOpts(); + { + const char* args[] = {"test"}; + prepareOpts(sizeof(args) / sizeof(const char*), (char **)args); + ensure(!has_opt("a")); + ensure_exit(3, [](){ opt(1);}); + } + { + const char* args[] = {"test", "-a", "-2147483648", "-f1", "0", "-f2", "1", "-f3", "true", "-f4", "false", "--test=me=me", "--d=-17.125", "--ex=3e6"}; + prepareOpts(sizeof(args) / sizeof(const char*), (char **)args); + ensure(has_opt("a")); + ensure(has_opt("f1")); + ensure(has_opt("f2")); + ensure(has_opt("f3")); + ensure(has_opt("f4")); + ensure(has_opt("test")); + ensure(has_opt("d")); + ensure(has_opt("ex")); + ensure(!has_opt("f")); + ensure(!has_opt("f5")); + ensure(!has_opt("true")); + ensure(!has_opt("0")); + ensure(!has_opt("1")); + ensure(!has_opt("-a")); + ensure(!has_opt("--test")); + ensure(opt("a") == INT_MIN); + ensure(!opt("f1")); + ensure(opt("f2")); + ensure(opt("f3")); + ensure(!opt("f4")); + ensure(opt("test") == "me=me"); + ensure(opt("d") == -17.125); + ensure(opt("ex") == 3000000); + ensure(opt("ex") == 3000000); + ensure_exit(3, [](){opt("ex");}); + ensure(opt(2) == INT_MIN); + ensure(opt(13) == "--ex=3e6"); + ensure_exit(3, [](){ opt(-1);}); + ensure("test" == opt(0)); + ensure_exit(3, [](){ opt(2);}); + ensure_exit(3, [](){ opt(3);}); + ensure_exit(3, [](){ opt(14);}); + ensure_exit(3, [](){ opt("a");}); + } + + { + // Testing opt with default value and unused opt. + // The following function are opts of the generators/gen-array-with-opt.cpp + // Test is conducted by throwing arguments to this function. + struct GenArrayOpts { + int test_count; + int sum_n, min_n; + int min_value, max_value, value_bias; + }; + auto gen_array_with_opt_parse_opt = [](const string& opts) { + { + auto parts = split(opts, ' '); + vector opts(parts.size() + 1); + opts[0] = "./gen-array-with-opt"; + for (size_t i = 0; i < parts.size(); ++i) { + opts[i + 1] = parts[i].c_str(); + } + prepareOpts(int(opts.size()), (char**)opts.data()); + } + { + GenArrayOpts res; + res.test_count = opt("test-count"); + res.sum_n = opt("sum-n"); + res.min_n = opt("min-n", 1); + + res.min_value = opt("min-value", 1); + res.max_value = opt("max-value", 1000 * 1000 * 1000); + res.value_bias = opt("value-bias", 0); + + ensureNoUnusedOpts(); + return res; + } + }; + + // missing test-count + ensure_exit(3, [&] { gen_array_with_opt_parse_opt(""); }); + // missing sum-n + ensure_exit(3, [&]{ gen_array_with_opt_parse_opt("-test-count 3"); }); + // min-value, not min-val + ensure_exit(3, [&]{ gen_array_with_opt_parse_opt("-test-count 3 -sum-n 10 -min-val 1"); } ); + // max-value, not max-val + ensure_exit(3, [&]{ gen_array_with_opt_parse_opt("-test-count 3 -sum-n 10 -min-value 1 -max-val 20"); } ); + // min-n, not min-length + ensure_exit(3, [&]{ gen_array_with_opt_parse_opt("-test-count 3 -sum-n 10 -min-length 3 -min-value 10 -max-value 20"); }); + // value-bias, not bias-value + ensure_exit(3, [&]{ gen_array_with_opt_parse_opt("-test-count 3 -sum-n 10 -min-n 3 -min-value 10 -max-value 20 -bias-value 3"); }); + + // OK cases + { + auto t = gen_array_with_opt_parse_opt("-test-count 3 -sum-n 10"); + ensure(t.test_count == 3); + ensure(t.sum_n == 10); + ensure(t.min_n == 1); + ensure(t.min_value == 1); + ensure(t.max_value == 1000 * 1000 * 1000); + ensure(t.value_bias == 0); + } + + { + auto t = gen_array_with_opt_parse_opt("-test-count 3 -sum-n 10 -min-value 10"); + ensure(t.test_count == 3); + ensure(t.sum_n == 10); + ensure(t.min_n == 1); + ensure(t.min_value == 10); + ensure(t.max_value == 1000 * 1000 * 1000); + ensure(t.value_bias == 0); + } + + { + auto t = gen_array_with_opt_parse_opt("-test-count 5 -sum-n 100 -min-n 3 -min-value 10 -max-value 20 -value-bias 3 "); + ensure(t.test_count == 5); + ensure(t.sum_n == 100); + ensure(t.min_n == 3); + ensure(t.min_value == 10); + ensure(t.max_value == 20); + ensure(t.value_bias == 3); + } + } +} + diff --git a/tests/test-004_use-test.h/tests/test-pattern.cpp b/tests/test-004_use-test.h/tests/test-pattern.cpp new file mode 100644 index 00000000..25e9b894 --- /dev/null +++ b/tests/test-004_use-test.h/tests/test-pattern.cpp @@ -0,0 +1,40 @@ +TEST(pattern) { + { + ensure(!pattern("a").matches("")); + ensure(!pattern("a").matches("b")); + ensure(pattern("a").matches("a")); + ensure(pattern("[^0-9]*").matches("")); + ensure(pattern("[^0-9]*").matches("wertyuiop(*&^%$#@!~")); + ensure(pattern("[^0-9]*").matches("?><")); + ensure(!pattern("[^0-9]*").matches("?>3<")); + ensure(pattern("id-([ac]|b{2})").matches("id-a")); + ensure(pattern("id-([ac]|b{2})").matches("id-c")); + ensure(pattern("id-([ac]|b{2})").matches("id-bb")); + ensure(!pattern("id-([ac]|b{2})").matches("id-aa")); + ensure(!pattern("id-([ac]|b{2})").matches("id-cb")); + ensure(!pattern("id-([ac]|b{2})").matches("id-b")); + ensure(pattern("[0-9][a-z]{1,3}.[!]{0,2}").matches("4me.!")); + ensure(pattern("[0-9][a-z]{1,3}.[!]{0,2}").matches("0z.")); + ensure(pattern("[0-9][a-z]{1,3}.[!]{0,2}").matches("9ttt.!!")); + ensure(pattern("[0-9][a-z]{1,3}.[!]{0,2}").matches("7oe.")); + ensure(!pattern("[0-9][a-z]{1,3}.[!]{0,2}").matches("4me.!!!")); + ensure(!pattern("[0-9][a-z]{1,3}.[!]{0,2}").matches("rz.")); + ensure(!pattern("[0-9][a-z]{1,3}.[!]{0,2}").matches("9A.!!")); + ensure(!pattern("[0-9][a-z]{1,3}.[!]{0,2}").matches("7oe")); + ensure(!pattern("No solution").matches("No solution")); + ensure(pattern("No\\ solution").matches("No solution")); + ensure(!pattern("((aa|ba)|(ac|dd))|yes").matches("No solution")); + ensure(!pattern("oo(x(aa|ba)|y(ac|dd))|yes").matches("")); + ensure(!pattern("oo(x(aa|ba)|y(ac|dd))|yes").matches("ooxbaydd")); + ensure(pattern("oo(x(aa|ba)|y(ac|dd))|yes").matches("ooxba")); + ensure(pattern("oo(x(aa|ba)|y(ac|dd))|yes").matches("ooyac")); + ensure(pattern("oo(x(aa|ba)|y(ac|dd))|yes").matches("ooydd")); + ensure(pattern("oo(x(aa|ba)|y(ac|dd))|yes").matches("ooxaa")); + ensure(pattern("oo(x(aa|ba)|y(ac|dd))|yes").matches("yes")); + ensure(!pattern("oo(x(aa|ba)|y(ac|dd))|yes").matches("ooyes")); + ensure(!pattern("oo(x(aa|ba)|y(ac|dd))|yes").matches("oo")); + ensure(!pattern("oo(x(aa|ba)|y(ac|dd))|yes").matches("ooyaa")); + ensure(!pattern("oo(x(aa|ba)|y(ac|dd))|yes").matches("ooxac")); + ensure(!pattern("oo(x(aa|ba)|y(ac|dd))|yes").matches("ooyddd")); + } +} diff --git a/tests/test-004_use-test.h/tests/test-split.cpp b/tests/test-004_use-test.h/tests/test-split.cpp new file mode 100644 index 00000000..08057bbc --- /dev/null +++ b/tests/test-004_use-test.h/tests/test-split.cpp @@ -0,0 +1,6 @@ +TEST(split) { + ensure(split(" ab b rrrr", ' ') == vector({"", "ab", "", "b", "rrrr"})); + ensure(split(" ab b rrrr ", ' ') == vector({"", "ab", "", "b", "rrrr", ""})); + ensure(split(" ab b rrrr ", ' ') == vector({"", "ab", "", "b", "rrrr", "", ""})); + ensure(split("", ',') == vector(1, "")); +} diff --git a/tests/test-004_use-test.h/tests/test-stringToLongLong.cpp b/tests/test-004_use-test.h/tests/test-stringToLongLong.cpp new file mode 100644 index 00000000..04050ce9 --- /dev/null +++ b/tests/test-004_use-test.h/tests/test-stringToLongLong.cpp @@ -0,0 +1,23 @@ +TEST(stringToLongLong) { + ensure(stringToLongLong(inf, "1234567891") == 1234567891LL); + ensure(stringToLongLong(inf, "-47292722921111") == -47292722921111LL); + ensure(stringToLongLong(inf, "0") == 0LL); + ensure(stringToLongLong(inf, "9223372036854775807") == 9223372036854775807LL); + ensure(stringToLongLong(inf, "-9223372036854775808") == -9223372036854775807LL - 1LL); + ensure_exit(3, [](){stringToLongLong(inf, "");}); + ensure_exit(3, [](){stringToLongLong(inf, "-");}); + ensure_exit(3, [](){stringToLongLong(inf, "+");}); + ensure_exit(3, [](){stringToLongLong(inf, "00");}); + ensure_exit(3, [](){stringToLongLong(inf, "0123");}); + ensure_exit(3, [](){stringToLongLong(inf, "+123");}); + ensure_exit(3, [](){stringToLongLong(inf, "09223372036854775807");}); + ensure_exit(3, [](){stringToLongLong(inf, "9223372036854775808");}); + ensure_exit(3, [](){stringToLongLong(inf, "-09223372036854775808");}); + ensure_exit(3, [](){stringToLongLong(inf, "-9223372036854775809");}); + ensure_exit(3, [](){stringToLongLong(inf, "1 ");}); + ensure_exit(3, [](){stringToLongLong(inf, " 1");}); + ensure_exit(3, [](){stringToLongLong(inf, "1 2");}); + ensure_exit(3, [](){stringToLongLong(inf, "-0");}); + ensure_exit(3, [](){stringToLongLong(inf, "--0");}); + ensure_exit(3, [](){stringToLongLong(inf, "123-");}); +} diff --git a/tests/test-004_use-test.h/tests/test-stringToUnsignedLongLong.cpp b/tests/test-004_use-test.h/tests/test-stringToUnsignedLongLong.cpp new file mode 100644 index 00000000..f0de5919 --- /dev/null +++ b/tests/test-004_use-test.h/tests/test-stringToUnsignedLongLong.cpp @@ -0,0 +1,24 @@ +TEST(stringToUnsignedLongLong) { + ensure(stringToUnsignedLongLong(inf, "123") == 123ULL); + ensure(stringToUnsignedLongLong(inf, "0") == 0ULL); + ensure(stringToUnsignedLongLong(inf, "7") == 7ULL); + ensure(stringToUnsignedLongLong(inf, "18446744073709551615") == 18446744073709551615ULL); + ensure(stringToUnsignedLongLong(inf, "9876543216540001000") == 9876543216540001000ULL); + + ensure_exit(3, [](){stringToUnsignedLongLong(inf, "");}); + ensure_exit(3, [](){stringToUnsignedLongLong(inf, "-");}); + ensure_exit(3, [](){stringToUnsignedLongLong(inf, "-1");}); + ensure_exit(3, [](){stringToUnsignedLongLong(inf, "+");}); + ensure_exit(3, [](){stringToUnsignedLongLong(inf, "00");}); + ensure_exit(3, [](){stringToUnsignedLongLong(inf, "0123");}); + ensure_exit(3, [](){stringToUnsignedLongLong(inf, "+123");}); + ensure_exit(3, [](){stringToUnsignedLongLong(inf, "18446744073709551616");}); + ensure_exit(3, [](){stringToUnsignedLongLong(inf, "18446744073709551617");}); + ensure_exit(3, [](){stringToUnsignedLongLong(inf, "36893488147419103232");}); + ensure_exit(3, [](){stringToUnsignedLongLong(inf, "1 ");}); + ensure_exit(3, [](){stringToUnsignedLongLong(inf, " 1");}); + ensure_exit(3, [](){stringToUnsignedLongLong(inf, "1 2");}); + ensure_exit(3, [](){stringToUnsignedLongLong(inf, "-0");}); + ensure_exit(3, [](){stringToUnsignedLongLong(inf, "--0");}); + ensure_exit(3, [](){stringToUnsignedLongLong(inf, "-00");}); +} diff --git a/tests/test-004_use-test.h/tests/test-tokenize.cpp b/tests/test-004_use-test.h/tests/test-tokenize.cpp new file mode 100644 index 00000000..a69bf32a --- /dev/null +++ b/tests/test-004_use-test.h/tests/test-tokenize.cpp @@ -0,0 +1,6 @@ +TEST(tokenize) { + ensure(tokenize(" a b", ' ') == vector({"a", "b"})); + ensure(tokenize(" best code\t4ever now! ", " \t") == vector({"best", "code", "4ever", "now!"})); + ensure(tokenize("abacabacaba", "ac") == vector({"b", "b", "b"})); + ensure(tokenize("", ',') == vector()); +} diff --git a/tests/test-005_no-register/refs/r1/exit_code b/tests/test-005_no-register/refs/r1/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-005_no-register/refs/r1/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-005_no-register/refs/r1/stderr b/tests/test-005_no-register/refs/r1/stderr new file mode 100644 index 00000000..19d39f50 --- /dev/null +++ b/tests/test-005_no-register/refs/r1/stderr @@ -0,0 +1 @@ +FAIL Call register-function in the first line of the main (registerTestlibCmd or other similar) diff --git a/tests/test-005_no-register/refs/r1/stdout b/tests/test-005_no-register/refs/r1/stdout new file mode 100644 index 00000000..b791709c --- /dev/null +++ b/tests/test-005_no-register/refs/r1/stdout @@ -0,0 +1,2 @@ +10 +3 7 10 1 9 5 4 8 6 2 diff --git a/tests/test-005_no-register/refs/r2/exit_code b/tests/test-005_no-register/refs/r2/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-005_no-register/refs/r2/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-005_no-register/refs/r2/stderr b/tests/test-005_no-register/refs/r2/stderr new file mode 100644 index 00000000..19d39f50 --- /dev/null +++ b/tests/test-005_no-register/refs/r2/stderr @@ -0,0 +1 @@ +FAIL Call register-function in the first line of the main (registerTestlibCmd or other similar) diff --git a/tests/test-005_no-register/refs/r2/stdout b/tests/test-005_no-register/refs/r2/stdout new file mode 100644 index 00000000..b791709c --- /dev/null +++ b/tests/test-005_no-register/refs/r2/stdout @@ -0,0 +1,2 @@ +10 +3 7 10 1 9 5 4 8 6 2 diff --git a/tests/test-005_no-register/run.sh b/tests/test-005_no-register/run.sh new file mode 100644 index 00000000..87a67245 --- /dev/null +++ b/tests/test-005_no-register/run.sh @@ -0,0 +1,7 @@ +#!/bin/bash +set -eo pipefail + +bash ../scripts/compile src/g.cpp +bash ../scripts/test-ref r1 "$VALGRIND" ./g +bash ../scripts/test-ref r2 "$VALGRIND" ./g 100 +rm -f g g.exe diff --git a/tests/test-005_no-register/src/g.cpp b/tests/test-005_no-register/src/g.cpp new file mode 100644 index 00000000..3dd2f85d --- /dev/null +++ b/tests/test-005_no-register/src/g.cpp @@ -0,0 +1,7 @@ +#include "testlib.h" + +int main(int argc, char* argv[]) { + int n = 10; + println(n); + println(rnd.perm(n, 1)); +} diff --git a/tests/test-005_opts/files/test-auto-ensure-no-unused-opts.cpp b/tests/test-005_opts/files/test-auto-ensure-no-unused-opts.cpp new file mode 100644 index 00000000..acd27385 --- /dev/null +++ b/tests/test-005_opts/files/test-auto-ensure-no-unused-opts.cpp @@ -0,0 +1,22 @@ +#include "testlib.h" + +using namespace std; + +int main(int argc, char** argv) { + registerGen(argc, argv, 1); + + int test_count = opt("test-count"); + int sum_n = opt("sum-n"); + int min_n = opt("min-n", 1); + + int min_value = opt("min-value", 1); + int max_value = opt("max-value", 1000 * 1000 * 1000); + int value_bias = opt("value-bias", 0); + + println("test-count =", test_count); + println("sum-n =", sum_n); + println("min-n =", min_n); + println("min-value =", min_value); + println("max-value =", max_value); + println("value-bias =", value_bias); +} diff --git a/tests/test-005_opts/files/test-suppress-auto-ensure-no-unused-opts.cpp b/tests/test-005_opts/files/test-suppress-auto-ensure-no-unused-opts.cpp new file mode 100644 index 00000000..27b51a68 --- /dev/null +++ b/tests/test-005_opts/files/test-suppress-auto-ensure-no-unused-opts.cpp @@ -0,0 +1,23 @@ +#include "testlib.h" + +using namespace std; + +int main(int argc, char** argv) { + registerGen(argc, argv, 1); + suppressEnsureNoUnusedOpts(); + + int test_count = opt("test-count"); + int sum_n = opt("sum-n"); + int min_n = opt("min-n", 1); + + int min_value = opt("min-value", 1); + int max_value = opt("max-value", 1000 * 1000 * 1000); + int value_bias = opt("value-bias", 0); + + println("test-count =", test_count); + println("sum-n =", sum_n); + println("min-n =", min_n); + println("min-value =", min_value); + println("max-value =", max_value); + println("value-bias =", value_bias); +} diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r1/exit_code b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r1/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r1/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r1/stderr b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r1/stderr new file mode 100644 index 00000000..3ccc5755 --- /dev/null +++ b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r1/stderr @@ -0,0 +1 @@ +FAIL Opts: unknown key 'test-count' diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r1/stdout b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r1/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r2/exit_code b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r2/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r2/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r2/stderr b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r2/stderr new file mode 100644 index 00000000..1fe8aacb --- /dev/null +++ b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r2/stderr @@ -0,0 +1 @@ +FAIL Opts: unknown key 'sum-n' diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r2/stdout b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r2/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r3/exit_code b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r3/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r3/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r3/stderr b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r3/stderr new file mode 100644 index 00000000..e751eb77 --- /dev/null +++ b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r3/stderr @@ -0,0 +1 @@ +FAIL Opts: unused key 'min-val' diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r3/stdout b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r3/stdout new file mode 100644 index 00000000..aec16468 --- /dev/null +++ b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r3/stdout @@ -0,0 +1,6 @@ +test-count = 3 +sum-n = 10 +min-n = 1 +min-value = 1 +max-value = 1000000000 +value-bias = 0 diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r4/exit_code b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r4/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r4/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r4/stderr b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r4/stderr new file mode 100644 index 00000000..54a68b09 --- /dev/null +++ b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r4/stderr @@ -0,0 +1 @@ +FAIL Opts: unused key 'max-val' diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r4/stdout b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r4/stdout new file mode 100644 index 00000000..6b4d9752 --- /dev/null +++ b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r4/stdout @@ -0,0 +1,6 @@ +test-count = 3 +sum-n = 10 +min-n = 1 +min-value = 10 +max-value = 1000000000 +value-bias = 0 diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r5/exit_code b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r5/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r5/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r5/stderr b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r5/stderr new file mode 100644 index 00000000..1d0981fd --- /dev/null +++ b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r5/stderr @@ -0,0 +1 @@ +FAIL Opts: unused key 'min-length' diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r5/stdout b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r5/stdout new file mode 100644 index 00000000..13eb4d6a --- /dev/null +++ b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r5/stdout @@ -0,0 +1,6 @@ +test-count = 3 +sum-n = 10 +min-n = 1 +min-value = 10 +max-value = 20 +value-bias = 0 diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r6/exit_code b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r6/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r6/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r6/stderr b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r6/stderr new file mode 100644 index 00000000..e3fb4ec7 --- /dev/null +++ b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r6/stderr @@ -0,0 +1 @@ +FAIL Opts: unused key 'bias-value' diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r6/stdout b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r6/stdout new file mode 100644 index 00000000..22585a1c --- /dev/null +++ b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r6/stdout @@ -0,0 +1,6 @@ +test-count = 3 +sum-n = 10 +min-n = 3 +min-value = 10 +max-value = 20 +value-bias = 0 diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r7/exit_code b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r7/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r7/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r7/stderr b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r7/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r7/stdout b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r7/stdout new file mode 100644 index 00000000..aec16468 --- /dev/null +++ b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r7/stdout @@ -0,0 +1,6 @@ +test-count = 3 +sum-n = 10 +min-n = 1 +min-value = 1 +max-value = 1000000000 +value-bias = 0 diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r8/exit_code b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r8/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r8/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r8/stderr b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r8/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r8/stdout b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r8/stdout new file mode 100644 index 00000000..6b4d9752 --- /dev/null +++ b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r8/stdout @@ -0,0 +1,6 @@ +test-count = 3 +sum-n = 10 +min-n = 1 +min-value = 10 +max-value = 1000000000 +value-bias = 0 diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r9/exit_code b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r9/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r9/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r9/stderr b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r9/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r9/stdout b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r9/stdout new file mode 100644 index 00000000..7b47e9fc --- /dev/null +++ b/tests/test-005_opts/refs/auto-ensure-no-unused-opts/r9/stdout @@ -0,0 +1,6 @@ +test-count = 5 +sum-n = 100 +min-n = 3 +min-value = 10 +max-value = 20 +value-bias = -3 diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r1/exit_code b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r1/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r1/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r1/stderr b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r1/stderr new file mode 100644 index 00000000..3ccc5755 --- /dev/null +++ b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r1/stderr @@ -0,0 +1 @@ +FAIL Opts: unknown key 'test-count' diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r1/stdout b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r1/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r2/exit_code b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r2/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r2/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r2/stderr b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r2/stderr new file mode 100644 index 00000000..1fe8aacb --- /dev/null +++ b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r2/stderr @@ -0,0 +1 @@ +FAIL Opts: unknown key 'sum-n' diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r2/stdout b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r2/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r3/exit_code b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r3/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r3/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r3/stderr b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r3/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r3/stdout b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r3/stdout new file mode 100644 index 00000000..aec16468 --- /dev/null +++ b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r3/stdout @@ -0,0 +1,6 @@ +test-count = 3 +sum-n = 10 +min-n = 1 +min-value = 1 +max-value = 1000000000 +value-bias = 0 diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r4/exit_code b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r4/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r4/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r4/stderr b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r4/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r4/stdout b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r4/stdout new file mode 100644 index 00000000..6b4d9752 --- /dev/null +++ b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r4/stdout @@ -0,0 +1,6 @@ +test-count = 3 +sum-n = 10 +min-n = 1 +min-value = 10 +max-value = 1000000000 +value-bias = 0 diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r5/exit_code b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r5/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r5/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r5/stderr b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r5/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r5/stdout b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r5/stdout new file mode 100644 index 00000000..13eb4d6a --- /dev/null +++ b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r5/stdout @@ -0,0 +1,6 @@ +test-count = 3 +sum-n = 10 +min-n = 1 +min-value = 10 +max-value = 20 +value-bias = 0 diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r6/exit_code b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r6/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r6/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r6/stderr b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r6/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r6/stdout b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r6/stdout new file mode 100644 index 00000000..22585a1c --- /dev/null +++ b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r6/stdout @@ -0,0 +1,6 @@ +test-count = 3 +sum-n = 10 +min-n = 3 +min-value = 10 +max-value = 20 +value-bias = 0 diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r7/exit_code b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r7/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r7/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r7/stderr b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r7/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r7/stdout b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r7/stdout new file mode 100644 index 00000000..aec16468 --- /dev/null +++ b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r7/stdout @@ -0,0 +1,6 @@ +test-count = 3 +sum-n = 10 +min-n = 1 +min-value = 1 +max-value = 1000000000 +value-bias = 0 diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r8/exit_code b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r8/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r8/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r8/stderr b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r8/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r8/stdout b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r8/stdout new file mode 100644 index 00000000..6b4d9752 --- /dev/null +++ b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r8/stdout @@ -0,0 +1,6 @@ +test-count = 3 +sum-n = 10 +min-n = 1 +min-value = 10 +max-value = 1000000000 +value-bias = 0 diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r9/exit_code b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r9/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r9/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r9/stderr b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r9/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r9/stdout b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r9/stdout new file mode 100644 index 00000000..7b47e9fc --- /dev/null +++ b/tests/test-005_opts/refs/suppress-auto-ensure-no-unused-opts/r9/stdout @@ -0,0 +1,6 @@ +test-count = 5 +sum-n = 100 +min-n = 3 +min-value = 10 +max-value = 20 +value-bias = -3 diff --git a/tests/test-005_opts/run.sh b/tests/test-005_opts/run.sh new file mode 100644 index 00000000..4e80e34b --- /dev/null +++ b/tests/test-005_opts/run.sh @@ -0,0 +1,26 @@ +#!/bin/bash +set -eo pipefail + +bash ../scripts/compile files/test-auto-ensure-no-unused-opts.cpp +bash ../scripts/test-ref auto-ensure-no-unused-opts/r1 "$VALGRIND" ./test-auto-ensure-no-unused-opts +bash ../scripts/test-ref auto-ensure-no-unused-opts/r2 "$VALGRIND" ./test-auto-ensure-no-unused-opts -test-count 3 +bash ../scripts/test-ref auto-ensure-no-unused-opts/r3 "$VALGRIND" ./test-auto-ensure-no-unused-opts -test-count 3 -sum-n 10 -min-val 1 +bash ../scripts/test-ref auto-ensure-no-unused-opts/r4 "$VALGRIND" ./test-auto-ensure-no-unused-opts -test-count 3 -sum-n 10 -min-value 10 -max-val 20 +bash ../scripts/test-ref auto-ensure-no-unused-opts/r5 "$VALGRIND" ./test-auto-ensure-no-unused-opts -test-count 3 -sum-n 10 -min-length 3 -min-value 10 -max-value 20 +bash ../scripts/test-ref auto-ensure-no-unused-opts/r6 "$VALGRIND" ./test-auto-ensure-no-unused-opts -test-count 3 -sum-n 10 -min-n 3 -min-value 10 -max-value 20 -bias-value 3 +bash ../scripts/test-ref auto-ensure-no-unused-opts/r7 "$VALGRIND" ./test-auto-ensure-no-unused-opts -test-count 3 -sum-n 10 +bash ../scripts/test-ref auto-ensure-no-unused-opts/r8 "$VALGRIND" ./test-auto-ensure-no-unused-opts -test-count 3 -sum-n 10 -min-value 10 +bash ../scripts/test-ref auto-ensure-no-unused-opts/r9 "$VALGRIND" ./test-auto-ensure-no-unused-opts -test-count 5 -sum-n 100 -min-n 3 -min-value 10 -max-value 20 -value-bias -3 +rm -f test-auto-ensure-no-unused-opts test-auto-ensure-no-unused-opts.exe + +bash ../scripts/compile files/test-suppress-auto-ensure-no-unused-opts.cpp +bash ../scripts/test-ref suppress-auto-ensure-no-unused-opts/r1 "$VALGRIND" ./test-suppress-auto-ensure-no-unused-opts +bash ../scripts/test-ref suppress-auto-ensure-no-unused-opts/r2 "$VALGRIND" ./test-suppress-auto-ensure-no-unused-opts -test-count 3 +bash ../scripts/test-ref suppress-auto-ensure-no-unused-opts/r3 "$VALGRIND" ./test-suppress-auto-ensure-no-unused-opts -test-count 3 -sum-n 10 -min-val 1 +bash ../scripts/test-ref suppress-auto-ensure-no-unused-opts/r4 "$VALGRIND" ./test-suppress-auto-ensure-no-unused-opts -test-count 3 -sum-n 10 -min-value 10 -max-val 20 +bash ../scripts/test-ref suppress-auto-ensure-no-unused-opts/r5 "$VALGRIND" ./test-suppress-auto-ensure-no-unused-opts -test-count 3 -sum-n 10 -min-length 3 -min-value 10 -max-value 20 +bash ../scripts/test-ref suppress-auto-ensure-no-unused-opts/r6 "$VALGRIND" ./test-suppress-auto-ensure-no-unused-opts -test-count 3 -sum-n 10 -min-n 3 -min-value 10 -max-value 20 -bias-value 3 +bash ../scripts/test-ref suppress-auto-ensure-no-unused-opts/r7 "$VALGRIND" ./test-suppress-auto-ensure-no-unused-opts -test-count 3 -sum-n 10 +bash ../scripts/test-ref suppress-auto-ensure-no-unused-opts/r8 "$VALGRIND" ./test-suppress-auto-ensure-no-unused-opts -test-count 3 -sum-n 10 -min-value 10 +bash ../scripts/test-ref suppress-auto-ensure-no-unused-opts/r9 "$VALGRIND" ./test-suppress-auto-ensure-no-unused-opts -test-count 5 -sum-n 100 -min-n 3 -min-value 10 -max-value 20 -value-bias -3 +rm -f test-suppress-auto-ensure-no-unused-opts test-suppress-auto-ensure-no-unused-opts.exe diff --git a/tests/test-006_interactors/files/crossrun/CrossRun.jar b/tests/test-006_interactors/files/crossrun/CrossRun.jar new file mode 100644 index 00000000..b41a8fb4 Binary files /dev/null and b/tests/test-006_interactors/files/crossrun/CrossRun.jar differ diff --git a/tests/test-006_interactors/files/crossrun/CrossRun.java b/tests/test-006_interactors/files/crossrun/CrossRun.java new file mode 100644 index 00000000..c5a1019d --- /dev/null +++ b/tests/test-006_interactors/files/crossrun/CrossRun.java @@ -0,0 +1,162 @@ +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class CrossRun { + private static final List messages = Collections.synchronizedList(new ArrayList()); + + private static volatile boolean failed = false; + + private static void error(String message) { + System.out.println("ERROR: " + message); + System.exit(1); + } + + public static void main(String[] args) { + int sep = -1; + for (int i = 0; i < args.length; i++) { + if (args[i].equals("--")) { + sep = i; + break; + } + } + + if (sep == -1) { + error("Expected exactly one '--' as separator for the two process command lines."); + } + + String[] params1 = new String[sep]; + System.arraycopy(args, 0, params1, 0, params1.length); + + String[] params2 = new String[args.length - sep - 1]; + System.arraycopy(args, sep + 1, params2, 0, params2.length); + + long startTime = System.currentTimeMillis(); + + try { + runProcesses(params1, params2); + } catch (IOException e) { + error(e.getMessage()); + } + + System.out.println("Completed in " + (System.currentTimeMillis() - startTime) + " ms."); + } + + private static void runProcesses(String[] params1, String[] params2) throws IOException { + Process process1 = new ProcessBuilder(params1).start(); + Process process2 = new ProcessBuilder(params2).start(); + + Thread readProcess1WriteProcess2Thread = + new Thread(new StreamProxyRunner("process1", "process2", process1.getInputStream(), process2.getOutputStream())); + Thread readProcess2WriteProcess1Thread = + new Thread(new StreamProxyRunner("process2", "process1", process2.getInputStream(), process1.getOutputStream())); + + readProcess1WriteProcess2Thread.start(); + readProcess2WriteProcess1Thread.start(); + + int processExitCode1 = -1; + try { + processExitCode1 = process1.waitFor(); + } catch (InterruptedException e) { + error(e.getMessage()); + } + + int processExitCode2 = -1; + try { + processExitCode2 = process2.waitFor(); + } catch (InterruptedException e) { + error(e.getMessage()); + } + + try { + readProcess1WriteProcess2Thread.join(); + } catch (InterruptedException e) { + error(e.getMessage()); + } + + try { + readProcess2WriteProcess1Thread.join(); + } catch (InterruptedException e) { + error(e.getMessage()); + } + + if (processExitCode1 != 0) { + messages.add("The process 1 returned with exit code " + processExitCode1 + "."); + } + + if (processExitCode2 != 0) { + messages.add("The process 2 returned with exit code " + processExitCode2 + "."); + } + + for (String message : messages) { + System.out.println("* " + message); + } + + if (failed) { + System.exit(1); + } + } + + @SuppressWarnings("ClassCanBeRecord") + private static final class StreamProxyRunner implements Runnable { + private final String processName1; + private final String processName2; + private final InputStream inputStream; + private final OutputStream outputStream; + + private StreamProxyRunner(final String processName1, + final String processName2, + final InputStream inputStream, + final OutputStream outputStream) { + this.processName1 = processName1; + this.processName2 = processName2; + this.inputStream = inputStream; + this.outputStream = outputStream; + } + + @Override + public void run() { + byte[] buffer = new byte[65536]; + + while (true) { + int size; + + try { + size = inputStream.read(buffer); + } catch (IOException e) { + messages.add("Unexpected exception " + e.getClass().getSimpleName() + " while reading from the output of the " + processName1 + " process: " + e.getMessage()); + failed = true; + break; + } + + if (size < 0) { + break; + } + + try { + outputStream.write(buffer, 0, size); + outputStream.flush(); + } catch (IOException e) { + messages.add("Unexpected exception " + e.getClass().getSimpleName() + " while writing to the input of the " + processName2 + " process: " + e.getMessage()); + failed = true; + break; + } + } + + try { + inputStream.close(); + } catch (IOException e) { + // No operations. + } + + try { + outputStream.close(); + } catch (IOException e) { + // No operations. + } + } + } +} diff --git a/tests/test-006_interactors/files/crossrun/build-cross-run.sh b/tests/test-006_interactors/files/crossrun/build-cross-run.sh new file mode 100644 index 00000000..da01e8e5 --- /dev/null +++ b/tests/test-006_interactors/files/crossrun/build-cross-run.sh @@ -0,0 +1,53 @@ +#!/bin/bash + +uname_output="$(uname -s)" +case "${uname_output}" in +Linux*) machine=Linux ;; +Darwin*) machine=Mac ;; +CYGWIN*) machine=Windows ;; +MINGW*) machine=Windows ;; +MSYS*) machine=Windows ;; +*) echo "Unknown system '${uname_output}'" && exit 1 ;; +esac + +# If JAVA8_32_HOME is set, use its javac +if [[ -n "$JAVA8_32_HOME" ]]; then + if [[ "$machine" == "Windows" ]]; then + JAVA8_32_HOME=$(cygpath "$JAVA8_32_HOME") + fi + export PATH="$JAVA8_32_HOME/bin:$PATH" +fi + +# If JAVA7_32_HOME is set, use its javac +if [[ -n "$JAVA7_32_HOME" ]]; then + if [[ "$machine" == "Windows" ]]; then + JAVA7_32_HOME=$(cygpath "$JAVA7_32_HOME") + fi + export PATH="$JAVA7_32_HOME/bin:$PATH" +fi + +echo $PATH + +# Show javac version +javac -version + +# Compile all .java files +javac *.java + +# Check if the compilation was successful +if [ $? -ne 0 ]; then + echo "Error during compilation. Exiting." + exit 1 +fi + +# Create a manifest file for the jar +echo "Main-Class: CrossRun" > manifest.mf + +# Package all .class files into a jar +jar cvfm CrossRun.jar manifest.mf *.class + +# Cleanup .class files and manifest file (optional) +rm *.class +rm manifest.mf + +echo "Done. CrossRun.jar created." diff --git a/tests/test-006_interactors/files/unix/input.01 b/tests/test-006_interactors/files/unix/input.01 new file mode 100644 index 00000000..95ea5f72 --- /dev/null +++ b/tests/test-006_interactors/files/unix/input.01 @@ -0,0 +1,4 @@ +3 +1 2 +3 4 +-1 -1 diff --git a/tests/test-006_interactors/files/unix/participant.01 b/tests/test-006_interactors/files/unix/participant.01 new file mode 100644 index 00000000..e64e44ec --- /dev/null +++ b/tests/test-006_interactors/files/unix/participant.01 @@ -0,0 +1,3 @@ +5 +6 +7 diff --git a/tests/test-006_interactors/files/win/input.01 b/tests/test-006_interactors/files/win/input.01 new file mode 100644 index 00000000..8924ce77 --- /dev/null +++ b/tests/test-006_interactors/files/win/input.01 @@ -0,0 +1,4 @@ +3 +1 2 +3 4 +-1 -1 diff --git a/tests/test-006_interactors/files/win/participant.01 b/tests/test-006_interactors/files/win/participant.01 new file mode 100644 index 00000000..fb5f06a8 --- /dev/null +++ b/tests/test-006_interactors/files/win/participant.01 @@ -0,0 +1,3 @@ +5 +6 +7 diff --git a/tests/test-006_interactors/refs/r-interactor-a-plus-b-1-1/exit_code b/tests/test-006_interactors/refs/r-interactor-a-plus-b-1-1/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-006_interactors/refs/r-interactor-a-plus-b-1-1/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-006_interactors/refs/r-interactor-a-plus-b-1-1/stderr b/tests/test-006_interactors/refs/r-interactor-a-plus-b-1-1/stderr new file mode 100644 index 00000000..029cfd42 --- /dev/null +++ b/tests/test-006_interactors/refs/r-interactor-a-plus-b-1-1/stderr @@ -0,0 +1 @@ +ok 3 queries processed diff --git a/tests/test-006_interactors/refs/r-interactor-a-plus-b-1-1/stdout b/tests/test-006_interactors/refs/r-interactor-a-plus-b-1-1/stdout new file mode 100644 index 00000000..05dd8d60 --- /dev/null +++ b/tests/test-006_interactors/refs/r-interactor-a-plus-b-1-1/stdout @@ -0,0 +1,3 @@ +1 2 +3 4 +-1 -1 diff --git a/tests/test-006_interactors/refs/r-interactor-a-plus-b-1-2/exit_code b/tests/test-006_interactors/refs/r-interactor-a-plus-b-1-2/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-006_interactors/refs/r-interactor-a-plus-b-1-2/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-006_interactors/refs/r-interactor-a-plus-b-1-2/stderr b/tests/test-006_interactors/refs/r-interactor-a-plus-b-1-2/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-006_interactors/refs/r-interactor-a-plus-b-1-2/stdout b/tests/test-006_interactors/refs/r-interactor-a-plus-b-1-2/stdout new file mode 100644 index 00000000..e64e44ec --- /dev/null +++ b/tests/test-006_interactors/refs/r-interactor-a-plus-b-1-2/stdout @@ -0,0 +1,3 @@ +5 +6 +7 diff --git a/tests/test-006_interactors/refs/r-interactor-a-plus-b-2-1/exit_code b/tests/test-006_interactors/refs/r-interactor-a-plus-b-2-1/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-006_interactors/refs/r-interactor-a-plus-b-2-1/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-006_interactors/refs/r-interactor-a-plus-b-2-1/stderr b/tests/test-006_interactors/refs/r-interactor-a-plus-b-2-1/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-006_interactors/refs/r-interactor-a-plus-b-2-1/stdout b/tests/test-006_interactors/refs/r-interactor-a-plus-b-2-1/stdout new file mode 100644 index 00000000..7daa7785 --- /dev/null +++ b/tests/test-006_interactors/refs/r-interactor-a-plus-b-2-1/stdout @@ -0,0 +1,3 @@ +3 +7 +-2 diff --git a/tests/test-006_interactors/run.sh b/tests/test-006_interactors/run.sh new file mode 100644 index 00000000..7d18216d --- /dev/null +++ b/tests/test-006_interactors/run.sh @@ -0,0 +1,20 @@ +#!/bin/bash +set -eo pipefail + +os="unix" +if [[ "$MACHINE" == "Windows" ]]; then + os="win" +fi + +bash ../scripts/compile src/interactor-a-plus-b.cpp +bash ../scripts/test-ref r-interactor-a-plus-b-1-1 "$VALGRIND" ./interactor-a-plus-b files/"$os"/input.01 output.01 < files/"$os"/participant.01 +tr -d '\r' < output.01 > output.01.nix +bash ../scripts/test-ref r-interactor-a-plus-b-1-2 cat output.01.nix +rm -f output.01 output.01.nix + +bash ../scripts/compile src/interactive-a-plus-b.cpp +echo "Running 'java -jar files/crossrun/CrossRun.jar ./interactor-a-plus-b files/"$os"/input.01 output.02 -- ./interactive-a-plus-b'" +java -jar files/crossrun/CrossRun.jar ./interactor-a-plus-b files/"$os"/input.01 output.02 -- ./interactive-a-plus-b +tr -d '\r' < output.02 > output.02.nix +bash ../scripts/test-ref r-interactor-a-plus-b-2-1 cat output.02.nix +rm -f output.02 output.02.nix interactive-a-plus-b interactive-a-plus-b.exe interactor-a-plus-b interactor-a-plus-b.exe interactive_runner.out interactive_runner.err diff --git a/tests/test-006_interactors/src/interactive-a-plus-b.cpp b/tests/test-006_interactors/src/interactive-a-plus-b.cpp new file mode 100644 index 00000000..68c0ad8c --- /dev/null +++ b/tests/test-006_interactors/src/interactive-a-plus-b.cpp @@ -0,0 +1,9 @@ +#include + +using namespace std; + +int main() { + int a, b; + while (cin >> a >> b) + cout << a + b << endl; +} diff --git a/tests/test-006_interactors/src/interactive_runner.py b/tests/test-006_interactors/src/interactive_runner.py new file mode 100644 index 00000000..c06bdbae --- /dev/null +++ b/tests/test-006_interactors/src/interactive_runner.py @@ -0,0 +1,122 @@ +# This code can be run as python2 or python3 in most systems. +# +# This is a small program that runs two processes, connecting the stdin of each +# one to the stdout of the other. +# It doesn't perform a lot of checking, so many errors may +# be caught internally by Python (e.g., if your command line has incorrect +# syntax) or not caught at all (e.g., if the judge or solution hangs). +# +# Run this as: +# python interactive_runner.py -- +# +# For example, if you have a testing_tool.py in python3 (that takes a single +# integer as a command line parameter) to use as judge -- like one +# downloaded from a problem statement -- and you would run your solution +# in a standalone using one of the following: +# 1. python3 my_solution.py +# 2. ./my_solution +# 3. java Solution +# 4. my_solution.exe +# Then you could run the judge and solution together, using this, as: +# 1. python interactive_runner.py python3 testing_tool.py 0 -- python3 my_solution.py +# 2. python interactive_runner.py python3 testing_tool.py 0 -- ./my_solution +# 3. python interactive_runner.py python3 testing_tool.py 0 -- java solution +# 4. python interactive_runner.py python3 testing_tool.py 0 -- my_solution.exe +# Notice that the solution in cases 2, 3 and 4 would usually have a +# compilation step before running, which you should run in your usual way +# before using this tool. +# +# This is only intended as a convenient tool to help contestants test solutions +# locally. In particular, it is not identical to the implementation on our +# server, which is more complex. +# +# The standard streams are handled the following way: +# - judge's stdin is connected to the solution's stdout; +# - judge's stdout is connected to the solution's stdin; +# - stderrs of both judge and solution are piped to standard error stream, with +# lines prepended by "judge: " or "sol: " respectively (note, no +# synchronization is done so it's possible for the messages from both programs +# to overlap with each other). + +from __future__ import print_function +import sys, subprocess, threading + +class SubprocessThread(threading.Thread): + def __init__(self, + args, + stdin_pipe=subprocess.PIPE, + stdout_pipe=subprocess.PIPE, + stderr_prefix=None): + threading.Thread.__init__(self) + self.stderr_prefix = stderr_prefix + self.p = subprocess.Popen( + args, stdin=stdin_pipe, stdout=stdout_pipe, stderr=subprocess.PIPE) + + def run(self): + try: + self.pipeToStdErr(self.p.stderr) + self.return_code = self.p.wait() + self.error_message = None + except (SystemError, OSError): + self.return_code = -1 + self.error_message = "The process crashed or produced too much output." + + # Reads bytes from the stream and writes them to sys.stderr prepending lines + # with self.stderr_prefix. + # We are not reading by lines to guard against the case when EOL is never + # found in the stream. + def pipeToStdErr(self, stream): + new_line = True + while True: + chunk = stream.readline(1) + if not chunk: + return + chunk = chunk.decode("UTF-8") + if new_line and self.stderr_prefix: + chunk = self.stderr_prefix + chunk + new_line = False + sys.stderr.write(chunk) + if chunk.endswith("\n"): + new_line = True + sys.stderr.flush() + + +assert sys.argv.count("--") == 1, ( + "There should be exactly one instance of '--' in the command line.") +sep_index = sys.argv.index("--") +judge_args = sys.argv[1:sep_index] +sol_args = sys.argv[sep_index + 1:] + +t_sol = SubprocessThread(sol_args, stderr_prefix=" sol: ") +t_judge = SubprocessThread( + judge_args, + stdin_pipe=t_sol.p.stdout, + stdout_pipe=t_sol.p.stdin, + stderr_prefix="judge: ") +t_sol.start() +t_judge.start() +t_sol.join() +t_judge.join() + +# Print an empty line to handle the case when stderr doesn't print EOL. +print() +print("Judge return code:", t_judge.return_code) +if t_judge.error_message: + print("Judge error message:", t_judge.error_message) + +print("Solution return code:", t_sol.return_code) +if t_sol.error_message: + print("Solution error message:", t_sol.error_message) + +if t_sol.return_code: + print("A solution finishing with exit code other than 0 (without exceeding " + "time or memory limits) would be interpreted as a Runtime Error " + "in the system.") +elif t_judge.return_code: + print("A solution finishing with exit code 0 (without exceeding time or " + "memory limits) and a judge finishing with exit code other than 0 " + "would be interpreted as a Wrong Answer in the system.") +else: + print("A solution and judge both finishing with exit code 0 (without " + "exceeding time or memory limits) would be interpreted as Correct " + "in the system.") diff --git a/tests/test-006_interactors/src/interactor-a-plus-b.cpp b/tests/test-006_interactors/src/interactor-a-plus-b.cpp new file mode 100644 index 00000000..e19e1487 --- /dev/null +++ b/tests/test-006_interactors/src/interactor-a-plus-b.cpp @@ -0,0 +1,26 @@ +#include "testlib.h" +#include + +using namespace std; + +int main(int argc, char *argv[]) { + setName("Interactor A+B"); + registerInteraction(argc, argv); + + // reads number of queries from test (input) file + int n = inf.readInt(); + for (int i = 0; i < n; i++) { + // reads query from test (input) file + int a = inf.readInt(); + int b = inf.readInt(); + + // writes query to the solution, endl makes flush + cout << a << " " << b << endl; + + // writes output file to be verified by checker later + tout << ouf.readInt() << endl; + } + + // just message + quitf(_ok, "%d queries processed", n); +} diff --git a/tests/test-007_validators/files/unix/input.01 b/tests/test-007_validators/files/unix/input.01 new file mode 100644 index 00000000..1f047995 --- /dev/null +++ b/tests/test-007_validators/files/unix/input.01 @@ -0,0 +1,3 @@ +1 +2 0 0 +1 2 diff --git a/tests/test-007_validators/files/unix/input.02 b/tests/test-007_validators/files/unix/input.02 new file mode 100644 index 00000000..e5838dcf --- /dev/null +++ b/tests/test-007_validators/files/unix/input.02 @@ -0,0 +1,7 @@ +3 +1 0 0 +1 +2 0 0 +2 1 +4 0 0 +1 2 3 4 diff --git a/tests/test-007_validators/files/unix/input.03 b/tests/test-007_validators/files/unix/input.03 new file mode 100644 index 00000000..6c661ae7 --- /dev/null +++ b/tests/test-007_validators/files/unix/input.03 @@ -0,0 +1,7 @@ +3 +1 0 0 +1 +2 0 0 +2 1 +4 0 0 +1 2 2 4 diff --git a/tests/test-007_validators/files/unix/input.04 b/tests/test-007_validators/files/unix/input.04 new file mode 100644 index 00000000..0275f06f --- /dev/null +++ b/tests/test-007_validators/files/unix/input.04 @@ -0,0 +1,5 @@ +2 +2 0 0 +1 2 +3 0 0 +1 3 2 diff --git a/tests/test-007_validators/files/unix/input.05 b/tests/test-007_validators/files/unix/input.05 new file mode 100644 index 00000000..fb96a973 --- /dev/null +++ b/tests/test-007_validators/files/unix/input.05 @@ -0,0 +1,9 @@ +4 +2 0 0 +1 2 +3 0 0 +1 3 2 +2 0 0 +1 2 +3 0 0 +1 3 2 diff --git a/tests/test-007_validators/files/unix/input.06 b/tests/test-007_validators/files/unix/input.06 new file mode 100644 index 00000000..38d340cd --- /dev/null +++ b/tests/test-007_validators/files/unix/input.06 @@ -0,0 +1,5 @@ +2 +4 -2 -5 +1 2 3 4 +4 2 5 +1 2 3 4 diff --git a/tests/test-007_validators/files/win/input.01 b/tests/test-007_validators/files/win/input.01 new file mode 100644 index 00000000..a5c30b16 --- /dev/null +++ b/tests/test-007_validators/files/win/input.01 @@ -0,0 +1,3 @@ +1 +2 0 0 +1 2 diff --git a/tests/test-007_validators/files/win/input.02 b/tests/test-007_validators/files/win/input.02 new file mode 100644 index 00000000..fe80acd9 --- /dev/null +++ b/tests/test-007_validators/files/win/input.02 @@ -0,0 +1,7 @@ +3 +1 0 0 +1 +2 0 0 +2 1 +4 0 0 +1 2 3 4 diff --git a/tests/test-007_validators/files/win/input.03 b/tests/test-007_validators/files/win/input.03 new file mode 100644 index 00000000..d4e5b811 --- /dev/null +++ b/tests/test-007_validators/files/win/input.03 @@ -0,0 +1,7 @@ +3 +1 0 0 +1 +2 0 0 +2 1 +4 0 0 +1 2 2 4 diff --git a/tests/test-007_validators/files/win/input.04 b/tests/test-007_validators/files/win/input.04 new file mode 100644 index 00000000..33eb40f2 --- /dev/null +++ b/tests/test-007_validators/files/win/input.04 @@ -0,0 +1,5 @@ +2 +2 0 0 +1 2 +3 0 0 +1 3 2 diff --git a/tests/test-007_validators/files/win/input.05 b/tests/test-007_validators/files/win/input.05 new file mode 100644 index 00000000..404b1ad7 --- /dev/null +++ b/tests/test-007_validators/files/win/input.05 @@ -0,0 +1,9 @@ +4 +2 0 0 +1 2 +3 0 0 +1 3 2 +2 0 0 +1 2 +3 0 0 +1 3 2 diff --git a/tests/test-007_validators/files/win/input.06 b/tests/test-007_validators/files/win/input.06 new file mode 100644 index 00000000..74b59694 --- /dev/null +++ b/tests/test-007_validators/files/win/input.06 @@ -0,0 +1,5 @@ +2 +4 -2 -5 +1 2 3 4 +4 2 5 +1 2 3 4 diff --git a/tests/test-007_validators/refs/v1-01/exit_code b/tests/test-007_validators/refs/v1-01/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-007_validators/refs/v1-01/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-007_validators/refs/v1-01/stderr b/tests/test-007_validators/refs/v1-01/stderr new file mode 100644 index 00000000..9db84fa1 --- /dev/null +++ b/tests/test-007_validators/refs/v1-01/stderr @@ -0,0 +1,9 @@ +"a": min-value-hit max-value-hit +"n": +"t": min-value-hit +constant-bounds "a": 1 2 +constant-bounds "n": 1 4 +constant-bounds "t": 1 3 +variable "a" +variable "n" +variable "t" diff --git a/tests/test-007_validators/refs/v1-01/stdout b/tests/test-007_validators/refs/v1-01/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-007_validators/refs/v1-02/exit_code b/tests/test-007_validators/refs/v1-02/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-007_validators/refs/v1-02/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-007_validators/refs/v1-02/stderr b/tests/test-007_validators/refs/v1-02/stderr new file mode 100644 index 00000000..561dedd1 --- /dev/null +++ b/tests/test-007_validators/refs/v1-02/stderr @@ -0,0 +1,9 @@ +"a": min-value-hit max-value-hit +"n": min-value-hit max-value-hit +"t": max-value-hit +constant-bounds "a": 1 ? +constant-bounds "n": 1 4 +constant-bounds "t": 1 3 +variable "a" +variable "n" +variable "t" diff --git a/tests/test-007_validators/refs/v1-02/stdout b/tests/test-007_validators/refs/v1-02/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-007_validators/refs/v1-03/exit_code b/tests/test-007_validators/refs/v1-03/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-007_validators/refs/v1-03/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-007_validators/refs/v1-03/stderr b/tests/test-007_validators/refs/v1-03/stderr new file mode 100644 index 00000000..93449207 --- /dev/null +++ b/tests/test-007_validators/refs/v1-03/stderr @@ -0,0 +1 @@ +FAIL not a permutation (duplicates) (test case 4) diff --git a/tests/test-007_validators/refs/v1-03/stdout b/tests/test-007_validators/refs/v1-03/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-007_validators/refs/v1-04/exit_code b/tests/test-007_validators/refs/v1-04/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-007_validators/refs/v1-04/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-007_validators/refs/v1-04/stderr b/tests/test-007_validators/refs/v1-04/stderr new file mode 100644 index 00000000..99e62a97 --- /dev/null +++ b/tests/test-007_validators/refs/v1-04/stderr @@ -0,0 +1,9 @@ +"a": min-value-hit max-value-hit +"n": +"t": +constant-bounds "a": 1 ? +constant-bounds "n": 1 4 +constant-bounds "t": 1 3 +variable "a" +variable "n" +variable "t" diff --git a/tests/test-007_validators/refs/v1-04/stdout b/tests/test-007_validators/refs/v1-04/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-007_validators/refs/v1-05/exit_code b/tests/test-007_validators/refs/v1-05/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-007_validators/refs/v1-05/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-007_validators/refs/v1-05/stderr b/tests/test-007_validators/refs/v1-05/stderr new file mode 100644 index 00000000..70188806 --- /dev/null +++ b/tests/test-007_validators/refs/v1-05/stderr @@ -0,0 +1 @@ +FAIL Integer parameter [name=t] equals to 4, violates the range [1, 3] (stdin, line 1) diff --git a/tests/test-007_validators/refs/v1-05/stdout b/tests/test-007_validators/refs/v1-05/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-007_validators/refs/v1-06/exit_code b/tests/test-007_validators/refs/v1-06/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-007_validators/refs/v1-06/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-007_validators/refs/v1-06/stderr b/tests/test-007_validators/refs/v1-06/stderr new file mode 100644 index 00000000..d441cadb --- /dev/null +++ b/tests/test-007_validators/refs/v1-06/stderr @@ -0,0 +1,9 @@ +"a": min-value-hit max-value-hit +"n": max-value-hit +"t": +constant-bounds "a": 1 4 +constant-bounds "n": 1 4 +constant-bounds "t": 1 3 +variable "a" +variable "n" +variable "t" diff --git a/tests/test-007_validators/refs/v1-06/stdout b/tests/test-007_validators/refs/v1-06/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-007_validators/refs/v2-01/exit_code b/tests/test-007_validators/refs/v2-01/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-007_validators/refs/v2-01/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-007_validators/refs/v2-01/stderr b/tests/test-007_validators/refs/v2-01/stderr new file mode 100644 index 00000000..5388e5f5 --- /dev/null +++ b/tests/test-007_validators/refs/v2-01/stderr @@ -0,0 +1,9 @@ +"a": min-value-hit max-value-hit +"n": max-value-hit +"t": min-value-hit +constant-bounds "a": 1 2 +constant-bounds "n": 1 4 +constant-bounds "t": 1 3 +variable "a" +variable "n" +variable "t" diff --git a/tests/test-007_validators/refs/v2-01/stdout b/tests/test-007_validators/refs/v2-01/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-007_validators/refs/v2-02/exit_code b/tests/test-007_validators/refs/v2-02/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-007_validators/refs/v2-02/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-007_validators/refs/v2-02/stderr b/tests/test-007_validators/refs/v2-02/stderr new file mode 100644 index 00000000..8604ba97 --- /dev/null +++ b/tests/test-007_validators/refs/v2-02/stderr @@ -0,0 +1,9 @@ +"a": min-value-hit max-value-hit +"n": min-value-hit max-value-hit +"t": min-value-hit max-value-hit +constant-bounds "a": 1 ? +constant-bounds "n": 1 4 +constant-bounds "t": 1 3 +variable "a" +variable "n" +variable "t" diff --git a/tests/test-007_validators/refs/v2-02/stdout b/tests/test-007_validators/refs/v2-02/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-007_validators/refs/v2-03/exit_code b/tests/test-007_validators/refs/v2-03/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-007_validators/refs/v2-03/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-007_validators/refs/v2-03/stderr b/tests/test-007_validators/refs/v2-03/stderr new file mode 100644 index 00000000..93449207 --- /dev/null +++ b/tests/test-007_validators/refs/v2-03/stderr @@ -0,0 +1 @@ +FAIL not a permutation (duplicates) (test case 4) diff --git a/tests/test-007_validators/refs/v2-03/stdout b/tests/test-007_validators/refs/v2-03/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-007_validators/refs/v2-04/exit_code b/tests/test-007_validators/refs/v2-04/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-007_validators/refs/v2-04/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-007_validators/refs/v2-04/stderr b/tests/test-007_validators/refs/v2-04/stderr new file mode 100644 index 00000000..d9453233 --- /dev/null +++ b/tests/test-007_validators/refs/v2-04/stderr @@ -0,0 +1,9 @@ +"a": min-value-hit max-value-hit +"n": max-value-hit +"t": min-value-hit +constant-bounds "a": 1 ? +constant-bounds "n": 1 4 +constant-bounds "t": 1 3 +variable "a" +variable "n" +variable "t" diff --git a/tests/test-007_validators/refs/v2-04/stdout b/tests/test-007_validators/refs/v2-04/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-007_validators/refs/v2-05/exit_code b/tests/test-007_validators/refs/v2-05/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-007_validators/refs/v2-05/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-007_validators/refs/v2-05/stderr b/tests/test-007_validators/refs/v2-05/stderr new file mode 100644 index 00000000..9db640fb --- /dev/null +++ b/tests/test-007_validators/refs/v2-05/stderr @@ -0,0 +1 @@ +FAIL Integer parameter [name=~t] equals to 4, violates the range [1, 3] (stdin, line 1) diff --git a/tests/test-007_validators/refs/v2-05/stdout b/tests/test-007_validators/refs/v2-05/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-007_validators/refs/v2-06/exit_code b/tests/test-007_validators/refs/v2-06/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-007_validators/refs/v2-06/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-007_validators/refs/v2-06/stderr b/tests/test-007_validators/refs/v2-06/stderr new file mode 100644 index 00000000..90e2bb46 --- /dev/null +++ b/tests/test-007_validators/refs/v2-06/stderr @@ -0,0 +1,9 @@ +"a": min-value-hit max-value-hit +"n": max-value-hit +"t": min-value-hit +constant-bounds "a": 1 4 +constant-bounds "n": 1 4 +constant-bounds "t": 1 3 +variable "a" +variable "n" +variable "t" diff --git a/tests/test-007_validators/refs/v2-06/stdout b/tests/test-007_validators/refs/v2-06/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-007_validators/refs/v3-01/exit_code b/tests/test-007_validators/refs/v3-01/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-007_validators/refs/v3-01/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-007_validators/refs/v3-01/stderr b/tests/test-007_validators/refs/v3-01/stderr new file mode 100644 index 00000000..5d346839 --- /dev/null +++ b/tests/test-007_validators/refs/v3-01/stderr @@ -0,0 +1,15 @@ +"a": min-value-hit max-value-hit +"l": +"n": min-value-hit +"r": +"t": min-value-hit max-value-hit +constant-bounds "a": 1 2 +constant-bounds "l": -2 2 +constant-bounds "n": 1 4 +constant-bounds "r": -5 5 +constant-bounds "t": 1 3 +variable "a" +variable "l" +variable "n" +variable "r" +variable "t" diff --git a/tests/test-007_validators/refs/v3-01/stdout b/tests/test-007_validators/refs/v3-01/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-007_validators/refs/v3-02/exit_code b/tests/test-007_validators/refs/v3-02/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-007_validators/refs/v3-02/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-007_validators/refs/v3-02/stderr b/tests/test-007_validators/refs/v3-02/stderr new file mode 100644 index 00000000..a97b774f --- /dev/null +++ b/tests/test-007_validators/refs/v3-02/stderr @@ -0,0 +1,15 @@ +"a": min-value-hit max-value-hit +"l": +"n": min-value-hit max-value-hit +"r": +"t": min-value-hit max-value-hit +constant-bounds "a": 1 ? +constant-bounds "l": -2 2 +constant-bounds "n": 1 4 +constant-bounds "r": -5 5 +constant-bounds "t": 1 3 +variable "a" +variable "l" +variable "n" +variable "r" +variable "t" diff --git a/tests/test-007_validators/refs/v3-02/stdout b/tests/test-007_validators/refs/v3-02/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-007_validators/refs/v3-03/exit_code b/tests/test-007_validators/refs/v3-03/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-007_validators/refs/v3-03/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-007_validators/refs/v3-03/stderr b/tests/test-007_validators/refs/v3-03/stderr new file mode 100644 index 00000000..93449207 --- /dev/null +++ b/tests/test-007_validators/refs/v3-03/stderr @@ -0,0 +1 @@ +FAIL not a permutation (duplicates) (test case 4) diff --git a/tests/test-007_validators/refs/v3-03/stdout b/tests/test-007_validators/refs/v3-03/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-007_validators/refs/v3-04/exit_code b/tests/test-007_validators/refs/v3-04/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-007_validators/refs/v3-04/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-007_validators/refs/v3-04/stderr b/tests/test-007_validators/refs/v3-04/stderr new file mode 100644 index 00000000..da3142d2 --- /dev/null +++ b/tests/test-007_validators/refs/v3-04/stderr @@ -0,0 +1,15 @@ +"a": min-value-hit max-value-hit +"l": +"n": min-value-hit +"r": +"t": min-value-hit max-value-hit +constant-bounds "a": 1 ? +constant-bounds "l": -2 2 +constant-bounds "n": 1 4 +constant-bounds "r": -5 5 +constant-bounds "t": 1 3 +variable "a" +variable "l" +variable "n" +variable "r" +variable "t" diff --git a/tests/test-007_validators/refs/v3-04/stdout b/tests/test-007_validators/refs/v3-04/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-007_validators/refs/v3-05/exit_code b/tests/test-007_validators/refs/v3-05/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-007_validators/refs/v3-05/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-007_validators/refs/v3-05/stderr b/tests/test-007_validators/refs/v3-05/stderr new file mode 100644 index 00000000..67b8a3ca --- /dev/null +++ b/tests/test-007_validators/refs/v3-05/stderr @@ -0,0 +1 @@ +FAIL Integer parameter [name=~t~] equals to 4, violates the range [1, 3] (stdin, line 1) diff --git a/tests/test-007_validators/refs/v3-05/stdout b/tests/test-007_validators/refs/v3-05/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-007_validators/refs/v3-06/exit_code b/tests/test-007_validators/refs/v3-06/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-007_validators/refs/v3-06/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-007_validators/refs/v3-06/stderr b/tests/test-007_validators/refs/v3-06/stderr new file mode 100644 index 00000000..10343738 --- /dev/null +++ b/tests/test-007_validators/refs/v3-06/stderr @@ -0,0 +1,15 @@ +"a": min-value-hit max-value-hit +"l": min-value-hit max-value-hit +"n": min-value-hit max-value-hit +"r": min-value-hit max-value-hit +"t": min-value-hit max-value-hit +constant-bounds "a": 1 4 +constant-bounds "l": -2 2 +constant-bounds "n": 1 4 +constant-bounds "r": -5 5 +constant-bounds "t": 1 3 +variable "a" +variable "l" +variable "n" +variable "r" +variable "t" diff --git a/tests/test-007_validators/refs/v3-06/stdout b/tests/test-007_validators/refs/v3-06/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-007_validators/refs/v4-01/exit_code b/tests/test-007_validators/refs/v4-01/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-007_validators/refs/v4-01/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-007_validators/refs/v4-01/stderr b/tests/test-007_validators/refs/v4-01/stderr new file mode 100644 index 00000000..eb0863c1 --- /dev/null +++ b/tests/test-007_validators/refs/v4-01/stderr @@ -0,0 +1,15 @@ +"a": min-value-hit max-value-hit +"l": max-value-hit +"n": min-value-hit +"r": min-value-hit max-value-hit +"t": min-value-hit max-value-hit +constant-bounds "a": 1 2 +constant-bounds "l": -2 2 +constant-bounds "n": 1 4 +constant-bounds "r": -5 5 +constant-bounds "t": 1 3 +variable "a" +variable "l" +variable "n" +variable "r" +variable "t" diff --git a/tests/test-007_validators/refs/v4-01/stdout b/tests/test-007_validators/refs/v4-01/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-007_validators/refs/v4-02/exit_code b/tests/test-007_validators/refs/v4-02/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-007_validators/refs/v4-02/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-007_validators/refs/v4-02/stderr b/tests/test-007_validators/refs/v4-02/stderr new file mode 100644 index 00000000..5528224c --- /dev/null +++ b/tests/test-007_validators/refs/v4-02/stderr @@ -0,0 +1,15 @@ +"a": min-value-hit max-value-hit +"l": max-value-hit +"n": min-value-hit max-value-hit +"r": min-value-hit max-value-hit +"t": min-value-hit max-value-hit +constant-bounds "a": 1 ? +constant-bounds "l": -2 2 +constant-bounds "n": 1 4 +constant-bounds "r": -5 5 +constant-bounds "t": 1 3 +variable "a" +variable "l" +variable "n" +variable "r" +variable "t" diff --git a/tests/test-007_validators/refs/v4-02/stdout b/tests/test-007_validators/refs/v4-02/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-007_validators/refs/v4-03/exit_code b/tests/test-007_validators/refs/v4-03/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-007_validators/refs/v4-03/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-007_validators/refs/v4-03/stderr b/tests/test-007_validators/refs/v4-03/stderr new file mode 100644 index 00000000..93449207 --- /dev/null +++ b/tests/test-007_validators/refs/v4-03/stderr @@ -0,0 +1 @@ +FAIL not a permutation (duplicates) (test case 4) diff --git a/tests/test-007_validators/refs/v4-03/stdout b/tests/test-007_validators/refs/v4-03/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-007_validators/refs/v4-04/exit_code b/tests/test-007_validators/refs/v4-04/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-007_validators/refs/v4-04/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-007_validators/refs/v4-04/stderr b/tests/test-007_validators/refs/v4-04/stderr new file mode 100644 index 00000000..ebc98fca --- /dev/null +++ b/tests/test-007_validators/refs/v4-04/stderr @@ -0,0 +1,15 @@ +"a": min-value-hit max-value-hit +"l": max-value-hit +"n": min-value-hit +"r": min-value-hit max-value-hit +"t": min-value-hit max-value-hit +constant-bounds "a": 1 ? +constant-bounds "l": -2 2 +constant-bounds "n": 1 4 +constant-bounds "r": -5 5 +constant-bounds "t": 1 3 +variable "a" +variable "l" +variable "n" +variable "r" +variable "t" diff --git a/tests/test-007_validators/refs/v4-04/stdout b/tests/test-007_validators/refs/v4-04/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-007_validators/refs/v4-05/exit_code b/tests/test-007_validators/refs/v4-05/exit_code new file mode 100644 index 00000000..00750edc --- /dev/null +++ b/tests/test-007_validators/refs/v4-05/exit_code @@ -0,0 +1 @@ +3 diff --git a/tests/test-007_validators/refs/v4-05/stderr b/tests/test-007_validators/refs/v4-05/stderr new file mode 100644 index 00000000..67b8a3ca --- /dev/null +++ b/tests/test-007_validators/refs/v4-05/stderr @@ -0,0 +1 @@ +FAIL Integer parameter [name=~t~] equals to 4, violates the range [1, 3] (stdin, line 1) diff --git a/tests/test-007_validators/refs/v4-05/stdout b/tests/test-007_validators/refs/v4-05/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-007_validators/refs/v4-06/exit_code b/tests/test-007_validators/refs/v4-06/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-007_validators/refs/v4-06/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-007_validators/refs/v4-06/stderr b/tests/test-007_validators/refs/v4-06/stderr new file mode 100644 index 00000000..10343738 --- /dev/null +++ b/tests/test-007_validators/refs/v4-06/stderr @@ -0,0 +1,15 @@ +"a": min-value-hit max-value-hit +"l": min-value-hit max-value-hit +"n": min-value-hit max-value-hit +"r": min-value-hit max-value-hit +"t": min-value-hit max-value-hit +constant-bounds "a": 1 4 +constant-bounds "l": -2 2 +constant-bounds "n": 1 4 +constant-bounds "r": -5 5 +constant-bounds "t": 1 3 +variable "a" +variable "l" +variable "n" +variable "r" +variable "t" diff --git a/tests/test-007_validators/refs/v4-06/stdout b/tests/test-007_validators/refs/v4-06/stdout new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-007_validators/run.sh b/tests/test-007_validators/run.sh new file mode 100644 index 00000000..cd849e31 --- /dev/null +++ b/tests/test-007_validators/run.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -eo pipefail + +os="unix" +if [[ "$MACHINE" == "Windows" ]]; then + os="win" +fi + +# Loop through the versions v1, v2, v3, and v4 +for version in v1 v2 v3 v4; do + bash ../scripts/compile src/"$version".cpp + + # Loop through the test numbers 01, 02, 03, and 04 + for test_num in 01 02 03 04 05 06; do + bash ../scripts/test-ref "$version"-"$test_num" "$VALGRIND" ./"$version" --testOverviewLogFileName stderr < files/"$os"/input."$test_num" + done + + rm -f "$version" "$version".exe +done diff --git a/tests/test-007_validators/src/v1.cpp b/tests/test-007_validators/src/v1.cpp new file mode 100644 index 00000000..794b2cf9 --- /dev/null +++ b/tests/test-007_validators/src/v1.cpp @@ -0,0 +1,27 @@ +#include "testlib.h" + +using namespace std; + +int main(int argc, char *argv[]) { + registerValidation(argc, argv); + + int t = inf.readInt(1, 3, "t"); + inf.readEoln(); + + for (int tt = 1; tt <= t; tt++) { + setTestCase(tt + 1); + + int n = inf.readInt(1, 4, "n"); + inf.readSpace(); + inf.readInt(-2, 2, "l0"); + inf.readSpace(); + inf.readInt(-5, 5, "r[1]"); + inf.readEoln(); + + vector a = inf.readInts(n, 1, n, "a"); + ensuref(int(set(a.begin(), a.end()).size()) == n, "not a permutation (duplicates)"); + inf.readEoln(); + } + + inf.readEof(); +} diff --git a/tests/test-007_validators/src/v2.cpp b/tests/test-007_validators/src/v2.cpp new file mode 100644 index 00000000..b90f27fc --- /dev/null +++ b/tests/test-007_validators/src/v2.cpp @@ -0,0 +1,27 @@ +#include "testlib.h" + +using namespace std; + +int main(int argc, char *argv[]) { + registerValidation(argc, argv); + + int t = inf.readInt(1, 3, "~t"); + inf.readEoln(); + + for (int tt = 1; tt <= t; tt++) { + setTestCase(tt + 1); + + int n = inf.readInt(1, 4, "n~"); + inf.readSpace(); + inf.readInt(-2, 2, "l0l"); + inf.readSpace(); + inf.readInt(-5, 5, "r1d"); + inf.readEoln(); + + vector a = inf.readInts(n, 1, n, "a"); + ensuref(int(set(a.begin(), a.end()).size()) == n, "not a permutation (duplicates)"); + inf.readEoln(); + } + + inf.readEof(); +} diff --git a/tests/test-007_validators/src/v3.cpp b/tests/test-007_validators/src/v3.cpp new file mode 100644 index 00000000..52cf3c9a --- /dev/null +++ b/tests/test-007_validators/src/v3.cpp @@ -0,0 +1,27 @@ +#include "testlib.h" + +using namespace std; + +int main(int argc, char *argv[]) { + registerValidation(argc, argv); + + int t = inf.readInt(1, 3, "~t~"); + inf.readEoln(); + + for (int tt = 1; tt <= t; tt++) { + setTestCase(tt + 1); + + int n = inf.readInt(1, 4, "~n"); + inf.readSpace(); + inf.readInt(-2, 2, "l"); + inf.readSpace(); + inf.readInt(-5, 5, "r"); + inf.readEoln(); + + vector a = inf.readInts(n, 1, n, "~a"); + ensuref(int(set(a.begin(), a.end()).size()) == n, "not a permutation (duplicates)"); + inf.readEoln(); + } + + inf.readEof(); +} diff --git a/tests/test-007_validators/src/v4.cpp b/tests/test-007_validators/src/v4.cpp new file mode 100644 index 00000000..8c2aa27e --- /dev/null +++ b/tests/test-007_validators/src/v4.cpp @@ -0,0 +1,27 @@ +#include "testlib.h" + +using namespace std; + +int main(int argc, char *argv[]) { + registerValidation(argc, argv); + + int t = inf.readInt(1, 3, "~t~"); + inf.readEoln(); + + for (int tt = 1; tt <= t; tt++) { + setTestCase(tt + 1); + + int n = inf.readInt(1, 4, "~n"); + inf.readSpace(); + inf.readInt(-2, 2, "l~"); + inf.readSpace(); + inf.readInt(-5, 5, "~r~"); + inf.readEoln(); + + vector a = inf.readInts(n, 1, n, "~a~"); + ensuref(int(set(a.begin(), a.end()).size()) == n, "not a permutation (duplicates)"); + inf.readEoln(); + } + + inf.readEof(); +} diff --git a/tests/test-008_format/files/test-format-format1.cpp b/tests/test-008_format/files/test-format-format1.cpp new file mode 100644 index 00000000..5f69d16f --- /dev/null +++ b/tests/test-008_format/files/test-format-format1.cpp @@ -0,0 +1,18 @@ +#if (__cplusplus >= 202002L && __has_include()) +# include +#endif + +#include "testlib.h" + +using namespace std; + +int main(int argc, char** argv) { + registerGen(argc, argv, 1); + + println(format("%d", 42)); + println(format("hello, %s!", "hat")); + println(format("%s%d!", "'hat'", 42)); + println(format("%s%d!", "'%s'", 42)); + + ensure(format("%f", 42.5).substr(0, 4) == "42.5"); +} diff --git a/tests/test-008_format/files/test-format-format2.cpp b/tests/test-008_format/files/test-format-format2.cpp new file mode 100644 index 00000000..f79f39e3 --- /dev/null +++ b/tests/test-008_format/files/test-format-format2.cpp @@ -0,0 +1,18 @@ +#include "testlib.h" + +#if (__cplusplus >= 202002L && __has_include()) +# include +#endif + +using namespace std; + +int main(int argc, char** argv) { + registerGen(argc, argv, 1); + + println(format("%d", 42)); + println(format("hello, %s!", "hat")); + println(format("%s%d!", "'hat'", 42)); + println(format("%s%d!", "'%s'", 42)); + + ensure(format("%f", 42.5).substr(0, 4) == "42.5"); +} diff --git a/tests/test-008_format/files/test-format.cpp b/tests/test-008_format/files/test-format.cpp new file mode 100644 index 00000000..19da9394 --- /dev/null +++ b/tests/test-008_format/files/test-format.cpp @@ -0,0 +1,14 @@ +#include "testlib.h" + +using namespace std; + +int main(int argc, char** argv) { + registerGen(argc, argv, 1); + + println(format("%d", 42)); + println(format("hello, %s!", "hat")); + println(format("%s%d!", "'hat'", 42)); + println(format("%s%d!", "'%s'", 42)); + + ensure(format("%f", 42.5).substr(0, 4) == "42.5"); +} diff --git a/tests/test-008_format/refs/test-format-format1/r1/exit_code b/tests/test-008_format/refs/test-format-format1/r1/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-008_format/refs/test-format-format1/r1/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-008_format/refs/test-format-format1/r1/stderr b/tests/test-008_format/refs/test-format-format1/r1/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-008_format/refs/test-format-format1/r1/stdout b/tests/test-008_format/refs/test-format-format1/r1/stdout new file mode 100644 index 00000000..e0f278fb --- /dev/null +++ b/tests/test-008_format/refs/test-format-format1/r1/stdout @@ -0,0 +1,4 @@ +42 +hello, hat! +'hat'42! +'%s'42! diff --git a/tests/test-008_format/refs/test-format-format1/r2/exit_code b/tests/test-008_format/refs/test-format-format1/r2/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-008_format/refs/test-format-format1/r2/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-008_format/refs/test-format-format1/r2/stderr b/tests/test-008_format/refs/test-format-format1/r2/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-008_format/refs/test-format-format1/r2/stdout b/tests/test-008_format/refs/test-format-format1/r2/stdout new file mode 100644 index 00000000..e0f278fb --- /dev/null +++ b/tests/test-008_format/refs/test-format-format1/r2/stdout @@ -0,0 +1,4 @@ +42 +hello, hat! +'hat'42! +'%s'42! diff --git a/tests/test-008_format/refs/test-format-format2/r1/exit_code b/tests/test-008_format/refs/test-format-format2/r1/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-008_format/refs/test-format-format2/r1/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-008_format/refs/test-format-format2/r1/stderr b/tests/test-008_format/refs/test-format-format2/r1/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-008_format/refs/test-format-format2/r1/stdout b/tests/test-008_format/refs/test-format-format2/r1/stdout new file mode 100644 index 00000000..e0f278fb --- /dev/null +++ b/tests/test-008_format/refs/test-format-format2/r1/stdout @@ -0,0 +1,4 @@ +42 +hello, hat! +'hat'42! +'%s'42! diff --git a/tests/test-008_format/refs/test-format-format2/r2/exit_code b/tests/test-008_format/refs/test-format-format2/r2/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-008_format/refs/test-format-format2/r2/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-008_format/refs/test-format-format2/r2/stderr b/tests/test-008_format/refs/test-format-format2/r2/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-008_format/refs/test-format-format2/r2/stdout b/tests/test-008_format/refs/test-format-format2/r2/stdout new file mode 100644 index 00000000..e0f278fb --- /dev/null +++ b/tests/test-008_format/refs/test-format-format2/r2/stdout @@ -0,0 +1,4 @@ +42 +hello, hat! +'hat'42! +'%s'42! diff --git a/tests/test-008_format/refs/test-format/r1/exit_code b/tests/test-008_format/refs/test-format/r1/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-008_format/refs/test-format/r1/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-008_format/refs/test-format/r1/stderr b/tests/test-008_format/refs/test-format/r1/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-008_format/refs/test-format/r1/stdout b/tests/test-008_format/refs/test-format/r1/stdout new file mode 100644 index 00000000..e0f278fb --- /dev/null +++ b/tests/test-008_format/refs/test-format/r1/stdout @@ -0,0 +1,4 @@ +42 +hello, hat! +'hat'42! +'%s'42! diff --git a/tests/test-008_format/refs/test-format/r2/exit_code b/tests/test-008_format/refs/test-format/r2/exit_code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/test-008_format/refs/test-format/r2/exit_code @@ -0,0 +1 @@ +0 diff --git a/tests/test-008_format/refs/test-format/r2/stderr b/tests/test-008_format/refs/test-format/r2/stderr new file mode 100644 index 00000000..e69de29b diff --git a/tests/test-008_format/refs/test-format/r2/stdout b/tests/test-008_format/refs/test-format/r2/stdout new file mode 100644 index 00000000..e0f278fb --- /dev/null +++ b/tests/test-008_format/refs/test-format/r2/stdout @@ -0,0 +1,4 @@ +42 +hello, hat! +'hat'42! +'%s'42! diff --git a/tests/test-008_format/run.sh b/tests/test-008_format/run.sh new file mode 100644 index 00000000..a670325b --- /dev/null +++ b/tests/test-008_format/run.sh @@ -0,0 +1,17 @@ +#!/bin/bash +set -eo pipefail + +bash ../scripts/compile files/test-format.cpp +bash ../scripts/test-ref test-format/r1 ./test-format +bash ../scripts/test-ref test-format/r2 "$VALGRIND" ./test-format +rm -f test-format test-format.exe + +bash ../scripts/compile files/test-format-format1.cpp +bash ../scripts/test-ref test-format-format1/r1 ./test-format-format1 +bash ../scripts/test-ref test-format-format1/r2 "$VALGRIND" ./test-format-format1 +rm -f test-format-format1 test-format-format1.exe + +bash ../scripts/compile files/test-format-format2.cpp +bash ../scripts/test-ref test-format-format2/r1 ./test-format-format2 +bash ../scripts/test-ref test-format-format2/r2 "$VALGRIND" ./test-format-format2 +rm -f test-format-format2 test-format-format2.exe diff --git a/validators/bipartite-graph-validator.cpp b/validators/bipartite-graph-validator.cpp index c37d23d1..94a7f1bf 100644 --- a/validators/bipartite-graph-validator.cpp +++ b/validators/bipartite-graph-validator.cpp @@ -1,33 +1,10 @@ #include "testlib.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include -#include -#include -#include -#include - -#define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { registerValidation(argc, argv); int n = inf.readInt(1, 400, "n"); @@ -37,19 +14,18 @@ int main(int argc, char* argv[]) int k = inf.readInt(0, n * m, "k"); inf.readEoln(); - set > edges; + set> edges; - forn(i, k) - { + for (int i = 0; i < k; i++) { int a = inf.readInt(1, n, "a_i"); inf.readSpace(); int b = inf.readInt(1, m, "b_i"); inf.readEoln(); - ensuref(edges.count(make_pair(a, b)) == 0, "Graph can't contain multiple edges between a pair of vertices"); + ensuref(edges.count(make_pair(a, b)) == 0, + "Graph can't contain multiple edges between a pair of vertices"); edges.insert(make_pair(a, b)); } inf.readEof(); - return 0; } diff --git a/validators/case-nval.cpp b/validators/case-nval.cpp index 2b86a7cc..928b49c7 100644 --- a/validators/case-nval.cpp +++ b/validators/case-nval.cpp @@ -9,7 +9,7 @@ using namespace std; -int main(int argc, char* argv[]) { +int main(int argc, char *argv[]) { registerValidation(argc, argv); int testCaseCount = inf.readInt(1, 10, "t"); @@ -22,6 +22,6 @@ int main(int argc, char* argv[]) { inf.readInts(n, -1000, 1000, "a"); inf.readEoln(); } - + inf.readEof(); } diff --git a/validators/ival.cpp b/validators/ival.cpp index 3efc4d1f..22227604 100644 --- a/validators/ival.cpp +++ b/validators/ival.cpp @@ -7,13 +7,10 @@ using namespace std; -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { registerValidation(argc, argv); inf.readInt(1, 100, "n"); inf.readEoln(); inf.readEof(); - - return 0; } diff --git a/validators/nval.cpp b/validators/nval.cpp index eb599f8f..8a6648db 100644 --- a/validators/nval.cpp +++ b/validators/nval.cpp @@ -8,22 +8,14 @@ using namespace std; -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { registerValidation(argc, argv); - + int n = inf.readInt(1, 100000, "n"); inf.readEoln(); - for (int i = 0; i < n; i++) - { - inf.readLong(-1000000000000000LL, 1000000000000000LL, format("a[%d]", i + 1)); - - if (i + 1 < n) - inf.readSpace(); - } + inf.readLongs(n, -1000000000LL * 1000000LL, 1000000000LL * 1000000LL, "a"); inf.readEoln(); inf.readEof(); - return 0; } diff --git a/validators/sval.cpp b/validators/sval.cpp index 0126824d..ab782b32 100644 --- a/validators/sval.cpp +++ b/validators/sval.cpp @@ -8,13 +8,10 @@ using namespace std; -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { registerValidation(argc, argv); - + inf.readToken("[a-z]{1,100}", "s"); inf.readEoln(); inf.readEof(); - - return 0; } diff --git a/validators/undirected-graph-validator.cpp b/validators/undirected-graph-validator.cpp index 9e1df0bf..747d7ba5 100644 --- a/validators/undirected-graph-validator.cpp +++ b/validators/undirected-graph-validator.cpp @@ -1,33 +1,10 @@ #include "testlib.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include -#include -#include -#include -#include - -#define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { registerValidation(argc, argv); int n = inf.readInt(1, 1000, "n"); @@ -35,22 +12,21 @@ int main(int argc, char* argv[]) int m = inf.readInt(0, 100000, "m"); inf.readEoln(); - set > edges; + set> edges; - forn(i, m) - { + for (int i = 0; i < m; i++) { int a = inf.readInt(1, n, "a_i"); inf.readSpace(); int b = inf.readInt(1, n, "b_i"); inf.readEoln(); ensuref(a != b, "Graph can't contain loops"); - ensuref(edges.count(make_pair(a, b)) == 0, "Graph can't contain multiple edges between a pair of vertices"); + ensuref(edges.count(make_pair(a, b)) == 0, + "Graph can't contain multiple edges between a pair of vertices"); edges.insert(make_pair(a, b)); edges.insert(make_pair(b, a)); } inf.readEof(); - return 0; } diff --git a/validators/undirected-tree-validator.cpp b/validators/undirected-tree-validator.cpp index a461a2fb..bd064f62 100644 --- a/validators/undirected-tree-validator.cpp +++ b/validators/undirected-tree-validator.cpp @@ -1,44 +1,20 @@ #include "testlib.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include -#include -#include -#include #include -#include -#include -#include -#include - -#define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; -int leader(vector& dsu, int idx) -{ +int leader(vector &dsu, int idx) { return dsu[idx] == idx ? dsu[idx] : (dsu[idx] = leader(dsu, dsu[idx])); } -bool merge(vector& dsu, int a, int b) -{ +bool merge(vector &dsu, int a, int b) { a = leader(dsu, a); b = leader(dsu, b); if (a == b) return false; - else - { + else { if (rnd.next(2) == 0) dsu[a] = b; else @@ -47,21 +23,19 @@ bool merge(vector& dsu, int a, int b) } } -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { registerValidation(argc, argv); int n = inf.readInt(2, 100000, "n"); inf.readEoln(); vector dsu(n); - forn(i, n) + for (int i = 0; i < n; i++) dsu[i] = i; - set > edges; + set> edges; - forn(i, n - 1) - { + for (int i = 0; i < n - 1; i++) { int x = inf.readInt(1, n, "x_i"); inf.readSpace(); int y = inf.readInt(1, n, "y_i"); @@ -77,5 +51,4 @@ int main(int argc, char* argv[]) } inf.readEof(); - return 0; } diff --git a/validators/validate-using-testset-and-group.cpp b/validators/validate-using-testset-and-group.cpp index 66e89a1c..3a2b4c79 100644 --- a/validators/validate-using-testset-and-group.cpp +++ b/validators/validate-using-testset-and-group.cpp @@ -1,33 +1,27 @@ /** - * Validates that input depenging on testset and group. + * Validates input depending on testset and group. */ #include "testlib.h" -#include using namespace std; -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { registerValidation(argc, argv); int n, m; - if (validator.testset() == "pretests") - { + if (validator.testset() == "pretests") { n = inf.readInt(1, 10, "n"); inf.readSpace(); m = inf.readInt(1, 10, "m"); - } - else - { + } else { n = inf.readInt(1, 100, "n"); inf.readSpace(); m = inf.readInt(1, 100, "m"); } - if (validator.group() == "even-n-and-m") - { + if (validator.group() == "even-n-and-m") { ensure(n % 2 == 0); ensure(m % 2 == 0); }