<commit_before>/*
Copyright libCellML Contributors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include "test_utils.h"

#include "gtest/gtest.h"

#include <libcellml>

TEST(Maths, setAndGetMath)
{
    libcellml::ComponentPtr c = libcellml::Component::create();
    c->setMath(EMPTY_MATH);
    EXPECT_EQ(EMPTY_MATH, c->math());
}

TEST(Maths, appendAndSerialiseMathComponent)
{
    const std::string e =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
        "  <component>\n"
        "    <math xmlns=\"http://www.w3.org/1998/Math/MathML\"/>\n"
        "  </component>\n"
        "</model>\n";

    libcellml::ModelPtr m = createModelWithComponent();
    libcellml::ComponentPtr c = m->component(0);
    c->appendMath(EMPTY_MATH);

    libcellml::PrinterPtr printer = libcellml::Printer::create();
    const std::string a = printer->printModel(m);
    EXPECT_EQ(e, a);
}

TEST(Maths, appendAndRemoveMathFromComponent)
{
    const std::string eNoMath =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
        "  <component/>\n"
        "</model>\n";
    const std::string eWithMath =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
        "  <component>\n"
        "    <math xmlns=\"http://www.w3.org/1998/Math/MathML\"/>\n"
        "  </component>\n"
        "</model>\n";
    libcellml::ModelPtr m = createModelWithComponent();
    libcellml::ComponentPtr c = m->component(0);
    libcellml::PrinterPtr printer = libcellml::Printer::create();

    c->appendMath(EMPTY_MATH);
    std::string a = printer->printModel(m);
    EXPECT_EQ(eWithMath, a);

    c->removeMath();
    a = printer->printModel(m);
    EXPECT_EQ(eNoMath, a);

    c->appendMath(EMPTY_MATH);
    a = printer->printModel(m);
    EXPECT_EQ(eWithMath, a);

    c->setMath("");
    a = printer->printModel(m);
    EXPECT_EQ(eNoMath, a);
}

TEST(Maths, appendSerialiseAndParseMathInComponent)
{
    const std::string e =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
        "  <component>\n"
        "    <math xmlns=\"http://www.w3.org/1998/Math/MathML\"/>\n"
        "  </component>\n"
        "</model>\n";

    libcellml::ModelPtr m = libcellml::Model::create();
    libcellml::ComponentPtr c = libcellml::Component::create();
    m->addComponent(c);
    c->appendMath(EMPTY_MATH);

    libcellml::PrinterPtr printer = libcellml::Printer::create();
    std::string a = printer->printModel(m);
    EXPECT_EQ(e, a);

    // Parse
    libcellml::ParserPtr parser = libcellml::Parser::create();
    libcellml::ModelPtr model = parser->parseModel(e);
    a = printer->printModel(model);
    EXPECT_EQ(e, a);
}

TEST(Maths, modelWithTwoVariablesAndTwoInvalidMaths)
{
    const std::string e =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
        "  <component name=\"component\">\n"
        "    <variable name=\"variable1\"/>\n"
        "    <variable name=\"variable2\"/>\n"
        "    <math xmlns=\"http://www.w3.org/1998/Math/MathML\"/>\n"
        "    <math xmlns=\"http://www.w3.org/1998/Math/MathML\"/>\n"
        "  </component>\n"
        "</model>\n";

    libcellml::ModelPtr m = libcellml::Model::create();
    libcellml::ComponentPtr c = libcellml::Component::create();
    libcellml::VariablePtr v1 = libcellml::Variable::create();
    libcellml::VariablePtr v2 = libcellml::Variable::create();
    c->setName("component");
    v1->setName("variable1");
    v2->setName("variable2");
    c->addVariable(v1);
    c->addVariable(v2);
    c->appendMath(EMPTY_MATH);
    c->appendMath(EMPTY_MATH);
    m->addComponent(c);

    libcellml::PrinterPtr printer = libcellml::Printer::create();
    const std::string a = printer->printModel(m);
    EXPECT_EQ(e, a);
}

TEST(Maths, modelWithTwoVariablesWithInitialValuesAndInvalidMath)
{
    const std::string e =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
        "  <component name=\"component\">\n"
        "    <variable name=\"variable1\" initial_value=\"1.0\"/>\n"
        "    <variable name=\"variable2\" initial_value=\"-1.0\"/>\n"
        "    <math xmlns=\"http://www.w3.org/1998/Math/MathML\"/>\n"
        "  </component>\n"
        "</model>\n";

    libcellml::ModelPtr m = libcellml::Model::create();
    libcellml::ComponentPtr c = libcellml::Component::create();
    libcellml::VariablePtr v1 = libcellml::Variable::create();
    libcellml::VariablePtr v2 = libcellml::Variable::create();
    c->setName("component");
    v1->setName("variable1");
    v2->setName("variable2");
    v1->setInitialValue("1.0");
    v2->setInitialValue("-1.0");
    c->addVariable(v1);
    c->addVariable(v2);
    c->appendMath(EMPTY_MATH);
    m->addComponent(c);

    libcellml::PrinterPtr printer = libcellml::Printer::create();
    const std::string a = printer->printModel(m);
    EXPECT_EQ(e, a);
}

// 1.xiii.a
TEST(Maths, modelWithTwoVariablesWithInitialValuesAndValidMath)
{
    const std::string e =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
        "  <component name=\"component\">\n"
        "    <variable name=\"A\" initial_value=\"1.0\"/>\n"
        "    <variable name=\"B\" initial_value=\"-1.0\"/>\n"
        "    <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
        "      <apply>\n"
        "        <eq/>\n"
        "        <ci>C</ci>\n"
        "        <apply>\n"
        "          <plus/>\n"
        "          <ci>A</ci>\n"
        "          <ci>B</ci>\n"
        "        </apply>\n"
        "      </apply>\n"
        "    </math>\n"
        "  </component>\n"
        "</model>\n";
    const std::string math =
        "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
        "  <apply>\n"
        "    <eq/>\n"
        "    <ci>C</ci>\n"
        "    <apply>\n"
        "      <plus/>\n"
        "      <ci>A</ci>\n"
        "      <ci>B</ci>\n"
        "    </apply>\n"
        "  </apply>\n"
        "</math>\n";

    libcellml::ModelPtr m = libcellml::Model::create();
    libcellml::ComponentPtr c = libcellml::Component::create();
    libcellml::VariablePtr v1 = libcellml::Variable::create();
    libcellml::VariablePtr v2 = libcellml::Variable::create();
    c->setName("component");
    v1->setName("A");
    v2->setName("B");
    v1->setInitialValue("1.0");
    v2->setInitialValue("-1.0");
    c->addVariable(v1);
    c->addVariable(v2);
    c->appendMath(math);
    m->addComponent(c);

    libcellml::PrinterPtr printer = libcellml::Printer::create();
    const std::string a = printer->printModel(m);
    EXPECT_EQ(e, a);
}

// 1.xiv.a
TEST(Maths, twoComponentsWithMathAndConnectionAndParse)
{
    const std::string e =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
        "  <component name=\"component1\">\n"
        "    <variable name=\"A1\"/>\n"
        "    <variable name=\"B1\"/>\n"
        "    <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
        "      <apply>\n"
        "        <eq/>\n"
        "        <ci>C1</ci>\n"
        "        <apply>\n"
        "          <plus/>\n"
        "          <ci>A1</ci>\n"
        "          <ci>B1</ci>\n"
        "        </apply>\n"
        "      </apply>\n"
        "    </math>\n"
        "  </component>\n"
        "  <component name=\"component2\">\n"
        "    <variable name=\"A2\"/>\n"
        "    <variable name=\"B2\"/>\n"
        "    <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
        "      <apply>\n"
        "        <eq/>\n"
        "        <ci>C2</ci>\n"
        "        <apply>\n"
        "          <plus/>\n"
        "          <ci>A2</ci>\n"
        "          <ci>B2</ci>\n"
        "        </apply>\n"
        "      </apply>\n"
        "    </math>\n"
        "  </component>\n"
        "  <connection component_1=\"component1\" component_2=\"component2\">\n"
        "    <map_variables variable_1=\"A1\" variable_2=\"A2\"/>\n"
        "  </connection>\n"
        "</model>\n";
    const std::string math1 =
        "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
        "  <apply>\n"
        "    <eq/>\n"
        "    <ci>C1</ci>\n"
        "    <apply>\n"
        "      <plus/>\n"
        "      <ci>A1</ci>\n"
        "      <ci>B1</ci>\n"
        "    </apply>\n"
        "  </apply>\n"
        "</math>\n";
    const std::string math2 =
        "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
        "  <apply>\n"
        "    <eq/>\n"
        "    <ci>C2</ci>\n"
        "    <apply>\n"
        "      <plus/>\n"
        "      <ci>A2</ci>\n"
        "      <ci>B2</ci>\n"
        "    </apply>\n"
        "  </apply>\n"
        "</math>\n";

    libcellml::ModelPtr m = libcellml::Model::create();
    libcellml::ComponentPtr comp1 = libcellml::Component::create();
    libcellml::ComponentPtr comp2 = libcellml::Component::create();
    libcellml::VariablePtr v11 = libcellml::Variable::create();
    libcellml::VariablePtr v12 = libcellml::Variable::create();
    libcellml::VariablePtr v21 = libcellml::Variable::create();
    libcellml::VariablePtr v22 = libcellml::Variable::create();

    comp1->setName("component1");
    comp2->setName("component2");
    v11->setName("A1");
    v12->setName("B1");
    v21->setName("A2");
    v22->setName("B2");

    comp1->addVariable(v11);
    comp1->addVariable(v12);
    comp2->addVariable(v21);
    comp2->addVariable(v22);
    comp1->appendMath(math1);
    comp2->appendMath(math2);
    m->addComponent(comp1);
    m->addComponent(comp2);
    libcellml::Variable::addEquivalence(v11, v21);

    libcellml::PrinterPtr printer = libcellml::Printer::create();
    std::string a = printer->printModel(m);
    EXPECT_EQ(e, a);

    // Parse
    libcellml::ParserPtr parser = libcellml::Parser::create();
    libcellml::ModelPtr model = parser->parseModel(e);
    a = printer->printModel(model);
    EXPECT_EQ(e, a);
}
<commit_msg>Adding test to show segfault when adding an entire XML MathML document.<commit_after>/*
Copyright libCellML Contributors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include "test_utils.h"

#include "gtest/gtest.h"

#include <libcellml>

TEST(Maths, setAndGetMath)
{
    libcellml::ComponentPtr c = libcellml::Component::create();
    c->setMath(EMPTY_MATH);
    EXPECT_EQ(EMPTY_MATH, c->math());
}

TEST(Maths, appendAndSerialiseMathComponent)
{
    const std::string e =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
        "  <component>\n"
        "    <math xmlns=\"http://www.w3.org/1998/Math/MathML\"/>\n"
        "  </component>\n"
        "</model>\n";

    libcellml::ModelPtr m = createModelWithComponent();
    libcellml::ComponentPtr c = m->component(0);
    c->appendMath(EMPTY_MATH);

    libcellml::PrinterPtr printer = libcellml::Printer::create();
    const std::string a = printer->printModel(m);
    EXPECT_EQ(e, a);
}

TEST(Maths, appendAndRemoveMathFromComponent)
{
    const std::string eNoMath =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
        "  <component/>\n"
        "</model>\n";
    const std::string eWithMath =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
        "  <component>\n"
        "    <math xmlns=\"http://www.w3.org/1998/Math/MathML\"/>\n"
        "  </component>\n"
        "</model>\n";
    libcellml::ModelPtr m = createModelWithComponent();
    libcellml::ComponentPtr c = m->component(0);
    libcellml::PrinterPtr printer = libcellml::Printer::create();

    c->appendMath(EMPTY_MATH);
    std::string a = printer->printModel(m);
    EXPECT_EQ(eWithMath, a);

    c->removeMath();
    a = printer->printModel(m);
    EXPECT_EQ(eNoMath, a);

    c->appendMath(EMPTY_MATH);
    a = printer->printModel(m);
    EXPECT_EQ(eWithMath, a);

    c->setMath("");
    a = printer->printModel(m);
    EXPECT_EQ(eNoMath, a);
}

TEST(Maths, appendSerialiseAndParseMathInComponent)
{
    const std::string e =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
        "  <component>\n"
        "    <math xmlns=\"http://www.w3.org/1998/Math/MathML\"/>\n"
        "  </component>\n"
        "</model>\n";

    libcellml::ModelPtr m = libcellml::Model::create();
    libcellml::ComponentPtr c = libcellml::Component::create();
    m->addComponent(c);
    c->appendMath(EMPTY_MATH);

    libcellml::PrinterPtr printer = libcellml::Printer::create();
    std::string a = printer->printModel(m);
    EXPECT_EQ(e, a);

    // Parse
    libcellml::ParserPtr parser = libcellml::Parser::create();
    libcellml::ModelPtr model = parser->parseModel(e);
    a = printer->printModel(model);
    EXPECT_EQ(e, a);
}

TEST(Maths, modelWithTwoVariablesAndTwoInvalidMaths)
{
    const std::string e =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
        "  <component name=\"component\">\n"
        "    <variable name=\"variable1\"/>\n"
        "    <variable name=\"variable2\"/>\n"
        "    <math xmlns=\"http://www.w3.org/1998/Math/MathML\"/>\n"
        "    <math xmlns=\"http://www.w3.org/1998/Math/MathML\"/>\n"
        "  </component>\n"
        "</model>\n";

    libcellml::ModelPtr m = libcellml::Model::create();
    libcellml::ComponentPtr c = libcellml::Component::create();
    libcellml::VariablePtr v1 = libcellml::Variable::create();
    libcellml::VariablePtr v2 = libcellml::Variable::create();
    c->setName("component");
    v1->setName("variable1");
    v2->setName("variable2");
    c->addVariable(v1);
    c->addVariable(v2);
    c->appendMath(EMPTY_MATH);
    c->appendMath(EMPTY_MATH);
    m->addComponent(c);

    libcellml::PrinterPtr printer = libcellml::Printer::create();
    const std::string a = printer->printModel(m);
    EXPECT_EQ(e, a);
}

TEST(Maths, modelWithTwoVariablesWithInitialValuesAndInvalidMath)
{
    const std::string e =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
        "  <component name=\"component\">\n"
        "    <variable name=\"variable1\" initial_value=\"1.0\"/>\n"
        "    <variable name=\"variable2\" initial_value=\"-1.0\"/>\n"
        "    <math xmlns=\"http://www.w3.org/1998/Math/MathML\"/>\n"
        "  </component>\n"
        "</model>\n";

    libcellml::ModelPtr m = libcellml::Model::create();
    libcellml::ComponentPtr c = libcellml::Component::create();
    libcellml::VariablePtr v1 = libcellml::Variable::create();
    libcellml::VariablePtr v2 = libcellml::Variable::create();
    c->setName("component");
    v1->setName("variable1");
    v2->setName("variable2");
    v1->setInitialValue("1.0");
    v2->setInitialValue("-1.0");
    c->addVariable(v1);
    c->addVariable(v2);
    c->appendMath(EMPTY_MATH);
    m->addComponent(c);

    libcellml::PrinterPtr printer = libcellml::Printer::create();
    const std::string a = printer->printModel(m);
    EXPECT_EQ(e, a);
}

// 1.xiii.a
TEST(Maths, modelWithTwoVariablesWithInitialValuesAndValidMath)
{
    const std::string e =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
        "  <component name=\"component\">\n"
        "    <variable name=\"A\" initial_value=\"1.0\"/>\n"
        "    <variable name=\"B\" initial_value=\"-1.0\"/>\n"
        "    <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
        "      <apply>\n"
        "        <eq/>\n"
        "        <ci>C</ci>\n"
        "        <apply>\n"
        "          <plus/>\n"
        "          <ci>A</ci>\n"
        "          <ci>B</ci>\n"
        "        </apply>\n"
        "      </apply>\n"
        "    </math>\n"
        "  </component>\n"
        "</model>\n";
    const std::string math =
        "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
        "  <apply>\n"
        "    <eq/>\n"
        "    <ci>C</ci>\n"
        "    <apply>\n"
        "      <plus/>\n"
        "      <ci>A</ci>\n"
        "      <ci>B</ci>\n"
        "    </apply>\n"
        "  </apply>\n"
        "</math>\n";

    libcellml::ModelPtr m = libcellml::Model::create();
    libcellml::ComponentPtr c = libcellml::Component::create();
    libcellml::VariablePtr v1 = libcellml::Variable::create();
    libcellml::VariablePtr v2 = libcellml::Variable::create();
    c->setName("component");
    v1->setName("A");
    v2->setName("B");
    v1->setInitialValue("1.0");
    v2->setInitialValue("-1.0");
    c->addVariable(v1);
    c->addVariable(v2);
    c->appendMath(math);
    m->addComponent(c);

    libcellml::PrinterPtr printer = libcellml::Printer::create();
    const std::string a = printer->printModel(m);
    EXPECT_EQ(e, a);
}

// 1.xiv.a
TEST(Maths, twoComponentsWithMathAndConnectionAndParse)
{
    const std::string e =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
        "  <component name=\"component1\">\n"
        "    <variable name=\"A1\"/>\n"
        "    <variable name=\"B1\"/>\n"
        "    <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
        "      <apply>\n"
        "        <eq/>\n"
        "        <ci>C1</ci>\n"
        "        <apply>\n"
        "          <plus/>\n"
        "          <ci>A1</ci>\n"
        "          <ci>B1</ci>\n"
        "        </apply>\n"
        "      </apply>\n"
        "    </math>\n"
        "  </component>\n"
        "  <component name=\"component2\">\n"
        "    <variable name=\"A2\"/>\n"
        "    <variable name=\"B2\"/>\n"
        "    <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
        "      <apply>\n"
        "        <eq/>\n"
        "        <ci>C2</ci>\n"
        "        <apply>\n"
        "          <plus/>\n"
        "          <ci>A2</ci>\n"
        "          <ci>B2</ci>\n"
        "        </apply>\n"
        "      </apply>\n"
        "    </math>\n"
        "  </component>\n"
        "  <connection component_1=\"component1\" component_2=\"component2\">\n"
        "    <map_variables variable_1=\"A1\" variable_2=\"A2\"/>\n"
        "  </connection>\n"
        "</model>\n";
    const std::string math1 =
        "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
        "  <apply>\n"
        "    <eq/>\n"
        "    <ci>C1</ci>\n"
        "    <apply>\n"
        "      <plus/>\n"
        "      <ci>A1</ci>\n"
        "      <ci>B1</ci>\n"
        "    </apply>\n"
        "  </apply>\n"
        "</math>\n";
    const std::string math2 =
        "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
        "  <apply>\n"
        "    <eq/>\n"
        "    <ci>C2</ci>\n"
        "    <apply>\n"
        "      <plus/>\n"
        "      <ci>A2</ci>\n"
        "      <ci>B2</ci>\n"
        "    </apply>\n"
        "  </apply>\n"
        "</math>\n";

    libcellml::ModelPtr m = libcellml::Model::create();
    libcellml::ComponentPtr comp1 = libcellml::Component::create();
    libcellml::ComponentPtr comp2 = libcellml::Component::create();
    libcellml::VariablePtr v11 = libcellml::Variable::create();
    libcellml::VariablePtr v12 = libcellml::Variable::create();
    libcellml::VariablePtr v21 = libcellml::Variable::create();
    libcellml::VariablePtr v22 = libcellml::Variable::create();

    comp1->setName("component1");
    comp2->setName("component2");
    v11->setName("A1");
    v12->setName("B1");
    v21->setName("A2");
    v22->setName("B2");

    comp1->addVariable(v11);
    comp1->addVariable(v12);
    comp2->addVariable(v21);
    comp2->addVariable(v22);
    comp1->appendMath(math1);
    comp2->appendMath(math2);
    m->addComponent(comp1);
    m->addComponent(comp2);
    libcellml::Variable::addEquivalence(v11, v21);

    libcellml::PrinterPtr printer = libcellml::Printer::create();
    std::string a = printer->printModel(m);
    EXPECT_EQ(e, a);

    // Parse
    libcellml::ParserPtr parser = libcellml::Parser::create();
    libcellml::ModelPtr model = parser->parseModel(e);
    a = printer->printModel(model);
    EXPECT_EQ(e, a);
}

TEST(Maths, addingMathMLAsACompleteDocument)
{
    const std::string e =
        "<?xml version= \"1.0 \" encoding= \"UTF-8 \"?>\n"
        "<model xmlns= \"http://www.cellml.org/cellml/2.0# \">\n"
        "  <component name= \"parameters \">\n"
        "    <math xmlns= \"http://www.w3.org/1998/Math/MathML \">\n"
        "      <apply>\n"
        "        <divide/>\n"
        "        <ci>eff</ci>\n"
        "        <ci>t_ave</ci>\n"
        "      </apply>\n"
        "    </math>\n"
        "  </component>\n"
        "</model>\n";

    const std::string math =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
        "  <apply>\n"
        "    <divide/>\n"
        "    <ci> eff </ci>\n"
        "    <ci> t_ave </ci>\n"
        "  </apply>\n"
        "</math>\n";

    libcellml::ModelPtr m = libcellml::Model::create();
    libcellml::ComponentPtr comp = libcellml::Component::create();
    comp->setName("parameters");

    comp->appendMath(math);
    m->addComponent(comp);

    libcellml::PrinterPtr printer = libcellml::Printer::create();
    std::string a = printer->printModel(m);
    EXPECT_EQ(e, a);
}
<|endoftext|>


<commit_before>#include "datalayer.h"
#include "person.h"
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

DataLayer::DataLayer()
{
    db = QSqlDatabase::addDatabase("QSQLITE");
    QString dbName = "amazingDatabase.sqlite";
    db.setDatabaseName(dbName);
}
void DataLayer::writeToFile(string name, char gender, int yearOfBirth, int yearOfDeath, string comment)
{
     ofstream myfile("amazingDatabase.txt", ios::app);
     myfile << name << endl;
     myfile << gender << endl;
     myfile << yearOfBirth << endl;
     myfile << yearOfDeath << endl;
     myfile << comment << endl;
     myfile.close();
}
void DataLayer::readFromFile(vector<Person>& getPersons)
{
    string line;
    string name = "1";
    string comment = "1";
    char gender = '1';
    int yearOfBirth = 1;
    int yearOfDeath = 1;
    ifstream myfile ("amazingDatabase.txt");
    if (myfile.is_open())
      {
        while ( getline (myfile,line) )
        {
          if(name == "1" && gender == '1' && yearOfBirth == 1 && yearOfDeath == 1 && comment == "1")
          {
              name = line;
          }
          else if(name != "1" && gender == '1' && yearOfBirth == 1 && yearOfDeath == 1 && comment == "1")
          {
              gender = line[0];
          }
          else if(name != "1" && gender != '1' && yearOfBirth == 1 && yearOfDeath == 1 && comment == "1")
          {
              yearOfBirth = stringToNumber(line);
          }
          else if(name != "1" && gender != '1' && yearOfBirth != 1 && yearOfDeath == 1 && comment == "1")
          {
              yearOfDeath = stringToNumber(line);
          }
          else if(name != "1" && gender != '1' && yearOfBirth != 1 && yearOfDeath != 1 && comment == "1")
          {
              comment = line;
              Person p(name, gender, yearOfBirth, yearOfDeath, comment);
              getPersons.push_back(p);
              name = "1";
              gender = '1';
              yearOfBirth = 1;
              yearOfDeath = 1;
              comment = "1";
          }
        }
    myfile.close();
    }
    else cout << "Unable to open file!" << endl;
}
bool sortByName(const Person &lhs, const Person &rhs)
{
    return lhs._getName() < rhs._getName();
}
bool sortByBirth(const Person &lhs, const Person &rhs)
{
    return lhs._getBirth() < rhs._getBirth();
}
bool sortByGender(const Person &lhs, const Person &rhs)
{
    return lhs._getGender() < rhs._getGender();
}
bool sortByAge(const Person &lhs, const Person &rhs)
{
    return lhs._getAge() < rhs._getAge();
}
void DataLayer::sortNames(vector<Person>& getPersons)
{
    std::sort(getPersons.begin(),getPersons.end(), sortByName);
}
void DataLayer::sortBirth(vector<Person>& getPersons)
{
    std::sort(getPersons.begin(),getPersons.end(), sortByBirth);
}
void DataLayer::sortGender(vector<Person>& getPersons)
{
    std::sort(getPersons.begin(),getPersons.end(), sortByGender);
}
void DataLayer::sortAge(vector<Person>& getPersons)
{
    std::sort(getPersons.begin(),getPersons.end(), sortByAge);
}
void DataLayer::deleteFile()
{
    remove("amazingDatabase.txt");
    ofstream myfile;
    myfile.open("amazingDatabase.txt");
    myfile.close();
}
int DataLayer::stringToNumber(string st)
{
    string text = st;
    int value = atoi(text.c_str());
    return value;
}

void DataLayer::readScientistsFromDatabase(vector<Person>& sci)
{
    db.open();

    QSqlQuery query(db);
    query.exec("SELECT * FROM Scientist");

    while(query.next())
    {
        int id = query.value("id").toUInt();
        string name = query.value("name").toString().toStdString();
        string gen = query.value("gender").toString().toStdString();
        int birth = query.value("YearOfBirth").toUInt();
        int death = query.value("YearOfDeath").toUInt();
        string comment = query.value("comment").toString().toStdString();
        if(death < 0 && death > 2016)
        {
            death = 0;
        }
        char gender = gen[0];
        sci.push_back(Person(name, gender, birth, death, comment));
   }
}

void DataLayer::readComputersFromDatabase(vector<computer>& com)
{
    db.open();

    QSqlQuery query(db);
    query.exec("SELECT * FROM Computers");

    while(query.next())
    {
        int id = query.value("id").toUInt();
        string name = query.value("name").toString().toStdString();
        string typeOf = query.value("type").toString().toStdString();
        int date = query.value("date").toUInt();
        string wasItBuilt = query.value("wasitbuilt").toString().toStdString();

        com.push_back(computer(name, typeOf, date, wasItBuilt));
   }
}

<commit_msg>laga smá breytunöfn<commit_after>#include "datalayer.h"
#include "person.h"
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

DataLayer::DataLayer()
{
    db = QSqlDatabase::addDatabase("QSQLITE");
    QString dbName = "amazingDatabase.sqlite";
    db.setDatabaseName(dbName);
}
void DataLayer::writeToFile(string name, char gender, int yearOfBirth, int yearOfDeath, string comment)
{
     ofstream myfile("amazingDatabase.txt", ios::app);
     myfile << name << endl;
     myfile << gender << endl;
     myfile << yearOfBirth << endl;
     myfile << yearOfDeath << endl;
     myfile << comment << endl;
     myfile.close();
}
void DataLayer::readFromFile(vector<Person>& getPersons)
{
    string line;
    string name = "1";
    string comment = "1";
    char gender = '1';
    int yearOfBirth = 1;
    int yearOfDeath = 1;
    ifstream myfile ("amazingDatabase.txt");
    if (myfile.is_open())
      {
        while ( getline (myfile,line) )
        {
          if(name == "1" && gender == '1' && yearOfBirth == 1 && yearOfDeath == 1 && comment == "1")
          {
              name = line;
          }
          else if(name != "1" && gender == '1' && yearOfBirth == 1 && yearOfDeath == 1 && comment == "1")
          {
              gender = line[0];
          }
          else if(name != "1" && gender != '1' && yearOfBirth == 1 && yearOfDeath == 1 && comment == "1")
          {
              yearOfBirth = stringToNumber(line);
          }
          else if(name != "1" && gender != '1' && yearOfBirth != 1 && yearOfDeath == 1 && comment == "1")
          {
              yearOfDeath = stringToNumber(line);
          }
          else if(name != "1" && gender != '1' && yearOfBirth != 1 && yearOfDeath != 1 && comment == "1")
          {
              comment = line;
              Person p(name, gender, yearOfBirth, yearOfDeath, comment);
              getPersons.push_back(p);
              name = "1";
              gender = '1';
              yearOfBirth = 1;
              yearOfDeath = 1;
              comment = "1";
          }
        }
    myfile.close();
    }
    else cout << "Unable to open file!" << endl;
}
bool sortByName(const Person &lhs, const Person &rhs)
{
    return lhs._getName() < rhs._getName();
}
bool sortByBirth(const Person &lhs, const Person &rhs)
{
    return lhs._getBirth() < rhs._getBirth();
}
bool sortByGender(const Person &lhs, const Person &rhs)
{
    return lhs._getGender() < rhs._getGender();
}
bool sortByAge(const Person &lhs, const Person &rhs)
{
    return lhs._getAge() < rhs._getAge();
}
void DataLayer::sortNames(vector<Person>& getPersons)
{
    std::sort(getPersons.begin(),getPersons.end(), sortByName);
}
void DataLayer::sortBirth(vector<Person>& getPersons)
{
    std::sort(getPersons.begin(),getPersons.end(), sortByBirth);
}
void DataLayer::sortGender(vector<Person>& getPersons)
{
    std::sort(getPersons.begin(),getPersons.end(), sortByGender);
}
void DataLayer::sortAge(vector<Person>& getPersons)
{
    std::sort(getPersons.begin(),getPersons.end(), sortByAge);
}
void DataLayer::deleteFile()
{
    remove("amazingDatabase.txt");
    ofstream myfile;
    myfile.open("amazingDatabase.txt");
    myfile.close();
}
int DataLayer::stringToNumber(string st)
{
    string text = st;
    int value = atoi(text.c_str());
    return value;
}

void DataLayer::readScientistsFromDatabase(vector<Person>& sci)
{
    db.open();

    QSqlQuery query(db);
    query.exec("SELECT * FROM Scientist");

    while(query.next())
    {
        int id = query.value("id").toUInt();
        string name = query.value("name").toString().toStdString();
        string gen = query.value("gender").toString().toStdString();
        int birth = query.value("YearOfBirth").toUInt();
        int death = query.value("YearOfDeath").toUInt();
        string comment = query.value("comment").toString().toStdString();
        if(death < 0 && death > 2016)
        {
            death = 0;
        }
        char gender = gen[0];
        sci.push_back(Person(name, gender, birth, death, comment));
   }
}

void DataLayer::readComputersFromDatabase(vector<computer>& com)
{
    db.open();

    QSqlQuery query(db);
    query.exec("SELECT * FROM Computers");

    while(query.next())
    {
        int id = query.value("id").toUInt();
        string name = query.value("name").toString().toStdString();
        string type = query.value("type").toString().toStdString();
        int date = query.value("date").toUInt();
        string wasItBuilt = query.value("wasitbuilt").toString().toStdString();

        com.push_back(computer(name, type, date, wasItBuilt));
   }
}

<|endoftext|>


<commit_before><commit_msg>Fixed incorrect draw order when flattening. A floating raster selection would be stamped on top of objects.<commit_after><|endoftext|>


<commit_before>#include "kfoldertree.h"
#include <klocale.h>
#include <kiconloader.h>
#include <kdebug.h>
#include <qpainter.h>
#include <qapplication.h>
#include <qheader.h>

//-----------------------------------------------------------------------------
KFolderTreeItem::KFolderTreeItem( KFolderTree *parent, const QString & label,
				  Protocol protocol, Type type )
  : KListViewItem( parent, label ), mProtocol( protocol ), mType( type ),
    mUnread(-1), mTotal(0)
{
}

//-----------------------------------------------------------------------------
KFolderTreeItem::KFolderTreeItem( KFolderTreeItem *parent,
				  const QString & label, Protocol protocol, Type type,
          int unread, int total )
    : KListViewItem( parent, label ), mProtocol( protocol ), mType( type ),
      mUnread( unread ), mTotal( total )
{
}

//-----------------------------------------------------------------------------
QString KFolderTreeItem::key(int column, bool) const
{
  if ( column > 0 ) return text(column);

  // local root-folder
  if ( !parent() && mProtocol == NONE )
    return "\t0";

  QString thiskey;

  /* basic sorting rules:
     local => imap => news => other
   */
  if (mProtocol == Local)
    thiskey = "\t1";
  else if (mProtocol == CachedImap)
    thiskey = "\t2";
  else if (mProtocol == Imap)
    thiskey = "\t3";
  else if (mProtocol == News)
    thiskey = "\t4";
  else
    thiskey = "\t5";

  // make sure system folders come first when sorting
  if (mType == Inbox)
    thiskey += "\t0";
  else if (mType == Outbox)
    thiskey += "\t1";
  else if (mType == SentMail)
    thiskey += "\t2";
  else if (mType == Trash)
    thiskey += "\t3";
  else if (mType == Drafts)
    thiskey += "\t4";
  else if (mType == Calendar)
    thiskey += "\t5";
  else if (mType == Contacts)
    thiskey += "\t6";
  else if (mType == Notes)
    thiskey += "\t7";
  else if (mType == Tasks)
    thiskey += "\t8";

  // the displayed text
  thiskey += text(0);

  return thiskey;
}

