// da3_test.cpp
// Glenn G. Chappell
// 18 Feb 2008
//
// For CS 311 Spring 2008
// Test program for Assignment 3 functions & function templates
// Used in Assignment 3, Exercises A, B, C, D

// Includes for code to be tested
#include "da3.h"      // For function templates
#include "da3.h"      // Double inclusion test

// Includes for testing package
#include <iostream>     // for std::cout, std::endl
#include <string>       // for std::string
#include <stdexcept>    // for std::runtime_error

// Includes for this test program
#include <vector>       // for std::vector
#include <list>         // for std::list
#include <deque>        // for std::deque
#include <sstream>      // for std::ostringstream
#include <stdexcept>    // for std::exception, std::runtime_error
#include <algorithm>    // for std::equal
#include <iterator>     // for std::advance


// ************************************************************************
// Testing Package:
//     Class Tester - For Tracking Tests
// ************************************************************************


// class Tester
// For extremely simple unit testing.
// Keeps track of number of tests and number of passes.
// Use test (with success/failure parameter) to do a test.
// Get results with numTests, numPassed, numFailed, allPassed.
// Restart testing with reset.
// Invariants:
//     countTests_ == number of tests (calls to test) since last reset.
//     countPasses_ == number of times function test called with true param
//      since last reset.
//     0 <= countPasses_ <= countTests_.
//     tolerance_ >= 0.
class Tester {

// ***** Tester: ctors, dctor, op= *****
public:

    // Default ctor
    // Sets countTests_, countPasses_ to zero, tolerance_ to given value
    // Pre: None.
    // Post:
    //     numTests == 0, countPasses == 0, tolerance_ == abs(theTolerance)
    // Does not throw (No-Throw Guarantee)
    Tester(double theTolerance = 0.0000001)
        :countTests_(0),
         countPasses_(0),
         tolerance_(theTolerance >= 0 ? theTolerance : -theTolerance)
    {}

    // Compiler-generated copy ctor, copy op=, dctor are used

// ***** Tester: general public functions *****
public:

    // test
    // Handles single test, param indicates pass/fail
    // Pre: None.
    // Post:
    //     countTests_ incremented
    //     countPasses_ incremented if (success)
    //     Message indicating test name (if given)
    //      and pass/fail printed to cout
    // Does not throw (No-Throw Guarantee)
    //  - Assuming exceptions have not been turned on for cout.
    void test(bool success,
              const std::string & testName = "")
    {
        ++countTests_;
        if (success) ++countPasses_;

        std::cout << "    ";
        if (testName != "")
        {
            std::cout << "Test: "
                      << testName
                      << " - ";
        }
        std::cout << (success ? "passed" : "********** FAILED **********")
                  << std::endl;
    }

    // ftest
    // Does single floating-point test.
    // Tests passes iff difference of first two values is <= tolerance.
    // Pre: None.
    // Post:
    //     countTests_ incremented
    //     countPasses_ incremented if (abs(val1-val2) <= tolerance_)
    //     Message indicating test name (if given)
    //      and pass/fail printed to cout
    // Does not throw (No-Throw Guarantee)
    void ftest(double val1,
               double val2,
               const std::string & testName = "")
    { test(val1-val2 <= tolerance_ && val2-val1 <= tolerance_, testName); }

    // reset
    // Resets *this to default constructed state
    // Pre: None.
    // Post:
    //     countTests_ == 0, countPasses_ == 0
    // Does not throw (No-Throw Guarantee)
    void reset()
    {
        countTests_ = 0;
        countPasses_ = 0;
    }

    // numTests
    // Returns the number of tests that have been done since last reset 
    // Pre: None.
    // Post:
    //     return == countTests_
    // Does not throw (No-Throw Guarantee)
    int numTests() const
    { return countTests_; }

    // numPassed
    // Returns the number of tests that have passed since last reset
    // Pre: None.
    // Post:
    //     return == countPasses_
    // Does not throw (No-Throw Guarantee)
    int numPassed() const
    { return countPasses_; }

    // numFailed
    // Returns the number of tests that have not passed since last reset
    // Pre: None.
    // Post:
    //     return + countPasses_ == numTests_
    // Does not throw (No-Throw Guarantee)
    int numFailed() const
    { return countTests_ - countPasses_; }

