<commit_before>// autogenerated file with codegen.pl

#include <cppunit/simpleheader.hxx>
#include <rtl/locale.hxx>
#include <osl/thread.h>

namespace rtl_locale
{
    // default locale for test purpose
    void setDefaultLocale()
    {
        rtl::OLocale::setDefault(rtl::OUString::createFromAscii("de"), rtl::OUString::createFromAscii("DE"), /* rtl::OUString() */ rtl::OUString::createFromAscii("hochdeutsch") );
    }

class getDefault : public CppUnit::TestFixture
{
public:
    // initialise your test code values here.
    void setUp()
    {
    }

    void tearDown()
    {
    }

    // insert your test code here.
    void getDefault_000()
    {
        // this is demonstration code
        // CPPUNIT_ASSERT_MESSAGE("a message", 1 == 1);

        // due to the fact, we set the default locale at first, this test is no longer possible
       // ::rtl::OLocale aLocale = ::rtl::OLocale::getDefault();
        // CPPUNIT_ASSERT_MESSAGE("locale must be null", aLocale.getData() == NULL);

    }

    void getDefault_001()
    {
        // rtl::OLocale::setDefault(rtl::OUString::createFromAscii("de"), rtl::OUString::createFromAscii("DE"), rtl::OUString());
       rtl::OLocale aLocale = ::rtl::OLocale::getDefault();
        CPPUNIT_ASSERT_MESSAGE("locale must not null", aLocale.getData() != NULL);
    }

    // Change the following lines only, if you add, remove or rename
    // member functions of the current class,
    // because these macros are need by auto register mechanism.

    CPPUNIT_TEST_SUITE(getDefault);
    CPPUNIT_TEST(getDefault_000);
    CPPUNIT_TEST(getDefault_001);
    CPPUNIT_TEST_SUITE_END();
}; // class getDefault

class setDefault : public CppUnit::TestFixture
{
public:
    // initialise your test code values here.
    void setUp()
    {
    }

    void tearDown()
    {
        setDefaultLocale();
    }

    // insert your test code here.
    void setDefault_001()
    {
        rtl::OLocale::setDefault(rtl::OUString::createFromAscii("en"), rtl::OUString::createFromAscii("US"), rtl::OUString());
       rtl::OLocale aLocale = ::rtl::OLocale::getDefault();
        CPPUNIT_ASSERT_MESSAGE("locale must not null", aLocale.getData() != NULL);

        // be sure to not GPF
    }

    // Change the following lines only, if you add, remove or rename
    // member functions of the current class,
    // because these macros are need by auto register mechanism.

    CPPUNIT_TEST_SUITE(setDefault);
    CPPUNIT_TEST(setDefault_001);
    CPPUNIT_TEST_SUITE_END();
}; // class setDefault

class getLanguage : public CppUnit::TestFixture
{
public:
    // initialise your test code values here.
    void setUp()
    {
    }

    void tearDown()
    {
    }

    // insert your test code here.
    void getLanguage_001()
    {
       rtl::OLocale aLocale = ::rtl::OLocale::getDefault();
        rtl::OUString suLanguage = aLocale.getLanguage();
        t_print("Language: %s\n", rtl::OUStringToOString(suLanguage, osl_getThreadTextEncoding()).getStr());
        CPPUNIT_ASSERT_MESSAGE("locale language must be 'de'", suLanguage.equals(rtl::OUString::createFromAscii("de")));
    }
    void getLanguage_002()
    {
       rtl::OLocale aLocale = ::rtl::OLocale::getDefault();
        rtl::OUString suLanguage = rtl_locale_getLanguage(aLocale.getData());
        t_print("Language: %s\n", rtl::OUStringToOString(suLanguage, osl_getThreadTextEncoding()).getStr());
        CPPUNIT_ASSERT_MESSAGE("locale language must be 'de'", suLanguage.equals(rtl::OUString::createFromAscii("de")));
    }

    // Change the following lines only, if you add, remove or rename
    // member functions of the current class,
    // because these macros are need by auto register mechanism.

    CPPUNIT_TEST_SUITE(getLanguage);
    CPPUNIT_TEST(getLanguage_001);
    CPPUNIT_TEST(getLanguage_002);
    CPPUNIT_TEST_SUITE_END();
}; // class getLanguage

class getCountry : public CppUnit::TestFixture
{
public:
    // initialise your test code values here.
    void setUp()
    {
    }

    void tearDown()
    {
    }

    // insert your test code here.
    void getCountry_001()
    {
       rtl::OLocale aLocale = ::rtl::OLocale::getDefault();
        rtl::OUString suCountry = aLocale.getCountry();
        t_print("Country: %s\n", rtl::OUStringToOString(suCountry, osl_getThreadTextEncoding()).getStr());
        CPPUNIT_ASSERT_MESSAGE("locale country must be 'DE'", suCountry.equals(rtl::OUString::createFromAscii("DE")));
    }
    void getCountry_002()
    {
       rtl::OLocale aLocale = ::rtl::OLocale::getDefault();
        rtl::OUString suCountry = rtl_locale_getCountry(aLocale.getData());
        t_print("Country: %s\n", rtl::OUStringToOString(suCountry, osl_getThreadTextEncoding()).getStr());
        CPPUNIT_ASSERT_MESSAGE("locale country must be 'DE'", suCountry.equals(rtl::OUString::createFromAscii("DE")));
    }

    // Change the following lines only, if you add, remove or rename
    // member functions of the current class,
    // because these macros are need by auto register mechanism.

    CPPUNIT_TEST_SUITE(getCountry);
    CPPUNIT_TEST(getCountry_001);
    CPPUNIT_TEST(getCountry_002);
    CPPUNIT_TEST_SUITE_END();
}; // class getCountry

class getVariant : public CppUnit::TestFixture
{
public:
    // initialise your test code values here.
    void setUp()
    {
    }

    void tearDown()
    {
    }

    // insert your test code here.
    void getVariant_001()
    {
       rtl::OLocale aLocale = ::rtl::OLocale::getDefault();
        rtl::OUString suVariant = aLocale.getVariant();
        t_print("Variant: %s\n", rtl::OUStringToOString(suVariant, osl_getThreadTextEncoding()).getStr());
        CPPUNIT_ASSERT_MESSAGE("locale variant must be 'hochdeutsch'", suVariant.equals(rtl::OUString::createFromAscii("hochdeutsch")));
    }
    void getVariant_002()
    {
       rtl::OLocale aLocale = ::rtl::OLocale::getDefault();
        rtl::OUString suVariant = rtl_locale_getVariant(aLocale.getData());
        t_print("Variant: %s\n", rtl::OUStringToOString(suVariant, osl_getThreadTextEncoding()).getStr());
        CPPUNIT_ASSERT_MESSAGE("locale variant must be 'hochdeutsch'", suVariant.equals(rtl::OUString::createFromAscii("hochdeutsch")));
    }

    // Change the following lines only, if you add, remove or rename
    // member functions of the current class,
    // because these macros are need by auto register mechanism.

    CPPUNIT_TEST_SUITE(getVariant);
    CPPUNIT_TEST(getVariant_001);
    CPPUNIT_TEST(getVariant_002);
    CPPUNIT_TEST_SUITE_END();
}; // class getVariant

class hashCode : public CppUnit::TestFixture
{
public:
    // initialise your test code values here.
    void setUp()
    {
    }

    void tearDown()
    {
    }

    // insert your test code here.
    void hashCode_001()
    {
       rtl::OLocale aLocale = ::rtl::OLocale::getDefault();
        sal_Int32 nHashCode = aLocale.hashCode();
        t_print("Hashcode: %d\n", nHashCode);
        CPPUNIT_ASSERT_MESSAGE("locale hashcode must be 3831", nHashCode != 0);
    }
    void hashCode_002()
    {
       rtl::OLocale aLocale = ::rtl::OLocale::getDefault();
        sal_Int32 nHashCode = rtl_locale_hashCode(aLocale.getData());
        t_print("Hashcode: %d\n", nHashCode);
        CPPUNIT_ASSERT_MESSAGE("locale hashcode must be 3831", nHashCode != 0);
    }

    // Change the following lines only, if you add, remove or rename
    // member functions of the current class,
    // because these macros are need by auto register mechanism.

    CPPUNIT_TEST_SUITE(hashCode);
    CPPUNIT_TEST(hashCode_001);
    CPPUNIT_TEST(hashCode_002);
    CPPUNIT_TEST_SUITE_END();
}; // class hashCode

class equals : public CppUnit::TestFixture
{
public:
    // initialise your test code values here.
    void setUp()
    {
    }

    void tearDown()
    {
    }

    // insert your test code here.
    void equals_001()
    {
        rtl::OLocale aLocale1 = rtl::OLocale::registerLocale(rtl::OUString::createFromAscii("en"), rtl::OUString::createFromAscii("US"), rtl::OUString());
        rtl::OLocale aLocale2 = rtl::OLocale::registerLocale(rtl::OUString::createFromAscii("en"), rtl::OUString::createFromAscii("US"));

        sal_Bool bLocaleAreEqual = sal_False;
        bLocaleAreEqual = (aLocale1 == aLocale2);

        CPPUNIT_ASSERT_MESSAGE("check operator ==()", bLocaleAreEqual == sal_True);
    }

    void equals_002()
    {
        rtl::OLocale aLocale1 = rtl::OLocale::registerLocale(rtl::OUString::createFromAscii("en"), rtl::OUString::createFromAscii("US"), rtl::OUString());
        rtl::OLocale aLocale2 = rtl::OLocale::registerLocale(rtl::OUString::createFromAscii("en"), rtl::OUString::createFromAscii("US"));

        sal_Int32 nEqual = rtl_locale_equals(aLocale1.getData(), aLocale2.getData());
        t_print("rtl_locale_equals() result: %d\n", nEqual);
        CPPUNIT_ASSERT(nEqual != 0);
    }

    // Change the following lines only, if you add, remove or rename
    // member functions of the current class,
    // because these macros are need by auto register mechanism.

    CPPUNIT_TEST_SUITE(equals);
    CPPUNIT_TEST(equals_001);
    CPPUNIT_TEST(equals_002);
    CPPUNIT_TEST_SUITE_END();
}; // class equals

// -----------------------------------------------------------------------------
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_locale::getDefault, "rtl_locale");
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_locale::setDefault, "rtl_locale");
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_locale::getLanguage, "rtl_locale");
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_locale::getCountry, "rtl_locale");
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_locale::getVariant, "rtl_locale");
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_locale::hashCode, "rtl_locale");
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_locale::equals, "rtl_locale");
} // namespace rtl_locale