//-----------------------------------------------------------------------------
int KFolderTreeItem::compare( QListViewItem * i, int col, bool ascending ) const
{
  if (col == 0)
  {
    // sort by folder
    return key(col, ascending).localeAwareCompare( i->key(col, ascending) );
  }
  else
  {
    // sort by unread or total-column
    int a = 0, b = 0;
    if (col == static_cast<KFolderTree*>(listView())->unreadIndex())
    {
      a = mUnread;
      b = static_cast<KFolderTreeItem*>(i)->unreadCount();
    }
    else if (col == static_cast<KFolderTree*>(listView())->totalIndex())
    {
      a = mTotal;
      b = static_cast<KFolderTreeItem*>(i)->totalCount();
    }

    if ( a == b )
      return 0;
    else
      return (a < b ? -1 : 1);
  }
}

//-----------------------------------------------------------------------------
void KFolderTreeItem::setUnreadCount( int aUnread )
{
  if ( aUnread < 0 ) return;

  mUnread = aUnread;

  QString unread = QString::null;
  if (mUnread == 0)
    unread = "- ";
  else {
    unread.setNum(mUnread);
    unread += " ";
  }

  setText( static_cast<KFolderTree*>(listView())->unreadIndex(),
      unread );
}

//-----------------------------------------------------------------------------
void KFolderTreeItem::setTotalCount( int aTotal )
{
  if ( aTotal < 0 ) return;

  mTotal = aTotal;

  QString total = QString::null;
  if (mTotal == 0)
    total = "- ";
  else {
    total.setNum(mTotal);
    total += " ";
  }

  setText( static_cast<KFolderTree*>(listView())->totalIndex(),
      total );
}