    // allPassed
    // Returns true if all tests since last reset have passed
    // Pre: None.
    // Post:
    //     return == (countPasses_ == countTests_)
    // Does not throw (No-Throw Guarantee)
    bool allPassed() const
    { return countPasses_ == countTests_; }

    // setTolerance
    // Sets tolerance_ to given value
    // Pre: None.
    // Post:
    //     tolerance_ = abs(theTolerance)
    // Does not throw (No-Throw Guarantee)
    void setTolerance(double theTolerance)
    { tolerance_ = (theTolerance >= 0 ? theTolerance : -theTolerance); }

// ***** Tester: data members *****
private:

    int countTests_;    // Number of tests done since last reset
    int countPasses_;   // Number of tests passed since last reset
    double tolerance_;  // Tolerance for floating-point near-equality tests

};  // end class Tester


// ************************************************************************
// Testing Package:
//     Class TypeCheck - Helper Class for Type Checking
// ************************************************************************


// class TypeCheck
// This class exists in order to have static member function check, which
// takes a parameter of a given type, by reference. Objects of type
// TypeCheck<T> cannot be created.
// Usage:
//     TypeCheck<MyType>::check(x)
//     returns true if the type of x is (MyType) or (const MyType),
//     otherwise false.
// Invariants: None.
// Requirements on Types: None.
template<typename T>
class TypeCheck {

private:

    // Uncopyable class. Do not define copy ctor, copy assn.
    TypeCheck(const TypeCheck &);
    TypeCheck<T> & operator=(const TypeCheck &);

    // Compiler-generated dctor is used (but irrelevant).

public:

    // check
    // The function and function template below simulate a single function
    // that takes a single parameter, and returns true iff the parameter has
    // type T or (const T).

    // check (reference-to-const T)
    // Pre: None.
    // Post:
    //     Return is true.
    // Does not throw (No-Throw Guarantee)
    static bool check(const T & param)
    { return true; }

    // check (reference-to-const non-T)
    // Pre: None.
    // Post:
    //     Return is false.
    // Requirements on types: None.
    // Does not throw (No-Throw Guarantee)
    template <typename OtherType>
    static bool check(const OtherType & param)
    { return false; }

};  // End class TypeCheck


// ************************************************************************
// Testing Package:
//     Class Counter - Helper Class for Counting Calls & Objects, Throwing
// ************************************************************************


// class Counter
// Item type for counting ctor, dctor, op= calls, counting existing
//  objects, and possibly throwing on copy.
// If static member copyThrow_ is set, then copy ctor and copy assn throw
//  std::runtime_error. Increments static data member ctorCount_ on default
//  construction and successful copy construction. Increments static data
//  member assnCount_ on successful copy assignment. Increments static
//  data member dctorCount_ on destruction. Increments static data member
//  existing_ on construction, and decrements it on destruction.
// Invariants:
//     Counter::existing_ is number of existing objects of this class.
//     Counter::ctorCount_ is number of successful ctor calls since
//      most recent call to reset, or start of program if reset has never
//      been called.
//     Counter::dctorCount_ is (similarly) number of dctor calls.
//     Counter::assnCount_ is (similarly) number of copy assn calls.
class Counter {

// ***** Counter: Ctors, dctor, op= *****
public:

    // Default ctor
    // Pre: None.
    // Post:
    //     (ctorCount_ has been incremented.)
    //     (existing_ has been incremented.)
    Counter()
    { ++existing_; ++ctorCount_; }

    // Copy ctor
    // Pre: None.
    // Post:
    //     (ctorCount_ has been incremented.)
    //     (existing_ has been incremented.)
    Counter(const Counter & other)
    {
        if (copyThrow_)
            throw std::runtime_error("C");
        ++existing_;
        ++ctorCount_;
    }

    // Copy assignment
    // Pre: None.
    // Post:
    //     Return value is *this.
    //     (assnCount_ has been incremented.)
    Counter & operator=(const Counter & rhs)
    {
        if (copyThrow_)
            throw std::runtime_error("A");
        ++assnCount_;
        return *this;
    }