// -----------------------------------------------------------------------------

// this macro creates an empty function, which will called by the RegisterAllFunctions()
// to let the user the possibility to also register some functions by hand.
// NOADDITIONAL;

void RegisterAdditionalFunctions(FktRegFuncPtr _pFunc)
{
    // start message
    t_print("Initializing ...\n" );
    rtl_locale::setDefaultLocale();
    t_print("Initialization Done.\n" );
}
<commit_msg>INTEGRATION: CWS warnings01 (1.2.160); FILE MERGED 2005/09/15 12:35:42 sb 1.2.160.1: #i53898# Fixed previous change.<commit_after>// autogenerated file with codegen.pl

#include <cppunit/simpleheader.hxx>
#include <rtl/locale.hxx>
#include <osl/thread.h>

namespace rtl_locale
{
    // default locale for test purpose
    void setDefaultLocale()
    {
        rtl::OLocale::setDefault(rtl::OUString::createFromAscii("de"), rtl::OUString::createFromAscii("DE"), /* rtl::OUString() */ rtl::OUString::createFromAscii("hochdeutsch") );
    }

class getDefault : public CppUnit::TestFixture
{
public:
    // initialise your test code values here.
    void setUp()
    {
    }

    void tearDown()
    {
    }

    // insert your test code here.
    void getDefault_000()
    {
        // this is demonstration code
        // CPPUNIT_ASSERT_MESSAGE("a message", 1 == 1);

        // due to the fact, we set the default locale at first, this test is no longer possible
       // ::rtl::OLocale aLocale = ::rtl::OLocale::getDefault();
        // CPPUNIT_ASSERT_MESSAGE("locale must be null", aLocale.getData() == NULL);

    }

    void getDefault_001()
    {
        // rtl::OLocale::setDefault(rtl::OUString::createFromAscii("de"), rtl::OUString::createFromAscii("DE"), rtl::OUString());
       rtl::OLocale aLocale = ::rtl::OLocale::getDefault();
        CPPUNIT_ASSERT_MESSAGE("locale must not null", aLocale.getData() != NULL);
    }

    // Change the following lines only, if you add, remove or rename
    // member functions of the current class,
    // because these macros are need by auto register mechanism.

    CPPUNIT_TEST_SUITE(getDefault);
    CPPUNIT_TEST(getDefault_000);
    CPPUNIT_TEST(getDefault_001);
    CPPUNIT_TEST_SUITE_END();
}; // class getDefault

class setDefault : public CppUnit::TestFixture
{
public:
    // initialise your test code values here.
    void setUp()
    {
    }

    void tearDown()
    {
        setDefaultLocale();
    }

    // insert your test code here.
    void setDefault_001()
    {
        rtl::OLocale::setDefault(rtl::OUString::createFromAscii("en"), rtl::OUString::createFromAscii("US"), rtl::OUString());
       rtl::OLocale aLocale = ::rtl::OLocale::getDefault();
        CPPUNIT_ASSERT_MESSAGE("locale must not null", aLocale.getData() != NULL);

        // be sure to not GPF
    }

    // Change the following lines only, if you add, remove or rename
    // member functions of the current class,
    // because these macros are need by auto register mechanism.

    CPPUNIT_TEST_SUITE(setDefault);
    CPPUNIT_TEST(setDefault_001);
    CPPUNIT_TEST_SUITE_END();
}; // class setDefault

class getLanguage : public CppUnit::TestFixture
{
public:
    // initialise your test code values here.
    void setUp()
    {
    }

    void tearDown()
    {
    }

    // insert your test code here.
    void getLanguage_001()
    {
       rtl::OLocale aLocale = ::rtl::OLocale::getDefault();
        rtl::OUString suLanguage = aLocale.getLanguage();
        t_print("Language: %s\n", rtl::OUStringToOString(suLanguage, osl_getThreadTextEncoding()).getStr());
        CPPUNIT_ASSERT_MESSAGE("locale language must be 'de'", suLanguage.equals(rtl::OUString::createFromAscii("de")));
    }
    void getLanguage_002()
    {
       rtl::OLocale aLocale = ::rtl::OLocale::getDefault();
        rtl::OUString suLanguage = rtl_locale_getLanguage(aLocale.getData());
        t_print("Language: %s\n", rtl::OUStringToOString(suLanguage, osl_getThreadTextEncoding()).getStr());
        CPPUNIT_ASSERT_MESSAGE("locale language must be 'de'", suLanguage.equals(rtl::OUString::createFromAscii("de")));
    }

    // Change the following lines only, if you add, remove or rename
    // member functions of the current class,
    // because these macros are need by auto register mechanism.

    CPPUNIT_TEST_SUITE(getLanguage);
    CPPUNIT_TEST(getLanguage_001);
    CPPUNIT_TEST(getLanguage_002);
    CPPUNIT_TEST_SUITE_END();
}; // class getLanguage

class getCountry : public CppUnit::TestFixture
{
public:
    // initialise your test code values here.
    void setUp()
    {
    }

    void tearDown()
    {
    }

    // insert your test code here.
    void getCountry_001()
    {
       rtl::OLocale aLocale = ::rtl::OLocale::getDefault();
        rtl::OUString suCountry = aLocale.getCountry();
        t_print("Country: %s\n", rtl::OUStringToOString(suCountry, osl_getThreadTextEncoding()).getStr());
        CPPUNIT_ASSERT_MESSAGE("locale country must be 'DE'", suCountry.equals(rtl::OUString::createFromAscii("DE")));
    }
    void getCountry_002()
    {
       rtl::OLocale aLocale = ::rtl::OLocale::getDefault();
        rtl::OUString suCountry = rtl_locale_getCountry(aLocale.getData());
        t_print("Country: %s\n", rtl::OUStringToOString(suCountry, osl_getThreadTextEncoding()).getStr());
        CPPUNIT_ASSERT_MESSAGE("locale country must be 'DE'", suCountry.equals(rtl::OUString::createFromAscii("DE")));
    }

    // Change the following lines only, if you add, remove or rename
    // member functions of the current class,
    // because these macros are need by auto register mechanism.

    CPPUNIT_TEST_SUITE(getCountry);
    CPPUNIT_TEST(getCountry_001);
    CPPUNIT_TEST(getCountry_002);
    CPPUNIT_TEST_SUITE_END();
}; // class getCountry

class getVariant : public CppUnit::TestFixture
{
public:
    // initialise your test code values here.
    void setUp()
    {
    }

    void tearDown()
    {
    }

    // insert your test code here.
    void getVariant_001()
    {
       rtl::OLocale aLocale = ::rtl::OLocale::getDefault();
        rtl::OUString suVariant = aLocale.getVariant();
        t_print("Variant: %s\n", rtl::OUStringToOString(suVariant, osl_getThreadTextEncoding()).getStr());
        CPPUNIT_ASSERT_MESSAGE("locale variant must be 'hochdeutsch'", suVariant.equals(rtl::OUString::createFromAscii("hochdeutsch")));
    }
    void getVariant_002()
    {
       rtl::OLocale aLocale = ::rtl::OLocale::getDefault();
        rtl::OUString suVariant = rtl_locale_getVariant(aLocale.getData());
        t_print("Variant: %s\n", rtl::OUStringToOString(suVariant, osl_getThreadTextEncoding()).getStr());
        CPPUNIT_ASSERT_MESSAGE("locale variant must be 'hochdeutsch'", suVariant.equals(rtl::OUString::createFromAscii("hochdeutsch")));
    }

    // Change the following lines only, if you add, remove or rename
    // member functions of the current class,
    // because these macros are need by auto register mechanism.

    CPPUNIT_TEST_SUITE(getVariant);
    CPPUNIT_TEST(getVariant_001);
    CPPUNIT_TEST(getVariant_002);
    CPPUNIT_TEST_SUITE_END();
}; // class getVariant

class hashCode : public CppUnit::TestFixture
{
public:
    // initialise your test code values here.
    void setUp()
    {
    }

    void tearDown()
    {
    }

    // insert your test code here.
    void hashCode_001()
    {
       rtl::OLocale aLocale = ::rtl::OLocale::getDefault();
        sal_Int32 nHashCode = aLocale.hashCode();
        t_print("Hashcode: %d\n", nHashCode);
        CPPUNIT_ASSERT_MESSAGE("locale hashcode must be 3831", nHashCode != 0);
    }
    void hashCode_002()
    {
       rtl::OLocale aLocale = ::rtl::OLocale::getDefault();
        sal_Int32 nHashCode = rtl_locale_hashCode(aLocale.getData());
        t_print("Hashcode: %d\n", nHashCode);
        CPPUNIT_ASSERT_MESSAGE("locale hashcode must be 3831", nHashCode != 0);
    }

    // Change the following lines only, if you add, remove or rename
    // member functions of the current class,
    // because these macros are need by auto register mechanism.

    CPPUNIT_TEST_SUITE(hashCode);
    CPPUNIT_TEST(hashCode_001);
    CPPUNIT_TEST(hashCode_002);
    CPPUNIT_TEST_SUITE_END();
}; // class hashCode

class equals : public CppUnit::TestFixture
{
public:
    // initialise your test code values here.
    void setUp()
    {
    }

    void tearDown()
    {
    }

    // insert your test code here.
    void equals_001()
    {
        rtl::OLocale aLocale1 = rtl::OLocale::registerLocale(rtl::OUString::createFromAscii("en"), rtl::OUString::createFromAscii("US"), rtl::OUString());
        rtl::OLocale aLocale2 = rtl::OLocale::registerLocale(rtl::OUString::createFromAscii("en"), rtl::OUString::createFromAscii("US"));

        sal_Bool bLocaleAreEqual = sal_False;
        bLocaleAreEqual = (aLocale1 == aLocale2);

        CPPUNIT_ASSERT_MESSAGE("check operator ==()", bLocaleAreEqual == sal_True);
    }

    void equals_002()
    {
        rtl::OLocale aLocale1 = rtl::OLocale::registerLocale(rtl::OUString::createFromAscii("en"), rtl::OUString::createFromAscii("US"), rtl::OUString());
        rtl::OLocale aLocale2 = rtl::OLocale::registerLocale(rtl::OUString::createFromAscii("en"), rtl::OUString::createFromAscii("US"));

        sal_Int32 nEqual = rtl_locale_equals(aLocale1.getData(), aLocale2.getData());
        t_print("rtl_locale_equals() result: %d\n", nEqual);
        CPPUNIT_ASSERT(nEqual != 0);
    }