//-----------------------------------------------------------------------------
int KFolderTreeItem::countUnreadRecursive()
{
  int count = (mUnread > 0) ? mUnread : 0;

  for ( QListViewItem *item = firstChild() ;
      item ; item = item->nextSibling() )
  {
    count += static_cast<KFolderTreeItem*>(item)->countUnreadRecursive();
  }

  return count;
}

//-----------------------------------------------------------------------------
void KFolderTreeItem::paintCell( QPainter * p, const QColorGroup & cg,
                                  int column, int width, int align )
{
  QListView *lv = listView();
  QString oldText = text(column);

  // set an empty text so that we can have our own implementation (see further down)
  // but still benefit from KListView::paintCell
  setText( column, "" );

  KListViewItem::paintCell( p, cg, column, width, align );

  KFolderTree *ft = static_cast<KFolderTree*>(listView());
  int r = lv ? lv->itemMargin() : 1;
  const QPixmap *icon = pixmap( column );
  int marg = lv ? lv->itemMargin() : 1;

  QString t;
  QRect br;
  setText( column, oldText );
  if ( isSelected() )
    p->setPen( cg.highlightedText() );
  else
    p->setPen( ft->paintInfo().colFore );

  if ( icon ) {
    r += icon->width() + lv->itemMargin();
  }
  t = text( column );
  if ( !t.isEmpty() )
  {
    // use a bold-font for the folder- and the unread-columns
    if ( countUnreadRecursive() > 0 &&
        (column == 0 || column == ft->unreadIndex()) )
    {
      QFont f = p->font();
      f.setWeight(QFont::Bold);
      p->setFont(f);
    }
    p->drawText( r, 0, width-marg-r, height(),
        align | AlignVCenter, t, -1, &br );
    if (!isSelected())
      p->setPen( ft->paintInfo().colUnread );
    if (column == 0) {
      // draw the unread-count if the unread-column is not active
      QString unread = QString::null;
      if ( !ft->isUnreadActive() && mUnread > 0 )
        unread = " (" + QString::number(mUnread) + ")";
      p->drawText( br.right(), 0, width-marg-br.right(), height(),
          align | AlignVCenter, unread );
    }
  } // end !t.isEmpty()
}