    // Dctor
    // Pre: None.
    // Post:
    //     (dctorCount_ has been incremented.)
    //     (existing_ has been decremented.)
    ~Counter()
    { --existing_; ++dctorCount_; }

// ***** Counter: Functions dealing with count *****
public:

    // resetCount
    // Pre: None.
    // Post:
    //     ctorCount_ == 0.
    //     dctorCount_ == 0.
    //     assnCount_ == 0.
    //     copyThrow_ == shouldThrow.
    static void reset(bool shouldThrow = false)
    {
        ctorCount_ = 0;
        dctorCount_ = 0;
        assnCount_ = 0;
        copyThrow_ = shouldThrow;
    }

    // getExisting
    // Pre: None.
    // Post:
    //     return == existing_.
    static int getExisting()
    { return existing_; }

    // getCtorCount
    // Pre: None.
    // Post:
    //     return == ctorCount_.
    static int getCtorCount()
    { return ctorCount_; }

    // getDctorCount
    // Pre: None.
    // Post:
    //     return == dctorCount_.
    static int getDctorCount()
    { return dctorCount_; }

    // getAssnCount
    // Pre: None.
    // Post:
    //     return == assnCount_.
    static int getAssnCount()
    { return assnCount_; }

    // setCopyThrow
    // Pre: None.
    // Post:
    //     copyThrow_ == shouldThrow
    static void setCopyThrow(bool shouldThrow)
    { copyThrow_ = shouldThrow; }

// ***** Counter: Data Members *****
private:

    static int existing_;    // # of existing objects
    static int ctorCount_;   // # of successful (non-throwing) ctor calls
    static int dctorCount_;  // # of dctor calls
    static int assnCount_;   // # of successful (non-throwing) copy = calls
    static bool copyThrow_;  // true if copy operations (ctor, =) throw

};  // End class Counter

// Definition of static data member of class Counter
int Counter::existing_ = 0;
int Counter::ctorCount_ = 0;
int Counter::dctorCount_ = 0;
int Counter::assnCount_ = 0;
bool Counter::copyThrow_ = false;


// ************************************************************************
// Utility Functions/Classes for This Testing Program
// ************************************************************************


// thisThrows
// Throws a std::runtime_error. For passing to function doesItThrow.
// Pre: None.
// Post: None.
// Will throw std::runtime_error.
void thisThrows()
{
    throw std::runtime_error("Hi!");
}

// thisThrowsOddly
// Throws an int. For passing to function doesItThrow.
// Pre: None.
// Post: None.
// Will throw int.
void thisThrowsOddly()
{
    throw 1;
}

// thisDoesNotThrow
// Does nothing. For passing to function doesItThrow.
// Pre: None.
// Post: None.
// Does not throw.
void thisDoesNotThrow()
{}


// class FuncObj
// Class for do-nothing function objects.
// Do "FuncObj x;", and then we can do "x();".
// The operator() returns nothing and does not throw.
// Invariants: None.
class FuncObj {

// ***** FuncObj: ctors, dctor, op= *****
public:

    // Compiler-generated default ctor, copy ctor, op=, dctor are used

// ***** FuncObj: public operators *****
public:

    // operator()
    // Makes an object of this class callable like a function.
    // Pre: None.
    // Post: None.
    // Does not throw.
    void operator()() const
    {}

};  // end class FuncObj


// ************************************************************************
// Test Suite Functions
// ************************************************************************