    // Change the following lines only, if you add, remove or rename
    // member functions of the current class,
    // because these macros are need by auto register mechanism.

    CPPUNIT_TEST_SUITE(equals);
    CPPUNIT_TEST(equals_001);
    CPPUNIT_TEST(equals_002);
    CPPUNIT_TEST_SUITE_END();
}; // class equals

// -----------------------------------------------------------------------------
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_locale::getDefault, "rtl_locale");
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_locale::setDefault, "rtl_locale");
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_locale::getLanguage, "rtl_locale");
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_locale::getCountry, "rtl_locale");
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_locale::getVariant, "rtl_locale");
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_locale::hashCode, "rtl_locale");
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_locale::equals, "rtl_locale");
} // namespace rtl_locale

// -----------------------------------------------------------------------------

// this macro creates an empty function, which will called by the RegisterAllFunctions()
// to let the user the possibility to also register some functions by hand.
// NOADDITIONAL;

void RegisterAdditionalFunctions(FktRegFuncPtr)
{
    // start message
    t_print("Initializing ...\n" );
    rtl_locale::setDefaultLocale();
    t_print("Initialization Done.\n" );
}
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "testwizard.h"
#include "testwizarddialog.h"

#include <cpptools/abstracteditorsupport.h>
#include <projectexplorer/projectexplorerconstants.h>

#include <utils/qtcassert.h>

#include <QtCore/QTextStream>
#include <QtCore/QFileInfo>

#include <QtGui/QIcon>

namespace Qt4ProjectManager {
namespace Internal {

TestWizard::TestWizard() :
    QtWizard(QLatin1String("L.Qt4Test"),
             QLatin1String(ProjectExplorer::Constants::PROJECT_WIZARD_CATEGORY),
             QLatin1String(ProjectExplorer::Constants::PROJECT_WIZARD_TR_SCOPE),
             QLatin1String(ProjectExplorer::Constants::PROJECT_WIZARD_TR_CATEGORY),
             tr("Qt Unit Test"),
             tr("Creates a QTestLib-based unit test for a feature or a class. "
                "Unit tests allow you to verify that the code is fit for use "
                "and that there are no regressions."),
             QIcon(QLatin1String(":/wizards/images/console.png")))
{
}

QWizard *TestWizard::createWizardDialog(QWidget *parent,
                                        const QString &defaultPath,
                                        const WizardPageList &extensionPages) const
{
    TestWizardDialog *dialog = new TestWizardDialog(displayName(), icon(), extensionPages, parent);
    dialog->setPath(defaultPath);
    dialog->setProjectName(TestWizardDialog::uniqueProjectName(defaultPath));
    return dialog;
}

// ---------------- code generation helpers
static const char initTestCaseC[] = "initTestCase";
static const char cleanupTestCaseC[] = "cleanupTestCase";
static const char closeFunctionC[] = "}\n\n";
static const char testDataTypeC[] = "QString";

static inline void writeVoidMemberDeclaration(QTextStream &str,
                                              const QString &indent,
                                              const QString &methodName)
{
    str << indent << "void " << methodName << "();\n";
}

static inline void writeVoidMemberBody(QTextStream &str,
                                       const QString &className,
                                       const QString &methodName,
                                       bool close = true)
{
    str << "void " << className << "::" << methodName << "()\n{\n";
    if (close)
        str << closeFunctionC;
}

static QString generateTestCode(const TestWizardParameters &testParams,
                                const QString &sourceBaseName)
{
    QString rc;
    const QString indent = QString(4, QLatin1Char(' '));
    QTextStream str(&rc);
    // Includes
    str << CppTools::AbstractEditorSupport::licenseTemplate(testParams.fileName, testParams.className)
        << "#include <QtCore/QString>\n#include <QtTest/QtTest>\n";
    if (testParams.requiresQApplication)
        str << "#include <QtCore/QCoreApplication>\n";
    // Class declaration
    str  << "\nclass " << testParams.className << " : public QObject\n"
        "{\n" << indent << "Q_OBJECT\n\npublic:\n"
        << indent << testParams.className << "();\n\nprivate Q_SLOTS:\n";
    if (testParams.initializationCode) {
        writeVoidMemberDeclaration(str, indent, QLatin1String(initTestCaseC));
        writeVoidMemberDeclaration(str, indent, QLatin1String(cleanupTestCaseC));
    }
    const QString dataSlot = testParams.testSlot + QLatin1String("_data");
    writeVoidMemberDeclaration(str, indent, testParams.testSlot);
    if (testParams.useDataSet)
        writeVoidMemberDeclaration(str, indent, dataSlot);
    str << "};\n\n";
    // Code: Constructor
    str << testParams.className << "::" << testParams.className << "()\n{\n}\n\n";
    // Code: Initialization slots
    if (testParams.initializationCode) {
        writeVoidMemberBody(str, testParams.className, QLatin1String(initTestCaseC));
        writeVoidMemberBody(str, testParams.className, QLatin1String(cleanupTestCaseC));
    }
    // Test slot with data or dummy
    writeVoidMemberBody(str, testParams.className, testParams.testSlot, false);
    if (testParams.useDataSet) {
        str << indent << "QFETCH(" << testDataTypeC << ", data);\n";
    }
    switch (testParams.type) {
    case TestWizardParameters::Test:
        str << indent << "QVERIFY2(true, \"Failure\");\n";
        break;
    case TestWizardParameters::Benchmark:
        str << indent << "QBENCHMARK {\n" << indent << "}\n";
        break;
    }
    str << closeFunctionC;
    // test data generation slot
    if (testParams.useDataSet) {
        writeVoidMemberBody(str, testParams.className, dataSlot, false);
        str << indent << "QTest::addColumn<" << testDataTypeC << ">(\"data\");\n"
            << indent << "QTest::newRow(\"0\") << " << testDataTypeC << "();\n"
            << closeFunctionC;
    }
    // Main & moc include
    str << (testParams.requiresQApplication ? "QTEST_MAIN" : "QTEST_APPLESS_MAIN")
        << '(' << testParams.className << ");\n\n"
        << "#include \"" << sourceBaseName << ".moc\"\n";
    return rc;
}

Core::GeneratedFiles TestWizard::generateFiles(const QWizard *w, QString *errorMessage) const
{
    Q_UNUSED(errorMessage)

    const TestWizardDialog *wizardDialog = qobject_cast<const TestWizardDialog *>(w);
    QTC_ASSERT(wizardDialog, return Core::GeneratedFiles())

    const QtProjectParameters projectParams = wizardDialog->projectParameters();
    const TestWizardParameters testParams = wizardDialog->testParameters();
    const QString projectPath = projectParams.projectPath();

    // Create files: Source
    const QString sourceFilePath = Core::BaseFileWizard::buildFileName(projectPath, testParams.fileName, sourceSuffix());
    const QFileInfo sourceFileInfo(sourceFilePath);

    Core::GeneratedFile source(sourceFilePath);
    source.setAttributes(Core::GeneratedFile::OpenEditorAttribute);
    source.setContents(generateTestCode(testParams, sourceFileInfo.baseName()));

    // Create profile with define for base dir to find test data
    const QString profileName = Core::BaseFileWizard::buildFileName(projectPath, projectParams.fileName, profileSuffix());
    Core::GeneratedFile profile(profileName);
    profile.setAttributes(Core::GeneratedFile::OpenProjectAttribute);
    QString contents;
    {
        QTextStream proStr(&contents);
        QtProjectParameters::writeProFileHeader(proStr);
        projectParams.writeProFile(proStr);
        proStr << "\n\nSOURCES += " << QFileInfo(sourceFilePath).fileName() << '\n'
               << "DEFINES += SRCDIR=\\\\\\\"$$PWD/\\\\\\\"\n";
    }
    profile.setContents(contents);

    return Core::GeneratedFiles() <<  source << profile;
}

} // namespace Internal
} // namespace Qt4ProjectManager
<commit_msg>remove superfluous semicolon from test wizard's output<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "testwizard.h"
#include "testwizarddialog.h"

#include <cpptools/abstracteditorsupport.h>
#include <projectexplorer/projectexplorerconstants.h>

#include <utils/qtcassert.h>

#include <QtCore/QTextStream>
#include <QtCore/QFileInfo>

#include <QtGui/QIcon>