//=============================================================================

KFolderTree::KFolderTree( QWidget *parent, const char* name )
  : KListView( parent, name ), mUnreadIndex(-1), mTotalIndex(-1)
{
  // GUI-options
  setLineWidth(0);
  setAcceptDrops(true);
  setDropVisualizer(false);
  setAllColumnsShowFocus(true);
  setShowSortIndicator(true);
  setUpdatesEnabled(true);
  setItemsRenameable(false);
  setRootIsDecorated(true);
  setSelectionModeExt(Extended);
  setAlternateBackground(QColor());
  setFullWidth(true);
}

//-----------------------------------------------------------------------------
void KFolderTree::drawContentsOffset( QPainter * p, int ox, int oy,
                                       int cx, int cy, int cw, int ch )
{
  bool oldUpdatesEnabled = isUpdatesEnabled();
  setUpdatesEnabled(false);
  KListView::drawContentsOffset( p, ox, oy, cx, cy, cw, ch );
  setUpdatesEnabled(oldUpdatesEnabled);
}

//-----------------------------------------------------------------------------
void KFolderTree::contentsMousePressEvent( QMouseEvent *e )
{
    setSelectionModeExt(Single);
    KListView::contentsMousePressEvent(e);
}

//-----------------------------------------------------------------------------
void KFolderTree::contentsMouseReleaseEvent( QMouseEvent *e )
{
    KListView::contentsMouseReleaseEvent(e);
    setSelectionModeExt(Extended);
}

//-----------------------------------------------------------------------------
void KFolderTree::addAcceptableDropMimetype( const char *mimeType, bool outsideOk )
{
  int oldSize = mAcceptableDropMimetypes.size();
  mAcceptableDropMimetypes.resize(oldSize+1);
  mAcceptOutside.resize(oldSize+1);

  mAcceptableDropMimetypes.at(oldSize) =  mimeType;
  mAcceptOutside.setBit(oldSize, outsideOk);
}

//-----------------------------------------------------------------------------
bool KFolderTree::acceptDrag( QDropEvent* event ) const
{
  QListViewItem* item = itemAt(contentsToViewport(event->pos()));

  for (uint i = 0; i < mAcceptableDropMimetypes.size(); i++)
  {
    if (event->provides(mAcceptableDropMimetypes[i]))
    {
      if (item)
        return (static_cast<KFolderTreeItem*>(item))->acceptDrag(event);
      else
        return mAcceptOutside[i];
    }
  }
  return false;
}

//-----------------------------------------------------------------------------
void KFolderTree::addUnreadColumn( const QString & name, int width )
{
  mUnreadIndex = addColumn( name, width );
  setColumnAlignment( mUnreadIndex, qApp->reverseLayout() ? Qt::AlignLeft : Qt::AlignRight );
}

//-----------------------------------------------------------------------------
void KFolderTree::addTotalColumn( const QString & name, int width )
{
  mTotalIndex = addColumn( name, width );
  setColumnAlignment( mTotalIndex, qApp->reverseLayout() ? Qt::AlignLeft : Qt::AlignRight );
}

//-----------------------------------------------------------------------------
void KFolderTree::removeUnreadColumn()
{
  if ( !isUnreadActive() ) return;
  removeColumn( mUnreadIndex );
  if ( isTotalActive() && mTotalIndex > mUnreadIndex )
    mTotalIndex--;
  mUnreadIndex = -1;
  header()->adjustHeaderSize();
}

//-----------------------------------------------------------------------------
void KFolderTree::removeTotalColumn()
{
  if ( !isTotalActive() ) return;
  removeColumn( mTotalIndex );
  if ( isUnreadActive() && mTotalIndex < mUnreadIndex )
    mUnreadIndex--;
  mTotalIndex = -1;
  header()->adjustHeaderSize();
}

//-----------------------------------------------------------------------------
void KFolderTree::setFullWidth( bool fullWidth )
{
  if (fullWidth)
    header()->setStretchEnabled( true, 0 );
}

#include "kfoldertree.moc"
<commit_msg>CCMAIL: zack@kde.org Explicit handling of the "Search" protocol in KFolderTreeItem::key().<commit_after>#include "kfoldertree.h"
#include <klocale.h>
#include <kiconloader.h>
#include <kdebug.h>
#include <qpainter.h>
#include <qapplication.h>
#include <qheader.h>