// test_function_doesItThrow
// Test suite for function template doesItThrow
//  ctor, dctor.
// Pre: None.
// Post:
//     Pass/fail status of tests have been registered with t.
//     Appropriate messages have been printed to cout.
void test_function_doesItThrow(Tester & t)
{
    std::cout << "Test Suite: function template doesItThrow (Exercise A)" << std::endl;

    bool didThrow;  // Whether function throws or not.

    // Function throws standard exception class
    didThrow = false;
    try
    {
        bool correctType = TypeCheck<bool>::check(doesItThrow(thisThrows));
        t.test(correctType, "Return type");
        t.test(doesItThrow(thisThrows), "Throwing function - return value");
    }
    catch (...)
    {
        // Function threw; fail test
        didThrow = true;
    }
    t.test(!didThrow, "Throwing function - doesItThrow should not throw");

    // Function throws int
    didThrow = false;
    try
    {
        t.test(doesItThrow(thisThrowsOddly), "Throwing function (non-std) - return value");
    }
    catch (...)
    {
        // Function threw; fail test
        didThrow = true;
    }
    t.test(!didThrow, "Throwing function (non-std) - doesItThrow should not throw");

    // Function does not throw
    didThrow = false;
    try
    {
        t.test(!doesItThrow(thisDoesNotThrow), "Non-throwing function - return value");
    }
    catch (...)
    {
        // Function threw; fail test
        didThrow = true;
    }
    t.test(!didThrow, "Non-throwing function - doesItThrow should not throw");

    // Function object - does not throw
    didThrow = false;
    try
    {
        t.test(!doesItThrow(FuncObj()), "Function object - return value");
    }
    catch (...)
    {
        // Function threw; fail test
        didThrow = true;
    }
    t.test(!didThrow, "Function object - doesItThrow should not throw");
}


// test_function_divideAll
// Test suite for function template divideAll
//  ctor, dctor.
// Pre: None.
// Post:
//     Pass/fail status of tests have been registered with t.
//     Appropriate messages have been printed to cout.
void test_function_divideAll(Tester & t)
{
    std::cout << "Test Suite: function template divideAll (Exercise B)" << std::endl;

    bool didThrow;  // Whether function throws or not.

    const int DATASIZE = 5;
    int data[DATASIZE] = { 6, 12, 18, 24, 30 };
    // Make copies of data
    const std::vector<int> dataCheck(data, data+DATASIZE);
    std::list<int> dataList(data, data+DATASIZE);
    // Modified data
    const int dataMod[DATASIZE] = { 6, 4, 6, 8, 30 };

    // Throwing behavior
    didThrow = false;
    bool threwNonStdType = false;
    try
    {
        divideAll(data, data+DATASIZE, 0);
    }
    catch (std::exception & e)  // Catch std exception object
    {
        didThrow = true;
        t.test(std::string("") != e.what(), "`what' member of exception object is non-empty");
    }
    catch (...)  // Catch non-std exection object
    {
        didThrow = true;
        threwNonStdType = true;
    }
    t.test(didThrow, "Exception thrown on division by zero");
    t.test(!threwNonStdType, "Exception object of standard class or a derived class");
    t.test(std::equal(data, data+DATASIZE, dataCheck.begin()), "Data unmodified when exception thrown");

    // Empty range
    didThrow = false;
    try
    {
        divideAll(data+2, data+2, 4);
    }
    catch (...)
    {
        didThrow = true;
    }
    t.test(!didThrow, "Empty range - does not throw");
    t.test(std::equal(data, data+DATASIZE, dataCheck.begin()), "Empty range - division");

    // Try array
    didThrow = false;
    try
    {
        divideAll(data+1, data+4, 3);
    }
    catch (...)
    {
        didThrow = true;
    }
    t.test(!didThrow, "Array data - does not throw");
    t.test(std::equal(data, data+DATASIZE, dataMod), "Array data - division");

    // Try std::list, in reverse
    std::list<int>::reverse_iterator it1 = dataList.rbegin();
    std::advance(it1, 1);
    std::list<int>::reverse_iterator it2 = dataList.rbegin();
    std::advance(it2, 4);
    didThrow = false;
    try
    {
        divideAll(it1, it2, 3);
    }
    catch (...)
    {
        didThrow = true;
    }
    t.test(!didThrow, "std::list - does not throw");
    t.test(std::equal(dataList.begin(), dataList.end(), dataMod), "std::list - division");

    // Try non-int data
    const int DOUBLEDATASIZE = 3;
    const double TOLERANCE = 0.00001;  // Tolerance for near equality
    double doubleData[DOUBLEDATASIZE] = { 0.11, 0.22, 0.33 };
    didThrow = false;
    try
    {
        divideAll(doubleData+1, doubleData+2, 0.2);
    }
    catch (...)
    {
        didThrow = true;
    }
    t.test(!didThrow, "non-int data - does not throw");
    t.setTolerance(TOLERANCE);
    t.ftest(doubleData[0], 0.11, "non-int data - division, value #1");
    t.ftest(doubleData[1], 1.1, "non-int data - division, value #2");
    t.ftest(doubleData[2], 0.33, "non-int data - division, value #3");
}