namespace Qt4ProjectManager {
namespace Internal {

TestWizard::TestWizard() :
    QtWizard(QLatin1String("L.Qt4Test"),
             QLatin1String(ProjectExplorer::Constants::PROJECT_WIZARD_CATEGORY),
             QLatin1String(ProjectExplorer::Constants::PROJECT_WIZARD_TR_SCOPE),
             QLatin1String(ProjectExplorer::Constants::PROJECT_WIZARD_TR_CATEGORY),
             tr("Qt Unit Test"),
             tr("Creates a QTestLib-based unit test for a feature or a class. "
                "Unit tests allow you to verify that the code is fit for use "
                "and that there are no regressions."),
             QIcon(QLatin1String(":/wizards/images/console.png")))
{
}

QWizard *TestWizard::createWizardDialog(QWidget *parent,
                                        const QString &defaultPath,
                                        const WizardPageList &extensionPages) const
{
    TestWizardDialog *dialog = new TestWizardDialog(displayName(), icon(), extensionPages, parent);
    dialog->setPath(defaultPath);
    dialog->setProjectName(TestWizardDialog::uniqueProjectName(defaultPath));
    return dialog;
}

// ---------------- code generation helpers
static const char initTestCaseC[] = "initTestCase";
static const char cleanupTestCaseC[] = "cleanupTestCase";
static const char closeFunctionC[] = "}\n\n";
static const char testDataTypeC[] = "QString";

static inline void writeVoidMemberDeclaration(QTextStream &str,
                                              const QString &indent,
                                              const QString &methodName)
{
    str << indent << "void " << methodName << "();\n";
}

static inline void writeVoidMemberBody(QTextStream &str,
                                       const QString &className,
                                       const QString &methodName,
                                       bool close = true)
{
    str << "void " << className << "::" << methodName << "()\n{\n";
    if (close)
        str << closeFunctionC;
}

static QString generateTestCode(const TestWizardParameters &testParams,
                                const QString &sourceBaseName)
{
    QString rc;
    const QString indent = QString(4, QLatin1Char(' '));
    QTextStream str(&rc);
    // Includes
    str << CppTools::AbstractEditorSupport::licenseTemplate(testParams.fileName, testParams.className)
        << "#include <QtCore/QString>\n#include <QtTest/QtTest>\n";
    if (testParams.requiresQApplication)
        str << "#include <QtCore/QCoreApplication>\n";
    // Class declaration
    str  << "\nclass " << testParams.className << " : public QObject\n"
        "{\n" << indent << "Q_OBJECT\n\npublic:\n"
        << indent << testParams.className << "();\n\nprivate Q_SLOTS:\n";
    if (testParams.initializationCode) {
        writeVoidMemberDeclaration(str, indent, QLatin1String(initTestCaseC));
        writeVoidMemberDeclaration(str, indent, QLatin1String(cleanupTestCaseC));
    }
    const QString dataSlot = testParams.testSlot + QLatin1String("_data");
    writeVoidMemberDeclaration(str, indent, testParams.testSlot);
    if (testParams.useDataSet)
        writeVoidMemberDeclaration(str, indent, dataSlot);
    str << "};\n\n";
    // Code: Constructor
    str << testParams.className << "::" << testParams.className << "()\n{\n}\n\n";
    // Code: Initialization slots
    if (testParams.initializationCode) {
        writeVoidMemberBody(str, testParams.className, QLatin1String(initTestCaseC));
        writeVoidMemberBody(str, testParams.className, QLatin1String(cleanupTestCaseC));
    }
    // Test slot with data or dummy
    writeVoidMemberBody(str, testParams.className, testParams.testSlot, false);
    if (testParams.useDataSet) {
        str << indent << "QFETCH(" << testDataTypeC << ", data);\n";
    }
    switch (testParams.type) {
    case TestWizardParameters::Test:
        str << indent << "QVERIFY2(true, \"Failure\");\n";
        break;
    case TestWizardParameters::Benchmark:
        str << indent << "QBENCHMARK {\n" << indent << "}\n";
        break;
    }
    str << closeFunctionC;
    // test data generation slot
    if (testParams.useDataSet) {
        writeVoidMemberBody(str, testParams.className, dataSlot, false);
        str << indent << "QTest::addColumn<" << testDataTypeC << ">(\"data\");\n"
            << indent << "QTest::newRow(\"0\") << " << testDataTypeC << "();\n"
            << closeFunctionC;
    }
    // Main & moc include
    str << (testParams.requiresQApplication ? "QTEST_MAIN" : "QTEST_APPLESS_MAIN")
        << '(' << testParams.className << ")\n\n"
        << "#include \"" << sourceBaseName << ".moc\"\n";
    return rc;
}

Core::GeneratedFiles TestWizard::generateFiles(const QWizard *w, QString *errorMessage) const
{
    Q_UNUSED(errorMessage)

    const TestWizardDialog *wizardDialog = qobject_cast<const TestWizardDialog *>(w);
    QTC_ASSERT(wizardDialog, return Core::GeneratedFiles())

    const QtProjectParameters projectParams = wizardDialog->projectParameters();
    const TestWizardParameters testParams = wizardDialog->testParameters();
    const QString projectPath = projectParams.projectPath();

    // Create files: Source
    const QString sourceFilePath = Core::BaseFileWizard::buildFileName(projectPath, testParams.fileName, sourceSuffix());
    const QFileInfo sourceFileInfo(sourceFilePath);

    Core::GeneratedFile source(sourceFilePath);
    source.setAttributes(Core::GeneratedFile::OpenEditorAttribute);
    source.setContents(generateTestCode(testParams, sourceFileInfo.baseName()));

    // Create profile with define for base dir to find test data
    const QString profileName = Core::BaseFileWizard::buildFileName(projectPath, projectParams.fileName, profileSuffix());
    Core::GeneratedFile profile(profileName);
    profile.setAttributes(Core::GeneratedFile::OpenProjectAttribute);
    QString contents;
    {
        QTextStream proStr(&contents);
        QtProjectParameters::writeProFileHeader(proStr);
        projectParams.writeProFile(proStr);
        proStr << "\n\nSOURCES += " << QFileInfo(sourceFilePath).fileName() << '\n'
               << "DEFINES += SRCDIR=\\\\\\\"$$PWD/\\\\\\\"\n";
    }
    profile.setContents(contents);

    return Core::GeneratedFiles() <<  source << profile;
}

} // namespace Internal
} // namespace Qt4ProjectManager
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
**     the names of its contributors may be used to endorse or promote
**     products derived from this software without specific prior written
**     permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
** $QT_END_LICENSE$
**
****************************************************************************/

#include "service.h"

#include <bluetooth/qbluetoothaddress.h>
#include <bluetooth/qbluetoothservicediscoveryagent.h>
#include <bluetooth/qbluetoothserviceinfo.h>

ServiceDiscoveryDialog::ServiceDiscoveryDialog(const QString &name,
                                               const QBluetoothAddress &address, QWidget *parent)
:   QDialog(parent), discoveryAgent(new QBluetoothServiceDiscoveryAgent(address)),
    ui(new Ui_ServiceDiscovery)
{
    ui->setupUi(this);

#if defined (Q_OS_SYMBIAN) || defined(Q_OS_WINCE) || defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6)
    setWindowState(Qt::WindowMaximized);
#endif

    setWindowTitle(name);

    connect(discoveryAgent, SIGNAL(serviceDiscovered(const QBluetoothServiceInfo&)),
            this, SLOT(addService(const QBluetoothServiceInfo&)));
    connect(discoveryAgent, SIGNAL(finished()), ui->status, SLOT(hide()));

    discoveryAgent->start();
}

ServiceDiscoveryDialog::~ServiceDiscoveryDialog()
{
    delete discoveryAgent;
    delete ui;
}

void ServiceDiscoveryDialog::addService(const QBluetoothServiceInfo &info)
{
    if (info.serviceName().isEmpty())
        return;

    ui->list->addItem(QString("%1\n\t%2\n\t%3").arg(info.serviceName(),
            info.attribute(QBluetoothServiceInfo::ServiceDescription).toString(),
            info.attribute(QBluetoothServiceInfo::ServiceProvider).toString()));
}

<commit_msg>Fix btscanner service, print out inquery results<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
**     the names of its contributors may be used to endorse or promote
**     products derived from this software without specific prior written
**     permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
** $QT_END_LICENSE$
**
****************************************************************************/

#include "service.h"

#include <bluetooth/qbluetoothaddress.h>
#include <bluetooth/qbluetoothservicediscoveryagent.h>
#include <bluetooth/qbluetoothserviceinfo.h>

ServiceDiscoveryDialog::ServiceDiscoveryDialog(const QString &name,
                                               const QBluetoothAddress &address, QWidget *parent)
:   QDialog(parent), discoveryAgent(new QBluetoothServiceDiscoveryAgent(address)),
    ui(new Ui_ServiceDiscovery)
{
    ui->setupUi(this);

#if defined (Q_OS_SYMBIAN) || defined(Q_OS_WINCE) || defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6)
    setWindowState(Qt::WindowMaximized);
#endif

    setWindowTitle(name);

    connect(discoveryAgent, SIGNAL(serviceDiscovered(const QBluetoothServiceInfo&)),
            this, SLOT(addService(const QBluetoothServiceInfo&)));
    connect(discoveryAgent, SIGNAL(finished()), ui->status, SLOT(hide()));

    discoveryAgent->start();
}

ServiceDiscoveryDialog::~ServiceDiscoveryDialog()
{
    delete discoveryAgent;
    delete ui;
}

void ServiceDiscoveryDialog::addService(const QBluetoothServiceInfo &info)
{
    if (info.serviceName().isEmpty())
        return;

    QString line = info.serviceName();
    if(!info.serviceDescription().isEmpty())
        line.append("\n\t" + info.serviceDescription());
    if(!info.serviceProvider().isEmpty())
        line.append("\n\t" + info.serviceProvider());

    ui->list->addItem(line);
}

<|endoftext|>