//-----------------------------------------------------------------------------
KFolderTreeItem::KFolderTreeItem( KFolderTree *parent, const QString & label,
				  Protocol protocol, Type type )
  : KListViewItem( parent, label ), mProtocol( protocol ), mType( type ),
    mUnread(-1), mTotal(0)
{
}

//-----------------------------------------------------------------------------
KFolderTreeItem::KFolderTreeItem( KFolderTreeItem *parent,
				  const QString & label, Protocol protocol, Type type,
          int unread, int total )
    : KListViewItem( parent, label ), mProtocol( protocol ), mType( type ),
      mUnread( unread ), mTotal( total )
{
}

//-----------------------------------------------------------------------------
QString KFolderTreeItem::key(int column, bool) const
{
  if ( column > 0 ) return text(column);

  // local root-folder
  if ( !parent() && mProtocol == NONE )
    return "\t0";

  QString thiskey;

  /* basic sorting rules:
     local => imap => news => other
   */
  if (mProtocol == Local)
    thiskey = "\t1";
  else if (mProtocol == CachedImap)
    thiskey = "\t2";
  else if (mProtocol == Imap)
    thiskey = "\t3";
  else if (mProtocol == News)
    thiskey = "\t4";
  else if (mProtocol == Search)
    thiskey = "\t5";
  else
    thiskey = "\t6";

  // make sure system folders come first when sorting
  if (mType == Inbox)
    thiskey += "\t0";
  else if (mType == Outbox)
    thiskey += "\t1";
  else if (mType == SentMail)
    thiskey += "\t2";
  else if (mType == Trash)
    thiskey += "\t3";
  else if (mType == Drafts)
    thiskey += "\t4";
  else if (mType == Calendar)
    thiskey += "\t5";
  else if (mType == Contacts)
    thiskey += "\t6";
  else if (mType == Notes)
    thiskey += "\t7";
  else if (mType == Tasks)
    thiskey += "\t8";

  // the displayed text
  thiskey += text(0);

  return thiskey;
}

//-----------------------------------------------------------------------------
int KFolderTreeItem::compare( QListViewItem * i, int col, bool ascending ) const
{
  if (col == 0)
  {
    // sort by folder
    return key(col, ascending).localeAwareCompare( i->key(col, ascending) );
  }
  else
  {
    // sort by unread or total-column
    int a = 0, b = 0;
    if (col == static_cast<KFolderTree*>(listView())->unreadIndex())
    {
      a = mUnread;
      b = static_cast<KFolderTreeItem*>(i)->unreadCount();
    }
    else if (col == static_cast<KFolderTree*>(listView())->totalIndex())
    {
      a = mTotal;
      b = static_cast<KFolderTreeItem*>(i)->totalCount();
    }

    if ( a == b )
      return 0;
    else
      return (a < b ? -1 : 1);
  }
}

//-----------------------------------------------------------------------------
void KFolderTreeItem::setUnreadCount( int aUnread )
{
  if ( aUnread < 0 ) return;

  mUnread = aUnread;

  QString unread = QString::null;
  if (mUnread == 0)
    unread = "- ";
  else {
    unread.setNum(mUnread);
    unread += " ";
  }

  setText( static_cast<KFolderTree*>(listView())->unreadIndex(),
      unread );
}

//-----------------------------------------------------------------------------
void KFolderTreeItem::setTotalCount( int aTotal )
{
  if ( aTotal < 0 ) return;

  mTotal = aTotal;

  QString total = QString::null;
  if (mTotal == 0)
    total = "- ";
  else {
    total.setNum(mTotal);
    total += " ";
  }

  setText( static_cast<KFolderTree*>(listView())->totalIndex(),
      total );
}

//-----------------------------------------------------------------------------
int KFolderTreeItem::countUnreadRecursive()
{
  int count = (mUnread > 0) ? mUnread : 0;

  for ( QListViewItem *item = firstChild() ;
      item ; item = item->nextSibling() )
  {
    count += static_cast<KFolderTreeItem*>(item)->countUnreadRecursive();
  }

  return count;
}

//-----------------------------------------------------------------------------
void KFolderTreeItem::paintCell( QPainter * p, const QColorGroup & cg,
                                  int column, int width, int align )
{
  QListView *lv = listView();
  QString oldText = text(column);

  // set an empty text so that we can have our own implementation (see further down)
  // but still benefit from KListView::paintCell
  setText( column, "" );

  KListViewItem::paintCell( p, cg, column, width, align );

  KFolderTree *ft = static_cast<KFolderTree*>(listView());
  int r = lv ? lv->itemMargin() : 1;
  const QPixmap *icon = pixmap( column );
  int marg = lv ? lv->itemMargin() : 1;

  QString t;
  QRect br;
  setText( column, oldText );
  if ( isSelected() )
    p->setPen( cg.highlightedText() );
  else
    p->setPen( ft->paintInfo().colFore );

  if ( icon ) {
    r += icon->width() + lv->itemMargin();
  }
  t = text( column );
  if ( !t.isEmpty() )
  {
    // use a bold-font for the folder- and the unread-columns
    if ( countUnreadRecursive() > 0 &&
        (column == 0 || column == ft->unreadIndex()) )
    {
      QFont f = p->font();
      f.setWeight(QFont::Bold);
      p->setFont(f);
    }
    p->drawText( r, 0, width-marg-r, height(),
        align | AlignVCenter, t, -1, &br );
    if (!isSelected())
      p->setPen( ft->paintInfo().colUnread );
    if (column == 0) {
      // draw the unread-count if the unread-column is not active
      QString unread = QString::null;
      if ( !ft->isUnreadActive() && mUnread > 0 )
        unread = " (" + QString::number(mUnread) + ")";
      p->drawText( br.right(), 0, width-marg-br.right(), height(),
          align | AlignVCenter, unread );
    }
  } // end !t.isEmpty()
}

//=============================================================================

KFolderTree::KFolderTree( QWidget *parent, const char* name )
  : KListView( parent, name ), mUnreadIndex(-1), mTotalIndex(-1)
{
  // GUI-options
  setLineWidth(0);
  setAcceptDrops(true);
  setDropVisualizer(false);
  setAllColumnsShowFocus(true);
  setShowSortIndicator(true);
  setUpdatesEnabled(true);
  setItemsRenameable(false);
  setRootIsDecorated(true);
  setSelectionModeExt(Extended);
  setAlternateBackground(QColor());
  setFullWidth(true);
}

//-----------------------------------------------------------------------------
void KFolderTree::drawContentsOffset( QPainter * p, int ox, int oy,
                                       int cx, int cy, int cw, int ch )
{
  bool oldUpdatesEnabled = isUpdatesEnabled();
  setUpdatesEnabled(false);
  KListView::drawContentsOffset( p, ox, oy, cx, cy, cw, ch );
  setUpdatesEnabled(oldUpdatesEnabled);
}

//-----------------------------------------------------------------------------
void KFolderTree::contentsMousePressEvent( QMouseEvent *e )
{
    setSelectionModeExt(Single);
    KListView::contentsMousePressEvent(e);
}

//-----------------------------------------------------------------------------
void KFolderTree::contentsMouseReleaseEvent( QMouseEvent *e )
{
    KListView::contentsMouseReleaseEvent(e);
    setSelectionModeExt(Extended);
}

//-----------------------------------------------------------------------------
void KFolderTree::addAcceptableDropMimetype( const char *mimeType, bool outsideOk )
{
  int oldSize = mAcceptableDropMimetypes.size();
  mAcceptableDropMimetypes.resize(oldSize+1);
  mAcceptOutside.resize(oldSize+1);

  mAcceptableDropMimetypes.at(oldSize) =  mimeType;
  mAcceptOutside.setBit(oldSize, outsideOk);
}

//-----------------------------------------------------------------------------
bool KFolderTree::acceptDrag( QDropEvent* event ) const
{
  QListViewItem* item = itemAt(contentsToViewport(event->pos()));

  for (uint i = 0; i < mAcceptableDropMimetypes.size(); i++)
  {
    if (event->provides(mAcceptableDropMimetypes[i]))
    {
      if (item)
        return (static_cast<KFolderTreeItem*>(item))->acceptDrag(event);
      else
        return mAcceptOutside[i];
    }
  }
  return false;
}

//-----------------------------------------------------------------------------
void KFolderTree::addUnreadColumn( const QString & name, int width )
{
  mUnreadIndex = addColumn( name, width );
  setColumnAlignment( mUnreadIndex, qApp->reverseLayout() ? Qt::AlignLeft : Qt::AlignRight );
}

//-----------------------------------------------------------------------------
void KFolderTree::addTotalColumn( const QString & name, int width )
{
  mTotalIndex = addColumn( name, width );
  setColumnAlignment( mTotalIndex, qApp->reverseLayout() ? Qt::AlignLeft : Qt::AlignRight );
}

//-----------------------------------------------------------------------------
void KFolderTree::removeUnreadColumn()
{
  if ( !isUnreadActive() ) return;
  removeColumn( mUnreadIndex );
  if ( isTotalActive() && mTotalIndex > mUnreadIndex )
    mTotalIndex--;
  mUnreadIndex = -1;
  header()->adjustHeaderSize();
}

//-----------------------------------------------------------------------------
void KFolderTree::removeTotalColumn()
{
  if ( !isTotalActive() ) return;
  removeColumn( mTotalIndex );
  if ( isUnreadActive() && mTotalIndex < mUnreadIndex )
    mUnreadIndex--;
  mTotalIndex = -1;
  header()->adjustHeaderSize();
}

//-----------------------------------------------------------------------------
void KFolderTree::setFullWidth( bool fullWidth )
{
  if (fullWidth)
    header()->setStretchEnabled( true, 0 );
}

#include "kfoldertree.moc"
<|endoftext|>


<commit_before>#include <test/unit/math/test_ad.hpp>