// test_function_sortDescendingInt
// Test suite for function template sortDescendingInt
//  ctor, dctor.
// Pre: None.
// Post:
//     Pass/fail status of tests have been registered with t.
//     Appropriate messages have been printed to cout.
void test_function_sortDescendingInt(Tester & t)
{
    std::cout << "Test Suite: function template sortDescendingInt (Exercise C)" << std::endl;

    const int DATASIZE = 20;
    int data[DATASIZE] = { 3, 6, 19, -2, 8, 6, 7, 1, 141, -2, -200, 4, 6, 6, 11, -5, 32, 2, 7, 0 };
    // Make copies of data
    const std::vector<int> dataCheck(data, data+DATASIZE);
    std::deque<int> data2(data, data+DATASIZE);
    // Sorted data (all but first, last)
    std::vector<int> dataSorted(data, data+DATASIZE);
    std::sort(dataSorted.begin() + 1, dataSorted.end() - 1, std::greater<int>());
    std::vector<int> dataSorted2(data, data+DATASIZE);
    std::sort(dataSorted2.begin() + 1, dataSorted2.end() - 1);

    // Empty range
    sortDescendingInt(data+3, data+3);
    t.test(std::equal(data, data+DATASIZE, dataCheck.begin()), "Array: empty range");

    // One item
    sortDescendingInt(data+3, data+4);
    t.test(std::equal(data, data+DATASIZE, dataCheck.begin()), "Array: one item");

    // Sort array
    sortDescendingInt(data+1, data+(DATASIZE-1));
    t.test(std::equal(data, data+DATASIZE, dataSorted.begin()), "Array: longer");

    // Sort other random-access container
    sortDescendingInt(data2.rbegin()+1, data2.rend()-1);
    t.test(std::equal(data2.begin(), data2.end(), dataSorted2.begin()), "Other random-access container");
}


// test_function_printReverse
// Test suite for function printReverse
//  ctor, dctor.
// Pre: None.
// Post:
//     Global allpassed is false if any tests failed;
//      it is unchanged otherwise.
//     Messages have been printed to cout.
void test_function_printReverse(Tester & t)
{
    std::cout << "Test Suite: function printReverse (Exercise D)" << std::endl;

    // Empty (char *)
    std::ostringstream os1;
    printReverse("", os1);
    t.test(os1.str() == "", "Empty (char *)");

    // Empty string object
    std::ostringstream os2;
    printReverse(std::string(""), os2);
    t.test(os2.str() == "", "Empty string object");

    // 1 char
    std::ostringstream os3;
    printReverse("x", os3);
    t.test(os3.str() == "x", "One character");

    // 2 chars
    std::ostringstream os4;
    printReverse("aB", os4);
    t.test(os4.str() == "Ba", "Two characters");

    // Longer string
    std::ostringstream os5;
    printReverse(" \n\n This is a test!  \n  ", os5);
    t.test(os5.str() == "  \n  !tset a si sihT \n\n ", "Longer string");
}


// test_da3_functions
// Test suite for Assignment 3 functions & function templates
// Uses other test-suite functions
// Pre: None.
// Post:
//     Pass/fail status of tests have been registered with t.
//     Appropriate messages have been printed to cout.
void test_da3_functions(Tester & t)
{
    // Do all the test suites
    std::cout << "TEST SUITES FOR ASSIGNMENT 3, EXERCISES A, B, C, D" << std::endl;
    test_function_doesItThrow(t);
    test_function_divideAll(t);
    test_function_sortDescendingInt(t);
    test_function_printReverse(t);
}


// ************************************************************************
// Main program
// ************************************************************************


// main
// Runs Assignment 3 test suite, prints results to cout.
int main()
{
    Tester t;
    test_da3_functions(t);

    std::cout << std::endl;
    if (t.allPassed())
    {
        std::cout << "All tests successful" 
                  << std::endl;
    }
    else
    {
        std::cout << "Tests ********** UNSUCCESSFUL **********"
                  << std::endl;
    }
    std::cout << std::endl;

    return 0;
}