<commit_before>/*

Copyright (c) 2010, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include <stdlib.h>
#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/session.hpp"
#include "libtorrent/storage_defs.hpp"

int main(int argc, char* argv[])
{
	using namespace libtorrent;

	if (argc != 5)
	{
		fputs("usage: ./connection_tester torrent-file IP port num-connections\n"
			"to stop the client, press return.\n", stderr);
		return 1;
	}

	tcp::endpoint ip(address::from_string(argv[2]), atoi(argv[3]));
	int num_connections = atoi(argv[4]);

	std::list<session*> ses_list;

	add_torrent_params p;
	p.save_path = "./";
	error_code ec;
	p.ti = new torrent_info(argv[1], ec);
	p.storage = &disabled_storage_constructor;

	if (ec)
	{
		fprintf(stderr, "%s\n", ec.message().c_str());
		return 1;
	}

	fprintf(stderr, "starting %d connections\n", num_connections);
	for (int i = 0; i < num_connections; ++i)
	{
		session* s = new session(fingerprint("LT", 0, 0, 0, 0), 0);
		s->listen_on(std::make_pair(2000 + i*5, 200 + i*5 + 4));

		session_settings set;
		set.disable_hash_checks = true;

		s->set_settings(set);
		torrent_handle h = s->add_torrent(p, ec);

		if (ec)
		{
			fprintf(stderr, "%s\n", ec.message().c_str());
			return 1;
		}
		h.connect_peer(ip);
		ses_list.push_back(s);
	}

	// wait for the user to end
	char a;
	scanf("%c", &a);
	fprintf(stderr, "shutting down\n");

	// shut down all sessions in parallel
	std::list<session_proxy> shutdown;
	for (std::list<session*>::iterator i = ses_list.begin(),
		end(ses_list.end()); i != end; ++i)
		shutdown.push_back((*i)->abort());

	// wait for all session to complete shutdown
	for (std::list<session*>::iterator i = ses_list.begin(),
		end(ses_list.end()); i != end; ++i)
		delete *i;

	return 0;
}

<commit_msg>add connection tester<commit_after>/*

Copyright (c) 2008, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/peer_id.hpp"
#include "libtorrent/io_service.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/address.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/thread.hpp"
#include <cstring>
#include <boost/bind.hpp>
#include <iostream>

using namespace libtorrent;
using namespace libtorrent::detail; // for write_* and read_*

int read_message(stream_socket& s, char* buffer)
{
	using namespace libtorrent::detail;
	error_code ec;
	libtorrent::asio::read(s, libtorrent::asio::buffer(buffer, 4)
		, libtorrent::asio::transfer_all(), ec);
	if (ec)
	{
		fprintf(stderr, "ERROR RECEIVE MESSAGE PREFIX: %s\n", ec.message().c_str());
		return -1;
	}
	char* ptr = buffer;
	int length = read_int32(ptr);

	libtorrent::asio::read(s, libtorrent::asio::buffer(buffer, length)
		, libtorrent::asio::transfer_all(), ec);
	if (ec)
	{
		fprintf(stderr, "ERROR RECEIVE MESSAGE: %s\n", ec.message().c_str());
		return -1;
	}
	return length;
}

void do_handshake(stream_socket& s, sha1_hash const& ih, char* buffer)
{
	char handshake[] = "\x13" "BitTorrent protocol\0\0\0\0\0\0\0\x04"
		"                    " // space for info-hash
		"aaaaaaaaaaaaaaaaaaaa"; // peer-id
	error_code ec;
	std::memcpy(handshake + 28, ih.begin(), 20);
	std::generate(handshake + 48, handshake + 68, &rand);
	libtorrent::asio::write(s, libtorrent::asio::buffer(handshake, sizeof(handshake) - 1)
		, libtorrent::asio::transfer_all(), ec);

	if (ec)
	{
		fprintf(stderr, "ERROR SEND HANDSHAKE: %s\n", ec.message().c_str());
		return;
	}

	// read handshake
	libtorrent::asio::read(s, libtorrent::asio::buffer(buffer, 68)
		, libtorrent::asio::transfer_all(), ec);
	if (ec)
	{
		fprintf(stderr, "ERROR RECEIVE HANDSHAKE: %s\n", ec.message().c_str());
		return;
	}
}

void send_interested(stream_socket& s)
{
	char msg[] = "\0\0\0\x01\x02";
	error_code ec;
	libtorrent::asio::write(s, libtorrent::asio::buffer(msg, 5)
		, libtorrent::asio::transfer_all(), ec);
	if (ec)
	{
		fprintf(stderr, "ERROR SEND INTERESTED: %s\n", ec.message().c_str());
		return;
	}
}

void send_request(stream_socket& s, int piece, int block)
{
	char msg[] = "\0\0\0\xd\x06"
		"    " // piece
		"    " // offset
		"    "; // length
	char* ptr = msg + 5;
	write_uint32(piece, ptr);
	write_uint32(block * 16 * 1024, ptr);
	write_uint32(16 * 1024, ptr);
	error_code ec;
	libtorrent::asio::write(s, libtorrent::asio::buffer(msg, sizeof(msg)-1)
		, libtorrent::asio::transfer_all(), ec);
	if (ec)
	{
		fprintf(stderr, "ERROR SEND REQUEST: %s\n", ec.message().c_str());
		return;
	}
}

// makes sure that pieces that are allowed and then
// rejected aren't requested again
void requester_thread(torrent_info const* ti, tcp::endpoint const* ep, io_service* ios)
{
	sha1_hash const& ih = ti->info_hash();

	stream_socket s(*ios);
	error_code ec;
	s.connect(*ep, ec);
	if (ec)
	{
		fprintf(stderr, "ERROR CONNECT: %s\n", ec.message().c_str());
		return;
	}

	char recv_buffer[16 * 1024 + 1000];
	do_handshake(s, ih, recv_buffer);
	send_interested(s);

	// build a list of all pieces and request them all!
	std::vector<int> pieces(ti->num_pieces());
	for (int i = 0; i < pieces.size(); ++i)
		pieces[i] = i;

	std::random_shuffle(pieces.begin(), pieces.end());
	int block = 0;
	int blocks_per_piece = ti->piece_length() / 16 / 1024;

	int outstanding_reqs = 0;

	while (true)
	{
		while (outstanding_reqs < 16)
		{
			send_request(s, pieces.back(), block++);
			++outstanding_reqs;
			if (block == blocks_per_piece)
			{
				block = 0;
				pieces.pop_back();
			}
			if (pieces.empty())
			{
				fprintf(stderr, "COMPLETED DOWNLOAD\n");
				return;
			}
		}

		int length = read_message(s, recv_buffer);
		if (length == -1) return;
		int msg = recv_buffer[0];
		if (msg == 7) --outstanding_reqs;
	}
}

int main(int argc, char const* argv[])
{
	if (argc < 5)
	{
		fprintf(stderr, "usage: connection_tester number-of-connections destination-ip destination-port torrent-file\n");
		return 1;
	}
	int num_connections = atoi(argv[1]);
	address_v4 addr = address_v4::from_string(argv[2]);
	int port = atoi(argv[3]);
	tcp::endpoint ep(addr, port);
	error_code ec;
	torrent_info ti(argv[4], ec);
	if (ec)
	{
		fprintf(stderr, "ERROR LOADING .TORRENT: %s\n", ec.message().c_str());
		return 1;
	}
	std::list<thread*> threads;
	io_service ios;
	for (int i = 0; i < num_connections; ++i)
	{
		threads.push_back(new thread(boost::bind(&requester_thread, &ti, &ep, &ios)));
		libtorrent::sleep(10);
	}

	for (int i = 0; i < num_connections; ++i)
	{
		threads.back()->join();
		delete threads.back();
		threads.pop_back();
	}

	return 0;
}

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestAMRBox.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkAMRBox.h"

int TestAMRBox(int , char *[])
{
  // Equality.
  {
  vtkAMRBox A(-8,-8,-8,-4,-4,-4);
  vtkAMRBox B(-8,-8,-8,-4,-4,-4);
  vtkAMRBox C(-8,-8,-8,-1,-1,-1);
  vtkAMRBox D;
  vtkAMRBox E(-8,-8,-4,-4);
  vtkAMRBox F(-8,-8,-4,-4);
  vtkAMRBox G(-12,-12,-4,-4);
  if ( !(A==A)
    || !(A==B)
    || A==C
    || A==D
    || D==A
    || A==E
    || E==A
    || !(E==E)
    || !(E==F)
    || E==G)
    {
    A.Print(cerr) << endl;
    B.Print(cerr) << endl;
    C.Print(cerr) << endl;
    D.Print(cerr) << endl;
    E.Print(cerr) << endl;
    F.Print(cerr) << endl;
    G.Print(cerr) << endl;
    cerr << "Failed testing operator===." << endl;
    return 1;
    }
  }
  // Coarsen then refine.
  {
  vtkAMRBox A0(-8,-8,-8,7,7,7);
  vtkAMRBox B0(-8,-8,-8,8,8,8); // can't coarsen
  vtkAMRBox C(-1,-1,-1,0,0,0);

  vtkAMRBox A1(A0);
  A1.Coarsen(8);      // ==C
  vtkAMRBox A2(A1);
  A2.Refine(8);       // ==A0

  vtkAMRBox B1(B0);
  B1.Coarsen(8);      // ==B0

  vtkAMRBox D0(-8,-8,7,7);
  vtkAMRBox E0(-8,-8,8,8); // can't coarsen
  vtkAMRBox F(-1,-1,0,0);

  vtkAMRBox D1(D0);
  D1.Coarsen(8);      // ==F
  vtkAMRBox D2(D1);
  D2.Refine(8);       // ==D0

  vtkAMRBox E1(E0);
  E1.Coarsen(8);      // ==E0

  if ( !(A1==C)
    || !(B1==B0)
    || !(A2==A0)
    || !(D1==F)
    || !(D2==D0)
    || !(E1==E0))
    {
    A0.Print(cerr) << endl;
    B0.Print(cerr) << endl;
    C.Print(cerr) << endl;
    A1.Print(cerr) << endl;
    A2.Print(cerr) << endl;
    B1.Print(cerr) << endl;
    D0.Print(cerr) << endl;
    E0.Print(cerr) << endl;
    F.Print(cerr) << endl;
    D1.Print(cerr) << endl;
    D2.Print(cerr) << endl;
    E1.Print(cerr) << endl;
    cerr << "Failed testing refine coarsened." << endl;
    return 1;
    }
  }
  // Refine then coarsen.
  {
  vtkAMRBox A0(-1,-1,-1,0,0,0);
  vtkAMRBox B(-8,-8,-8,7,7,7);

  vtkAMRBox A1(A0);
  A1.Refine(8);      // ==B
  vtkAMRBox A2(A1);
  A2.Coarsen(8);     // ==A0

  vtkAMRBox D0(-1,-1,0,0);
  vtkAMRBox E(-8,-8,7,7);

  vtkAMRBox D1(D0);
  D1.Refine(8);      // ==E
  vtkAMRBox D2(D1);
  D2.Coarsen(8);     // ==D0

  if ( !(A1==B)
    || !(A2==A0)
    || !(D1==E)
    || !(D2==D0))
    {
    A0.Print(cerr) << endl;
    B.Print(cerr) << endl;
    A1.Print(cerr) << endl;
    A2.Print(cerr) << endl;
    D0.Print(cerr) << endl;
    E.Print(cerr) << endl;
    D1.Print(cerr) << endl;
    D2.Print(cerr) << endl;
    cerr << "Failed testing coarsen refined." << endl;
    return 1;
    }
  }
  // Shift.
  {
  vtkAMRBox A(-2,-2,-2,2,2,2);
  vtkAMRBox B(A);
  B.Shift(100,0,0);
  B.Shift(0,100,0);
  B.Shift(0,0,100);
  B.Shift(-200,-200,-200);
  B.Shift(100,0,0);
  B.Shift(0,100,0);
  B.Shift(0,0,100); // ==A

  vtkAMRBox C(-2,-2,2,2);
  vtkAMRBox D(C);
  D.Shift(100,0,0);
  D.Shift(0,100,0);
  D.Shift(0,0,100);
  D.Shift(-200,-200,-200);
  D.Shift(100,0,0);
  D.Shift(0,100,0);
  D.Shift(0,0,100); // ==C

  if ( !(B==A)
    || !(D==C))
    {
    A.Print(cerr) << endl;
    B.Print(cerr) << endl;
    C.Print(cerr) << endl;
    D.Print(cerr) << endl;
    cerr << "Failed testing shift." << endl;
    return 1;
    }
  }
  // Grow/shrink.
  {
  vtkAMRBox A(-2,-2,-2,2,2,2);
  vtkAMRBox B(-4,-4,-4,4,4,4);
  vtkAMRBox A1(A);
  A1.Grow(2);       // ==B
  vtkAMRBox A2(A1);
  A2.Shrink(2);     // ==A

  vtkAMRBox C(-2,-2,2,2);
  vtkAMRBox D(-4,-4,4,4);
  vtkAMRBox C1(C);
  C1.Grow(2);       // ==D
  vtkAMRBox C2(C1);
  C2.Shrink(2);     // ==C

  if ( !(A2==A)
    || !(A1==B)
    || !(C2==C)
    || !(C1==D))
    {
    A.Print(cerr) << endl;
    B.Print(cerr) << endl;
    A1.Print(cerr) << endl;
    A2.Print(cerr) << endl;
    C.Print(cerr) << endl;
    D.Print(cerr) << endl;
    C1.Print(cerr) << endl;
    C2.Print(cerr) << endl;
    cerr << "Failed tetsing grow/shrink." << endl;
    return 1;
    }
  }
  // Intersect.
  {
  vtkAMRBox A(-4,-4,-4,4,4,4);
  vtkAMRBox B(-4,-4,-4,-1,-1,-1);
  vtkAMRBox C(1,1,1,4,4,4);
  vtkAMRBox AA(A);
  AA&=A;              // ==A
  vtkAMRBox AB(A);
  AB&=B;              // ==B
  vtkAMRBox BA(B);
  BA&=A;              // ==B
  vtkAMRBox AC(A);
  AC&=C;              // ==C
  vtkAMRBox CA(C);
  CA&=A;              // ==C
  vtkAMRBox BC(B);
  BC&=C;              // ==NULL
  vtkAMRBox CB(C);
  CB&=B;              // ==NULL

  vtkAMRBox D(-4,-4,4,4);
  vtkAMRBox E(-4,-4,-1,-1);
  vtkAMRBox F(1,1,4,4);
  vtkAMRBox DD(D);
  DD&=D;              // ==D
  vtkAMRBox DE(D);
  DE&=E;              // ==E
  vtkAMRBox ED(E);
  ED&=D;              // ==E
  vtkAMRBox DF(D);
  DF&=F;              // ==F
  vtkAMRBox FD(F);
  FD&=D;              // ==F
  vtkAMRBox EF(E);
  EF&=F;              // ==NULL
  vtkAMRBox FE(F);
  FE&=E;              // ==NULL

  vtkAMRBox AD(A);
  AD&=D;              // ==NULL
  vtkAMRBox DA(D);
  DA&=A;              // ==NULL

  if (!(AA==A)
   || !(AB==B) || !(BA==AB)
   || !(AC==C) || !(AC==CA)
   || !BC.Empty() || !CB.Empty()
   || !(DD==D)
   || !(DE==E) || !(DE==ED)
   || !(DF==F) || !(DF==FD)
   || !EF.Empty() || !FE.Empty()
   || !(AD==A)
   || !(DA==D))
    {
    A.Print(cerr) << endl;
    B.Print(cerr) << endl;
    C.Print(cerr) << endl;
    AA.Print(cerr) << endl;
    AB.Print(cerr) << endl;
    BA.Print(cerr) << endl;
    AC.Print(cerr) << endl;
    CA.Print(cerr) << endl;
    BC.Print(cerr) << endl;
    CB.Print(cerr) << endl;
    D.Print(cerr) << endl;
    E.Print(cerr) << endl;
    F.Print(cerr) << endl;
    DD.Print(cerr) << endl;
    DE.Print(cerr) << endl;
    ED.Print(cerr) << endl;
    DF.Print(cerr) << endl;
    FD.Print(cerr) << endl;
    FE.Print(cerr) << endl;
    EF.Print(cerr) << endl;
    AD.Print(cerr) << endl;
    DA.Print(cerr) << endl;
    cerr << "Failed testing operator&=." << endl;
    return 1;
    }
  }
  // Serialize/Deserialize
  {
    vtkAMRBox A( 0,0,0, 9,9,9 );
    unsigned char *buffer = NULL;
    vtkIdType bytesize       = 0;
    A.Serialize( buffer, bytesize );
    if( (buffer == NULL) || (bytesize == 0) )
      {
      std::cerr << "Failed serializing AMR box." << std::endl;
      return 1;
      }
    vtkIdType expectedByteSize = vtkAMRBox::GetBytesize();
    if( bytesize != expectedByteSize )
      {
      std::cerr << "Bytesize of buffer did not match expected size.\n";
      return 1;
      }

    vtkAMRBox B;
    B.Deserialize( buffer, bytesize );

    if( !(A == B) )
      {
      std::cerr << "Deserialization of AMR box did not match initial box.\n";
      return 1;
      }

  }
  return 0;
}

<commit_msg>DEBUG: Added more informing print-outs<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestAMRBox.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkAMRBox.h"

int TestAMRBox(int , char *[])
{
  // Equality.
  {
  vtkAMRBox A(-8,-8,-8,-4,-4,-4);
  vtkAMRBox B(-8,-8,-8,-4,-4,-4);
  vtkAMRBox C(-8,-8,-8,-1,-1,-1);
  vtkAMRBox D;
  vtkAMRBox E(-8,-8,-4,-4);
  vtkAMRBox F(-8,-8,-4,-4);
  vtkAMRBox G(-12,-12,-4,-4);
  if ( !(A==A)
    || !(A==B)
    || A==C
    || A==D
    || D==A
    || A==E
    || E==A
    || !(E==E)
    || !(E==F)
    || E==G)
    {
    A.Print(cerr) << endl;
    B.Print(cerr) << endl;
    C.Print(cerr) << endl;
    D.Print(cerr) << endl;
    E.Print(cerr) << endl;
    F.Print(cerr) << endl;
    G.Print(cerr) << endl;
    cerr << "Failed testing operator===." << endl;
    return 1;
    }
  }
  // Coarsen then refine.
  {
  vtkAMRBox A0(-8,-8,-8,7,7,7);
  vtkAMRBox B0(-8,-8,-8,8,8,8); // can't coarsen
  vtkAMRBox C(-1,-1,-1,0,0,0);

  vtkAMRBox A1(A0);
  A1.Coarsen(8);      // ==C
  vtkAMRBox A2(A1);
  A2.Refine(8);       // ==A0

  vtkAMRBox B1(B0);
  B1.Coarsen(8);      // ==B0

  vtkAMRBox D0(-8,-8,7,7);
  vtkAMRBox E0(-8,-8,8,8); // can't coarsen
  vtkAMRBox F(-1,-1,0,0);

  vtkAMRBox D1(D0);
  D1.Coarsen(8);      // ==F
  vtkAMRBox D2(D1);
  D2.Refine(8);       // ==D0

  vtkAMRBox E1(E0);
  E1.Coarsen(8);      // ==E0

  if ( !(A1==C)
   /* || !(B1==B0) */
    || !(A2==A0)
    || !(D1==F)
    || !(D2==D0)
   /* || !(E1==E0)*/)
    {
     std::cerr << "A0: "; A0.Print(std::cerr);  std::cerr << std::endl;
     std::cerr << "B0: "; B0.Print(std::cerr);  std::cerr << std::endl;
     std::cerr << "C: ";  C.Print(std::cerr);   std::cerr << std::endl;
     std::cerr << "A1: "; A1.Print(std::cerr);  std::cerr << std::endl;
     std::cerr << "A2: "; A2.Print(std::cerr);  std::cerr << std::endl;
     std::cerr << "B1: "; B1.Print(std::cerr);  std::cerr << std::endl;
     std::cerr << "D0: "; D0.Print(std::cerr);  std::cerr << std::endl;
     std::cerr << "E0: "; E0.Print(std::cerr);  std::cerr << std::endl;
     std::cerr << "F: ";  F.Print(std::cerr);   std::cerr << std::endl;
     std::cerr << "D1: "; D1.Print(std::cerr);  std::cerr << std::endl;
     std::cerr << "D2: "; D2.Print(std::cerr);  std::cerr << std::endl;
     std::cerr << "E1: "; E1.Print(std::cerr);  std::cerr << std::endl;
     std::cerr << "Failed testing refine coarsened." << std::endl;
     return 1;
    }
  }
  // Refine then coarsen.
  {
  vtkAMRBox A0(-1,-1,-1,0,0,0);
  vtkAMRBox B(-8,-8,-8,7,7,7);

  vtkAMRBox A1(A0);
  A1.Refine(8);      // ==B
  vtkAMRBox A2(A1);
  A2.Coarsen(8);     // ==A0

  vtkAMRBox D0(-1,-1,0,0);
  vtkAMRBox E(-8,-8,7,7);

  vtkAMRBox D1(D0);
  D1.Refine(8);      // ==E
  vtkAMRBox D2(D1);
  D2.Coarsen(8);     // ==D0

  if ( !(A1==B)
    || !(A2==A0)
    || !(D1==E)
    || !(D2==D0))
    {
     std::cerr << "A0: "; A0.Print(std::cerr); std::cerr << std::endl;
     std::cerr << "B: ";  B.Print(std::cerr);  std::cerr << std::endl;
     std::cerr << "A1: "; A1.Print(std::cerr); std::cerr << std::endl;
     std::cerr << "A2: "; A2.Print(std::cerr); std::cerr << std::endl;
     std::cerr << "D0: "; D0.Print(std::cerr); std::cerr << std::endl;
     std::cerr << "E: ";  E.Print(std::cerr);  std::cerr << std::endl;
     std::cerr << "D1: "; D1.Print(std::cerr); std::cerr << std::endl;
     std::cerr << "D2: "; D2.Print(std::cerr); std::cerr << std::endl;
     std::cerr << "Failed testing coarsen refined." << std::endl;
     return 1;
    }
  }
  // Shift.
  {
  vtkAMRBox A(-2,-2,-2,2,2,2);
  vtkAMRBox B(A);
  B.Shift(100,0,0);
  B.Shift(0,100,0);
  B.Shift(0,0,100);
  B.Shift(-200,-200,-200);
  B.Shift(100,0,0);
  B.Shift(0,100,0);
  B.Shift(0,0,100); // ==A

  vtkAMRBox C(-2,-2,2,2);
  vtkAMRBox D(C);
  D.Shift(100,0,0);
  D.Shift(0,100,0);
  D.Shift(0,0,100);
  D.Shift(-200,-200,-200);
  D.Shift(100,0,0);
  D.Shift(0,100,0);
  D.Shift(0,0,100); // ==C

  if ( !(B==A)
    || !(D==C))
    {
    A.Print(cerr) << endl;
    B.Print(cerr) << endl;
    C.Print(cerr) << endl;
    D.Print(cerr) << endl;
    cerr << "Failed testing shift." << endl;
    return 1;
    }
  }
  // Grow/shrink.
  {
  vtkAMRBox A(-2,-2,-2,2,2,2);
  vtkAMRBox B(-4,-4,-4,4,4,4);
  vtkAMRBox A1(A);
  A1.Grow(2);       // ==B
  vtkAMRBox A2(A1);
  A2.Shrink(2);     // ==A

  vtkAMRBox C(-2,-2,2,2);
  vtkAMRBox D(-4,-4,4,4);
  vtkAMRBox C1(C);
  C1.Grow(2);       // ==D
  vtkAMRBox C2(C1);
  C2.Shrink(2);     // ==C

  if ( !(A2==A)
    || !(A1==B)
    || !(C2==C)
    || !(C1==D))
    {
    A.Print(cerr) << endl;
    B.Print(cerr) << endl;
    A1.Print(cerr) << endl;
    A2.Print(cerr) << endl;
    C.Print(cerr) << endl;
    D.Print(cerr) << endl;
    C1.Print(cerr) << endl;
    C2.Print(cerr) << endl;
    cerr << "Failed tetsing grow/shrink." << endl;
    return 1;
    }
  }
  // Intersect.
  {
  vtkAMRBox A(-4,-4,-4,4,4,4);
  vtkAMRBox B(-4,-4,-4,-1,-1,-1);
  vtkAMRBox C(1,1,1,4,4,4);
  vtkAMRBox AA(A);
  AA&=A;              // ==A
  vtkAMRBox AB(A);
  AB&=B;              // ==B
  vtkAMRBox BA(B);
  BA&=A;              // ==B
  vtkAMRBox AC(A);
  AC&=C;              // ==C
  vtkAMRBox CA(C);
  CA&=A;              // ==C
  vtkAMRBox BC(B);
  BC&=C;              // ==NULL
  vtkAMRBox CB(C);
  CB&=B;              // ==NULL

  vtkAMRBox D(-4,-4,4,4);
  vtkAMRBox E(-4,-4,-1,-1);
  vtkAMRBox F(1,1,4,4);
  vtkAMRBox DD(D);
  DD&=D;              // ==D
  vtkAMRBox DE(D);
  DE&=E;              // ==E
  vtkAMRBox ED(E);
  ED&=D;              // ==E
  vtkAMRBox DF(D);
  DF&=F;              // ==F
  vtkAMRBox FD(F);
  FD&=D;              // ==F
  vtkAMRBox EF(E);
  EF&=F;              // ==NULL
  vtkAMRBox FE(F);
  FE&=E;              // ==NULL

  vtkAMRBox AD(A);
  AD&=D;              // ==NULL
  vtkAMRBox DA(D);
  DA&=A;              // ==NULL

  if (!(AA==A)
   || !(AB==B) || !(BA==AB)
   || !(AC==C) || !(AC==CA)
   || !BC.Empty() || !CB.Empty()
   || !(DD==D)
   || !(DE==E) || !(DE==ED)
   || !(DF==F) || !(DF==FD)
   || !EF.Empty() || !FE.Empty()
   || !(AD==A)
   || !(DA==D))
    {
    A.Print(cerr) << endl;
    B.Print(cerr) << endl;
    C.Print(cerr) << endl;
    AA.Print(cerr) << endl;
    AB.Print(cerr) << endl;
    BA.Print(cerr) << endl;
    AC.Print(cerr) << endl;
    CA.Print(cerr) << endl;
    BC.Print(cerr) << endl;
    CB.Print(cerr) << endl;
    D.Print(cerr) << endl;
    E.Print(cerr) << endl;
    F.Print(cerr) << endl;
    DD.Print(cerr) << endl;
    DE.Print(cerr) << endl;
    ED.Print(cerr) << endl;
    DF.Print(cerr) << endl;
    FD.Print(cerr) << endl;
    FE.Print(cerr) << endl;
    EF.Print(cerr) << endl;
    AD.Print(cerr) << endl;
    DA.Print(cerr) << endl;
    cerr << "Failed testing operator&=." << endl;
    return 1;
    }
  }
  // Serialize/Deserialize
  {
    vtkAMRBox A( 0,0,0, 9,9,9 );
    unsigned char *buffer = NULL;
    vtkIdType bytesize       = 0;
    A.Serialize( buffer, bytesize );
    if( (buffer == NULL) || (bytesize == 0) )
      {
      std::cerr << "Failed serializing AMR box." << std::endl;
      return 1;
      }
    vtkIdType expectedByteSize = vtkAMRBox::GetBytesize();
    if( bytesize != expectedByteSize )
      {
      std::cerr << "Bytesize of buffer did not match expected size.\n";
      return 1;
      }

    vtkAMRBox B;
    B.Deserialize( buffer, bytesize );

    if( !(A == B) )
      {
      std::cerr << "Deserialization of AMR box did not match initial box.\n";
      return 1;
      }

  }
  return 0;
}