TEST(MathMixMatFun, subtract_1) {
  auto f
      = [](const auto& x, const auto& y) { return stan::math::subtract(x, y); };

  double d = 2;
  Eigen::MatrixXd m11(1, 1);
  m11 << 1;
  Eigen::MatrixXd m11b(1, 1);
  m11b << 10;
  Eigen::VectorXd v1(1);
  v1 << 2;
  Eigen::VectorXd v1b(1);
  v1b << -20;
  Eigen::RowVectorXd rv1(1);
  rv1 << 3;
  Eigen::RowVectorXd rv1b(1);
  rv1b << -3;
  stan::test::expect_ad(f, d, v1);
  stan::test::expect_ad(f, d, rv1);
  stan::test::expect_ad(f, d, m11);
  stan::test::expect_ad(f, v1, d);
  stan::test::expect_ad(f, rv1, d);
  stan::test::expect_ad(f, m11, d);
  stan::test::expect_ad(f, v1, v1b);
  stan::test::expect_ad(f, rv1, rv1b);
  stan::test::expect_ad(f, m11, m11b);
}

TEST(MathMixMatFun, subtract_empty) {
  auto f
      = [](const auto& x, const auto& y) { return stan::math::subtract(x, y); };

  double d = 2;
  Eigen::MatrixXd m00(0, 0);
  Eigen::MatrixXd m00b(0, 0);
  Eigen::VectorXd v0(0);
  Eigen::VectorXd v0b(0);
  Eigen::RowVectorXd rv0(0);
  Eigen::RowVectorXd rv0b(0);
  stan::test::expect_ad(f, d, v0);
  stan::test::expect_ad(f, d, rv0);
  stan::test::expect_ad(f, d, m00);
  stan::test::expect_ad(f, v0, d);
  stan::test::expect_ad(f, rv0, d);
  stan::test::expect_ad(f, m00, d);
  stan::test::expect_ad(f, v0, v0b);
  stan::test::expect_ad(f, rv0, rv0b);
  stan::test::expect_ad(f, m00, m00b);
}

TEST(MathMixMatFun, subtract_scalar_mat) {
  auto f
      = [](const auto& x, const auto& y) { return stan::math::subtract(x, y); };

  double d = 2;
  Eigen::MatrixXd m22(2, 2);
  m22 << 1, 2, 3, 4;
  Eigen::MatrixXd m22b(2, 2);
  m22b << 10, 20, 40, 100;
  Eigen::VectorXd v2(2);
  v2 << 10, 12;
  Eigen::VectorXd v2b(2);
  v2b << -1, -5;
  Eigen::RowVectorXd rv2(2);
  rv2 << 11, 15;
  Eigen::RowVectorXd rv2b(2);
  rv2b << 100, -1001;
  stan::test::expect_ad(f, d, v2);
  stan::test::expect_ad(f, d, rv2);
  stan::test::expect_ad(f, d, m22);
  stan::test::expect_ad(f, v2, d);
  stan::test::expect_ad(f, rv2, d);
  stan::test::expect_ad(f, m22, d);
  stan::test::expect_ad(f, v2, v2b);
  stan::test::expect_ad(f, rv2, rv2b);
  stan::test::expect_ad(f, m22b, m22b);
}

TEST(MathMixMatFun, subtract_vec_mat) {
  auto f
      = [](const auto& x, const auto& y) { return stan::math::subtract(x, y); };

  Eigen::VectorXd v5(5);
  v5 << 1, 2, 3, 4, 5;
  Eigen::VectorXd v5b(5);
  v5 << 2, 3, 4, 5, 6;
  Eigen::VectorXd rv5(5);
  v5 << 1, 2, 3, 4, 5;
  Eigen::VectorXd rv5b(5);
  v5 << 2, 3, 4, 5, 6;
  stan::test::expect_ad(f, v5, v5b);
  stan::test::expect_ad(f, rv5, rv5b);
}

TEST(MathMixMatFun, subtract_mat_mat) {
  auto f
      = [](const auto& x, const auto& y) { return stan::math::subtract(x, y); };

  Eigen::MatrixXd m22c(2, 2);
  m22c << -10, 1, 10, 0;
  Eigen::MatrixXd m22d(2, 2);
  m22d << 10, -10, 1, 2;
  stan::test::expect_ad(f, m22c, m22d);

  Eigen::MatrixXd m23(2, 3);
  m23 << 1, 2, 3, 4, 5, 6;
  Eigen::MatrixXd m23b(2, 3);
  m23b << 10, 12, 14, -1, -3, -10;
  stan::test::expect_ad(f, m23, m23b);
}

// these will throw
TEST(MathMixMatFun, subtract_throw) {
  auto f
      = [](const auto& x, const auto& y) { return stan::math::subtract(x, y); };

  Eigen::VectorXd v1(1);
  v1 << 2;
  Eigen::VectorXd v2(2);
  v2 << 10, 12;
  stan::test::expect_ad(f, v1, v2);

  Eigen::RowVectorXd rv1(1);
  rv1 << 3;
  Eigen::RowVectorXd rv2(2);
  rv2 << 11, 15;
  stan::test::expect_ad(f, rv1, rv2);

  Eigen::MatrixXd m22(2, 2);
  m22 << 1, 2, 3, 4;
  Eigen::MatrixXd m11(1, 1);
  m11 << 1;
  stan::test::expect_ad(f, m11, m22);
}
<commit_msg>increase tolerances in substract_vec_mat test<commit_after>#include <test/unit/math/test_ad.hpp>

TEST(MathMixMatFun, subtract_1) {
  auto f
      = [](const auto& x, const auto& y) { return stan::math::subtract(x, y); };

  double d = 2;
  Eigen::MatrixXd m11(1, 1);
  m11 << 1;
  Eigen::MatrixXd m11b(1, 1);
  m11b << 10;
  Eigen::VectorXd v1(1);
  v1 << 2;
  Eigen::VectorXd v1b(1);
  v1b << -20;
  Eigen::RowVectorXd rv1(1);
  rv1 << 3;
  Eigen::RowVectorXd rv1b(1);
  rv1b << -3;
  stan::test::expect_ad(f, d, v1);
  stan::test::expect_ad(f, d, rv1);
  stan::test::expect_ad(f, d, m11);
  stan::test::expect_ad(f, v1, d);
  stan::test::expect_ad(f, rv1, d);
  stan::test::expect_ad(f, m11, d);
  stan::test::expect_ad(f, v1, v1b);
  stan::test::expect_ad(f, rv1, rv1b);
  stan::test::expect_ad(f, m11, m11b);
}

TEST(MathMixMatFun, subtract_empty) {
  auto f
      = [](const auto& x, const auto& y) { return stan::math::subtract(x, y); };

  double d = 2;
  Eigen::MatrixXd m00(0, 0);
  Eigen::MatrixXd m00b(0, 0);
  Eigen::VectorXd v0(0);
  Eigen::VectorXd v0b(0);
  Eigen::RowVectorXd rv0(0);
  Eigen::RowVectorXd rv0b(0);
  stan::test::expect_ad(f, d, v0);
  stan::test::expect_ad(f, d, rv0);
  stan::test::expect_ad(f, d, m00);
  stan::test::expect_ad(f, v0, d);
  stan::test::expect_ad(f, rv0, d);
  stan::test::expect_ad(f, m00, d);
  stan::test::expect_ad(f, v0, v0b);
  stan::test::expect_ad(f, rv0, rv0b);
  stan::test::expect_ad(f, m00, m00b);
}

TEST(MathMixMatFun, subtract_scalar_mat) {
  auto f
      = [](const auto& x, const auto& y) { return stan::math::subtract(x, y); };

  double d = 2;
  Eigen::MatrixXd m22(2, 2);
  m22 << 1, 2, 3, 4;
  Eigen::MatrixXd m22b(2, 2);
  m22b << 10, 20, 40, 100;
  Eigen::VectorXd v2(2);
  v2 << 10, 12;
  Eigen::VectorXd v2b(2);
  v2b << -1, -5;
  Eigen::RowVectorXd rv2(2);
  rv2 << 11, 15;
  Eigen::RowVectorXd rv2b(2);
  rv2b << 100, -1001;
  stan::test::expect_ad(f, d, v2);
  stan::test::expect_ad(f, d, rv2);
  stan::test::expect_ad(f, d, m22);
  stan::test::expect_ad(f, v2, d);
  stan::test::expect_ad(f, rv2, d);
  stan::test::expect_ad(f, m22, d);
  stan::test::expect_ad(f, v2, v2b);
  stan::test::expect_ad(f, rv2, rv2b);
  stan::test::expect_ad(f, m22b, m22b);
}

TEST(MathMixMatFun, subtract_vec_mat) {
  auto f
      = [](const auto& x, const auto& y) { return stan::math::subtract(x, y); };
  stan::test::ad_tolerances tols;
  tols.hessian_hessian_ = 5e-3;
  tols.hessian_fvar_hessian_ = 5e-3;

  Eigen::VectorXd v5(5);
  v5 << 1, 2, 3, 4, 5;
  Eigen::VectorXd v5b(5);
  v5 << 2, 3, 4, 5, 6;
  Eigen::VectorXd rv5(5);
  v5 << 1, 2, 3, 4, 5;
  Eigen::VectorXd rv5b(5);
  v5 << 2, 3, 4, 5, 6;
  stan::test::expect_ad(tols, f, v5, v5b);
  stan::test::expect_ad(tols, f, rv5, rv5b);
}

TEST(MathMixMatFun, subtract_mat_mat) {
  auto f
      = [](const auto& x, const auto& y) { return stan::math::subtract(x, y); };

  Eigen::MatrixXd m22c(2, 2);
  m22c << -10, 1, 10, 0;
  Eigen::MatrixXd m22d(2, 2);
  m22d << 10, -10, 1, 2;
  stan::test::expect_ad(f, m22c, m22d);

  Eigen::MatrixXd m23(2, 3);
  m23 << 1, 2, 3, 4, 5, 6;
  Eigen::MatrixXd m23b(2, 3);
  m23b << 10, 12, 14, -1, -3, -10;
  stan::test::expect_ad(f, m23, m23b);
}

// these will throw
TEST(MathMixMatFun, subtract_throw) {
  auto f
      = [](const auto& x, const auto& y) { return stan::math::subtract(x, y); };

  Eigen::VectorXd v1(1);
  v1 << 2;
  Eigen::VectorXd v2(2);
  v2 << 10, 12;
  stan::test::expect_ad(f, v1, v2);

  Eigen::RowVectorXd rv1(1);
  rv1 << 3;
  Eigen::RowVectorXd rv2(2);
  rv2 << 11, 15;
  stan::test::expect_ad(f, rv1, rv2);

  Eigen::MatrixXd m22(2, 2);
  m22 << 1, 2, 3, 4;
  Eigen::MatrixXd m11(1, 1);
  m11 << 1;
  stan::test::expect_ad(f, m11, m22);
}
<|endoftext|>


<commit_before>#include <mettle.hpp>
using namespace mettle;

#include "run_counter.hpp"

namespace mettle {
  std::string to_printable(const test_result &result) {
    std::ostringstream ss;
    ss << "test_result(" << to_printable(result.passed) << ", "
       << to_printable(result.message) << ")";
    return ss.str();
  }
}

template<typename T, typename U>
auto equal_test_result(T &&result, U &&message) {
  auto res = ensure_matcher(std::forward<T>(result));
  auto msg = ensure_matcher(std::forward<U>(message));

  std::ostringstream ss;
  ss << "test_result(" << res.desc() << ", " << msg.desc() << ")";

  return make_matcher(
    [res = std::move(res), msg = std::move(msg)]
    (const auto &actual) -> bool {
      return res(actual.passed) && msg(actual.message);
    }, ss.str()
  );
}

struct basic_fixture {
  basic_fixture() = default;
  basic_fixture(const basic_fixture &) = delete;
  basic_fixture & operator =(const basic_fixture &) = delete;

  int data;
};

struct basic_factory {
  template<typename T>
  T make() {
    return { data };
  }

  int data = 0;
};

suite<> test_calling("test calling", [](auto &_) {

  _.test("passing test called", []() {
    run_counter<> test;
    auto s = make_suite<>("inner", [&test](auto &_){
      _.test("inner test", test);
    });

    auto result = s.tests()[0].function();
    expect(result, equal_test_result(true, ""));

    expect("test run count", test.runs(), equal_to(1));
  });

  _.test("failing test called", []() {
    run_counter<> test([]() {
      expect(false, equal_to(true));
    });
    auto s = make_suite<>("inner", [&test](auto &_){
      _.test("inner test", test);
    });

    auto result = s.tests()[0].function();
    expect(result, equal_test_result(
      false, regex_match("(.*\n)?expected: true\nactual:   false$")
    ));

    expect("test run count", test.runs(), equal_to(1));
  });

  _.test("setup and teardown called", []() {
    run_counter<> setup, teardown, test;
    auto s = make_suite<>("inner", [&setup, &teardown, &test](auto &_){
      _.setup(setup);
      _.teardown(teardown);
      _.test("inner test", test);
    });

    auto result = s.tests()[0].function();
    expect("test passed", result, equal_test_result(true, ""));

    expect("setup run count", setup.runs(), equal_to(1));
    expect("test run count", test.runs(), equal_to(1));
    expect("teardown run count", teardown.runs(), equal_to(1));
  });

  _.test("teardown called when test fails", []() {
    run_counter<> setup, teardown;
    run_counter<> test([]() {
      expect(false, equal_to(true));
    });
    auto s = make_suite<>("inner", [&setup, &teardown, &test](auto &_){
      _.setup(setup);
      _.teardown(teardown);
      _.test("inner test", test);
    });

    auto result = s.tests()[0].function();
    expect(result, equal_test_result(
      false, regex_match("(.*\n)?expected: true\nactual:   false$")
    ));

    expect("setup run count", setup.runs(), equal_to(1));
    expect("test run count", test.runs(), equal_to(1));
    expect("teardown run count", teardown.runs(), equal_to(1));
  });

  _.test("teardown not called when setup fails", []() {
    run_counter<> setup([]() {
      expect(false, equal_to(true));
    });
    run_counter<> teardown, test;
    auto s = make_suite<>("inner", [&setup, &teardown, &test](auto &_){
      _.setup(setup);
      _.teardown(teardown);
      _.test("inner test", test);
    });

    auto result = s.tests()[0].function();
    expect(result, equal_test_result(
      false, regex_match("(.*\n)?expected: true\nactual:   false$")
    ));

    expect("setup run count", setup.runs(), equal_to(1));
    expect("test run count", test.runs(), equal_to(0));
    expect("teardown run count", teardown.runs(), equal_to(0));
  });

  _.test("test fails when teardown fails", []() {
    run_counter<> teardown([]() {
      expect(false, equal_to(true));
    });
    run_counter<> setup, test;
    auto s = make_suite<>("inner", [&setup, &teardown, &test](auto &_){
      _.setup(setup);
      _.teardown(teardown);
      _.test("inner test", test);
    });

    auto result = s.tests()[0].function();
    expect(result, equal_test_result(
      false, regex_match("(.*\n)?expected: true\nactual:   false$")
    ));

    expect("setup run count", setup.runs(), equal_to(1));
    expect("test run count", test.runs(), equal_to(1));
    expect("teardown run count", teardown.runs(), equal_to(1));
  });

  _.test("test failure reported if test and teardown fail", []() {
    run_counter<> setup;
    run_counter<> teardown([]() {
      expect(std::string("teardown"), equal_to("foo"));
    });
    run_counter<> test([]() {
      expect(std::string("test"), equal_to("foo"));
    });
    auto s = make_suite<>("inner", [&setup, &teardown, &test](auto &_){
      _.setup(setup);
      _.teardown(teardown);
      _.test("inner test", test);
    });

    auto result = s.tests()[0].function();
    expect(result, equal_test_result(
      false, regex_match("(.*\n)?expected: \"foo\"\nactual:   \"test\"$")
    ));

    expect("setup run count", setup.runs(), equal_to(1));
    expect("test run count", test.runs(), equal_to(1));
    expect("teardown run count", teardown.runs(), equal_to(1));
  });

});

// XXX: Enable these tests on MSVC (they trigger an ICE somewhere).
#if !defined(_MSC_VER) || defined(__clang__)

suite<basic_fixture> test_fixtures("suite fixtures", [](auto &_) {

  _.template subsuite<int>("subsuite", type_only, [](auto &_) {
    _.setup([](basic_fixture &f) {
      f.data++;
    });

    _.test("outer fixture was passed by reference", [](basic_fixture &f) {
      expect(f.data, equal_to(2));
    });

    _.template subsuite<basic_fixture>("sub-subsuite", basic_factory{5},
                                       [](auto &_) {
      _.setup([](basic_fixture &f, basic_fixture &) {
        f.data++;
      });

      _.test("outer fixture was passed by reference",
             [](basic_fixture &f, basic_fixture &) {
        expect(f.data, equal_to(3));
      });

      _.test("inner fixture was constructed by factory",
             [](basic_fixture &, basic_fixture &f2) {
        expect(f2.data, equal_to(5));
      });

    });

  });

  // Put the setup after the subsuite is created to ensure that order doesn't
  // matter.
  _.setup([](basic_fixture &f) {
    f.data = 1;
  });

});

#endif
<commit_msg>Fix test_suite_execution.cpp on MSVC<commit_after>#include <mettle.hpp>
using namespace mettle;

#include "run_counter.hpp"

namespace mettle {
  std::string to_printable(const test_result &result) {
    std::ostringstream ss;
    ss << "test_result(" << to_printable(result.passed) << ", "
       << to_printable(result.message) << ")";
    return ss.str();
  }
}

template<typename T, typename U>
auto equal_test_result(T &&result, U &&message) {
  auto res = ensure_matcher(std::forward<T>(result));
  auto msg = ensure_matcher(std::forward<U>(message));

  std::ostringstream ss;
  ss << "test_result(" << res.desc() << ", " << msg.desc() << ")";

  return make_matcher(
    [res = std::move(res), msg = std::move(msg)]
    (const auto &actual) -> bool {
      return res(actual.passed) && msg(actual.message);
    }, ss.str()
  );
}

struct basic_fixture {
  basic_fixture() = default;
  basic_fixture(const basic_fixture &) = delete;
  basic_fixture & operator =(const basic_fixture &) = delete;

  int data;
};

struct basic_factory {
  basic_factory(int data) : data(data) {}

  template<typename T>
  T make() {
    return { data };
  }

  int data = 0;
};

suite<> test_calling("test calling", [](auto &_) {

  _.test("passing test called", []() {
    run_counter<> test;
    auto s = make_suite<>("inner", [&test](auto &_){
      _.test("inner test", test);
    });

    auto result = s.tests()[0].function();
    expect(result, equal_test_result(true, ""));

    expect("test run count", test.runs(), equal_to(1));
  });

  _.test("failing test called", []() {
    run_counter<> test([]() {
      expect(false, equal_to(true));
    });
    auto s = make_suite<>("inner", [&test](auto &_){
      _.test("inner test", test);
    });

    auto result = s.tests()[0].function();
    expect(result, equal_test_result(
      false, regex_match("(.*\n)?expected: true\nactual:   false$")
    ));

    expect("test run count", test.runs(), equal_to(1));
  });

  _.test("setup and teardown called", []() {
    run_counter<> setup, teardown, test;
    auto s = make_suite<>("inner", [&setup, &teardown, &test](auto &_){
      _.setup(setup);
      _.teardown(teardown);
      _.test("inner test", test);
    });

    auto result = s.tests()[0].function();
    expect("test passed", result, equal_test_result(true, ""));

    expect("setup run count", setup.runs(), equal_to(1));
    expect("test run count", test.runs(), equal_to(1));
    expect("teardown run count", teardown.runs(), equal_to(1));
  });

  _.test("teardown called when test fails", []() {
    run_counter<> setup, teardown;
    run_counter<> test([]() {
      expect(false, equal_to(true));
    });
    auto s = make_suite<>("inner", [&setup, &teardown, &test](auto &_){
      _.setup(setup);
      _.teardown(teardown);
      _.test("inner test", test);
    });

    auto result = s.tests()[0].function();
    expect(result, equal_test_result(
      false, regex_match("(.*\n)?expected: true\nactual:   false$")
    ));

    expect("setup run count", setup.runs(), equal_to(1));
    expect("test run count", test.runs(), equal_to(1));
    expect("teardown run count", teardown.runs(), equal_to(1));
  });

  _.test("teardown not called when setup fails", []() {
    run_counter<> setup([]() {
      expect(false, equal_to(true));
    });
    run_counter<> teardown, test;
    auto s = make_suite<>("inner", [&setup, &teardown, &test](auto &_){
      _.setup(setup);
      _.teardown(teardown);
      _.test("inner test", test);
    });

    auto result = s.tests()[0].function();
    expect(result, equal_test_result(
      false, regex_match("(.*\n)?expected: true\nactual:   false$")
    ));

    expect("setup run count", setup.runs(), equal_to(1));
    expect("test run count", test.runs(), equal_to(0));
    expect("teardown run count", teardown.runs(), equal_to(0));
  });

  _.test("test fails when teardown fails", []() {
    run_counter<> teardown([]() {
      expect(false, equal_to(true));
    });
    run_counter<> setup, test;
    auto s = make_suite<>("inner", [&setup, &teardown, &test](auto &_){
      _.setup(setup);
      _.teardown(teardown);
      _.test("inner test", test);
    });

    auto result = s.tests()[0].function();
    expect(result, equal_test_result(
      false, regex_match("(.*\n)?expected: true\nactual:   false$")
    ));

    expect("setup run count", setup.runs(), equal_to(1));
    expect("test run count", test.runs(), equal_to(1));
    expect("teardown run count", teardown.runs(), equal_to(1));
  });

  _.test("test failure reported if test and teardown fail", []() {
    run_counter<> setup;
    run_counter<> teardown([]() {
      expect(std::string("teardown"), equal_to("foo"));
    });
    run_counter<> test([]() {
      expect(std::string("test"), equal_to("foo"));
    });
    auto s = make_suite<>("inner", [&setup, &teardown, &test](auto &_){
      _.setup(setup);
      _.teardown(teardown);
      _.test("inner test", test);
    });

    auto result = s.tests()[0].function();
    expect(result, equal_test_result(
      false, regex_match("(.*\n)?expected: \"foo\"\nactual:   \"test\"$")
    ));

    expect("setup run count", setup.runs(), equal_to(1));
    expect("test run count", test.runs(), equal_to(1));
    expect("teardown run count", teardown.runs(), equal_to(1));
  });

});