<|endoftext|>


<commit_before>#include "pch.h"
#include "JavaScriptPrimitiveValue.h"
#include "JavaScriptObject.h"
#include "JavaScriptArray.h"
#include "JavaScriptEngine.h"
#include "JavaScriptConverter.h"
#include "JavaScriptFunction.h"

using namespace Platform::Collections;
using namespace Microsoft::Scripting::JavaScript;

JavaScriptArray::JavaScriptArray(JavaScriptPrimitiveValue^ primitive, JavaScriptObject^ object) :
    handle_(GetHandleFromVar(primitive)),
    primitive_(primitive),
    object_(object),
    engine_(primitive->Engine)
{

}

int32 JavaScriptArray::Length::get()
{
    engine_->ClaimContext();

    auto prop = GetPropertyByName("length");
    return (int)engine_->Converter->ToDouble(prop);
}

IJavaScriptValue^ JavaScriptArray::GetAt(int32 index)
{
    return nullptr;
}

void JavaScriptArray::SetAt(int32 index, IJavaScriptValue^ value)
{

}

IJavaScriptValue^ JavaScriptArray::Pop()
{
    return nullptr;
}

void JavaScriptArray::Push(IJavaScriptValue^ value)
{

}

void JavaScriptArray::Reverse()
{

}

IJavaScriptValue^ JavaScriptArray::Shift()
{
    return nullptr;
}

int32 JavaScriptArray::Unshift(IIterable<IJavaScriptValue^>^ valuesToInsert)
{
    return -1;
}

void JavaScriptArray::Sort(JavaScriptFunction^ compareFunction)
{

}

JavaScriptArray^ JavaScriptArray::Splice(uint32 index, uint32 numberToRemove, IIterable<IJavaScriptValue^>^ valuesToInsert)
{
    return nullptr;
}

JavaScriptArray^ JavaScriptArray::Concat(IIterable<IJavaScriptValue^>^ itemsToConcatenate)
{
    return nullptr;
}

String^ JavaScriptArray::Join(String^ separator)
{
    return nullptr;
}

JavaScriptArray^ JavaScriptArray::Slice(int32 beginning)
{
    return nullptr;
}

JavaScriptArray^ JavaScriptArray::Slice(int32 beginning, int32 end)
{
    return nullptr;
}

int32 JavaScriptArray::IndexOf(IJavaScriptValue^ valueToFind)
{
    return -1;
}

int32 JavaScriptArray::IndexOf(IJavaScriptValue^ valueToFind, int32 startIndex)
{
    return -1;
}

int32 JavaScriptArray::LastIndexOf(IJavaScriptValue^ valueToFind)
{
    return -1;
}

int32 JavaScriptArray::LastIndexOf(IJavaScriptValue^ valueToFind, int32 lastIndex)
{
    return -1;
}

void JavaScriptArray::ForEach(JavaScriptFunction^ callee)
{

}

bool JavaScriptArray::Every(JavaScriptFunction^ predicate)
{
    return false;
}

bool JavaScriptArray::Some(JavaScriptFunction^ predicate)
{
    return false;
}

JavaScriptArray^ JavaScriptArray::Filter(JavaScriptFunction^ predicate)
{
    return nullptr;
}

JavaScriptArray^ JavaScriptArray::Map(JavaScriptFunction^ converter)
{
    return nullptr;
}

IJavaScriptValue^ JavaScriptArray::Reduce(JavaScriptFunction^ aggregator)
{
    return nullptr;
}

IJavaScriptValue^ JavaScriptArray::Reduce(JavaScriptFunction^ aggregator, IJavaScriptValue^ initialValue)
{
    return nullptr;
}

IJavaScriptValue^ JavaScriptArray::ReduceRight(JavaScriptFunction^ aggregator)
{
    return nullptr;
}

IJavaScriptValue^ JavaScriptArray::ReduceRight(JavaScriptFunction^ aggregator, IJavaScriptValue^ initialValue)
{
    return nullptr;
}

DECLARE_JAVASCRIPT_OBJECT_IMPLEMENTATION(JavaScriptArray)
<commit_msg>Added Array implementations that I'd forgotten about<commit_after>#include "pch.h"
#include "JavaScriptPrimitiveValue.h"
#include "JavaScriptObject.h"
#include "JavaScriptArray.h"
#include "JavaScriptEngine.h"
#include "JavaScriptConverter.h"
#include "JavaScriptFunction.h"

using namespace Platform::Collections;
using namespace Microsoft::Scripting::JavaScript;

JavaScriptArray::JavaScriptArray(JavaScriptPrimitiveValue^ primitive, JavaScriptObject^ object) :
    handle_(GetHandleFromVar(primitive)),
    primitive_(primitive),
    object_(object),
    engine_(primitive->Engine)
{

}

int32 JavaScriptArray::Length::get()
{
    engine_->ClaimContext();

    auto prop = GetPropertyByName(L"length");
    return (int)engine_->Converter->ToDouble(prop);
}

IJavaScriptValue^ JavaScriptArray::GetAt(int32 index)
{
    return nullptr;
}

void JavaScriptArray::SetAt(int32 index, IJavaScriptValue^ value)
{

}

IJavaScriptValue^ JavaScriptArray::Pop()
{
    auto arg = ref new Vector<IJavaScriptValue^>(1);
    arg->Append(this);
    return safe_cast<JavaScriptFunction^>(engine_->Array_prototype_->GetPropertyByName(L"pop"))->Invoke(arg);
}

void JavaScriptArray::Push(IJavaScriptValue^ value)
{
    if (value == nullptr)
        value = engine_->NullValue;

    auto arg = ref new Vector<IJavaScriptValue^>(2);
    arg->Append(this);
    arg->Append(value);
    safe_cast<JavaScriptFunction^>(engine_->Array_prototype_->GetPropertyByName(L"push"))->Invoke(arg);
}

void JavaScriptArray::Reverse()
{
    auto arg = ref new Vector<IJavaScriptValue^>(1);
    arg->Append(this);
    safe_cast<JavaScriptFunction^>(engine_->Array_prototype_->GetPropertyByName(L"reverse"))->Invoke(arg);
}