suite<basic_fixture> test_fixtures("suite fixtures", [](auto &_) {

  subsuite<int>(_, "subsuite", type_only, [](auto &_) {
    _.setup([](basic_fixture &f) {
      f.data++;
    });

    _.test("outer fixture was passed by reference", [](basic_fixture &f) {
      expect(f.data, equal_to(2));
    });

    subsuite<basic_fixture>(_, "sub-subsuite", basic_factory(5), [](auto &_) {
      _.setup([](basic_fixture &f, basic_fixture &) {
        f.data++;
      });

      _.test("outer fixture was passed by reference",
             [](basic_fixture &f, basic_fixture &) {
        expect(f.data, equal_to(3));
      });

      _.test("inner fixture was constructed by factory",
             [](basic_fixture &, basic_fixture &f2) {
        expect(f2.data, equal_to(5));
      });

    });

  });

  // Put the setup after the subsuite is created to ensure that order doesn't
  // matter.
  _.setup([](basic_fixture &f) {
    f.data = 1;
  });

});
<|endoftext|>


<commit_before>#define BOOST_TEST_MODULE ButlerVolmerKinetics
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <cmath>
#include <iostream>
#include <fstream>

double const TOLERANCE = 1.0e-6;

BOOST_AUTO_TEST_CASE( test_butler_volmer_kinetic )
{
    double const faraday_constant                     =   9.64853365e4;
    double const gas_constant                         =   8.3144621;
    double const boltzmann_constant                   =   8.6173324e-5;
    double const temperature                          = 300.0;
    double const anodic_charge_transfer_coefficient   =   0.5;
    double const cathodic_charge_transfer_coefficient =   0.5;
    double const exchange_current_density             =   1.0;
    BOOST_CHECK_CLOSE(
        faraday_constant/(gas_constant*temperature),
        1.0/(boltzmann_constant*temperature),
        TOLERANCE);
    std::cout<<boost::format("  %15.7e  %15.7e  \n")
        % static_cast<double>(faraday_constant/(gas_constant*temperature))
        % static_cast<double>(1.0/(boltzmann_constant*temperature))
        ;

    std::fstream fout;
    fout.open("butler_volmer_kinetics_data", std::fstream::out);

    std::shared_ptr<boost::property_tree::ptree> database =
        std::make_shared<boost::property_tree::ptree>();
    read_xml("input_butler_volmer_kinetics", *database);

    double const overpotential_lower_limit = database->get<double>("overpotential_lower_limit");
    double const overpotential_upper_limit = database->get<double>("overpotential_upper_limit");
    int    const n_points                  = database->get<int   >("n_points"                 );
    double const step = (overpotential_upper_limit - overpotential_lower_limit) / (n_points + 1);
    for (double overpotential = overpotential_lower_limit;
        overpotential <= overpotential_upper_limit;
        overpotential += step)
    {
        fout<<boost::format("  %10.7f  %15.7e  %15.7e  \n")
            % overpotential
            % static_cast<double>(
                exchange_current_density *
                (std::exp(anodic_charge_transfer_coefficient * overpotential / (boltzmann_constant*temperature))
                - std::exp(- cathodic_charge_transfer_coefficient * overpotential / (boltzmann_constant*temperature)))
              )
            % static_cast<double>(
                exchange_current_density *
                (anodic_charge_transfer_coefficient + cathodic_charge_transfer_coefficient)
                    * overpotential / (boltzmann_constant*temperature)
              )
            ;

    }

    fout.close();
}
<commit_msg>update test butler volmer kin for new boost test<commit_after>#define BOOST_TEST_MODULE ButlerVolmerKinetics
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <cmath>
#include <iostream>
#include <fstream>

BOOST_AUTO_TEST_CASE( test_butler_volmer_kinetic )
{
    double const faraday_constant                     =   9.64853365e4;
    double const gas_constant                         =   8.3144621;
    double const boltzmann_constant                   =   8.6173324e-5;
    double const temperature                          = 300.0;
    double const anodic_charge_transfer_coefficient   =   0.5;
    double const cathodic_charge_transfer_coefficient =   0.5;
    double const exchange_current_density             =   1.0;
    BOOST_TEST(
        faraday_constant/(gas_constant*temperature) ==
        1.0/(boltzmann_constant*temperature),
        boost::test_tools::tolerance(1.0e-6));
    std::cout<<boost::format("  %15.7e  %15.7e  \n")
        % static_cast<double>(faraday_constant/(gas_constant*temperature))
        % static_cast<double>(1.0/(boltzmann_constant*temperature))
        ;

    std::fstream fout;
    fout.open("butler_volmer_kinetics_data", std::fstream::out);

    std::shared_ptr<boost::property_tree::ptree> database =
        std::make_shared<boost::property_tree::ptree>();
    read_xml("input_butler_volmer_kinetics", *database);

    double const overpotential_lower_limit = database->get<double>("overpotential_lower_limit");
    double const overpotential_upper_limit = database->get<double>("overpotential_upper_limit");
    int    const n_points                  = database->get<int   >("n_points"                 );
    double const step = (overpotential_upper_limit - overpotential_lower_limit) / (n_points + 1);
    for (double overpotential = overpotential_lower_limit;
        overpotential <= overpotential_upper_limit;
        overpotential += step)
    {
        fout<<boost::format("  %10.7f  %15.7e  %15.7e  \n")
            % overpotential
            % static_cast<double>(
                exchange_current_density *
                (std::exp(anodic_charge_transfer_coefficient * overpotential / (boltzmann_constant*temperature))
                - std::exp(- cathodic_charge_transfer_coefficient * overpotential / (boltzmann_constant*temperature)))
              )
            % static_cast<double>(
                exchange_current_density *
                (anodic_charge_transfer_coefficient + cathodic_charge_transfer_coefficient)
                    * overpotential / (boltzmann_constant*temperature)
              )
            ;

    }

    fout.close();
}
<|endoftext|>


<commit_before>/**
 * This file is part of the CernVM File System.
 */

#include <gtest/gtest.h>

#include <session_context.h>

using namespace upload;
typedef SessionContext::Stats Stats;

class T_SessionContext : public ::testing::Test {};

TEST_F(T_SessionContext, BasicLifeCycle) {
  SessionContext ctx;
  EXPECT_TRUE(ctx.Initialize("http://my.repo.address:8080/api/v1",
                             "/path/to/the/session_file"));

  Stats stats = ctx.stats();

  EXPECT_EQ(stats.buckets_created, 0u);
  EXPECT_EQ(stats.buckets_committed, 0u);
  EXPECT_EQ(stats.objects_dispatched, 0u);
  EXPECT_EQ(stats.bytes_committed, 0u);
  EXPECT_EQ(stats.bytes_dispatched, 0u);

  EXPECT_TRUE(ctx.FinalizeSession());
}
<commit_msg>T_SessionContext - add basic lifecycle test<commit_after>/**
 * This file is part of the CernVM File System.
 */

#include <gtest/gtest.h>

#include <session_context.h>

using namespace upload;

class SessionContextMocked : public SessionContext {
  virtual Future<bool>* DispatchObjectPack(ObjectPack* pack) {
    delete pack;  // Discard object pack

    // Just return a completed future saying everything is "fine" (TM)
    Future<bool>* future = new Future<bool>();
    future->Set(true);
    return future;
  }
};

typedef SessionContext::Stats Stats;

class T_SessionContext : public ::testing::Test {};

TEST_F(T_SessionContext, BasicLifeCycle) {
  SessionContextMocked ctx;
  EXPECT_TRUE(ctx.Initialize("http://my.repo.address:8080/api/v1",
                             "/path/to/the/session_file"));

  Stats stats = ctx.stats();

  EXPECT_EQ(stats.buckets_created, 0u);
  EXPECT_EQ(stats.buckets_committed, 0u);
  EXPECT_EQ(stats.objects_dispatched, 0u);
  EXPECT_EQ(stats.bytes_committed, 0u);
  EXPECT_EQ(stats.bytes_dispatched, 0u);

  ObjectPack::BucketHandle hd = ctx.NewBucket();
  stats = ctx.stats();
  EXPECT_EQ(stats.buckets_created, 1u);

  unsigned char buffer[4096];
  memset(buffer, 0, 4096);
  ObjectPack::AddToBucket(buffer, 4096, hd);

  shash::Any hash(shash::kSha1);
  EXPECT_TRUE(ctx.CommitBucket(ObjectPack::kCas, hash, hd));
  ctx.Dispatch();
  stats = ctx.stats();
  EXPECT_EQ(stats.buckets_committed, 1u);
  EXPECT_EQ(stats.bytes_committed, 4096u);
  EXPECT_EQ(stats.objects_dispatched, 1u);
  EXPECT_EQ(stats.bytes_dispatched, 4096u);

  EXPECT_TRUE(ctx.Finalize());
}
<|endoftext|>