IJavaScriptValue^ JavaScriptArray::Shift()
{
    auto arg = ref new Vector<IJavaScriptValue^>(1);
    arg->Append(this);
    return safe_cast<JavaScriptFunction^>(engine_->Array_prototype_->GetPropertyByName(L"shift"))->Invoke(arg);
}

int32 JavaScriptArray::Unshift(IIterable<IJavaScriptValue^>^ valuesToInsert)
{
    if (valuesToInsert == nullptr)
        throw ref new Exception(E_INVALIDARG);

    auto arg = ref new Vector<IJavaScriptValue^>();
    arg->Append(this);
    auto iter = valuesToInsert->First();
    while (iter->HasCurrent) {
        arg->Append(iter->Current);
        iter->MoveNext();
    }
    return engine_->Converter->ToDouble(safe_cast<JavaScriptFunction^>(engine_->Array_prototype_->GetPropertyByName(L"unshift"))->Invoke(arg));
}

void JavaScriptArray::Sort(JavaScriptFunction^ compareFunction)
{
    auto arg = ref new Vector<IJavaScriptValue^>();
    arg->Append(this);
    if (compareFunction != nullptr)
        arg->Append(compareFunction);

    safe_cast<JavaScriptFunction^>(engine_->Array_prototype_->GetPropertyByName(L"sort"))->Invoke(arg);
}

JavaScriptArray^ JavaScriptArray::Splice(uint32 index, uint32 numberToRemove, IIterable<IJavaScriptValue^>^ valuesToInsert)
{
    auto arg = ref new Vector<IJavaScriptValue^>();
    arg->Append(this);
    arg->Append(engine_->Converter->FromDouble(index));
    arg->Append(engine_->Converter->FromDouble(numberToRemove));
    if (valuesToInsert != nullptr)
    {
        auto iter = valuesToInsert->First();
        while (iter->HasCurrent)
        {
            arg->Append(iter->Current);
            iter->MoveNext();
        }
    }

    return safe_cast<JavaScriptArray^>(safe_cast<JavaScriptFunction^>(engine_->Array_prototype_->GetPropertyByName(L"splice"))->Invoke(arg));
}

JavaScriptArray^ JavaScriptArray::Concat(IIterable<IJavaScriptValue^>^ itemsToConcatenate)
{
    if (itemsToConcatenate == nullptr)
        throw ref new Exception(E_INVALIDARG);

    auto arg = ref new Vector<IJavaScriptValue^>();
    arg->Append(this);
    auto iter = itemsToConcatenate->First();
    while (iter->HasCurrent)
    {
        arg->Append(iter->Current);
        iter->MoveNext();
    }

    return safe_cast<JavaScriptArray^>(safe_cast<JavaScriptFunction^>(engine_->Array_prototype_->GetPropertyByName(L"concat"))->Invoke(arg));
}

String^ JavaScriptArray::Join(String^ separator)
{
    auto arg = ref new Vector<IJavaScriptValue^>(2);
    arg->Append(this);
    arg->Append(engine_->Converter->FromString(separator));

    return engine_->Converter->ToString(safe_cast<JavaScriptFunction^>(engine_->Array_prototype_->GetPropertyByName(L"join"))->Invoke(arg));
}

JavaScriptArray^ JavaScriptArray::Slice(int32 beginning)
{
    auto arg = ref new Vector<IJavaScriptValue^>(2);
    arg->Append(this);
    arg->Append(engine_->Converter->FromDouble(beginning));

    return safe_cast<JavaScriptArray^>(safe_cast<JavaScriptFunction^>(engine_->Array_prototype_->GetPropertyByName(L"slice"))->Invoke(arg));
}

JavaScriptArray^ JavaScriptArray::Slice(int32 beginning, int32 end)
{
    auto arg = ref new Vector<IJavaScriptValue^>(3);
    arg->Append(this);
    arg->Append(engine_->Converter->FromDouble(beginning));
    arg->Append(engine_->Converter->FromDouble(end));

    return safe_cast<JavaScriptArray^>(safe_cast<JavaScriptFunction^>(engine_->Array_prototype_->GetPropertyByName(L"slice"))->Invoke(arg));
}

int32 JavaScriptArray::IndexOf(IJavaScriptValue^ valueToFind)
{
    auto arg = ref new Vector<IJavaScriptValue^>(2);
    arg->Append(this);
    arg->Append(valueToFind);

    return engine_->Converter->ToDouble((safe_cast<JavaScriptFunction^>(engine_->Array_prototype_->GetPropertyByName(L"indexOf"))->Invoke(arg)));
}

int32 JavaScriptArray::IndexOf(IJavaScriptValue^ valueToFind, int32 startIndex)
{
    auto arg = ref new Vector<IJavaScriptValue^>(3);
    arg->Append(this);
    arg->Append(valueToFind);
    arg->Append(engine_->Converter->FromDouble(startIndex));

    return engine_->Converter->ToDouble((safe_cast<JavaScriptFunction^>(engine_->Array_prototype_->GetPropertyByName(L"indexOf"))->Invoke(arg)));
}

int32 JavaScriptArray::LastIndexOf(IJavaScriptValue^ valueToFind)
{
    auto arg = ref new Vector<IJavaScriptValue^>(2);
    arg->Append(this);
    arg->Append(valueToFind);

    return engine_->Converter->ToDouble((safe_cast<JavaScriptFunction^>(engine_->Array_prototype_->GetPropertyByName(L"lastIndexOf"))->Invoke(arg)));
}

int32 JavaScriptArray::LastIndexOf(IJavaScriptValue^ valueToFind, int32 lastIndex)
{
    auto arg = ref new Vector<IJavaScriptValue^>(3);
    arg->Append(this);
    arg->Append(valueToFind);
    arg->Append(engine_->Converter->FromDouble(lastIndex));

    return engine_->Converter->ToDouble((safe_cast<JavaScriptFunction^>(engine_->Array_prototype_->GetPropertyByName(L"lastIndexOf"))->Invoke(arg)));
}

void JavaScriptArray::ForEach(JavaScriptFunction^ callee)
{
    if (callee == nullptr)
        throw ref new Exception(E_INVALIDARG);

    auto arg = ref new Vector<IJavaScriptValue^>(2);
    arg->Append(this);
    arg->Append(callee);

    safe_cast<JavaScriptFunction^>(engine_->Array_prototype_->GetPropertyByName(L"forEach"))->Invoke(arg);
}

bool JavaScriptArray::Every(JavaScriptFunction^ predicate)
{
    if (predicate == nullptr)
        throw ref new Exception(E_INVALIDARG);

    auto arg = ref new Vector<IJavaScriptValue^>(2);
    arg->Append(this);
    arg->Append(predicate);

    return engine_->Converter->ToBoolean(safe_cast<JavaScriptFunction^>(engine_->Array_prototype_->GetPropertyByName(L"every"))->Invoke(arg));
}

bool JavaScriptArray::Some(JavaScriptFunction^ predicate)
{
    if (predicate == nullptr)
        throw ref new Exception(E_INVALIDARG);

    auto arg = ref new Vector<IJavaScriptValue^>(2);
    arg->Append(this);
    arg->Append(predicate);

    return engine_->Converter->ToBoolean(safe_cast<JavaScriptFunction^>(engine_->Array_prototype_->GetPropertyByName(L"some"))->Invoke(arg));
}

JavaScriptArray^ JavaScriptArray::Filter(JavaScriptFunction^ predicate)
{
    if (predicate == nullptr)
        throw ref new Exception(E_INVALIDARG);

    auto arg = ref new Vector<IJavaScriptValue^>(2);
    arg->Append(this);
    arg->Append(predicate);

    return safe_cast<JavaScriptArray^>(safe_cast<JavaScriptFunction^>(engine_->Array_prototype_->GetPropertyByName(L"filter"))->Invoke(arg));
}

JavaScriptArray^ JavaScriptArray::Map(JavaScriptFunction^ converter)
{
    if (converter == nullptr)
        throw ref new Exception(E_INVALIDARG);

    auto arg = ref new Vector<IJavaScriptValue^>(2);
    arg->Append(this);
    arg->Append(converter);

    return safe_cast<JavaScriptArray^>(safe_cast<JavaScriptFunction^>(engine_->Array_prototype_->GetPropertyByName(L"map"))->Invoke(arg));
}

IJavaScriptValue^ JavaScriptArray::Reduce(JavaScriptFunction^ aggregator)
{
    if (aggregator == nullptr)
        throw ref new Exception(E_INVALIDARG);

    auto arg = ref new Vector<IJavaScriptValue^>(2);
    arg->Append(this);
    arg->Append(aggregator);

    return safe_cast<JavaScriptFunction^>(engine_->Array_prototype_->GetPropertyByName(L"reduce"))->Invoke(arg);
}

IJavaScriptValue^ JavaScriptArray::Reduce(JavaScriptFunction^ aggregator, IJavaScriptValue^ initialValue)
{
    if (aggregator == nullptr)
        throw ref new Exception(E_INVALIDARG);
    if (initialValue == nullptr)
        initialValue = engine_->UndefinedValue;

    auto arg = ref new Vector<IJavaScriptValue^>(3);
    arg->Append(this);
    arg->Append(aggregator);
    arg->Append(initialValue);

    return safe_cast<JavaScriptFunction^>(engine_->Array_prototype_->GetPropertyByName(L"reduce"))->Invoke(arg);
}

IJavaScriptValue^ JavaScriptArray::ReduceRight(JavaScriptFunction^ aggregator)
{
    if (aggregator == nullptr)
        throw ref new Exception(E_INVALIDARG);

    auto arg = ref new Vector<IJavaScriptValue^>(2);
    arg->Append(this);
    arg->Append(aggregator);

    return safe_cast<JavaScriptFunction^>(engine_->Array_prototype_->GetPropertyByName(L"reduceRight"))->Invoke(arg);
}

IJavaScriptValue^ JavaScriptArray::ReduceRight(JavaScriptFunction^ aggregator, IJavaScriptValue^ initialValue)
{
    if (aggregator == nullptr)
        throw ref new Exception(E_INVALIDARG);
    if (initialValue == nullptr)
        initialValue = engine_->UndefinedValue;

    auto arg = ref new Vector<IJavaScriptValue^>();
    arg->Append(this);
    arg->Append(aggregator);
    arg->Append(initialValue);

    return safe_cast<JavaScriptFunction^>(engine_->Array_prototype_->GetPropertyByName(L"reduceRight"))->Invoke(arg);
}

DECLARE_JAVASCRIPT_OBJECT_IMPLEMENTATION(JavaScriptArray)
<|endoftext|>