code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#define LOG4CXX_TEST 1
#include <log4cxx/private/log4cxx_private.h>
#include "../logunit.h"
#include <log4cxx/logger.h>
#include <log4cxx/xml/domconfigurator.h>
#include <log4cxx/consoleappender.h>
#include <log4cxx/patternlayout.h>
#include <log4cxx/file.h>
#include "../util/compare.h"
#include "xlevel.h"
#include "../testchar.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::xml;
LOGUNIT_CLASS(CustomLevelTestCase)
{
LOGUNIT_TEST_SUITE(CustomLevelTestCase);
LOGUNIT_TEST(test1);
LOGUNIT_TEST(test2);
LOGUNIT_TEST(test3);
LOGUNIT_TEST(test4);
LOGUNIT_TEST_SUITE_END();
LoggerPtr root;
LoggerPtr logger;
static const File TEMP;
public:
void setUp()
{
root = Logger::getRootLogger();
logger = Logger::getLogger(LOG4CXX_TEST_STR("xml.CustomLevelTestCase"));
}
void tearDown()
{
root->getLoggerRepository()->resetConfiguration();
LoggerPtr logger1 = Logger::getLogger(LOG4CXX_TEST_STR("LOG4J"));
logger1->setAdditivity(false);
logger1->addAppender(
new ConsoleAppender(new PatternLayout(LOG4CXX_STR("log4j: %-22c{2} - %m%n"))));
}
void test1()
{
DOMConfigurator::configure(LOG4CXX_TEST_STR("input/xml/customLevel1.xml"));
common();
const File witness("witness/customLevel.1");
LOGUNIT_ASSERT(Compare::compare(TEMP, witness));
}
void test2()
{
DOMConfigurator::configure(LOG4CXX_TEST_STR("input/xml/customLevel2.xml"));
common();
const File witness("witness/customLevel.2");
LOGUNIT_ASSERT(Compare::compare(TEMP, witness));
}
void test3()
{
DOMConfigurator::configure(LOG4CXX_TEST_STR("input/xml/customLevel3.xml"));
common();
const File witness("witness/customLevel.3");
LOGUNIT_ASSERT(Compare::compare(TEMP, witness));
}
void test4()
{
DOMConfigurator::configure(LOG4CXX_TEST_STR("input/xml/customLevel4.xml"));
common();
const File witness("witness/customLevel.4");
LOGUNIT_ASSERT(Compare::compare(TEMP, witness));
}
void common()
{
int i = 0;
std::ostringstream os;
os << "Message " << ++i;
LOG4CXX_DEBUG(logger, os.str());
os.str("");
os << "Message " << ++i;
LOG4CXX_INFO(logger, os.str());
os.str("");
os << "Message " << ++i;
LOG4CXX_WARN(logger, os.str());
os.str("");
os << "Message " << ++i;
LOG4CXX_ERROR(logger, os.str());
os.str("");
os << "Message " << ++i;
LOG4CXX_LOG(logger, XLevel::getTrace(), os.str());
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(CustomLevelTestCase);
const File CustomLevelTestCase::TEMP("output/temp");
| 001-log4cxx | trunk/src/test/cpp/xml/customleveltestcase.cpp | C++ | asf20 | 3,568 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "../logunit.h"
#include <log4cxx/logger.h>
#include <log4cxx/xml/xmllayout.h>
#include <log4cxx/fileappender.h>
#include <log4cxx/mdc.h>
#include "../util/transformer.h"
#include "../util/compare.h"
#include "../util/xmltimestampfilter.h"
#include "../util/xmllineattributefilter.h"
#include "../util/xmlthreadfilter.h"
#include "../util/filenamefilter.h"
#include <iostream>
#include <log4cxx/helpers/stringhelper.h>
#include "../testchar.h"
#include <log4cxx/spi/loggerrepository.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::xml;
#if defined(__LOG4CXX_FUNC__)
#undef __LOG4CXX_FUNC__
#define __LOG4CXX_FUNC__ "X::X()"
#else
#error __LOG4CXX_FUNC__ expected to be defined
#endif
class X
{
public:
X()
{
LoggerPtr logger =
Logger::getLogger(LOG4CXX_TEST_STR("org.apache.log4j.xml.XMLLayoutTestCase$X"));
LOG4CXX_INFO(logger, LOG4CXX_TEST_STR("in X() constructor"));
}
};
LOGUNIT_CLASS(XMLLayoutTestCase)
{
LOGUNIT_TEST_SUITE(XMLLayoutTestCase);
LOGUNIT_TEST(basic);
LOGUNIT_TEST(locationInfo);
LOGUNIT_TEST(testCDATA);
LOGUNIT_TEST(testNull);
LOGUNIT_TEST(testMDC);
LOGUNIT_TEST(testMDCEscaped);
LOGUNIT_TEST_SUITE_END();
LoggerPtr root;
LoggerPtr logger;
public:
void setUp()
{
root = Logger::getRootLogger();
root->setLevel(Level::getTrace());
logger = Logger::getLogger(LOG4CXX_TEST_STR("org.apache.log4j.xml.XMLLayoutTestCase"));
logger->setLevel(Level::getTrace());
}
void tearDown()
{
logger->getLoggerRepository()->resetConfiguration();
}
void basic()
{
const LogString tempFileName(LOG4CXX_STR("output/temp.xmlLayout.1"));
const File filteredFile("output/filtered.xmlLayout.1");
XMLLayoutPtr xmlLayout = new XMLLayout();
AppenderPtr appender(new FileAppender(xmlLayout, tempFileName, false));
root->addAppender(appender);
common();
XMLTimestampFilter xmlTimestampFilter;
XMLThreadFilter xmlThreadFilter;
std::vector<Filter *> filters;
filters.push_back(&xmlThreadFilter);
filters.push_back(&xmlTimestampFilter);
try
{
Transformer::transform(tempFileName, filteredFile, filters);
}
catch(UnexpectedFormatException& e)
{
std::cout << "UnexpectedFormatException :" << e.what() << std::endl;
throw;
}
LOGUNIT_ASSERT(Compare::compare(filteredFile, LOG4CXX_FILE("witness/xmlLayout.1")));
}
void locationInfo()
{
const LogString tempFileName(LOG4CXX_STR("output/temp.xmlLayout.2"));
const File filteredFile("output/filtered.xmlLayout.2");
XMLLayoutPtr xmlLayout = new XMLLayout();
xmlLayout->setLocationInfo(true);
root->addAppender(new FileAppender(xmlLayout, tempFileName, false));
common();
XMLTimestampFilter xmlTimestampFilter;
XMLThreadFilter xmlThreadFilter;
FilenameFilter xmlFilenameFilter(__FILE__, "XMLLayoutTestCase.java");
Filter line2XX("[23][0-9][0-9]", "X");
Filter line5X("5[0-9]", "X");
std::vector<Filter *> filters;
filters.push_back(&xmlFilenameFilter);
filters.push_back(&xmlThreadFilter);
filters.push_back(&xmlTimestampFilter);
filters.push_back(&line2XX);
filters.push_back(&line5X);
try
{
Transformer::transform(tempFileName, filteredFile, filters);
}
catch(UnexpectedFormatException& e)
{
std::cout << "UnexpectedFormatException :" << e.what() << std::endl;
throw;
}
LOGUNIT_ASSERT(Compare::compare(filteredFile, LOG4CXX_FILE("witness/xmlLayout.2")));
}
#undef __LOG4CXX_FUNC__
#define __LOG4CXX_FUNC__ "void XMLLayoutTestCase::testCDATA()"
void testCDATA()
{
const LogString tempFileName(LOG4CXX_STR("output/temp.xmlLayout.3"));
const File filteredFile("output/filtered.xmlLayout.3");
XMLLayoutPtr xmlLayout = new XMLLayout();
xmlLayout->setLocationInfo(true);
FileAppenderPtr appender(new FileAppender(xmlLayout, tempFileName, false));
root->addAppender(appender);
LOG4CXX_TRACE(logger,
LOG4CXX_TEST_STR("Message with embedded <![CDATA[<hello>hi</hello>]]>."));
LOG4CXX_DEBUG(logger,
LOG4CXX_TEST_STR("Message with embedded <![CDATA[<hello>hi</hello>]]>."));
XMLTimestampFilter xmlTimestampFilter;
XMLThreadFilter xmlThreadFilter;
FilenameFilter xmlFilenameFilter(__FILE__, "XMLLayoutTestCase.java");
Filter line1xx("1[0-9][0-9]", "X");
std::vector<Filter *> filters;
filters.push_back(&xmlFilenameFilter);
filters.push_back(&xmlThreadFilter);
filters.push_back(&xmlTimestampFilter);
filters.push_back(&line1xx);
try
{
Transformer::transform(tempFileName, filteredFile, filters);
}
catch(UnexpectedFormatException& e)
{
std::cout << "UnexpectedFormatException :" << e.what() << std::endl;
throw;
}
LOGUNIT_ASSERT(Compare::compare(filteredFile, LOG4CXX_FILE("witness/xmlLayout.3")));
}
void testNull()
{
const LogString tempFileName(LOG4CXX_STR("output/temp.xmlLayout.null"));
const File filteredFile("output/filtered.xmlLayout.null");
XMLLayoutPtr xmlLayout = new XMLLayout();
FileAppenderPtr appender(new FileAppender(xmlLayout, tempFileName, false));
root->addAppender(appender);
LOG4CXX_DEBUG(logger, LOG4CXX_TEST_STR("hi"));
LOG4CXX_DEBUG(logger, (char*) 0);
LOG4CXX_DEBUG(logger, "hi");
XMLTimestampFilter xmlTimestampFilter;
XMLThreadFilter xmlThreadFilter;
std::vector<Filter *> filters;
filters.push_back(&xmlThreadFilter);
filters.push_back(&xmlTimestampFilter);
try
{
Transformer::transform(tempFileName, filteredFile, filters);
}
catch(UnexpectedFormatException& e)
{
std::cout << "UnexpectedFormatException :" << e.what() << std::endl;
throw;
}
LOGUNIT_ASSERT(Compare::compare(filteredFile, LOG4CXX_FILE("witness/xmlLayout.null")));
}
void testMDC()
{
const LogString tempFileName(LOG4CXX_STR("output/temp.xmlLayout.mdc.1"));
const File filteredFile("output/filtered.xmlLayout.mdc.1");
XMLLayoutPtr xmlLayout = new XMLLayout();
xmlLayout->setProperties(true);
FileAppenderPtr appender(new FileAppender(xmlLayout, tempFileName, false));
root->addAppender(appender);
MDC::clear();
MDC::put(LOG4CXX_TEST_STR("key1"), LOG4CXX_TEST_STR("val1"));
MDC::put(LOG4CXX_TEST_STR("key2"), LOG4CXX_TEST_STR("val2"));
LOG4CXX_DEBUG(logger, LOG4CXX_TEST_STR("Hello"));
MDC::clear();
XMLTimestampFilter xmlTimestampFilter;
XMLThreadFilter xmlThreadFilter;
std::vector<Filter *> filters;
filters.push_back(&xmlThreadFilter);
filters.push_back(&xmlTimestampFilter);
try
{
Transformer::transform(tempFileName, filteredFile, filters);
}
catch(UnexpectedFormatException& e)
{
std::cout << "UnexpectedFormatException :" << e.what() << std::endl;
throw;
}
LOGUNIT_ASSERT(Compare::compare(filteredFile, LOG4CXX_FILE("witness/xmlLayout.mdc.1")));
}
// not incuded in the tests for the moment !
void testMDCEscaped()
{
const LogString tempFileName(LOG4CXX_STR("output/temp.xmlLayout.mdc.2"));
const File filteredFile("output/filtered.xmlLayout.mdc.2");
XMLLayoutPtr xmlLayout = new XMLLayout();
xmlLayout->setProperties(true);
FileAppenderPtr appender(new FileAppender(xmlLayout, tempFileName, false));
root->addAppender(appender);
MDC::clear();
MDC::put(LOG4CXX_TEST_STR("blahAttribute"), LOG4CXX_TEST_STR("<blah value='blah'>"));
MDC::put(LOG4CXX_TEST_STR("<blahKey value='blah'/>"), LOG4CXX_TEST_STR("blahValue"));
LOG4CXX_DEBUG(logger, LOG4CXX_TEST_STR("Hello"));
MDC::clear();
XMLTimestampFilter xmlTimestampFilter;
XMLThreadFilter xmlThreadFilter;
std::vector<Filter *> filters;
filters.push_back(&xmlThreadFilter);
filters.push_back(&xmlTimestampFilter);
try
{
Transformer::transform(tempFileName, filteredFile, filters);
}
catch(UnexpectedFormatException& e)
{
std::cout << "UnexpectedFormatException :" << e.what() << std::endl;
throw;
}
LOGUNIT_ASSERT(Compare::compare(filteredFile, LOG4CXX_FILE("witness/xmlLayout.mdc.2")));
}
#undef __LOG4CXX_FUNC__
#define __LOG4CXX_FUNC__ "void XMLLayoutTestCase::common()"
void common()
{
int i = 0;
X x;
std::string msg("Message ");
LOG4CXX_TRACE(logger, msg << i);
LOG4CXX_TRACE(root, msg << i);
i++;
LOG4CXX_DEBUG(logger, msg << i);
LOG4CXX_DEBUG(root, msg << i);
i++;
LOG4CXX_INFO(logger, msg << i);
LOG4CXX_INFO(root, msg << i);
i++;
LOG4CXX_WARN(logger, msg << i);
LOG4CXX_WARN(root, msg << i);
i++;
LOG4CXX_ERROR(logger, msg << i);
LOG4CXX_ERROR(root, msg << i);
i++;
LOG4CXX_FATAL(logger, msg << i);
LOG4CXX_FATAL(root, msg << i);
i++;
LOG4CXX_DEBUG(logger, "Message " << i);
LOG4CXX_DEBUG(root, "Message " << i);
i++;
LOG4CXX_ERROR(logger, "Message " << i);
LOG4CXX_ERROR(root, "Message " << i);
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(XMLLayoutTestCase);
| 001-log4cxx | trunk/src/test/cpp/xml/xmllayouttestcase.cpp | C++ | asf20 | 12,573 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "../logunit.h"
#include <log4cxx/logger.h>
#include <log4cxx/xml/xmllayout.h>
#include <log4cxx/fileappender.h>
#include <log4cxx/mdc.h>
#include "../util/transformer.h"
#include "../util/compare.h"
#include "../util/xmltimestampfilter.h"
#include "../util/xmllineattributefilter.h"
#include "../util/xmlthreadfilter.h"
#include "../util/filenamefilter.h"
#include <iostream>
#include <log4cxx/helpers/stringhelper.h>
#include "../testchar.h"
#include <log4cxx/spi/loggerrepository.h>
#include <apr_xml.h>
#include <log4cxx/ndc.h>
#include <log4cxx/mdc.h>
#include "../xml/xlevel.h"
#include <log4cxx/helpers/bytebuffer.h>
#include <log4cxx/helpers/transcoder.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::xml;
using namespace log4cxx::spi;
#if defined(__LOG4CXX_FUNC__)
#undef __LOG4CXX_FUNC__
#define __LOG4CXX_FUNC__ "X::X()"
#else
#error __LOG4CXX_FUNC__ expected to be defined
#endif
/**
* Test for XMLLayout.
*
*/
LOGUNIT_CLASS(XMLLayoutTest) {
LOGUNIT_TEST_SUITE(XMLLayoutTest);
LOGUNIT_TEST(testGetContentType);
LOGUNIT_TEST(testIgnoresThrowable);
LOGUNIT_TEST(testGetHeader);
LOGUNIT_TEST(testGetFooter);
LOGUNIT_TEST(testFormat);
LOGUNIT_TEST(testFormatWithNDC);
LOGUNIT_TEST(testGetSetLocationInfo);
LOGUNIT_TEST(testActivateOptions);
LOGUNIT_TEST(testProblemCharacters);
LOGUNIT_TEST(testNDCWithCDATA);
LOGUNIT_TEST_SUITE_END();
public:
/**
* Clear MDC and NDC before test.
*/
void setUp() {
NDC::clear();
MDC::clear();
}
/**
* Clear MDC and NDC after test.
*/
void tearDown() {
setUp();
}
public:
/**
* Tests getContentType.
*/
void testGetContentType() {
LogString expected(LOG4CXX_STR("text/plain"));
LogString actual(XMLLayout().getContentType());
LOGUNIT_ASSERT(expected == actual);
}
/**
* Tests ignoresThrowable.
*/
void testIgnoresThrowable() {
LOGUNIT_ASSERT_EQUAL(false, XMLLayout().ignoresThrowable());
}
/**
* Tests getHeader.
*/
void testGetHeader() {
Pool p;
LogString header;
XMLLayout().appendHeader(header, p);
LOGUNIT_ASSERT_EQUAL((size_t) 0, header.size());
}
/**
* Tests getFooter.
*/
void testGetFooter() {
Pool p;
LogString footer;
XMLLayout().appendFooter(footer, p);
LOGUNIT_ASSERT_EQUAL((size_t) 0, footer.size());
}
private:
/**
* Parses the string as the body of an XML document and returns the document element.
* @param source source string.
* @return document element.
* @throws Exception if parser can not be constructed or source is not a valid XML document.
*/
static apr_xml_elem* parse(const LogString& source, Pool& p) {
char backing[3000];
ByteBuffer buf(backing, sizeof(backing));
CharsetEncoderPtr encoder(CharsetEncoder::getUTF8Encoder());
LogString header(LOG4CXX_STR("<log4j:eventSet xmlns:log4j='http://jakarta.apache.org/log4j/'>"));
LogString::const_iterator iter(header.begin());
encoder->encode(header, iter, buf);
LOGUNIT_ASSERT(iter == header.end());
iter = source.begin();
encoder->encode(source, iter, buf);
LOGUNIT_ASSERT(iter == source.end());
LogString footer(LOG4CXX_STR("</log4j:eventSet>"));
iter = footer.begin();
encoder->encode(footer, iter, buf);
buf.flip();
apr_pool_t* apr_pool = p.getAPRPool();
apr_xml_parser* parser = apr_xml_parser_create(apr_pool);
LOGUNIT_ASSERT(parser != 0);
apr_status_t stat = apr_xml_parser_feed(parser, buf.data(), buf.remaining());
LOGUNIT_ASSERT(stat == APR_SUCCESS);
apr_xml_doc* doc = 0;
stat = apr_xml_parser_done(parser, &doc);
LOGUNIT_ASSERT(doc != 0);
apr_xml_elem* eventSet = doc->root;
LOGUNIT_ASSERT(eventSet != 0);
apr_xml_elem* event = eventSet->first_child;
LOGUNIT_ASSERT(event != 0);
return event;
}
std::string getAttribute(apr_xml_elem* elem, const char* attrName) {
for(apr_xml_attr* attr = elem->attr;
attr != NULL;
attr = attr->next) {
if (strcmp(attr->name, attrName) == 0) {
return attr->value;
}
}
return "";
}
std::string getText(apr_xml_elem* elem) {
std::string dMessage;
for(apr_text* t = elem->first_cdata.first;
t != NULL;
t = t->next) {
dMessage.append(t->text);
}
return dMessage;
}
/**
* Checks a log4j:event element against expectations.
* @param element element, may not be null.
* @param event event, may not be null.
*/
void checkEventElement(
apr_xml_elem* element, LoggingEventPtr& event) {
std::string tagName("event");
LOGUNIT_ASSERT_EQUAL(tagName, (std::string) element->name);
LOG4CXX_ENCODE_CHAR(cLoggerName, event->getLoggerName());
LOGUNIT_ASSERT_EQUAL(cLoggerName, getAttribute(element, "logger"));
LOG4CXX_ENCODE_CHAR(cLevelName, event->getLevel()->toString());
LOGUNIT_ASSERT_EQUAL(cLevelName, getAttribute(element, "level"));
}
/**
* Checks a log4j:message element against expectations.
* @param element element, may not be null.
* @param message expected message.
*/
void checkMessageElement(
apr_xml_elem* element, std::string message) {
std::string tagName = "message";
LOGUNIT_ASSERT_EQUAL(tagName, (std::string) element->name);
LOGUNIT_ASSERT_EQUAL(message, getText(element));
}
/**
* Checks a log4j:message element against expectations.
* @param element element, may not be null.
* @param message expected message.
*/
void checkNDCElement(apr_xml_elem* element, std::string message) {
std::string tagName = "NDC";
LOGUNIT_ASSERT_EQUAL(tagName, (std::string) element->name);
std::string dMessage = getText(element);
LOGUNIT_ASSERT_EQUAL(message, dMessage);
}
/**
* Checks a log4j:properties element against expectations.
* @param element element, may not be null.
* @param key key.
* @param value value.
*/
void checkPropertiesElement(
apr_xml_elem* element, std::string key, std::string value) {
std::string tagName = "properties";
std::string dataTag = "data";
int childNodeCount = 0;
LOGUNIT_ASSERT_EQUAL(tagName, (std::string) element->name);
for(apr_xml_elem* child = element->first_child;
child != NULL;
child = child->next) {
LOGUNIT_ASSERT_EQUAL(dataTag, (std::string) child->name);
LOGUNIT_ASSERT_EQUAL(key, getAttribute(child, "name"));
LOGUNIT_ASSERT_EQUAL(value, getAttribute(child, "value"));
childNodeCount++;
}
LOGUNIT_ASSERT_EQUAL(1, childNodeCount);
}
public:
/**
* Tests formatted results.
* @throws Exception if parser can not be constructed or source is not a valid XML document.
*/
void testFormat() {
LogString logger = LOG4CXX_STR("org.apache.log4j.xml.XMLLayoutTest");
LoggingEventPtr event =
new LoggingEvent(
logger, Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION);
Pool p;
XMLLayout layout;
LogString result;
layout.format(result, event, p);
apr_xml_elem* parsedResult = parse(result, p);
checkEventElement(parsedResult, event);
int childElementCount = 0;
for (
apr_xml_elem* node = parsedResult->first_child;
node != NULL;
node = node->next) {
childElementCount++;
checkMessageElement(node, "Hello, World");
}
LOGUNIT_ASSERT_EQUAL(1, childElementCount);
}
/**
* Tests formatted results with an exception.
* @throws Exception if parser can not be constructed or source is not a valid XML document.
*/
void testFormatWithNDC() {
LogString logger = LOG4CXX_STR("org.apache.log4j.xml.XMLLayoutTest");
NDC::push("NDC goes here");
LoggingEventPtr event =
new LoggingEvent(
logger, Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION);
Pool p;
XMLLayout layout;
LogString result;
layout.format(result, event, p);
NDC::pop();
apr_xml_elem* parsedResult = parse(result, p);
checkEventElement(parsedResult, event);
int childElementCount = 0;
for (
apr_xml_elem* node = parsedResult->first_child; node != NULL;
node = node->next) {
childElementCount++;
if (childElementCount == 1) {
checkMessageElement(node, "Hello, World");
} else {
checkNDCElement(node, "NDC goes here");
}
}
LOGUNIT_ASSERT_EQUAL(2, childElementCount);
}
/**
* Tests getLocationInfo and setLocationInfo.
*/
void testGetSetLocationInfo() {
XMLLayout layout;
LOGUNIT_ASSERT_EQUAL(false, layout.getLocationInfo());
layout.setLocationInfo(true);
LOGUNIT_ASSERT_EQUAL(true, layout.getLocationInfo());
layout.setLocationInfo(false);
LOGUNIT_ASSERT_EQUAL(false, layout.getLocationInfo());
}
/**
* Tests activateOptions().
*/
void testActivateOptions() {
Pool p;
XMLLayout layout;
layout.activateOptions(p);
}
/**
* Tests problematic characters in multiple fields.
* @throws Exception if parser can not be constructed or source is not a valid XML document.
*/
void testProblemCharacters() {
std::string problemName = "com.example.bar<>&\"'";
LogString problemNameLS = LOG4CXX_STR("com.example.bar<>&\"'");
LevelPtr level = new XLevel(6000, problemNameLS, 7);
NDC::push(problemName);
MDC::clear();
MDC::put(problemName, problemName);
LoggingEventPtr event =
new LoggingEvent(problemNameLS, level, problemNameLS, LOG4CXX_LOCATION);
XMLLayout layout;
layout.setProperties(true);
Pool p;
LogString result;
layout.format(result, event, p);
MDC::clear();
apr_xml_elem* parsedResult = parse(result, p);
checkEventElement(parsedResult, event);
int childElementCount = 0;
for (
apr_xml_elem* node = parsedResult->first_child; node != NULL;
node = node->next) {
childElementCount++;
switch(childElementCount) {
case 1:
checkMessageElement(node, problemName);
break;
case 2:
checkNDCElement(node, problemName);
break;
case 3:
checkPropertiesElement(node, problemName.c_str(), problemName.c_str());
break;
default:
break;
}
}
LOGUNIT_ASSERT_EQUAL(3, childElementCount);
}
/**
* Tests CDATA element within NDC content. See bug 37560.
*/
void testNDCWithCDATA() {
LogString logger = LOG4CXX_STR("com.example.bar");
LevelPtr level = Level::getInfo();
std::string ndcMessage ="<envelope><faultstring><![CDATA[The EffectiveDate]]></faultstring><envelope>";
NDC::push(ndcMessage);
LoggingEventPtr event =
new LoggingEvent(
logger, level, LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION);
XMLLayout layout;
Pool p;
LogString result;
layout.format(result, event, p);
NDC::clear();
apr_xml_elem* parsedResult = parse(result, p);
int ndcCount = 0;
for(apr_xml_elem* node = parsedResult->first_child;
node != NULL;
node = node->next) {
if (strcmp(node->name, "NDC") == 0) {
ndcCount++;
LOGUNIT_ASSERT_EQUAL(ndcMessage, getText(node));
}
}
LOGUNIT_ASSERT_EQUAL(1, ndcCount);
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(XMLLayoutTest);
| 001-log4cxx | trunk/src/test/cpp/xml/xmllayouttest.cpp | C++ | asf20 | 12,641 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "xlevel.h"
#include <log4cxx/helpers/stringhelper.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_LEVEL(XLevel)
XLevel::XLevel(int level1, const LogString& name1, int syslogEquivalent1)
: Level(level1, name1, syslogEquivalent1)
{
}
LevelPtr XLevel::getTrace() {
static const LevelPtr trace(new XLevel(XLevel::TRACE_INT, LOG4CXX_STR("TRACE"), 7));
return trace;
}
LevelPtr XLevel::getLethal() {
static const LevelPtr lethal(new XLevel(XLevel::LETHAL_INT, LOG4CXX_STR("LETHAL"), 0));
return lethal;
}
LevelPtr XLevel::toLevelLS(const LogString& sArg)
{
return toLevelLS(sArg, getTrace());
}
LevelPtr XLevel::toLevel(int val)
{
return toLevel(val, getTrace());
}
LevelPtr XLevel::toLevel(int val, const LevelPtr& defaultLevel)
{
switch(val)
{
case TRACE_INT: return getTrace();
case LETHAL_INT: return getLethal();
default: return defaultLevel;
}
}
LevelPtr XLevel::toLevelLS(const LogString& sArg, const LevelPtr& defaultLevel)
{
if (sArg.empty())
{
return defaultLevel;
}
if (StringHelper::equalsIgnoreCase(sArg,
LOG4CXX_STR("TRACE"), LOG4CXX_STR("trace"))) {
return getTrace();
}
if (StringHelper::equalsIgnoreCase(sArg,
LOG4CXX_STR("LETHAL"), LOG4CXX_STR("lethal"))) {
return getLethal();
}
return Level::toLevel(sArg, defaultLevel);
}
| 001-log4cxx | trunk/src/test/cpp/xml/xlevel.cpp | C++ | asf20 | 2,209 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <log4cxx/logger.h>
#include <log4cxx/xml/domconfigurator.h>
#include "../logunit.h"
#include "../util/compare.h"
#include "xlevel.h"
#include "../util/controlfilter.h"
#include "../util/iso8601filter.h"
#include "../util/threadfilter.h"
#include "../util/transformer.h"
#include <iostream>
#include <log4cxx/file.h>
#include <log4cxx/fileappender.h>
#include <apr_pools.h>
#include <apr_file_io.h>
#include "../testchar.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::xml;
#define TEST1_1A_PAT \
"(DEBUG|INFO |WARN |ERROR|FATAL) \\w*\\.\\w* - Message [0-9]"
#define TEST1_1B_PAT "(DEBUG|INFO |WARN |ERROR|FATAL) root - Message [0-9]"
#define TEST1_2_PAT "^[0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [0-9]\\{2\\}:[0-9]\\{2\\}:[0-9]\\{2\\},[0-9]\\{3\\} " \
"\\[0x[0-9A-F]*]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* - Message [0-9]"
LOGUNIT_CLASS(DOMTestCase)
{
LOGUNIT_TEST_SUITE(DOMTestCase);
LOGUNIT_TEST(test1);
#if defined(_WIN32)
LOGUNIT_TEST(test2);
#endif
LOGUNIT_TEST(test3);
LOGUNIT_TEST(test4);
LOGUNIT_TEST_SUITE_END();
LoggerPtr root;
LoggerPtr logger;
static const File TEMP_A1;
static const File TEMP_A2;
static const File FILTERED_A1;
static const File FILTERED_A2;
static const File TEMP_A1_2;
static const File TEMP_A2_2;
static const File FILTERED_A1_2;
static const File FILTERED_A2_2;
public:
void setUp()
{
root = Logger::getRootLogger();
logger = Logger::getLogger(LOG4CXX_TEST_STR("org.apache.log4j.xml.DOMTestCase"));
}
void tearDown()
{
root->getLoggerRepository()->resetConfiguration();
}
void test1() {
DOMConfigurator::configure(LOG4CXX_TEST_STR("input/xml/DOMTestCase1.xml"));
common();
ControlFilter cf1;
cf1 << TEST1_1A_PAT << TEST1_1B_PAT;
ControlFilter cf2;
cf2 << TEST1_2_PAT;
ThreadFilter threadFilter;
ISO8601Filter iso8601Filter;
std::vector<Filter *> filters1;
filters1.push_back(&cf1);
std::vector<Filter *> filters2;
filters2.push_back(&cf2);
filters2.push_back(&threadFilter);
filters2.push_back(&iso8601Filter);
try
{
Transformer::transform(TEMP_A1, FILTERED_A1, filters1);
Transformer::transform(TEMP_A2, FILTERED_A2, filters2);
}
catch(UnexpectedFormatException& e)
{
std::cout << "UnexpectedFormatException :" << e.what() << std::endl;
throw;
}
const File witness1(LOG4CXX_TEST_STR("witness/dom.A1.1"));
const File witness2(LOG4CXX_TEST_STR("witness/dom.A2.1"));
// TODO: A1 doesn't contain duplicate entries
//
// LOGUNIT_ASSERT(Compare::compare(FILTERED_A1, witness1));
LOGUNIT_ASSERT(Compare::compare(FILTERED_A2, witness2));
}
//
// Same test but backslashes instead of forward
//
void test2() {
DOMConfigurator::configure(LOG4CXX_TEST_STR("input\\xml\\DOMTestCase2.xml"));
common();
ThreadFilter threadFilter;
ISO8601Filter iso8601Filter;
std::vector<Filter *> filters1;
std::vector<Filter *> filters2;
filters2.push_back(&threadFilter);
filters2.push_back(&iso8601Filter);
try
{
Transformer::transform(TEMP_A1_2, FILTERED_A1_2, filters1);
Transformer::transform(TEMP_A2_2, FILTERED_A2_2, filters2);
}
catch(UnexpectedFormatException& e)
{
std::cout << "UnexpectedFormatException :" << e.what() << std::endl;
throw;
}
const File witness1(LOG4CXX_TEST_STR("witness/dom.A1.2"));
const File witness2(LOG4CXX_TEST_STR("witness/dom.A2.2"));
// TODO: A1 doesn't contain duplicate entries
//
// LOGUNIT_ASSERT(Compare::compare(FILTERED_A1, witness1));
LOGUNIT_ASSERT(Compare::compare(FILTERED_A2, witness2));
}
void common()
{
int i = 0;
LOG4CXX_DEBUG(logger, "Message " << i);
LOG4CXX_DEBUG(root, "Message " << i);
i++;
LOG4CXX_INFO(logger, "Message " << i);
LOG4CXX_INFO(root, "Message " << i);
i++;
LOG4CXX_WARN(logger, "Message " << i);
LOG4CXX_WARN(root, "Message " << i);
i++;
LOG4CXX_ERROR(logger, "Message " << i);
LOG4CXX_ERROR(root, "Message " << i);
i++;
LOG4CXX_FATAL(logger, "Message " << i);
LOG4CXX_FATAL(root, "Message " << i);
}
/**
* Creates a output file that ends with a superscript 3.
* Output file is checked by build.xml after completion.
*/
void test3() {
DOMConfigurator::configure(LOG4CXX_TEST_STR("input/xml/DOMTestCase3.xml"));
LOG4CXX_INFO(logger, "File name is expected to end with a superscript 3");
#if LOG4CXX_LOGCHAR_IS_UTF8
const logchar fname[] = { 0x6F, 0x75, 0x74, 0x70, 0x75, 0x74, 0x2F, 0x64, 0x6F, 0x6D, 0xC2, 0xB3, 0 };
#else
const logchar fname[] = { 0x6F, 0x75, 0x74, 0x70, 0x75, 0x74, 0x2F, 0x64, 0x6F, 0x6D, 0xB3, 0 };
#endif
File file;
file.setPath(fname);
Pool p;
bool exists = file.exists(p);
LOGUNIT_ASSERT(exists);
}
/**
* Creates a output file that ends with a ideographic 4.
* Output file is checked by build.xml after completion.
*/
void test4() {
DOMConfigurator::configure(LOG4CXX_TEST_STR("input/xml/DOMTestCase4.xml"));
LOG4CXX_INFO(logger, "File name is expected to end with an ideographic 4");
#if LOG4CXX_LOGCHAR_IS_UTF8
const logchar fname[] = { 0x6F, 0x75, 0x74, 0x70, 0x75, 0x74, 0x2F, 0x64, 0x6F, 0x6D, 0xE3, 0x86, 0x95, 0 };
#else
const logchar fname[] = { 0x6F, 0x75, 0x74, 0x70, 0x75, 0x74, 0x2F, 0x64, 0x6F, 0x6D, 0x3195, 0 };
#endif
File file;
file.setPath(fname);
Pool p;
bool exists = file.exists(p);
LOGUNIT_ASSERT(exists);
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(DOMTestCase);
const File DOMTestCase::TEMP_A1(LOG4CXX_TEST_STR("output/temp.A1"));
const File DOMTestCase::TEMP_A2(LOG4CXX_TEST_STR("output/temp.A2"));
const File DOMTestCase::FILTERED_A1(LOG4CXX_TEST_STR("output/filtered.A1"));
const File DOMTestCase::FILTERED_A2(LOG4CXX_TEST_STR("output/filtered.A2"));
const File DOMTestCase::TEMP_A1_2(LOG4CXX_TEST_STR("output/temp.A1.2"));
const File DOMTestCase::TEMP_A2_2(LOG4CXX_TEST_STR("output/temp.A2.2"));
const File DOMTestCase::FILTERED_A1_2(LOG4CXX_TEST_STR("output/filtered.A1.2"));
const File DOMTestCase::FILTERED_A2_2(LOG4CXX_TEST_STR("output/filtered.A2.2"));
| 001-log4cxx | trunk/src/test/cpp/xml/domtestcase.cpp | C++ | asf20 | 8,552 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <log4cxx/level.h>
namespace log4cxx
{
class XLevel : public Level
{
DECLARE_LOG4CXX_LEVEL(XLevel)
public:
enum
{
TRACE_INT = Level::DEBUG_INT - 1,
LETHAL_INT = Level::FATAL_INT + 1
};
static LevelPtr getTrace();
static LevelPtr getLethal();
XLevel(int level, const LogString& name, int syslogEquivalent);
/**
Convert the string passed as argument to a level. If the
conversion fails, then this method returns #DEBUG.
*/
static LevelPtr toLevelLS(const LogString& sArg);
/**
Convert an integer passed as argument to a level. If the
conversion fails, then this method returns #DEBUG.
*/
static LevelPtr toLevel(int val);
/**
Convert an integer passed as argument to a level. If the
conversion fails, then this method returns the specified default.
*/
static LevelPtr toLevel(int val, const LevelPtr& defaultLevel);
/**
Convert the string passed as argument to a level. If the
conversion fails, then this method returns the value of
<code>defaultLevel</code>.
*/
static LevelPtr toLevelLS(const LogString& sArg,
const LevelPtr& defaultLevel);
};
}
| 001-log4cxx | trunk/src/test/cpp/xml/xlevel.h | C++ | asf20 | 2,086 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <log4cxx/level.h>
#include "testchar.h"
#include "logunit.h"
#if LOG4CXX_CFSTRING_API
#include <CoreFoundation/CFString.h>
#endif
using namespace log4cxx;
LOGUNIT_CLASS(LevelTestCase)
{
LOGUNIT_TEST_SUITE(LevelTestCase);
LOGUNIT_TEST(testToLevelFatal);
LOGUNIT_TEST(testTraceInt);
LOGUNIT_TEST(testTrace);
LOGUNIT_TEST(testIntToTrace);
LOGUNIT_TEST(testStringToTrace);
#if LOG4CXX_WCHAR_T_API
LOGUNIT_TEST(testWideStringToTrace);
#endif
#if LOG4CXX_UNICHAR_API
LOGUNIT_TEST(testUniCharStringToTrace);
#endif
#if LOG4CXX_CFSTRING_API
LOGUNIT_TEST(testCFStringToTrace);
#endif
LOGUNIT_TEST_SUITE_END();
public:
void testToLevelFatal()
{
LevelPtr level(Level::toLevel(LOG4CXX_TEST_STR("fATal")));
LOGUNIT_ASSERT_EQUAL((int) Level::FATAL_INT, level->toInt());
}
/**
* Tests Level::TRACE_INT.
*/
void testTraceInt() {
LOGUNIT_ASSERT_EQUAL(5000, (int) Level::TRACE_INT);
}
/**
* Tests Level.TRACE.
*/
void testTrace() {
LOGUNIT_ASSERT(Level::getTrace()->toString() == LOG4CXX_STR("TRACE"));
LOGUNIT_ASSERT_EQUAL(5000, Level::getTrace()->toInt());
LOGUNIT_ASSERT_EQUAL(7, Level::getTrace()->getSyslogEquivalent());
}
/**
* Tests Level.toLevel(Level.TRACE_INT).
*/
void testIntToTrace() {
LevelPtr trace(Level::toLevel(5000));
LOGUNIT_ASSERT(trace->toString() == LOG4CXX_STR("TRACE"));
}
/**
* Tests Level.toLevel("TRACE");
*/
void testStringToTrace() {
LevelPtr trace(Level::toLevel("TRACE"));
LOGUNIT_ASSERT(trace->toString() == LOG4CXX_STR("TRACE"));
}
#if LOG4CXX_WCHAR_T_API
/**
* Tests Level.toLevel(L"TRACE");
*/
void testWideStringToTrace() {
LevelPtr trace(Level::toLevel(L"TRACE"));
LOGUNIT_ASSERT(trace->toString() == LOG4CXX_STR("TRACE"));
}
#endif
#if LOG4CXX_UNICHAR_API
/**
* Tests Level.toLevel("TRACE");
*/
void testUniCharStringToTrace() {
const log4cxx::UniChar name[] = { 'T', 'R', 'A', 'C', 'E', 0 };
LevelPtr trace(Level::toLevel(name));
LOGUNIT_ASSERT(trace->toString() == LOG4CXX_STR("TRACE"));
}
#endif
#if LOG4CXX_CFSTRING_API
/**
* Tests Level.toLevel(CFSTR("TRACE"));
*/
void testCFStringToTrace() {
LevelPtr trace(Level::toLevel(CFSTR("TRACE")));
LOGUNIT_ASSERT(trace->toString() == LOG4CXX_STR("TRACE"));
}
#endif
};
LOGUNIT_TEST_SUITE_REGISTRATION(LevelTestCase);
| 001-log4cxx | trunk/src/test/cpp/leveltestcase.cpp | C++ | asf20 | 3,517 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#ifndef APR_TEST_INCLUDES
#define APR_TEST_INCLUDES
#include "abts.h"
#include "testutil.h"
#endif /* APR_TEST_INCLUDES */
| 001-log4cxx | trunk/src/test/cpp/abts_tests.h | C | asf20 | 925 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "logunit.h"
#include <log4cxx/logger.h>
#include <log4cxx/logmanager.h>
#include <log4cxx/simplelayout.h>
#include "vectorappender.h"
#include <log4cxx/asyncappender.h>
#include "appenderskeletontestcase.h"
#include <log4cxx/helpers/pool.h>
#include <apr_strings.h>
#include "testchar.h"
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/synchronized.h>
#include <log4cxx/spi/location/locationinfo.h>
#include <log4cxx/xml/domconfigurator.h>
#include <log4cxx/file.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::spi;
class NullPointerAppender : public AppenderSkeleton {
public:
NullPointerAppender() {
}
/**
* @{inheritDoc}
*/
void append(const spi::LoggingEventPtr&, log4cxx::helpers::Pool&) {
throw NullPointerException(LOG4CXX_STR("Intentional NullPointerException"));
}
void close() {
}
bool requiresLayout() const {
return false;
}
};
/**
* Vector appender that can be explicitly blocked.
*/
class BlockableVectorAppender : public VectorAppender {
private:
Mutex blocker;
public:
/**
* Create new instance.
*/
BlockableVectorAppender() : blocker(pool) {
}
/**
* {@inheritDoc}
*/
void append(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p) {
synchronized sync(blocker);
VectorAppender::append(event, p);
//
// if fatal, echo messages for testLoggingInDispatcher
//
if (event->getLevel() == Level::getInfo()) {
LoggerPtr logger = Logger::getLoggerLS(event->getLoggerName());
LOG4CXX_LOGLS(logger, Level::getError(), event->getMessage());
LOG4CXX_LOGLS(logger, Level::getWarn(), event->getMessage());
LOG4CXX_LOGLS(logger, Level::getInfo(), event->getMessage());
LOG4CXX_LOGLS(logger, Level::getDebug(), event->getMessage());
}
}
Mutex& getBlocker() {
return blocker;
}
};
typedef helpers::ObjectPtrT<BlockableVectorAppender> BlockableVectorAppenderPtr;
#if APR_HAS_THREADS
/**
* Tests of AsyncAppender.
*/
class AsyncAppenderTestCase : public AppenderSkeletonTestCase
{
LOGUNIT_TEST_SUITE(AsyncAppenderTestCase);
//
// tests inherited from AppenderSkeletonTestCase
//
LOGUNIT_TEST(testDefaultThreshold);
LOGUNIT_TEST(testSetOptionThreshold);
LOGUNIT_TEST(closeTest);
LOGUNIT_TEST(test2);
LOGUNIT_TEST(test3);
//
// TODO: test fails on Linux.
//LOGUNIT_TEST(testBadAppender);
LOGUNIT_TEST(testLocationInfoTrue);
LOGUNIT_TEST(testConfiguration);
LOGUNIT_TEST_SUITE_END();
public:
void setUp() {
AppenderSkeletonTestCase::setUp();
}
void tearDown()
{
LogManager::shutdown();
AppenderSkeletonTestCase::tearDown();
}
AppenderSkeleton* createAppenderSkeleton() const {
return new AsyncAppender();
}
// this test checks whether it is possible to write to a closed AsyncAppender
void closeTest()
{
LoggerPtr root = Logger::getRootLogger();
LayoutPtr layout = new SimpleLayout();
VectorAppenderPtr vectorAppender = new VectorAppender();
AsyncAppenderPtr asyncAppender = new AsyncAppender();
asyncAppender->setName(LOG4CXX_STR("async-CloseTest"));
asyncAppender->addAppender(vectorAppender);
root->addAppender(asyncAppender);
root->debug(LOG4CXX_TEST_STR("m1"));
asyncAppender->close();
root->debug(LOG4CXX_TEST_STR("m2"));
const std::vector<spi::LoggingEventPtr>& v = vectorAppender->getVector();
LOGUNIT_ASSERT_EQUAL((size_t) 1, v.size());
}
// this test checks whether appenders embedded within an AsyncAppender are also
// closed
void test2()
{
LoggerPtr root = Logger::getRootLogger();
LayoutPtr layout = new SimpleLayout();
VectorAppenderPtr vectorAppender = new VectorAppender();
AsyncAppenderPtr asyncAppender = new AsyncAppender();
asyncAppender->setName(LOG4CXX_STR("async-test2"));
asyncAppender->addAppender(vectorAppender);
root->addAppender(asyncAppender);
root->debug(LOG4CXX_TEST_STR("m1"));
asyncAppender->close();
root->debug(LOG4CXX_TEST_STR("m2"));
const std::vector<spi::LoggingEventPtr>& v = vectorAppender->getVector();
LOGUNIT_ASSERT_EQUAL((size_t) 1, v.size());
LOGUNIT_ASSERT(vectorAppender->isClosed());
}
// this test checks whether appenders embedded within an AsyncAppender are also
// closed
void test3()
{
size_t LEN = 200;
LoggerPtr root = Logger::getRootLogger();
VectorAppenderPtr vectorAppender = new VectorAppender();
AsyncAppenderPtr asyncAppender = new AsyncAppender();
asyncAppender->setName(LOG4CXX_STR("async-test3"));
asyncAppender->addAppender(vectorAppender);
root->addAppender(asyncAppender);
for (size_t i = 0; i < LEN; i++) {
LOG4CXX_DEBUG(root, "message" << i);
}
asyncAppender->close();
root->debug(LOG4CXX_TEST_STR("m2"));
const std::vector<spi::LoggingEventPtr>& v = vectorAppender->getVector();
LOGUNIT_ASSERT_EQUAL(LEN, v.size());
LOGUNIT_ASSERT_EQUAL(true, vectorAppender->isClosed());
}
/**
* Tests that a bad appender will switch async back to sync.
*/
void testBadAppender() {
AppenderPtr nullPointerAppender = new NullPointerAppender();
AsyncAppenderPtr asyncAppender = new AsyncAppender();
asyncAppender->addAppender(nullPointerAppender);
asyncAppender->setBufferSize(5);
Pool p;
asyncAppender->activateOptions(p);
LoggerPtr root = Logger::getRootLogger();
root->addAppender(asyncAppender);
LOG4CXX_INFO(root, "Message");
Thread::sleep(10);
try {
LOG4CXX_INFO(root, "Message");
LOGUNIT_FAIL("Should have thrown exception");
} catch(NullPointerException& ex) {
}
}
/**
* Tests non-blocking behavior.
*/
void testLocationInfoTrue() {
BlockableVectorAppenderPtr blockableAppender = new BlockableVectorAppender();
AsyncAppenderPtr async = new AsyncAppender();
async->addAppender(blockableAppender);
async->setBufferSize(5);
async->setLocationInfo(true);
async->setBlocking(false);
Pool p;
async->activateOptions(p);
LoggerPtr rootLogger = Logger::getRootLogger();
rootLogger->addAppender(async);
{
synchronized sync(blockableAppender->getBlocker());
for (int i = 0; i < 100; i++) {
LOG4CXX_INFO(rootLogger, "Hello, World");
Thread::sleep(1);
}
LOG4CXX_ERROR(rootLogger, "That's all folks.");
}
async->close();
const std::vector<spi::LoggingEventPtr>& events = blockableAppender->getVector();
LOGUNIT_ASSERT(events.size() > 0);
LoggingEventPtr initialEvent = events[0];
LoggingEventPtr discardEvent = events[events.size() - 1];
LOGUNIT_ASSERT(initialEvent->getMessage() == LOG4CXX_STR("Hello, World"));
LOGUNIT_ASSERT(discardEvent->getMessage().substr(0,10) == LOG4CXX_STR("Discarded "));
LOGUNIT_ASSERT_EQUAL(log4cxx::spi::LocationInfo::getLocationUnavailable().getClassName(),
discardEvent->getLocationInformation().getClassName());
}
void testConfiguration() {
log4cxx::xml::DOMConfigurator::configure("input/xml/asyncAppender1.xml");
AsyncAppenderPtr asyncAppender(Logger::getRootLogger()->getAppender(LOG4CXX_STR("ASYNC")));
LOGUNIT_ASSERT(!(asyncAppender == 0));
LOGUNIT_ASSERT_EQUAL(100, asyncAppender->getBufferSize());
LOGUNIT_ASSERT_EQUAL(false, asyncAppender->getBlocking());
LOGUNIT_ASSERT_EQUAL(true, asyncAppender->getLocationInfo());
AppenderList nestedAppenders(asyncAppender->getAllAppenders());
// TODO:
// test seems to work okay, but have not found a working way to
// get a reference to the nested vector appender
//
// LOGUNIT_ASSERT_EQUAL((size_t) 1, nestedAppenders.size());
// VectorAppenderPtr vectorAppender(nestedAppenders[0]);
// LOGUNIT_ASSERT(0 != vectorAppender);
LoggerPtr root(Logger::getRootLogger());
size_t LEN = 20;
for (size_t i = 0; i < LEN; i++) {
LOG4CXX_DEBUG(root, "message" << i);
}
asyncAppender->close();
// const std::vector<spi::LoggingEventPtr>& v = vectorAppender->getVector();
// LOGUNIT_ASSERT_EQUAL(LEN, v.size());
// LOGUNIT_ASSERT_EQUAL(true, vectorAppender->isClosed());
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(AsyncAppenderTestCase);
#endif
| 001-log4cxx | trunk/src/test/cpp/asyncappendertestcase.cpp | C++ | asf20 | 10,646 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "abts.h"
#ifndef APR_TEST_UTIL
#define APR_TEST_UTIL
void initialize(void);
abts_suite* abts_run_suites(abts_suite*);
#endif /* APR_TEST_INCLUDES */
| 001-log4cxx | trunk/src/test/cpp/testutil.h | C | asf20 | 964 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <log4cxx/writerappender.h>
#include "appenderskeletontestcase.h"
/**
An abstract set of tests for inclusion in concrete
appender test case
*/
class WriterAppenderTestCase : public AppenderSkeletonTestCase
{
public:
log4cxx::AppenderSkeleton* createAppenderSkeleton() const;
virtual log4cxx::WriterAppender* createWriterAppender() const = 0;
};
| 001-log4cxx | trunk/src/test/cpp/writerappendertestcase.h | C++ | asf20 | 1,185 |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#
noinst_HEADERS = \
$(top_srcdir)/src/test/cpp/customlogger/*.h \
$(top_srcdir)/src/test/cpp/helpers/*.h \
$(top_srcdir)/src/test/cpp/net/*.h \
$(top_srcdir)/src/test/cpp/pattern/*.h \
$(top_srcdir)/src/test/cpp/util/*.h \
$(top_srcdir)/src/test/cpp/xml/*.h \
$(top_srcdir)/src/test/cpp/*.h
INCLUDES = -I$(top_srcdir)/src/main/include -I$(top_builddir)/src/main/include
noinst_PROGRAMS = testsuite
customlogger_tests = \
customlogger/xlogger.cpp\
customlogger/xloggertestcase.cpp
defaultinit_tests = \
defaultinit/testcase1.cpp\
defaultinit/testcase2.cpp\
defaultinit/testcase3.cpp\
defaultinit/testcase4.cpp
helpers = \
helpers/absolutetimedateformattestcase.cpp \
helpers/cacheddateformattestcase.cpp \
helpers/charsetdecodertestcase.cpp \
helpers/charsetencodertestcase.cpp \
helpers/cyclicbuffertestcase.cpp\
helpers/datetimedateformattestcase.cpp \
helpers/inetaddresstestcase.cpp \
helpers/iso8601dateformattestcase.cpp \
helpers/localechanger.cpp\
helpers/messagebuffertest.cpp \
helpers/optionconvertertestcase.cpp \
helpers/propertiestestcase.cpp \
helpers/relativetimedateformattestcase.cpp \
helpers/stringtokenizertestcase.cpp \
helpers/stringhelpertestcase.cpp \
helpers/syslogwritertest.cpp \
helpers/timezonetestcase.cpp \
helpers/transcodertestcase.cpp
net_tests = \
net/smtpappendertestcase.cpp \
net/socketappendertestcase.cpp \
net/sockethubappendertestcase.cpp \
net/socketservertestcase.cpp \
net/syslogappendertestcase.cpp \
net/telnetappendertestcase.cpp \
net/xmlsocketappendertestcase.cpp
pattern_tests = \
pattern/num343patternconverter.cpp \
pattern/patternparsertestcase.cpp
rolling_tests = \
rolling/filenamepatterntestcase.cpp \
rolling/filterbasedrollingtest.cpp \
rolling/manualrollingtest.cpp \
rolling/obsoletedailyrollingfileappendertest.cpp \
rolling/obsoleterollingfileappendertest.cpp \
rolling/sizebasedrollingtest.cpp \
rolling/timebasedrollingtest.cpp
util = \
util/absolutetimefilter.cpp\
util/absolutedateandtimefilter.cpp\
util/binarycompare.cpp\
util/compare.cpp\
util/controlfilter.cpp\
util/filenamefilter.cpp \
util/utilfilter.cpp\
util/iso8601filter.cpp\
util/linenumberfilter.cpp\
util/relativetimefilter.cpp\
util/serializationtesthelper.cpp \
util/threadfilter.cpp\
util/transformer.cpp\
util/xmlfilenamefilter.cpp \
util/xmllineattributefilter.cpp\
util/xmltimestampfilter.cpp \
util/xmlthreadfilter.cpp
varia_tests = \
varia/errorhandlertestcase.cpp \
varia/levelmatchfiltertestcase.cpp \
varia/levelrangefiltertestcase.cpp
db_tests = \
db/odbcappendertestcase.cpp
xml_tests = \
xml/customleveltestcase.cpp \
xml/domtestcase.cpp \
xml/xlevel.cpp \
xml/xmllayouttestcase.cpp \
xml/xmllayouttest.cpp
nt_tests = \
nt/nteventlogappendertestcase.cpp
testsuite_SOURCES = \
$(customlogger_tests) \
$(defaultinit_tests) \
$(helpers) \
$(net_tests) \
$(pattern_tests) \
$(rolling_tests) \
$(util) \
$(varia_tests) \
$(db_tests) \
$(xml_tests) \
$(nt_tests) \
abts.cpp \
asyncappendertestcase.cpp\
encodingtest.cpp\
filetestcase.cpp \
hierarchytest.cpp\
hierarchythresholdtestcase.cpp\
l7dtestcase.cpp\
leveltestcase.cpp \
logunit.cpp \
loggertestcase.cpp\
minimumtestcase.cpp\
patternlayouttest.cpp\
vectorappender.cpp\
appenderskeletontestcase.cpp\
consoleappendertestcase.cpp\
fileappendertestcase.cpp\
rollingfileappendertestcase.cpp\
streamtestcase.cpp\
writerappendertestcase.cpp \
ndctestcase.cpp \
propertyconfiguratortest.cpp
testsuite_LDADD = \
$(top_builddir)/src/main/cpp/liblog4cxx.la
testsuite_DEPENDENCIES = \
$(top_builddir)/src/main/cpp/liblog4cxx.la
check: testsuite
| 001-log4cxx | trunk/src/test/cpp/Makefile.am | Makefile | asf20 | 4,865 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#if defined(_MSC_VER)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include "logunit.h"
#include <apr_general.h>
#include <algorithm>
#include <stdlib.h>
#include <locale.h>
void initialize() {
setlocale(LC_CTYPE, "");
const char* ctype = setlocale(LC_CTYPE, 0);
if (ctype == 0) {
puts("LC_CTYPE: NULL");
} else {
printf("LC_CTYPE: %s\n", ctype);
}
apr_initialize();
}
extern const char** testlist;
static bool suite_sort(const LogUnit::SuiteList::value_type& lhs, const LogUnit::SuiteList::value_type& rhs) {
return lhs.first < rhs.first;
}
abts_suite* abts_run_suites(abts_suite* suite) {
LogUnit::SuiteList sorted(LogUnit::getAllSuites());
#if !defined(_MSC_VER)
std::sort(sorted.begin(), sorted.end(), suite_sort);
#endif
for(LogUnit::SuiteList::const_iterator iter = sorted.begin();
iter != sorted.end();
iter++) {
//
// if there is an explicit testlist or if the suite is not by default disabled
// pump suite through filter
if(testlist || !iter->second->isDisabled()) {
suite = iter->second->run(suite);
}
}
apr_terminate();
return suite;
}
using namespace LogUnit;
using namespace std;
TestException::TestException() {}
TestException::TestException(const TestException& src) : std::exception(src) {
}
TestException& TestException::operator=(const TestException& src) {
exception::operator=(src);
return *this;
}
AssertException::AssertException(std::string message, int line) : msg(message), lineno(line) {}
AssertException::AssertException(bool expected, const char* actualExpr, int line) : msg(actualExpr), lineno(line) {
if (expected) {
msg.append(" was expected to be true, was false.");
} else {
msg.append(" was expected to be true, was false.");
}
}
AssertException::AssertException(const AssertException& src)
: std::exception(src),
msg(src.msg),
lineno(src.lineno) {
}
AssertException::~AssertException() throw() {
}
AssertException& AssertException::operator=(const AssertException& src) {
exception::operator=(src);
msg = src.msg;
lineno = src.lineno;
return *this;
}
std::string AssertException::getMessage() const {
return msg;
}
int AssertException::getLine() const {
return lineno;
}
TestFixture::TestFixture() : tc(0) {}
TestFixture::~TestFixture() {}
void TestFixture::setCase(abts_case* tc) {
this->tc = tc;
}
void TestFixture::setUp() {}
void TestFixture::tearDown() {}
void TestFixture::assertEquals(const char* expected,
const char* actual,
const char* expectedExpr,
const char* actualExpr,
int lineno) {
abts_str_equal(tc, expected, actual, lineno);
if ((expected == 0 || actual != 0) ||
(expected != 0 || actual == 0) ||
(expected != 0 && strcmp(expected, actual) != 0)) {
throw TestException();
}
}
void TestFixture::assertEquals(const std::string expected,
const std::string actual,
const char* expectedExpr,
const char* actualExpr,
int lineno) {
abts_str_equal(tc, expected.c_str(), actual.c_str(), lineno);
if (expected != actual) {
throw TestException();
}
}
template<class S>
static void transcode(std::string& dst, const S& src) {
for(typename S::const_iterator iter = src.begin();
iter != src.end();
iter++) {
if (*iter <= 0x7F) {
dst.append(1, (char) *iter);
} else {
dst.append(1, '?');
}
}
}
#if LOG4CXX_LOGCHAR_IS_WCHAR || LOG4CXX_WCHAR_T_API
void TestFixture::assertEquals(const std::wstring expected,
const std::wstring actual,
const char* expectedExpr,
const char* actualExpr,
int lineno) {
if (expected != actual) {
std::string exp, act;
transcode(exp, expected);
transcode(act, actual);
abts_str_equal(tc, exp.c_str(), act.c_str(), lineno);
throw TestException();
}
}
#endif
#if LOG4CXX_LOGCHAR_IS_UNICHAR || LOG4CXX_UNICHAR_API || LOG4CXX_CFSTRING_API
void TestFixture::assertEquals(const std::basic_string<log4cxx::UniChar> expected,
const std::basic_string<log4cxx::UniChar> actual,
const char* expectedExpr,
const char* actualExpr,
int lineno) {
if (expected != actual) {
std::string exp, act;
transcode(exp, expected);
transcode(act, actual);
abts_str_equal(tc, exp.c_str(), act.c_str(), lineno);
throw TestException();
}
}
#endif
void TestFixture::assertEquals(const int expected, const int actual, int lineno) {
abts_int_equal(tc, expected, actual, lineno);
if (expected != actual) {
throw TestException();
}
}
LogUnit::TestSuite::TestSuite(const char* fname) : filename(fname), disabled(false) {
#if defined(_WIN32)
for(size_t i = filename.find('\\');
i != std::string::npos;
i = filename.find('\\', i+1)) {
filename.replace(i, 1, 1, '/');
}
#endif
}
void LogUnit::TestSuite::addTest(const char*, test_func func) {
test_funcs.push_back(func);
}
std::string LogUnit::TestSuite::getName() const {
return filename;
}
void LogUnit::TestSuite::setDisabled(bool newVal) {
disabled = newVal;
}
bool LogUnit::TestSuite::isDisabled() const {
return disabled;
}
abts_suite* TestSuite::run(abts_suite* suite) const {
suite = abts_add_suite(suite, filename.c_str());
for(TestList::const_iterator iter = test_funcs.begin();
iter != test_funcs.end();
iter++) {
abts_run_test(suite, *iter, NULL);
}
return suite;
}
LogUnit::SuiteList& LogUnit::getAllSuites() {
static LogUnit::SuiteList allSuites;
return allSuites;
}
| 001-log4cxx | trunk/src/test/cpp/logunit.cpp | C++ | asf20 | 6,617 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <log4cxx/appenderskeleton.h>
#include "logunit.h"
/**
An abstract set of tests for inclusion in concrete
appender test case
*/
LOGUNIT_CLASS(AppenderSkeletonTestCase)
{
public:
virtual log4cxx::AppenderSkeleton* createAppenderSkeleton() const = 0;
void testDefaultThreshold();
void testSetOptionThreshold();
};
| 001-log4cxx | trunk/src/test/cpp/appenderskeletontestcase.h | C++ | asf20 | 1,159 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <log4cxx/helpers/datagramsocket.h>
#include <log4cxx/net/syslogappender.h>
#include "../appenderskeletontestcase.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
/**
Unit tests of log4cxx::SyslogAppender
*/
class SyslogAppenderTestCase : public AppenderSkeletonTestCase
{
LOGUNIT_TEST_SUITE(SyslogAppenderTestCase);
//
// tests inherited from AppenderSkeletonTestCase
//
LOGUNIT_TEST(testDefaultThreshold);
LOGUNIT_TEST(testSetOptionThreshold);
LOGUNIT_TEST_SUITE_END();
public:
AppenderSkeleton* createAppenderSkeleton() const {
return new log4cxx::net::SyslogAppender();
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(SyslogAppenderTestCase);
| 001-log4cxx | trunk/src/test/cpp/net/syslogappendertestcase.cpp | C++ | asf20 | 1,587 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <log4cxx/net/telnetappender.h>
#include <log4cxx/ttcclayout.h>
#include "../appenderskeletontestcase.h"
#include <apr_thread_proc.h>
#include <apr_time.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::net;
#if APR_HAS_THREADS
/**
Unit tests of log4cxx::TelnetAppender
*/
class TelnetAppenderTestCase : public AppenderSkeletonTestCase
{
LOGUNIT_TEST_SUITE(TelnetAppenderTestCase);
//
// tests inherited from AppenderSkeletonTestCase
//
LOGUNIT_TEST(testDefaultThreshold);
LOGUNIT_TEST(testSetOptionThreshold);
LOGUNIT_TEST(testActivateClose);
LOGUNIT_TEST(testActivateSleepClose);
LOGUNIT_TEST(testActivateWriteClose);
LOGUNIT_TEST_SUITE_END();
enum { TEST_PORT = 1723 };
public:
AppenderSkeleton* createAppenderSkeleton() const {
return new log4cxx::net::TelnetAppender();
}
void testActivateClose() {
TelnetAppenderPtr appender(new TelnetAppender());
appender->setLayout(new TTCCLayout());
appender->setPort(TEST_PORT);
Pool p;
appender->activateOptions(p);
appender->close();
}
void testActivateSleepClose() {
TelnetAppenderPtr appender(new TelnetAppender());
appender->setLayout(new TTCCLayout());
appender->setPort(TEST_PORT);
Pool p;
appender->activateOptions(p);
Thread::sleep(1000);
appender->close();
}
void testActivateWriteClose() {
TelnetAppenderPtr appender(new TelnetAppender());
appender->setLayout(new TTCCLayout());
appender->setPort(TEST_PORT);
Pool p;
appender->activateOptions(p);
LoggerPtr root(Logger::getRootLogger());
root->addAppender(appender);
for (int i = 0; i < 50; i++) {
LOG4CXX_INFO(root, "Hello, World " << i);
}
appender->close();
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(TelnetAppenderTestCase);
#endif
| 001-log4cxx | trunk/src/test/cpp/net/telnetappendertestcase.cpp | C++ | asf20 | 3,013 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#define LOG4CXX_TEST 1
#include <log4cxx/private/log4cxx_private.h>
#if LOG4CXX_HAVE_SMTP
#include <log4cxx/net/smtpappender.h>
#include "../appenderskeletontestcase.h"
#include <log4cxx/xml/domconfigurator.h>
#include <log4cxx/logmanager.h>
#include <log4cxx/ttcclayout.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::net;
using namespace log4cxx::xml;
using namespace log4cxx::spi;
namespace log4cxx {
namespace net {
class MockTriggeringEventEvaluator :
public virtual spi::TriggeringEventEvaluator,
public virtual helpers::ObjectImpl
{
public:
DECLARE_LOG4CXX_OBJECT(MockTriggeringEventEvaluator)
BEGIN_LOG4CXX_CAST_MAP()
LOG4CXX_CAST_ENTRY(MockTriggeringEventEvaluator)
LOG4CXX_CAST_ENTRY(spi::TriggeringEventEvaluator)
END_LOG4CXX_CAST_MAP()
MockTriggeringEventEvaluator() {
}
virtual bool isTriggeringEvent(const spi::LoggingEventPtr& event) {
return true;
}
private:
MockTriggeringEventEvaluator(const MockTriggeringEventEvaluator&);
MockTriggeringEventEvaluator& operator=(const MockTriggeringEventEvaluator&);
};
}
}
IMPLEMENT_LOG4CXX_OBJECT(MockTriggeringEventEvaluator)
/**
Unit tests of log4cxx::SocketAppender
*/
class SMTPAppenderTestCase : public AppenderSkeletonTestCase
{
LOGUNIT_TEST_SUITE(SMTPAppenderTestCase);
//
// tests inherited from AppenderSkeletonTestCase
//
LOGUNIT_TEST(testDefaultThreshold);
LOGUNIT_TEST(testSetOptionThreshold);
LOGUNIT_TEST(testTrigger);
LOGUNIT_TEST(testInvalid);
LOGUNIT_TEST_SUITE_END();
public:
AppenderSkeleton* createAppenderSkeleton() const {
return new log4cxx::net::SMTPAppender();
}
void setUp() {
}
void tearDown() {
LogManager::resetConfiguration();
}
/**
* Tests that triggeringPolicy element will set evaluator.
*/
void testTrigger() {
DOMConfigurator::configure("input/xml/smtpAppender1.xml");
SMTPAppenderPtr appender(Logger::getRootLogger()->getAppender(LOG4CXX_STR("A1")));
TriggeringEventEvaluatorPtr evaluator(appender->getEvaluator());
LOGUNIT_ASSERT_EQUAL(true, evaluator->instanceof(MockTriggeringEventEvaluator::getStaticClass()));
}
void testInvalid() {
SMTPAppenderPtr appender(new SMTPAppender());
appender->setSMTPHost(LOG4CXX_STR("smtp.invalid"));
appender->setTo(LOG4CXX_STR("you@example.invalid"));
appender->setFrom(LOG4CXX_STR("me@example.invalid"));
appender->setLayout(new TTCCLayout());
Pool p;
appender->activateOptions(p);
LoggerPtr root(Logger::getRootLogger());
root->addAppender(appender);
LOG4CXX_INFO(root, "Hello, World.");
LOG4CXX_ERROR(root, "Sending Message");
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(SMTPAppenderTestCase);
#endif
| 001-log4cxx | trunk/src/test/cpp/net/smtpappendertestcase.cpp | C++ | asf20 | 4,129 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#ifndef _LOG4CXX_NET_SOCKETSERVER_TESTCASE_H
#define _LOG4CXX_NET_SOCKETSERVER_TESTCASE_H
#define PORT 12345
#endif //_LOG4CXX_NET_SOCKETSERVER_TESTCASE_H
| 001-log4cxx | trunk/src/test/cpp/net/socketservertestcase.h | C | asf20 | 964 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <log4cxx/net/xmlsocketappender.h>
#include "../appenderskeletontestcase.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
#if APR_HAS_THREADS
/**
Unit tests of log4cxx::net::XMLSocketAppender
*/
class XMLSocketAppenderTestCase : public AppenderSkeletonTestCase
{
LOGUNIT_TEST_SUITE(XMLSocketAppenderTestCase);
//
// tests inherited from AppenderSkeletonTestCase
//
LOGUNIT_TEST(testDefaultThreshold);
LOGUNIT_TEST(testSetOptionThreshold);
LOGUNIT_TEST_SUITE_END();
public:
AppenderSkeleton* createAppenderSkeleton() const {
return new log4cxx::net::XMLSocketAppender();
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(XMLSocketAppenderTestCase);
#endif
| 001-log4cxx | trunk/src/test/cpp/net/xmlsocketappendertestcase.cpp | C++ | asf20 | 1,593 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <log4cxx/logger.h>
#include <log4cxx/net/socketappender.h>
#include <log4cxx/ndc.h>
#include <log4cxx/mdc.h>
#include <log4cxx/asyncappender.h>
#include "socketservertestcase.h"
#include "../util/compare.h"
#include "../util/transformer.h"
#include "../util/controlfilter.h"
#include "../util/absolutedateandtimefilter.h"
#include "../util/threadfilter.h"
#include "../util/filenamefilter.h"
#include <apr_time.h>
#include <log4cxx/file.h>
#include <iostream>
#include <log4cxx/helpers/transcoder.h>
#include <log4cxx/helpers/stringhelper.h>
#include "../testchar.h"
#include "../logunit.h"
#include <log4cxx/spi/loggerrepository.h>
//Define INT64_C for compilers that don't have it
#if (!defined(INT64_C))
#define INT64_C(value) value ## LL
#endif
#if defined(WIN32) || defined(_WIN32)
#include <windows.h>
#endif
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::net;
#define REGEX_STR(x) x
// %5p %x [%t] %c %m%n
// DEBUG T1 [thread] org.apache.log4j.net.SocketAppenderTestCase Message 1
#define PAT1 \
REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) T1 \\[0x[0-9A-F]*]\\ ") \
REGEX_STR(".* Message [0-9]\\{1,2\\}")
// DEBUG T2 [thread] patternlayouttest.cpp(?) Message 1
#define PAT2 \
REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) T2 \\[0x[0-9A-F]*]\\ ") \
REGEX_STR(".*socketservertestcase.cpp\\([0-9]\\{1,4\\}\\) Message [0-9]\\{1,2\\}")
// DEBUG T3 [thread] patternlayouttest.cpp(?) Message 1
#define PAT3 \
REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) T3 \\[0x[0-9A-F]*]\\ ") \
REGEX_STR(".*socketservertestcase.cpp\\([0-9]\\{1,4\\}\\) Message [0-9]\\{1,2\\}")
// DEBUG some T4 MDC-TEST4 [thread] SocketAppenderTestCase - Message 1
// DEBUG some T4 MDC-TEST4 [thread] SocketAppenderTestCase - Message 1
#define PAT4 \
REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some T4 MDC-TEST4 \\[0x[0-9A-F]*]\\") \
REGEX_STR(" (root|SocketServerTestCase) - Message [0-9]\\{1,2\\}")
#define PAT5 \
REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some5 T5 MDC-TEST5 \\[0x[0-9A-F]*]\\") \
REGEX_STR(" (root|SocketServerTestCase) - Message [0-9]\\{1,2\\}")
#define PAT6 \
REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some6 T6 client-test6 MDC-TEST6") \
REGEX_STR(" \\[0x[0-9A-F]*]\\ (root|SocketServerTestCase) - Message [0-9]\\{1,2\\}")
#define PAT7 \
REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some7 T7 client-test7 MDC-TEST7") \
REGEX_STR(" \\[0x[0-9A-F]*]\\ (root|SocketServerTestCase) - Message [0-9]\\{1,2\\}")
// DEBUG some8 T8 shortSocketServer MDC-TEST7 [thread] SocketServerTestCase - Message 1
#define PAT8 \
REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some8 T8 shortSocketServer") \
REGEX_STR(" MDC-TEST8 \\[0x[0-9A-F]*]\\ (root|SocketServerTestCase) - Message [0-9]\\{1,2\\}")
/**
* This test checks receipt of SocketAppender messages by the ShortSocketServer
* class from log4j. That class must be started externally to this class
* for this test to succeed.
*/
LOGUNIT_CLASS(SocketServerTestCase)
{
LOGUNIT_TEST_SUITE(SocketServerTestCase);
LOGUNIT_TEST(test1);
LOGUNIT_TEST(test2);
LOGUNIT_TEST(test3);
LOGUNIT_TEST(test4);
LOGUNIT_TEST(test5);
LOGUNIT_TEST(test6);
LOGUNIT_TEST(test7);
LOGUNIT_TEST(test8);
LOGUNIT_TEST_SUITE_END();
SocketAppenderPtr socketAppender;
LoggerPtr logger;
LoggerPtr root;
class LineNumberFilter : public Filter {
public:
LineNumberFilter() {
patterns.push_back(PatternReplacement("cpp:[0-9]*", "cpp:XXX"));
}
};
public:
void setUp()
{
logger = Logger::getLogger(LOG4CXX_STR("org.apache.log4j.net.SocketServerTestCase"));
root = Logger::getRootLogger();
}
void tearDown()
{
socketAppender = 0;
root->getLoggerRepository()->resetConfiguration();
logger = 0;
root = 0;
}
/**
The pattern on the server side: %5p %x [%t] %c %m%n.
We are testing NDC functionality across the wire.
*/
void test1()
{
SocketAppenderPtr socketAppender1 =
new SocketAppender(LOG4CXX_STR("localhost"), PORT);
root->addAppender(socketAppender1);
common("test1", LOG4CXX_STR("T1"), LOG4CXX_STR("key1"), LOG4CXX_STR("MDC-TEST1"));
delay(1);
ControlFilter cf;
cf << PAT1;
ThreadFilter threadFilter;
std::vector<Filter *> filters;
filters.push_back(&cf);
filters.push_back(&threadFilter);
try
{
Transformer::transform(TEMP, FILTERED, filters);
}
catch(UnexpectedFormatException& e)
{
std::cout << "UnexpectedFormatException :" << e.what() << std::endl;
throw;
}
LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/socketServer.1")));
}
void test2()
{
SocketAppenderPtr socketAppender1 =
new SocketAppender(LOG4CXX_STR("localhost"), PORT);
root->addAppender(socketAppender1);
common("test2", LOG4CXX_STR("T2"), LOG4CXX_STR("key2"), LOG4CXX_STR("MDC-TEST2"));
delay(1);
ControlFilter cf;
cf << PAT2;
ThreadFilter threadFilter;
LineNumberFilter lineNumberFilter;
LogString thisFile;
FilenameFilter filenameFilter(__FILE__, "socketservertestcase.cpp");
std::vector<Filter *> filters;
filters.push_back(&filenameFilter);
filters.push_back(&cf);
filters.push_back(&threadFilter);
filters.push_back(&lineNumberFilter);
try
{
Transformer::transform(TEMP, FILTERED, filters);
}
catch(UnexpectedFormatException& e)
{
std::cout << "UnexpectedFormatException :" << e.what() << std::endl;
throw;
}
LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/socketServer.2")));
}
void test3()
{
SocketAppenderPtr socketAppender1 =
new SocketAppender(LOG4CXX_STR("localhost"), PORT);
root->addAppender(socketAppender1);
common("test3", LOG4CXX_STR("T3"), LOG4CXX_STR("key3"), LOG4CXX_STR("MDC-TEST3"));
delay(1);
ControlFilter cf;
cf << PAT3;
ThreadFilter threadFilter;
LineNumberFilter lineNumberFilter;
LogString thisFile;
FilenameFilter filenameFilter(__FILE__, "socketservertestcase.cpp");
std::vector<Filter *> filters;
filters.push_back(&filenameFilter);
filters.push_back(&cf);
filters.push_back(&threadFilter);
filters.push_back(&lineNumberFilter);
try
{
Transformer::transform(TEMP, FILTERED, filters);
}
catch(UnexpectedFormatException& e)
{
std::cout << "UnexpectedFormatException :" << e.what() << std::endl;
throw;
}
LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/socketServer.3")));
}
void test4()
{
SocketAppenderPtr socketAppender1 =
new SocketAppender(LOG4CXX_STR("localhost"), PORT);
root->addAppender(socketAppender1);
NDC::push(LOG4CXX_TEST_STR("some"));
common("test4", LOG4CXX_STR("T4"), LOG4CXX_STR("key4"), LOG4CXX_STR("MDC-TEST4"));
NDC::pop();
delay(1);
ControlFilter cf;
cf << PAT4;
ThreadFilter threadFilter;
std::vector<Filter *> filters;
filters.push_back(&cf);
filters.push_back(&threadFilter);
try
{
Transformer::transform(TEMP, FILTERED, filters);
}
catch(UnexpectedFormatException& e)
{
std::cout << "UnexpectedFormatException :" << e.what() << std::endl;
throw;
}
LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/socketServer.4")));
}
void test5()
{
SocketAppenderPtr socketAppender1 =
new SocketAppender(LOG4CXX_STR("localhost"), PORT);
AsyncAppenderPtr asyncAppender = new AsyncAppender();
root->addAppender(socketAppender1);
root->addAppender(asyncAppender);
NDC::push(LOG4CXX_TEST_STR("some5"));
common("test5", LOG4CXX_STR("T5"), LOG4CXX_STR("key5"), LOG4CXX_STR("MDC-TEST5"));
NDC::pop();
delay(2);
ControlFilter cf;
cf << PAT5;
ThreadFilter threadFilter;
std::vector<Filter *> filters;
filters.push_back(&cf);
filters.push_back(&threadFilter);
try
{
Transformer::transform(TEMP, FILTERED, filters);
}
catch(UnexpectedFormatException& e)
{
std::cout << "UnexpectedFormatException :" << e.what() << std::endl;
throw;
}
LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/socketServer.5")));
}
void test6()
{
SocketAppenderPtr socketAppender1 =
new SocketAppender(LOG4CXX_STR("localhost"), PORT);
AsyncAppenderPtr asyncAppender = new AsyncAppender();
root->addAppender(socketAppender1);
root->addAppender(asyncAppender);
NDC::push(LOG4CXX_TEST_STR("some6"));
MDC::put(LOG4CXX_TEST_STR("hostID"), LOG4CXX_TEST_STR("client-test6"));
common("test6", LOG4CXX_STR("T6"), LOG4CXX_STR("key6"), LOG4CXX_STR("MDC-TEST6"));
NDC::pop();
MDC::remove(LOG4CXX_TEST_STR("hostID"));
delay(2);
ControlFilter cf;
cf << PAT6;
ThreadFilter threadFilter;
std::vector<Filter *> filters;
filters.push_back(&cf);
filters.push_back(&threadFilter);
try
{
Transformer::transform(TEMP, FILTERED, filters);
}
catch(UnexpectedFormatException& e)
{
std::cout << "UnexpectedFormatException :" << e.what() << std::endl;
throw;
}
LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/socketServer.6")));
}
void test7()
{
SocketAppenderPtr socketAppender1 =
new SocketAppender(LOG4CXX_STR("localhost"), PORT);
AsyncAppenderPtr asyncAppender = new AsyncAppender();
root->addAppender(socketAppender1);
root->addAppender(asyncAppender);
NDC::push(LOG4CXX_TEST_STR("some7"));
MDC::put(LOG4CXX_TEST_STR("hostID"), LOG4CXX_TEST_STR("client-test7"));
common("test7", LOG4CXX_STR("T7"), LOG4CXX_STR("key7"), LOG4CXX_STR("MDC-TEST7"));
NDC::pop();
MDC::remove(LOG4CXX_TEST_STR("hostID"));
delay(2);
ControlFilter cf;
cf << PAT7;
ThreadFilter threadFilter;
std::vector<Filter *> filters;
filters.push_back(&cf);
filters.push_back(&threadFilter);
try
{
Transformer::transform(TEMP, FILTERED, filters);
}
catch(UnexpectedFormatException& e)
{
std::cout << "UnexpectedFormatException :" << e.what() << std::endl;
throw;
}
LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/socketServer.7")));
}
void test8()
{
SocketAppenderPtr socketAppender1 =
new SocketAppender(LOG4CXX_STR("localhost"), PORT);
root->addAppender(socketAppender1);
NDC::push(LOG4CXX_TEST_STR("some8"));
common("test8", LOG4CXX_STR("T8"), LOG4CXX_STR("key8"), LOG4CXX_STR("MDC-TEST8"));
NDC::pop();
delay(2);
ControlFilter cf;
cf << PAT8;
ThreadFilter threadFilter;
std::vector<Filter *> filters;
filters.push_back(&cf);
filters.push_back(&threadFilter);
try
{
Transformer::transform(TEMP, FILTERED, filters);
}
catch(UnexpectedFormatException& e)
{
std::cout << "UnexpectedFormatException :" << e.what() << std::endl;
throw;
}
LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/socketServer.8")));
}
void common(const std::string& testName, const LogString& dc, const LogString& key, const LogString& val)
{
int i = -1;
NDC::push(dc);
MDC::put(key, val);
logger->setLevel(Level::getDebug());
root->setLevel(Level::getDebug());
LOG4CXX_TRACE(logger, "Message " << i);
i++;
logger->setLevel(Level::getTrace());
root->setLevel(Level::getTrace());
LOG4CXX_TRACE(logger, "Message " << ++i);
LOG4CXX_TRACE(root, "Message " << ++i);
LOG4CXX_DEBUG(logger, "Message " << ++i);
LOG4CXX_DEBUG(root, "Message " << ++i);
LOG4CXX_INFO(logger, "Message " << ++i);
LOG4CXX_WARN(logger, "Message " << ++i);
LOG4CXX_FATAL(logger, "Message " << ++i); //5
std::string exceptionMsg("\njava.lang.Exception: Just testing\n"
"\tat org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX)\n"
"\tat org.apache.log4j.net.SocketServerTestCase.");
exceptionMsg.append(testName);
exceptionMsg.append("(SocketServerTestCase.java:XXX)\n"
"\tat junit.framework.TestCase.runTest(TestCase.java:XXX)\n"
"\tat junit.framework.TestCase.runBare(TestCase.java:XXX)\n"
"\tat junit.framework.TestResult$1.protect(TestResult.java:XXX)\n"
"\tat junit.framework.TestResult.runProtected(TestResult.java:XXX)\n"
"\tat junit.framework.TestResult.run(TestResult.java:XXX)\n"
"\tat junit.framework.TestCase.run(TestCase.java:XXX)\n"
"\tat junit.framework.TestSuite.runTest(TestSuite.java:XXX)\n"
"\tat junit.framework.TestSuite.run(TestSuite.java:XXX)");
LOG4CXX_DEBUG(logger, "Message " << ++i << exceptionMsg);
LOG4CXX_ERROR(root, "Message " << ++i << exceptionMsg);
NDC::pop();
MDC::remove(key);
}
void delay(int secs)
{
apr_sleep(APR_USEC_PER_SEC * secs);
}
private:
static const File TEMP;
static const File FILTERED;
};
const File SocketServerTestCase::TEMP("output/temp");
const File SocketServerTestCase::FILTERED("output/filtered");
LOGUNIT_TEST_SUITE_REGISTRATION_DISABLED(SocketServerTestCase)
| 001-log4cxx | trunk/src/test/cpp/net/socketservertestcase.cpp | C++ | asf20 | 17,718 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <log4cxx/net/socketappender.h>
#include "../appenderskeletontestcase.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
#if APR_HAS_THREADS
/**
Unit tests of log4cxx::SocketAppender
*/
class SocketAppenderTestCase : public AppenderSkeletonTestCase
{
LOGUNIT_TEST_SUITE(SocketAppenderTestCase);
//
// tests inherited from AppenderSkeletonTestCase
//
LOGUNIT_TEST(testDefaultThreshold);
LOGUNIT_TEST(testSetOptionThreshold);
LOGUNIT_TEST_SUITE_END();
public:
AppenderSkeleton* createAppenderSkeleton() const {
return new log4cxx::net::SocketAppender();
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(SocketAppenderTestCase);
#endif
| 001-log4cxx | trunk/src/test/cpp/net/socketappendertestcase.cpp | C++ | asf20 | 1,570 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <log4cxx/net/sockethubappender.h>
#include "../appenderskeletontestcase.h"
#include <log4cxx/helpers/thread.h>
#include <apr.h>
using namespace log4cxx;
using namespace log4cxx::net;
using namespace log4cxx::helpers;
#if APR_HAS_THREADS
/**
Unit tests of log4cxx::SocketHubAppender
*/
class SocketHubAppenderTestCase : public AppenderSkeletonTestCase
{
LOGUNIT_TEST_SUITE(SocketHubAppenderTestCase);
//
// tests inherited from AppenderSkeletonTestCase
//
LOGUNIT_TEST(testDefaultThreshold);
LOGUNIT_TEST(testSetOptionThreshold);
LOGUNIT_TEST(testActivateClose);
LOGUNIT_TEST(testActivateSleepClose);
LOGUNIT_TEST(testActivateWriteClose);
LOGUNIT_TEST_SUITE_END();
public:
AppenderSkeleton* createAppenderSkeleton() const {
return new log4cxx::net::SocketHubAppender();
}
void testActivateClose() {
SocketHubAppenderPtr hubAppender(new SocketHubAppender());
Pool p;
hubAppender->activateOptions(p);
hubAppender->close();
}
void testActivateSleepClose() {
SocketHubAppenderPtr hubAppender(new SocketHubAppender());
Pool p;
hubAppender->activateOptions(p);
Thread::sleep(1000);
hubAppender->close();
}
void testActivateWriteClose() {
SocketHubAppenderPtr hubAppender(new SocketHubAppender());
Pool p;
hubAppender->activateOptions(p);
LoggerPtr root(Logger::getRootLogger());
root->addAppender(hubAppender);
for(int i = 0; i < 50; i++) {
LOG4CXX_INFO(root, "Hello, World " << i);
}
hubAppender->close();
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(SocketHubAppenderTestCase);
#endif
| 001-log4cxx | trunk/src/test/cpp/net/sockethubappendertestcase.cpp | C++ | asf20 | 2,738 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <log4cxx/logger.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/helpers/system.h>
#include <log4cxx/level.h>
#include "num343patternconverter.h"
#include "../testchar.h"
#include "../insertwide.h"
#include "../logunit.h"
#include <log4cxx/spi/loggerrepository.h>
#include <log4cxx/pattern/patternparser.h>
#include <log4cxx/pattern/patternconverter.h>
#include <log4cxx/helpers/relativetimedateformat.h>
#include <log4cxx/helpers/simpledateformat.h>
#include <log4cxx/pattern/loggerpatternconverter.h>
#include <log4cxx/pattern/literalpatternconverter.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/pattern/classnamepatternconverter.h>
#include <log4cxx/pattern/datepatternconverter.h>
#include <log4cxx/pattern/filedatepatternconverter.h>
#include <log4cxx/pattern/filelocationpatternconverter.h>
#include <log4cxx/pattern/fulllocationpatternconverter.h>
#include <log4cxx/pattern/integerpatternconverter.h>
#include <log4cxx/pattern/linelocationpatternconverter.h>
#include <log4cxx/pattern/messagepatternconverter.h>
#include <log4cxx/pattern/lineseparatorpatternconverter.h>
#include <log4cxx/pattern/methodlocationpatternconverter.h>
#include <log4cxx/pattern/levelpatternconverter.h>
#include <log4cxx/pattern/relativetimepatternconverter.h>
#include <log4cxx/pattern/threadpatternconverter.h>
#include <log4cxx/pattern/ndcpatternconverter.h>
#include <log4cxx/pattern/propertiespatternconverter.h>
#include <log4cxx/pattern/throwableinformationpatternconverter.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::spi;
using namespace log4cxx::pattern;
#define RULES_PUT(spec, cls) \
map.insert(PatternMap::value_type(LOG4CXX_STR(spec), (PatternConstructor) cls ::newInstance))
LOGUNIT_CLASS(PatternParserTestCase)
{
LOGUNIT_TEST_SUITE(PatternParserTestCase);
LOGUNIT_TEST(testNewWord);
LOGUNIT_TEST(testNewWord2);
LOGUNIT_TEST(testBogusWord1);
LOGUNIT_TEST(testBogusWord2);
LOGUNIT_TEST(testBasic1);
LOGUNIT_TEST(testBasic2);
LOGUNIT_TEST(testMultiOption);
LOGUNIT_TEST_SUITE_END();
LoggingEventPtr event;
public:
void setUp()
{
event = new LoggingEvent(
LOG4CXX_STR("org.foobar"), Level::getInfo(), LOG4CXX_STR("msg 1"), LOG4CXX_LOCATION);
}
void tearDown()
{
}
PatternMap getFormatSpecifiers() {
PatternMap map;
RULES_PUT("c", LoggerPatternConverter);
RULES_PUT("logger", LoggerPatternConverter);
RULES_PUT("C", ClassNamePatternConverter);
RULES_PUT("class", ClassNamePatternConverter);
RULES_PUT("d", DatePatternConverter);
RULES_PUT("date", DatePatternConverter);
RULES_PUT("F", FileLocationPatternConverter);
RULES_PUT("file", FileLocationPatternConverter);
RULES_PUT("l", FullLocationPatternConverter);
RULES_PUT("L", LineLocationPatternConverter);
RULES_PUT("line", LineLocationPatternConverter);
RULES_PUT("m", MessagePatternConverter);
RULES_PUT("message", MessagePatternConverter);
RULES_PUT("n", LineSeparatorPatternConverter);
RULES_PUT("M", MethodLocationPatternConverter);
RULES_PUT("method", MethodLocationPatternConverter);
RULES_PUT("p", LevelPatternConverter);
RULES_PUT("level", LevelPatternConverter);
RULES_PUT("r", RelativeTimePatternConverter);
RULES_PUT("relative", RelativeTimePatternConverter);
RULES_PUT("t", ThreadPatternConverter);
RULES_PUT("thread", ThreadPatternConverter);
RULES_PUT("x", NDCPatternConverter);
RULES_PUT("ndc", NDCPatternConverter);
RULES_PUT("X", PropertiesPatternConverter);
RULES_PUT("properties", PropertiesPatternConverter);
RULES_PUT("throwable", ThrowableInformationPatternConverter);
return map;
}
void assertFormattedEquals(const LogString& pattern,
const PatternMap& patternMap,
const LogString& expected) {
std::vector<PatternConverterPtr> converters;
std::vector<FormattingInfoPtr> fields;
PatternParser::parse(pattern, converters, fields, patternMap);
Pool p;
LogString actual;
std::vector<FormattingInfoPtr>::const_iterator fieldIter = fields.begin();
for(std::vector<PatternConverterPtr>::const_iterator converterIter = converters.begin();
converterIter != converters.end();
converterIter++, fieldIter++) {
int fieldStart = actual.length();
(*converterIter)->format(event, actual, p);
(*fieldIter)->format(fieldStart, actual);
}
LOGUNIT_ASSERT_EQUAL(expected, actual);
}
void testNewWord() {
PatternMap testRules(getFormatSpecifiers());
testRules.insert(
PatternMap::value_type(LOG4CXX_STR("z343"),
(PatternConstructor) Num343PatternConverter::newInstance));
assertFormattedEquals(LOG4CXX_STR("%z343"), testRules, LOG4CXX_STR("343"));
}
/* Test whether words starting with the letter 'n' are treated differently,
* which was previously the case by mistake.
*/
void testNewWord2() {
PatternMap testRules(getFormatSpecifiers());
testRules.insert(
PatternMap::value_type(LOG4CXX_STR("n343"),
(PatternConstructor) Num343PatternConverter::newInstance));
assertFormattedEquals(LOG4CXX_STR("%n343"), testRules, LOG4CXX_STR("343"));
}
void testBogusWord1() {
assertFormattedEquals(LOG4CXX_STR("%, foobar"),
getFormatSpecifiers(),
LOG4CXX_STR("%, foobar"));
}
void testBogusWord2() {
assertFormattedEquals(LOG4CXX_STR("xyz %, foobar"),
getFormatSpecifiers(),
LOG4CXX_STR("xyz %, foobar"));
}
void testBasic1() {
assertFormattedEquals(LOG4CXX_STR("hello %-5level - %m%n"),
getFormatSpecifiers(),
LogString(LOG4CXX_STR("hello INFO - msg 1")) + LOG4CXX_EOL);
}
void testBasic2() {
Pool pool;
RelativeTimeDateFormat relativeFormat;
LogString expected;
relativeFormat.format(expected, event->getTimeStamp(), pool);
expected.append(LOG4CXX_STR(" INFO ["));
expected.append(event->getThreadName());
expected.append(LOG4CXX_STR("] org.foobar - msg 1"));
expected.append(LOG4CXX_EOL);
assertFormattedEquals(LOG4CXX_STR("%relative %-5level [%thread] %logger - %m%n"),
getFormatSpecifiers(),
expected);
}
void testMultiOption() {
Pool pool;
SimpleDateFormat dateFormat(LOG4CXX_STR("HH:mm:ss"));
LogString localTime;
dateFormat.format(localTime, event->getTimeStamp(), pool);
dateFormat.setTimeZone(TimeZone::getGMT());
LogString utcTime;
dateFormat.format(utcTime, event->getTimeStamp(), pool);
LogString expected(utcTime);
expected.append(1, LOG4CXX_STR(' '));
expected.append(localTime);
expected.append(LOG4CXX_STR(" org.foobar - msg 1"));
assertFormattedEquals(LOG4CXX_STR("%d{HH:mm:ss}{GMT} %d{HH:mm:ss} %c - %m"),
getFormatSpecifiers(),
expected);
}
};
//
// See bug LOGCXX-204
//
#if !defined(_MSC_VER) || _MSC_VER > 1200
LOGUNIT_TEST_SUITE_REGISTRATION(PatternParserTestCase);
#endif
| 001-log4cxx | trunk/src/test/cpp/pattern/patternparsertestcase.cpp | C++ | asf20 | 7,966 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <log4cxx/pattern/loggingeventpatternconverter.h>
#include <vector>
namespace log4cxx
{
namespace pattern {
class Num343PatternConverter : public LoggingEventPatternConverter
{
public:
DECLARE_LOG4CXX_OBJECT(Num343PatternConverter)
Num343PatternConverter();
static PatternConverterPtr newInstance(
const std::vector<LogString>& options);
protected:
void format(
const log4cxx::spi::LoggingEventPtr& event,
LogString& toAppendTo,
log4cxx::helpers::Pool& pool) const;
};
}
}
| 001-log4cxx | trunk/src/test/cpp/pattern/num343patternconverter.h | C++ | asf20 | 1,403 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#if defined(_MSC_VER)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <log4cxx/logstring.h>
#include "num343patternconverter.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::pattern;
IMPLEMENT_LOG4CXX_OBJECT(Num343PatternConverter)
Num343PatternConverter::Num343PatternConverter() :
LoggingEventPatternConverter(LOG4CXX_STR("Num343"), LOG4CXX_STR("num343")) {
}
PatternConverterPtr Num343PatternConverter::newInstance(
const std::vector<LogString>&) {
return new Num343PatternConverter();
}
void Num343PatternConverter::format(
const spi::LoggingEventPtr&,
LogString& sbuf,
Pool&) const
{
sbuf.append(LOG4CXX_STR("343"));
}
| 001-log4cxx | trunk/src/test/cpp/pattern/num343patternconverter.cpp | C++ | asf20 | 1,520 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#ifndef _LOG4CXX_TESTS_UTIL_XML_LINE_ATTRIBUTE_FILTER_H
#define _LOG4CXX_TESTS_UTIL_XML_LINE_ATTRIBUTE_FILTER_H
#include "filter.h"
namespace log4cxx
{
class XMLLineAttributeFilter : public Filter
{
public:
XMLLineAttributeFilter();
};
}
#endif //_LOG4CXX_TESTS_UTIL_XML_LINE_ATTRIBUTE_FILTER_H
| 001-log4cxx | trunk/src/test/cpp/util/xmllineattributefilter.h | C++ | asf20 | 1,122 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "serializationtesthelper.h"
#include <log4cxx/helpers/bytearrayoutputstream.h>
#include <log4cxx/helpers/objectoutputstream.h>
#include <log4cxx/helpers/fileinputstream.h>
#include <log4cxx/helpers/bytebuffer.h>
#include <log4cxx/file.h>
#include "apr_pools.h"
using namespace log4cxx;
using namespace log4cxx::util;
using namespace log4cxx::helpers;
using namespace log4cxx::spi;
bool SerializationTestHelper::compare(
const char* witness, const LoggingEventPtr& event, size_t endCompare) {
ByteArrayOutputStreamPtr memOut = new ByteArrayOutputStream();
Pool p;
ObjectOutputStream objOut(memOut, p);
event->write(objOut, p);
objOut.close(p);
return compare(witness, memOut->toByteArray(), endCompare, p);
}
/**
* Asserts the serialized form of an object.
* @param witness file name of expected serialization.
* @param actual byte array of actual serialization.
* @param skip positions to skip comparison.
* @param endCompare position to stop comparison.
* @throws IOException thrown on IO or serialization exception.
*/
bool SerializationTestHelper::compare(
const char* witness, const std::vector<unsigned char>& actual,
size_t endCompare, Pool& p) {
File witnessFile(witness);
char* expected = p.pstralloc(actual.size());
FileInputStreamPtr is(new FileInputStream(witnessFile));
ByteBuffer readBuffer(expected, actual.size());
int bytesRead = is->read(readBuffer);
is->close();
if(bytesRead < endCompare) {
puts("Witness file is shorter than expected");
return false;
}
int endScan = actual.size();
if (endScan > endCompare) {
endScan = endCompare;
}
for (int i = 0; i < endScan; i++) {
if (((unsigned char) expected[i]) != actual[i]) {
printf("Difference at offset %d, expected %x, actual %x\n", i, expected[i], actual[i]);
return false;
}
}
return true;
}
| 001-log4cxx | trunk/src/test/cpp/util/serializationtesthelper.cpp | C++ | asf20 | 2,804 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "absolutetimefilter.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
AbsoluteTimeFilter::AbsoluteTimeFilter()
: Filter(ABSOLUTE_TIME_PAT, "") {}
| 001-log4cxx | trunk/src/test/cpp/util/absolutetimefilter.cpp | C++ | asf20 | 977 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "iso8601filter.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
ISO8601Filter::ISO8601Filter() : Filter(ISO8601_PAT, "") {}
| 001-log4cxx | trunk/src/test/cpp/util/iso8601filter.cpp | C++ | asf20 | 952 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "compare.h"
#include <log4cxx/helpers/pool.h>
#include <log4cxx/file.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/fileinputstream.h>
#include <log4cxx/helpers/inputstreamreader.h>
#include <log4cxx/helpers/systemoutwriter.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
bool Compare::compare(const File& file1, const File& file2)
{
Pool pool;
InputStreamPtr fileIn1 = new FileInputStream(file1);
InputStreamReaderPtr reader1 = new InputStreamReader(fileIn1);
LogString in1(reader1->read(pool));
Pool pool2;
InputStreamPtr fileIn2 = new FileInputStream(file2);
InputStreamReaderPtr reader2 = new InputStreamReader(fileIn2);
LogString in2(reader2->read(pool2));
LogString back1(in1);
LogString back2(in2);
LogString s1;
LogString s2;
int lineCounter = 0;
while (getline(in1, s1))
{
lineCounter++;
if(!getline(in2, s2)) {
s2.erase(s2.begin(), s2.end());
}
if (s1 != s2) {
LogString msg(LOG4CXX_STR("Files ["));
msg += file1.getPath();
msg += LOG4CXX_STR("] and [");
msg += file2.getPath();
msg += LOG4CXX_STR("] differ on line ");
StringHelper::toString(lineCounter, pool, msg);
msg += LOG4CXX_EOL;
msg += LOG4CXX_STR("One reads: [");
msg += s1;
msg += LOG4CXX_STR("].");
msg += LOG4CXX_EOL;
msg += LOG4CXX_STR("Other reads:[");
msg += s2;
msg += LOG4CXX_STR("].");
msg += LOG4CXX_EOL;
emit(msg);
outputFile(file1, back1, pool);
outputFile(file2, back2, pool);
return false;
}
}
// the second file is longer
if (getline(in2, s2)) {
LogString msg(LOG4CXX_STR("File ["));
msg += file2.getPath();
msg += LOG4CXX_STR("] longer than file [");
msg += file1.getPath();
msg += LOG4CXX_STR("].");
msg += LOG4CXX_EOL;
emit(msg);
outputFile(file1, back1, pool);
outputFile(file2, back2, pool);
return false;
}
return true;
}
void Compare::outputFile(const File& file,
const LogString& contents,
log4cxx::helpers::Pool& pool)
{
int lineCounter = 0;
emit(LOG4CXX_STR("--------------------------------"));
emit(LOG4CXX_EOL);
LogString msg(LOG4CXX_STR("Contents of "));
msg += file.getPath();
msg += LOG4CXX_STR(":");
msg += LOG4CXX_EOL;
emit(msg);
LogString in1(contents);
LogString s1;
while (getline(in1, s1))
{
lineCounter++;
LogString line;
StringHelper::toString(lineCounter, pool, line);
emit(line);
if (lineCounter < 10)
{
emit(LOG4CXX_STR(" : "));
}
else if (lineCounter < 100)
{
emit(LOG4CXX_STR(" : "));
}
else if (lineCounter < 1000)
{
emit(LOG4CXX_STR(" : "));
}
else
{
emit(LOG4CXX_STR(": "));
}
emit(s1);
emit(LOG4CXX_EOL);
}
}
void Compare::emit(const LogString& s1) {
SystemOutWriter::write(s1);
}
bool Compare::getline(LogString& in, LogString& line) {
if (in.empty()) {
return false;
}
size_t nl = in.find(0x0A);
if (nl == std::string::npos) {
line = in;
in.erase(in.begin(), in.end());
} else {
//
// if the file has CR-LF then
// drop the carriage return alse
//
if(nl > 0 && in[nl -1] == 0x0D) {
line.assign(in, 0, nl - 1);
} else {
line.assign(in, 0, nl);
}
in.erase(in.begin(), in.begin() + nl + 1);
}
return true;
}
| 001-log4cxx | trunk/src/test/cpp/util/compare.cpp | C++ | asf20 | 4,968 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 "binarycompare.h"
#include <apr_file_io.h>
#include <log4cxx/helpers/pool.h>
#include "../logunit.h"
#include <apr_pools.h>
#include <apr_strings.h>
using namespace log4cxx;
using namespace log4cxx::util;
using namespace log4cxx::helpers;
void BinaryCompare::compare(const char* filename1,
const char* filename2) {
Pool p;
apr_pool_t* pool = p.getAPRPool();
apr_file_t* file1;
apr_int32_t flags = APR_FOPEN_READ;
apr_fileperms_t perm = APR_OS_DEFAULT;
apr_status_t stat1 = apr_file_open(&file1,
filename1, flags, perm, pool);
if (stat1 != APR_SUCCESS) {
LOGUNIT_FAIL(std::string("Unable to open ") + filename1);
}
apr_file_t* file2;
apr_status_t stat2 = apr_file_open(&file2,
filename2, flags, perm, pool);
if (stat2 != APR_SUCCESS) {
LOGUNIT_FAIL(std::string("Unable to open ") + filename2);
}
enum { BUFSIZE = 1024 };
char* contents1 = (char*) apr_palloc(pool, BUFSIZE);
char* contents2 = (char*) apr_palloc(pool, BUFSIZE);
memset(contents1, 0, BUFSIZE);
memset(contents2, 0, BUFSIZE);
apr_size_t bytesRead1 = BUFSIZE;
apr_size_t bytesRead2 = BUFSIZE;
stat1 = apr_file_read(file1, contents1, &bytesRead1);
if (stat1 != APR_SUCCESS) {
LOGUNIT_FAIL(std::string("Unable to read ") + filename1);
}
stat2 = apr_file_read(file2, contents2, &bytesRead2);
if (stat2 != APR_SUCCESS) {
LOGUNIT_FAIL(std::string("Unable to read ") + filename2);
}
for (int i = 0; i < BUFSIZE; i++) {
if (contents1[i] != contents2[i]) {
std::string msg("Contents differ at position ");
msg += apr_itoa(pool, i);
msg += ": [";
msg += filename1;
msg += "] has ";
msg += apr_itoa(pool, contents1[i]);
msg += ", [";
msg += filename2;
msg += "] has ";
msg += apr_itoa(pool, contents2[i]);
msg += ".";
LOGUNIT_FAIL(msg);
}
}
}
| 001-log4cxx | trunk/src/test/cpp/util/binarycompare.cpp | C++ | asf20 | 2,811 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "xmltimestampfilter.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
XMLTimestampFilter::XMLTimestampFilter()
: Filter("[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*", "XXX") {}
| 001-log4cxx | trunk/src/test/cpp/util/xmltimestampfilter.cpp | C++ | asf20 | 1,018 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "xmlthreadfilter.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
XMLThreadFilter::XMLThreadFilter()
: Filter("thread=\\\"[0-9A-Fa-fXx]*", "thread=\\\"main") {
}
| 001-log4cxx | trunk/src/test/cpp/util/xmlthreadfilter.cpp | C++ | asf20 | 995 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "xmllineattributefilter.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
XMLLineAttributeFilter::XMLLineAttributeFilter() {
patterns.push_back( PatternReplacement("line=\\(.+\\)[0-9]+", "line=\\\\1X"));
}
| 001-log4cxx | trunk/src/test/cpp/util/xmllineattributefilter.cpp | C++ | asf20 | 1,041 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#ifndef _LOG4CXX_TESTS_UTIL_FILTER_H
#define _LOG4CXX_TESTS_UTIL_FILTER_H
#if defined(_MSC_VER)
#pragma warning (push)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <string>
#include <vector>
#include <map>
#include <log4cxx/helpers/exception.h>
#define BASIC_PAT "\\[0x[0-9A-F]*] (FATAL|ERROR|WARN|INFO|DEBUG)"
#define ISO8601_PAT "[0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [0-9]\\{2\\}:[0-9]\\{2\\}:[0-9]\\{2\\},[0-9]\\{3\\}"
#define ABSOLUTE_DATE_AND_TIME_PAT \
"[0-9]\\{1,2\\} .* 200[0-9] [0-9]\\{2\\}:[0-9]\\{2\\}:[0-9]\\{2\\},[0-9]\\{3\\}"
#define ABSOLUTE_TIME_PAT "[0-2][0-9]:[0-9][0-9]:[0-9][0-9],[0-9][0-9][0-9]"
#define RELATIVE_TIME_PAT "^[0-9]+"
namespace log4cxx
{
class UnexpectedFormatException : public std::exception {
};
class Filter
{
public:
Filter(const std::string& match, const std::string& replacement);
Filter();
virtual ~Filter();
typedef std::pair<std::string, std::string> PatternReplacement;
typedef std::vector <PatternReplacement> PatternList;
const PatternList& getPatterns() const{
return patterns;
}
private:
Filter(const Filter&);
Filter& operator=(const Filter&);
protected:
PatternList patterns;
};
}
#if defined(_MSC_VER)
#pragma warning (pop)
#endif
#endif //_LOG4CXX_TESTS_UTIL_FILTER_H
| 001-log4cxx | trunk/src/test/cpp/util/filter.h | C++ | asf20 | 2,266 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "controlfilter.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
ControlFilter::ControlFilter()
{
}
ControlFilter& ControlFilter::operator<<(const std::string&)
{
return *this;
}
| 001-log4cxx | trunk/src/test/cpp/util/controlfilter.cpp | C++ | asf20 | 1,010 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "linenumberfilter.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
LineNumberFilter::LineNumberFilter()
{
patterns.push_back( PatternReplacement(" [^ ]*[\\\\]", " "));
patterns.push_back( PatternReplacement("([0-9]*)", "(X)"));
}
| 001-log4cxx | trunk/src/test/cpp/util/linenumberfilter.cpp | C++ | asf20 | 1,066 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#ifndef _LOG4CXX_TESTS_UTIL_XML_TIMESTAMP_FILTER_H
#define _LOG4CXX_TESTS_UTIL_XML_TIMESTAMP_FILTER_H
#include "filter.h"
namespace log4cxx
{
class XMLTimestampFilter : public Filter
{
public:
XMLTimestampFilter();
};
}
#endif //_LOG4CXX_TESTS_UTIL_XML_TIMESTAMP_FILTER_H
| 001-log4cxx | trunk/src/test/cpp/util/xmltimestampfilter.h | C++ | asf20 | 1,099 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#ifndef _LOG4CXX_TESTS_UTIL_XML_THREAD_FILTER_H
#define _LOG4CXX_TESTS_UTIL_XML_THREAD_FILTER_H
#include "filter.h"
namespace log4cxx
{
class XMLThreadFilter : public Filter
{
public:
XMLThreadFilter();
};
}
#endif //_LOG4CXX_TESTS_UTIL_XML_THREAD_FILTER_H
| 001-log4cxx | trunk/src/test/cpp/util/xmlthreadfilter.h | C++ | asf20 | 1,084 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#ifndef _LOG4CXX_TESTS_UTIL_FILENAME_FILTER_H
#define _LOG4CXX_TESTS_UTIL_FILENAME_FILTER_H
#include "filter.h"
namespace log4cxx
{
class FilenameFilter : public Filter
{
public:
FilenameFilter(const std::string& actual, const std::string& expected);
static const std::string getMatch(const std::string& actual);
};
}
#endif //_LOG4CXX_TESTS_UTIL_FILENAME_FILTER_H
| 001-log4cxx | trunk/src/test/cpp/util/filenamefilter.h | C++ | asf20 | 1,201 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#ifndef _LOG4CXX_TESTS_UTIL_XML_FILENAME_FILTER_H
#define _LOG4CXX_TESTS_UTIL_XML_FILENAME_FILTER_H
#include "filter.h"
namespace log4cxx
{
class XMLFilenameFilter : public Filter
{
public:
XMLFilenameFilter(const std::string& actual, const std::string& expected);
};
}
#endif //_LOG4CXX_TESTS_UTIL_XML_FILENAME_FILTER_H
| 001-log4cxx | trunk/src/test/cpp/util/xmlfilenamefilter.h | C++ | asf20 | 1,151 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#ifndef _LOG4CXX_TESTS_UTIL_THREAD_FILTER_H
#define _LOG4CXX_TESTS_UTIL_THREAD_FILTER_H
#include "filter.h"
namespace log4cxx
{
class ThreadFilter : public Filter
{
public:
ThreadFilter();
};
}
#endif //_LOG4CXX_TESTS_UTIL_THREAD_FILTER_H
| 001-log4cxx | trunk/src/test/cpp/util/threadfilter.h | C++ | asf20 | 1,066 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#ifndef _LOG4CXX_TESTS_UTIL_CONTROL_FILTER_H
#define _LOG4CXX_TESTS_UTIL_CONTROL_FILTER_H
#include "filter.h"
#include <vector>
namespace log4cxx
{
class ControlFilter : public Filter
{
public:
ControlFilter();
ControlFilter& operator<<(const std::string& allowedPattern);
};
}
#endif //_LOG4CXX_TESTS_UTIL_CONTROL_FILTER_H
| 001-log4cxx | trunk/src/test/cpp/util/controlfilter.h | C++ | asf20 | 1,157 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#ifndef _LOG4CXX_TESTS_UTIL_ISO_8601_FILTER_H
#define _LOG4CXX_TESTS_UTIL_ISO_8601_FILTER_H
#include "filter.h"
namespace log4cxx
{
class ISO8601Filter : public Filter
{
public:
ISO8601Filter();
};
}
#endif //_LOG4CXX_TESTS_UTIL_ISO_8601_FILTER_H
| 001-log4cxx | trunk/src/test/cpp/util/iso8601filter.h | C++ | asf20 | 1,074 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "relativetimefilter.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
RelativeTimeFilter::RelativeTimeFilter()
: Filter(RELATIVE_TIME_PAT, "") {}
| 001-log4cxx | trunk/src/test/cpp/util/relativetimefilter.cpp | C++ | asf20 | 977 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#ifndef _LOG4CXX_TESTS_UTIL_SERIALIZATIONTESTHELPER_H
#define _LOG4CXX_TESTS_UTIL_SERIALIZATIONTESTHELPER_H
#include <log4cxx/spi/loggingevent.h>
namespace log4cxx
{
namespace util {
class SerializationTestHelper {
public:
static bool compare(const char* filename,
const log4cxx::spi::LoggingEventPtr& event,
size_t stopCompare);
static bool compare(const char* filename,
const std::vector<unsigned char>& array,
size_t stopCompare, log4cxx::helpers::Pool& p);
private:
SerializationTestHelper();
SerializationTestHelper(const SerializationTestHelper&);
SerializationTestHelper& operator=(SerializationTestHelper&);
};
}
}
#endif
| 001-log4cxx | trunk/src/test/cpp/util/serializationtesthelper.h | C++ | asf20 | 1,684 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#ifndef _LOG4CXX_TESTS_UTIL_ABS_DATE_TIME_FILTER_H
#define _LOG4CXX_TESTS_UTIL_ABS_DATE_TIME_FILTER_H
#include "filter.h"
namespace log4cxx
{
class AbsoluteDateAndTimeFilter : public Filter
{
public:
AbsoluteDateAndTimeFilter();
};
}
#endif //_LOG4CXX_TESTS_UTIL_ABS_DATE_TIME_FILTER_H
| 001-log4cxx | trunk/src/test/cpp/util/absolutedateandtimefilter.h | C++ | asf20 | 1,113 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "filenamefilter.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
FilenameFilter::FilenameFilter(const std::string& actual, const std::string& expected) {
std::string pattern(actual);
size_t backslash = pattern.rfind('\\', pattern.length() - 1);
while (backslash != std::string::npos) {
pattern.replace(backslash, 1, "\\\\", 2);
if (backslash == 0) {
backslash = std::string::npos;
} else {
backslash = pattern.rfind('\\', backslash - 1);
}
}
patterns.push_back( PatternReplacement(pattern, expected) );
}
| 001-log4cxx | trunk/src/test/cpp/util/filenamefilter.cpp | C++ | asf20 | 1,398 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#ifndef _LOG4CXX_TESTS_UTIL_TRANSFORMER_H
#define _LOG4CXX_TESTS_UTIL_TRANSFORMER_H
#include "filter.h"
#include <vector>
extern "C" {
struct apr_pool_t;
}
namespace log4cxx
{
class File;
class Transformer
{
public:
static void transform(const File& in,
const File& out,
const std::vector<Filter *>& filters);
static void transform(const File& in,
const File& out,
const Filter& filter);
static void transform(const File& in,
const File& out,
const std::vector< log4cxx::Filter::PatternReplacement >& patterns);
private:
static void copyFile(const File& in,
const File& out);
static void createSedCommandFile(const std::string& regexName,
const log4cxx::Filter::PatternList& patterns,
apr_pool_t* pool);
};
}
#endif //_LOG4CXX_TESTS_UTIL_TRANSFORMER_H
| 001-log4cxx | trunk/src/test/cpp/util/transformer.h | C++ | asf20 | 1,974 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#ifndef _LOG4CXX_TESTS_UTIL_ABS_TIME_FILTER_H
#define _LOG4CXX_TESTS_UTIL_ABS_TIME_FILTER_H
#include "filter.h"
namespace log4cxx
{
class AbsoluteTimeFilter : public Filter
{
public:
AbsoluteTimeFilter();
};
}
#endif //_LOG4CXX_TESTS_UTIL_ABS_TIME_FILTER_H
| 001-log4cxx | trunk/src/test/cpp/util/absolutetimefilter.h | C++ | asf20 | 1,084 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "absolutedateandtimefilter.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
AbsoluteDateAndTimeFilter::AbsoluteDateAndTimeFilter() :
Filter(ABSOLUTE_DATE_AND_TIME_PAT, "") {}
| 001-log4cxx | trunk/src/test/cpp/util/absolutedateandtimefilter.cpp | C++ | asf20 | 1,008 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <log4cxx/logstring.h>
namespace log4cxx
{
namespace util {
class BinaryCompare
{
private:
/**
* Class can not be constructed.
*/
BinaryCompare();
public:
static void compare(const char* filename1,
const char* filename2);
};
}
}
| 001-log4cxx | trunk/src/test/cpp/util/binarycompare.h | C++ | asf20 | 1,179 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "threadfilter.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
ThreadFilter::ThreadFilter() : Filter("\\[[0-9A-Fa-fXx]*]", "\\[main]") {}
| 001-log4cxx | trunk/src/test/cpp/util/threadfilter.cpp | C++ | asf20 | 966 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "xmlfilenamefilter.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
XMLFilenameFilter::XMLFilenameFilter(const std::string& /*actual*/, const std::string& expected) {
std::string pattern(" file=\\(.\\).*");
pattern += expected;
std::string replacement(" file=\\\\1");
replacement += expected;
// patterns.push_back( PatternReplacement(pattern, replacement) );
}
| 001-log4cxx | trunk/src/test/cpp/util/xmlfilenamefilter.cpp | C++ | asf20 | 1,210 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <log4cxx/logstring.h>
namespace log4cxx
{
class File;
namespace helpers {
class Pool;
}
class Compare
{
public:
static bool compare(const File& file1,
const File& file2);
private:
/// Prints file on the console.
static void outputFile(const File& file,
const LogString& contents,
log4cxx::helpers::Pool& pool);
static void emit(const LogString &line);
static bool getline(LogString& buf, LogString& line);
};
}
| 001-log4cxx | trunk/src/test/cpp/util/compare.h | C++ | asf20 | 1,447 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#ifndef _LOG4CXX_TESTS_UTIL_LINE_NUMBER_FILTER_H
#define _LOG4CXX_TESTS_UTIL_LINE_NUMBER_FILTER_H
#include "filter.h"
namespace log4cxx
{
class LineNumberFilter : public Filter
{
public:
LineNumberFilter();
};
}
#endif //_LOG4CXX_TESTS_UTIL_LINE_NUMBER_FILTER_H
| 001-log4cxx | trunk/src/test/cpp/util/linenumberfilter.h | C++ | asf20 | 1,089 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "filter.h"
#include <log4cxx/helpers/transcoder.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
Filter::Filter() {}
Filter::Filter(const std::string& match,
const std::string& replacement) {
patterns.push_back( PatternReplacement(match, replacement));
}
Filter::~Filter() {}
| 001-log4cxx | trunk/src/test/cpp/util/utilfilter.cpp | C++ | asf20 | 1,141 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#ifndef _LOG4CXX_TESTS_UTIL_REL_TIME_FILTER_H
#define _LOG4CXX_TESTS_UTIL_REL_TIME_FILTER_H
#include "filter.h"
namespace log4cxx
{
class RelativeTimeFilter : public Filter
{
public:
RelativeTimeFilter();
};
}
#endif //_LOG4CXX_TESTS_UTIL_REL_TIME_FILTER_H
| 001-log4cxx | trunk/src/test/cpp/util/relativetimefilter.h | C++ | asf20 | 1,084 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "transformer.h"
#include <log4cxx/file.h>
#include <log4cxx/helpers/transcoder.h>
#include <apr_thread_proc.h>
#include <apr_pools.h>
#include <apr_file_io.h>
#include <apr_strings.h>
#include <assert.h>
#include <iostream>
using namespace log4cxx;
using namespace log4cxx::helpers;
#if !defined(APR_FOPEN_READ)
#define APR_FOPEN_READ APR_READ
#define APR_FOPEN_CREATE APR_CREATE
#define APR_FOPEN_WRITE APR_WRITE
#define APR_FOPEN_TRUNCATE APR_TRUNCATE
#define APR_FOPEN_APPEND APR_APPEND
#endif
void Transformer::transform(const File& in, const File& out,
const std::vector<Filter *>& filters)
{
log4cxx::Filter::PatternList patterns;
for(std::vector<Filter*>::const_iterator iter = filters.begin();
iter != filters.end();
iter++) {
const log4cxx::Filter::PatternList& thesePatterns = (*iter)->getPatterns();
for (log4cxx::Filter::PatternList::const_iterator pattern = thesePatterns.begin();
pattern != thesePatterns.end();
pattern++) {
patterns.push_back(*pattern);
}
}
transform(in, out, patterns);
}
void Transformer::transform(const File& in, const File& out,
const Filter& filter)
{
transform(in, out, filter.getPatterns());
}
void Transformer::copyFile(const File& in, const File& out) {
Pool p;
apr_pool_t* pool = p.getAPRPool();
//
// fairly naive file copy code
//
//
apr_file_t* child_out;
apr_int32_t flags = APR_FOPEN_WRITE | APR_FOPEN_CREATE | APR_FOPEN_TRUNCATE;
apr_status_t stat = out.open(&child_out, flags, APR_OS_DEFAULT, p);
assert(stat == APR_SUCCESS);
apr_file_t* in_file;
stat = in.open(&in_file, APR_FOPEN_READ, APR_OS_DEFAULT, p);
assert(stat == APR_SUCCESS);
apr_size_t bufsize = 32000;
void* buf = apr_palloc(pool, bufsize);
apr_size_t bytesRead = bufsize;
while(stat == 0 && bytesRead == bufsize) {
stat = apr_file_read(in_file, buf, &bytesRead);
if (stat == 0 && bytesRead > 0) {
stat = apr_file_write(child_out, buf, &bytesRead);
assert(stat == APR_SUCCESS);
}
}
stat = apr_file_close(child_out);
assert(stat == APR_SUCCESS);
}
void Transformer::createSedCommandFile(const std::string& regexName,
const log4cxx::Filter::PatternList& patterns,
apr_pool_t* pool) {
apr_file_t* regexFile;
apr_status_t stat = apr_file_open(®exFile,
regexName.c_str(),
APR_FOPEN_WRITE | APR_FOPEN_CREATE | APR_FOPEN_TRUNCATE, APR_OS_DEFAULT,
pool);
assert(stat == APR_SUCCESS);
std::string tmp;
for (log4cxx::Filter::PatternList::const_iterator iter = patterns.begin();
iter != patterns.end();
iter++) {
tmp = "sQ";
tmp.append(iter->first);
tmp.append(1, 'Q');
tmp.append(iter->second);
tmp.append("Qg\n");
apr_file_puts(tmp.c_str(), regexFile);
}
apr_file_close(regexFile);
}
void Transformer::transform(const File& in, const File& out,
const log4cxx::Filter::PatternList& patterns)
{
//
// if no patterns just copy the file
//
if (patterns.size() == 0) {
copyFile(in, out);
} else {
Pool p;
apr_pool_t* pool = p.getAPRPool();
//
// write the regex's to a temporary file since they
// may get mangled if passed as parameters
//
std::string regexName;
Transcoder::encode(in.getPath(), regexName);
regexName.append(".sed");
createSedCommandFile(regexName, patterns, pool);
//
// prepare to launch sed
//
//
apr_procattr_t* attr = NULL;
apr_status_t stat = apr_procattr_create(&attr, pool);
assert(stat == APR_SUCCESS);
stat = apr_procattr_io_set(attr, APR_NO_PIPE, APR_FULL_BLOCK,
APR_FULL_BLOCK);
assert(stat == APR_SUCCESS);
//
// find the program on the path
//
stat = apr_procattr_cmdtype_set(attr, APR_PROGRAM_PATH);
assert(stat == APR_SUCCESS);
//
// build the argument list
// using Q as regex separator on s command
//
const char** args = (const char**)
apr_palloc(pool, 5 * sizeof(*args));
int i = 0;
//
// not well documented
// but the first arg is a duplicate of the executable name
//
args[i++] = "sed";
std::string regexArg("-f");
regexArg.append(regexName);
args[i++] = apr_pstrdup(pool, regexArg.c_str());
//
// specify the input file
args[i++] = Transcoder::encode(in.getPath(), p);
args[i] = NULL;
//
// set the output stream to the filtered file
//
apr_file_t* child_out;
apr_int32_t flags = APR_FOPEN_READ | APR_FOPEN_WRITE |
APR_FOPEN_CREATE | APR_FOPEN_TRUNCATE;
stat = out.open(&child_out, flags, APR_OS_DEFAULT, p);
assert(stat == APR_SUCCESS);
stat = apr_procattr_child_out_set(attr, child_out, NULL);
assert(stat == APR_SUCCESS);
//
// redirect the child's error stream to this processes' error stream
//
apr_file_t* child_err;
stat = apr_file_open_stderr(&child_err, pool);
assert(stat == 0);
stat = apr_procattr_child_err_set(attr, child_err, NULL);
assert(stat == APR_SUCCESS);
apr_proc_t pid;
stat = apr_proc_create(&pid,"sed", args, NULL, attr, pool);
if (stat != APR_SUCCESS) {
puts("Error invoking sed, sed must be on the path in order to run unit tests");
}
assert(stat == APR_SUCCESS);
apr_proc_wait(&pid, NULL, NULL, APR_WAIT);
stat = apr_file_close(child_out);
assert(stat == APR_SUCCESS);
}
}
| 001-log4cxx | trunk/src/test/cpp/util/transformer.cpp | C++ | asf20 | 6,916 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <log4cxx/consoleappender.h>
#include "logunit.h"
#include "writerappendertestcase.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
/**
Unit tests of log4cxx::nt::NTEventLogAppender
*/
class ConsoleAppenderTestCase : public WriterAppenderTestCase
{
LOGUNIT_TEST_SUITE(ConsoleAppenderTestCase);
//
// tests inherited from AppenderSkeletonTestCase
//
LOGUNIT_TEST(testDefaultThreshold);
LOGUNIT_TEST(testSetOptionThreshold);
LOGUNIT_TEST_SUITE_END();
public:
WriterAppender* createWriterAppender() const {
return new log4cxx::ConsoleAppender();
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(ConsoleAppenderTestCase);
| 001-log4cxx | trunk/src/test/cpp/consoleappendertestcase.cpp | C++ | asf20 | 1,557 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <log4cxx/fileappender.h>
#include "writerappendertestcase.h"
/**
An abstract set of tests for inclusion in concrete
appender test case
*/
class FileAppenderAbstractTestCase : public WriterAppenderTestCase
{
public:
log4cxx::WriterAppender* createWriterAppender() const;
virtual log4cxx::FileAppender* createFileAppender() const = 0;
};
| 001-log4cxx | trunk/src/test/cpp/fileappendertestcase.h | C++ | asf20 | 1,177 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <log4cxx/logger.h>
#include <log4cxx/hierarchy.h>
#include "logunit.h"
#include "insertwide.h"
using namespace log4cxx;
/**
* Tests hierarchy.
*
*/
LOGUNIT_CLASS(HierarchyTest) {
LOGUNIT_TEST_SUITE(HierarchyTest);
LOGUNIT_TEST(testGetParent);
LOGUNIT_TEST_SUITE_END();
public:
/**
* Tests getParent.
*/
void testGetParent() {
//
// Note: test inspired by LOGCXX-118.
//
LoggerPtr logger1(Logger::getLogger("HierarchyTest_testGetParent.logger1"));
LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("root")), logger1->getParent()->getName());
LoggerPtr logger2(Logger::getLogger("HierarchyTest_testGetParent.logger2"));
LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("root")), logger1->getParent()->getName());
LoggerPtr logger3(Logger::getLogger("HierarchyTest_testGetParent"));
LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("HierarchyTest_testGetParent")),
logger1->getParent()->getName());
LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("HierarchyTest_testGetParent")),
logger2->getParent()->getName());
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(HierarchyTest);
| 001-log4cxx | trunk/src/test/cpp/hierarchytest.cpp | C++ | asf20 | 1,979 |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#
SUBDIRS = cpp resources
| 001-log4cxx | trunk/src/test/Makefile.am | Makefile | asf20 | 808 |
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You 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.
*/
| 001-log4cxx | trunk/src/site/resources/css/site.css | CSS | asf20 | 775 |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#
| 001-log4cxx | trunk/src/site/fml/Makefile.am | Makefile | asf20 | 784 |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#
EXTRA_DIST = Doxyfile mainpage.dox license_notice_footer.txt
# DOC is defined if installer requests doc generation.
if DOC
htmldest = $(pkgdatadir)/html
install-data-hook:
$(mkinstalldirs) $(DESTDIR)$(htmldest)
cp -dpR @manual_dest@/* $(DESTDIR)$(htmldest)
# Automake's "distcheck" is sensitive to having files left over
# after "make uninstall", so we have to clean up the install hook.
uninstall-local:
rm -rf $(DESTDIR)$(htmldest)
dox: @manual_dest@/index.html
if LATEX_DOC
pdf: @PACKAGE@.pdf
@PACKAGE@.pdf:
$(MAKE) -C ./latex pdf
ln -s ./latex/refman.ps @PACKAGE@.ps
ln -s ./latex/refman.pdf @PACKAGE@.pdf
endif
else
# We repeat the three targets in both the "if" and "else" clauses
# of the conditional, because the generated makefile will contain
# references to the targets (target "install" depends on target
# "install-datahook", for example), and some make programs get upset
# if no target exists.
install-data-hook:
uninstall-local:
dox:
endif
all-local: dox
@manual_dest@/index.html: Doxyfile mainpage.dox
"@DOXYGEN@"
distdir = $(top_builddir)/$(PACKAGE)-$(VERSION)
# Make tarfile to distribute the HTML documentation.
doc-dist: dox
rm -rf $(distdir)
mkdir $(distdir)
mkdir $(distdir)/docs
mkdir $(distdir)/docs/html
cp @manual_dest@/* $(distdir)/docs/html
tar -czf $(top_builddir)/$(PACKAGE)-docs-$(VERSION).tar.gz -C $(distdir) docs
rm -rf $(distdir)
clean-local:
$(RM) -r latex
$(RM) -r @manual_dest@ man @PACKAGE@.ps @PACKAGE@.pdf
dist-hook:
-rm -f $(distdir)/Doxyfile
| 001-log4cxx | trunk/src/site/doxy/Makefile.am | Makefile | asf20 | 2,313 |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#
SUBDIRS = doxy
| 001-log4cxx | trunk/src/site/Makefile.am | Makefile | asf20 | 799 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
H1, H2, H3 {
color: #101099;
}
A:link, A:visited {
text-decoration: none;
color: #006699;
}
A:link:hover {
text-decoration: underline;
}
.centercol {
margin-top: 120px;
margin-left: 210px;
margin-right:210px;
max-width: 800px;
}
.leftcol {
position: absolute;
left: 10px;
top: 130px;
width: 190px;
}
.banner {
position: absolute;
left: 10px;
top: 10px;
height: 130px;
width: 1000px;
}
.menu_header, .menu_item {
/* width: 190px; */
font-family: "trebuchet MS", Arial, Helvetica, sans-serif;
font-size: smaller;
}
.menu_header {
border:1px solid #AAAAAA;
background: #CCCCCC;
padding-left: 1ex;
}
.menu_item:hover {
background: #DDD;
}
.menu_item {
background: #EEEEEE;
padding-left: 2ex;
border-top: 0px solid #AAAAAA;
border-right: 1px solid #AAAAAA;
border-bottom:1px solid #AAAAAA;
border-left: 1px solid #AAAAAA;
}
.source {
border-top: 1px solid #DDDDDD;
border-bottom: 1px solid #DDDDDD;
background:#eee;
font-family: Courier, "MS Courier New", Prestige, Everson Monocourrier, monospace;
font-size: smaller;
padding-bottom: 0.5ex;
padding-top: 0.5ex;
padding-left: 2ex;
}
table.ls {
background: #FFFFFF;
}
table.ls td {
background: #f4f4f4;
vertical-align: top;
padding-bottom: 1ex;
}
table.ls th {
background: #E4E4E4;
}
.index-faqSection {
font-size: larger;
padding-left: 0em;
font-weight: bolder;
}
.index-question {
padding-left: 1em;
}
.faqSection {
font-size: larger;
font-weight: bolder;
}
.question {
font-weight: bolder;
}
/* this class is used for screen output placed in <pre></pre> tags */
.screen_output {
padding-left: 1em;
padding-right: 1em;
border-top: 1px solid #AAAAAA;
border-right: 1px solid #AAAAAA;
border-bottom:1px solid #AAAAAA;
border-left: 1px solid #AAAAAA;
}
.big {
font-size: larger;
font-weight: bold;
}
.small {
font-size: smaller;
}
.red {
color: #AA0000;
}
.msg_title {
padding-left: 1ex;
padding-right: 1ex;
font-family: Courier, "MS Courier New", Prestige, Everson Monocourrier, monospace;
border: 1px solid #AAAAAA;
background: #DDDDFF;
}
.msg_meaning {
padding-left: 1em;
padding-right: 1em;
}
| 001-log4cxx | trunk/src/site/xdoc/stylesheets/site.css | CSS | asf20 | 3,025 |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#
| 001-log4cxx | trunk/src/site/xdoc/Makefile.am | Makefile | asf20 | 784 |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#
| 001-log4cxx | trunk/src/site/apt/Makefile.am | Makefile | asf20 | 784 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "apr_errno.h"
#include "apr_general.h"
#include "apr_getopt.h"
#include "apr_strings.h"
#include "testutil.h"
static void format_arg(char *str, char option, const char *arg)
{
if (arg) {
apr_snprintf(str, 8196, "%soption: %c with %s\n", str, option, arg);
}
else {
apr_snprintf(str, 8196, "%soption: %c\n", str, option);
}
}
static void unknown_arg(void *str, const char *err, ...)
{
va_list va;
va_start(va, err);
apr_vsnprintf(str, 8196, err, va);
va_end(va);
}
static void no_options_found(abts_case *tc, void *data)
{
int largc = 5;
const char * const largv[] = {"testprog", "-a", "-b", "-c", "-d"};
apr_getopt_t *opt;
apr_status_t rv;
char ch;
const char *optarg;
char str[8196];
str[0] = '\0';
rv = apr_getopt_init(&opt, p, largc, largv);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
while (apr_getopt(opt, "abcd", &ch, &optarg) == APR_SUCCESS) {
switch (ch) {
case 'a':
case 'b':
case 'c':
case 'd':
default:
format_arg(str, ch, optarg);
}
}
ABTS_STR_EQUAL(tc, "option: a\n"
"option: b\n"
"option: c\n"
"option: d\n", str);
}
static void no_options(abts_case *tc, void *data)
{
int largc = 5;
const char * const largv[] = {"testprog", "-a", "-b", "-c", "-d"};
apr_getopt_t *opt;
apr_status_t rv;
char ch;
const char *optarg;
char str[8196];
str[0] = '\0';
rv = apr_getopt_init(&opt, p, largc, largv);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
opt->errfn = unknown_arg;
opt->errarg = str;
while (apr_getopt(opt, "efgh", &ch, &optarg) == APR_SUCCESS) {
switch (ch) {
case 'a':
case 'b':
case 'c':
case 'd':
format_arg(str, ch, optarg);
break;
default:
break;
}
}
ABTS_STR_EQUAL(tc, "testprog: illegal option -- a\n", str);
}
static void required_option(abts_case *tc, void *data)
{
int largc = 3;
const char * const largv[] = {"testprog", "-a", "foo"};
apr_getopt_t *opt;
apr_status_t rv;
char ch;
const char *optarg;
char str[8196];
str[0] = '\0';
rv = apr_getopt_init(&opt, p, largc, largv);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
opt->errfn = unknown_arg;
opt->errarg = str;
while (apr_getopt(opt, "a:", &ch, &optarg) == APR_SUCCESS) {
switch (ch) {
case 'a':
format_arg(str, ch, optarg);
break;
default:
break;
}
}
ABTS_STR_EQUAL(tc, "option: a with foo\n", str);
}
static void required_option_notgiven(abts_case *tc, void *data)
{
int largc = 2;
const char * const largv[] = {"testprog", "-a"};
apr_getopt_t *opt;
apr_status_t rv;
char ch;
const char *optarg;
char str[8196];
str[0] = '\0';
rv = apr_getopt_init(&opt, p, largc, largv);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
opt->errfn = unknown_arg;
opt->errarg = str;
while (apr_getopt(opt, "a:", &ch, &optarg) == APR_SUCCESS) {
switch (ch) {
case 'a':
format_arg(str, ch, optarg);
break;
default:
break;
}
}
ABTS_STR_EQUAL(tc, "testprog: option requires an argument -- a\n", str);
}
static void optional_option(abts_case *tc, void *data)
{
int largc = 3;
const char * const largv[] = {"testprog", "-a", "foo"};
apr_getopt_t *opt;
apr_status_t rv;
char ch;
const char *optarg;
char str[8196];
str[0] = '\0';
rv = apr_getopt_init(&opt, p, largc, largv);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
opt->errfn = unknown_arg;
opt->errarg = str;
while (apr_getopt(opt, "a::", &ch, &optarg) == APR_SUCCESS) {
switch (ch) {
case 'a':
format_arg(str, ch, optarg);
break;
default:
break;
}
}
ABTS_STR_EQUAL(tc, "option: a with foo\n", str);
}
static void optional_option_notgiven(abts_case *tc, void *data)
{
int largc = 2;
const char * const largv[] = {"testprog", "-a"};
apr_getopt_t *opt;
apr_status_t rv;
char ch;
const char *optarg;
char str[8196];
str[0] = '\0';
rv = apr_getopt_init(&opt, p, largc, largv);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
opt->errfn = unknown_arg;
opt->errarg = str;
while (apr_getopt(opt, "a::", &ch, &optarg) == APR_SUCCESS) {
switch (ch) {
case 'a':
format_arg(str, ch, optarg);
break;
default:
break;
}
}
#if 0
/* Our version of getopt doesn't allow for optional arguments. */
ABTS_STR_EQUAL(tc, "option: a\n", str);
#endif
ABTS_STR_EQUAL(tc, "testprog: option requires an argument -- a\n", str);
}
abts_suite *testgetopt(abts_suite *suite)
{
suite = ADD_SUITE(suite)
abts_run_test(suite, no_options, NULL);
abts_run_test(suite, no_options_found, NULL);
abts_run_test(suite, required_option, NULL);
abts_run_test(suite, required_option_notgiven, NULL);
abts_run_test(suite, optional_option, NULL);
abts_run_test(suite, optional_option_notgiven, NULL);
return suite;
}
| 001-log4cxx | trunk/src/apr/test/testargs.c | C | asf20 | 6,271 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "testglobalmutex.h"
#include "apr_pools.h"
#include "apr_file_io.h"
#include "apr_general.h"
#include "apr_global_mutex.h"
#include "apr_strings.h"
#include "apr.h"
#if APR_HAVE_STDLIB_H
#include <stdlib.h>
#endif
int main(int argc, const char * const argv[])
{
apr_pool_t *p;
int i = 0;
apr_lockmech_e mech;
apr_global_mutex_t *global_lock;
apr_status_t rv;
apr_initialize();
atexit(apr_terminate);
apr_pool_create(&p, NULL);
if (argc >= 2) {
mech = (apr_lockmech_e)apr_strtoi64(argv[1], NULL, 0);
}
else {
mech = APR_LOCK_DEFAULT;
}
rv = apr_global_mutex_create(&global_lock, LOCKNAME, mech, p);
if (rv != APR_SUCCESS) {
exit(-rv);
}
apr_global_mutex_child_init(&global_lock, LOCKNAME, p);
while (1) {
apr_global_mutex_lock(global_lock);
if (i == MAX_ITER) {
apr_global_mutex_unlock(global_lock);
exit(i);
}
i++;
apr_global_mutex_unlock(global_lock);
}
exit(0);
}
| 001-log4cxx | trunk/src/apr/test/globalmutexchild.c | C | asf20 | 1,853 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "apr_thread_proc.h"
#include "apr_thread_mutex.h"
#include "apr_thread_rwlock.h"
#include "apr_file_io.h"
#include "apr_errno.h"
#include "apr_general.h"
#include "apr_getopt.h"
#include "errno.h"
#include <stdio.h>
#include <stdlib.h>
#include "testutil.h"
#if !APR_HAS_THREADS
int main(void)
{
printf("This program won't work on this platform because there is no "
"support for threads.\n");
return 0;
}
#else /* !APR_HAS_THREADS */
#define MAX_COUNTER 1000000
#define MAX_THREADS 6
static long mutex_counter;
static apr_thread_mutex_t *thread_lock;
void * APR_THREAD_FUNC thread_mutex_func(apr_thread_t *thd, void *data);
apr_status_t test_thread_mutex(int num_threads); /* apr_thread_mutex_t */
static apr_thread_rwlock_t *thread_rwlock;
void * APR_THREAD_FUNC thread_rwlock_func(apr_thread_t *thd, void *data);
apr_status_t test_thread_rwlock(int num_threads); /* apr_thread_rwlock_t */
int test_thread_mutex_nested(int num_threads);
apr_pool_t *pool;
int i = 0, x = 0;
void * APR_THREAD_FUNC thread_mutex_func(apr_thread_t *thd, void *data)
{
int i;
for (i = 0; i < MAX_COUNTER; i++) {
apr_thread_mutex_lock(thread_lock);
mutex_counter++;
apr_thread_mutex_unlock(thread_lock);
}
return NULL;
}
void * APR_THREAD_FUNC thread_rwlock_func(apr_thread_t *thd, void *data)
{
int i;
for (i = 0; i < MAX_COUNTER; i++) {
apr_thread_rwlock_wrlock(thread_rwlock);
mutex_counter++;
apr_thread_rwlock_unlock(thread_rwlock);
}
return NULL;
}
int test_thread_mutex(int num_threads)
{
apr_thread_t *t[MAX_THREADS];
apr_status_t s[MAX_THREADS];
apr_time_t time_start, time_stop;
int i;
mutex_counter = 0;
printf("apr_thread_mutex_t Tests\n");
printf("%-60s", " Initializing the apr_thread_mutex_t (UNNESTED)");
s[0] = apr_thread_mutex_create(&thread_lock, APR_THREAD_MUTEX_UNNESTED, pool);
if (s[0] != APR_SUCCESS) {
printf("Failed!\n");
return s[0];
}
printf("OK\n");
apr_thread_mutex_lock(thread_lock);
/* set_concurrency(4)? -aaron */
printf(" Starting %d threads ", num_threads);
for (i = 0; i < num_threads; ++i) {
s[i] = apr_thread_create(&t[i], NULL, thread_mutex_func, NULL, pool);
if (s[i] != APR_SUCCESS) {
printf("Failed!\n");
return s[i];
}
}
printf("OK\n");
time_start = apr_time_now();
apr_thread_mutex_unlock(thread_lock);
/* printf("%-60s", " Waiting for threads to exit"); */
for (i = 0; i < num_threads; ++i) {
apr_thread_join(&s[i], t[i]);
}
/* printf("OK\n"); */
time_stop = apr_time_now();
printf("microseconds: %" APR_INT64_T_FMT " usec\n",
(time_stop - time_start));
if (mutex_counter != MAX_COUNTER * num_threads)
printf("error: counter = %ld\n", mutex_counter);
return APR_SUCCESS;
}
int test_thread_mutex_nested(int num_threads)
{
apr_thread_t *t[MAX_THREADS];
apr_status_t s[MAX_THREADS];
apr_time_t time_start, time_stop;
int i;
mutex_counter = 0;
printf("apr_thread_mutex_t Tests\n");
printf("%-60s", " Initializing the apr_thread_mutex_t (NESTED)");
s[0] = apr_thread_mutex_create(&thread_lock, APR_THREAD_MUTEX_NESTED, pool);
if (s[0] != APR_SUCCESS) {
printf("Failed!\n");
return s[0];
}
printf("OK\n");
apr_thread_mutex_lock(thread_lock);
/* set_concurrency(4)? -aaron */
printf(" Starting %d threads ", num_threads);
for (i = 0; i < num_threads; ++i) {
s[i] = apr_thread_create(&t[i], NULL, thread_mutex_func, NULL, pool);
if (s[i] != APR_SUCCESS) {
printf("Failed!\n");
return s[i];
}
}
printf("OK\n");
time_start = apr_time_now();
apr_thread_mutex_unlock(thread_lock);
/* printf("%-60s", " Waiting for threads to exit"); */
for (i = 0; i < num_threads; ++i) {
apr_thread_join(&s[i], t[i]);
}
/* printf("OK\n"); */
time_stop = apr_time_now();
printf("microseconds: %" APR_INT64_T_FMT " usec\n",
(time_stop - time_start));
if (mutex_counter != MAX_COUNTER * num_threads)
printf("error: counter = %ld\n", mutex_counter);
return APR_SUCCESS;
}
int test_thread_rwlock(int num_threads)
{
apr_thread_t *t[MAX_THREADS];
apr_status_t s[MAX_THREADS];
apr_time_t time_start, time_stop;
int i;
mutex_counter = 0;
printf("apr_thread_rwlock_t Tests\n");
printf("%-60s", " Initializing the apr_thread_rwlock_t");
s[0] = apr_thread_rwlock_create(&thread_rwlock, pool);
if (s[0] != APR_SUCCESS) {
printf("Failed!\n");
return s[0];
}
printf("OK\n");
apr_thread_rwlock_wrlock(thread_rwlock);
/* set_concurrency(4)? -aaron */
printf(" Starting %d threads ", num_threads);
for (i = 0; i < num_threads; ++i) {
s[i] = apr_thread_create(&t[i], NULL, thread_rwlock_func, NULL, pool);
if (s[i] != APR_SUCCESS) {
printf("Failed!\n");
return s[i];
}
}
printf("OK\n");
time_start = apr_time_now();
apr_thread_rwlock_unlock(thread_rwlock);
/* printf("%-60s", " Waiting for threads to exit"); */
for (i = 0; i < num_threads; ++i) {
apr_thread_join(&s[i], t[i]);
}
/* printf("OK\n"); */
time_stop = apr_time_now();
printf("microseconds: %" APR_INT64_T_FMT " usec\n",
(time_stop - time_start));
if (mutex_counter != MAX_COUNTER * num_threads)
printf("error: counter = %ld\n", mutex_counter);
return APR_SUCCESS;
}
int main(int argc, const char * const *argv)
{
apr_status_t rv;
char errmsg[200];
const char *lockname = "multi.lock";
apr_getopt_t *opt;
char optchar;
const char *optarg;
printf("APR Lock Performance Test\n==============\n\n");
apr_initialize();
atexit(apr_terminate);
if (apr_pool_create(&pool, NULL) != APR_SUCCESS)
exit(-1);
if ((rv = apr_getopt_init(&opt, pool, argc, argv)) != APR_SUCCESS) {
fprintf(stderr, "Could not set up to parse options: [%d] %s\n",
rv, apr_strerror(rv, errmsg, sizeof errmsg));
exit(-1);
}
while ((rv = apr_getopt(opt, "f:", &optchar, &optarg)) == APR_SUCCESS) {
if (optchar == 'f') {
lockname = optarg;
}
}
if (rv != APR_SUCCESS && rv != APR_EOF) {
fprintf(stderr, "Could not parse options: [%d] %s\n",
rv, apr_strerror(rv, errmsg, sizeof errmsg));
exit(-1);
}
for (i = 1; i <= MAX_THREADS; ++i) {
if ((rv = test_thread_mutex(i)) != APR_SUCCESS) {
fprintf(stderr,"thread_mutex test failed : [%d] %s\n",
rv, apr_strerror(rv, (char*)errmsg, 200));
exit(-3);
}
if ((rv = test_thread_mutex_nested(i)) != APR_SUCCESS) {
fprintf(stderr,"thread_mutex (NESTED) test failed : [%d] %s\n",
rv, apr_strerror(rv, (char*)errmsg, 200));
exit(-4);
}
if ((rv = test_thread_rwlock(i)) != APR_SUCCESS) {
fprintf(stderr,"thread_rwlock test failed : [%d] %s\n",
rv, apr_strerror(rv, (char*)errmsg, 200));
exit(-6);
}
}
return 0;
}
#endif /* !APR_HAS_THREADS */
| 001-log4cxx | trunk/src/apr/test/testlockperf.c | C | asf20 | 8,240 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "apr_general.h"
#include "apr_pools.h"
#include "apr_errno.h"
#include "apr_file_io.h"
#include "testutil.h"
#define TEST "Testing\n"
#define TEST2 "Testing again\n"
#define FILEPATH "data/"
static void test_file_dup(abts_case *tc, void *data)
{
apr_file_t *file1 = NULL;
apr_file_t *file3 = NULL;
apr_status_t rv;
apr_finfo_t finfo;
/* First, create a new file, empty... */
rv = apr_file_open(&file1, FILEPATH "testdup.file",
APR_READ | APR_WRITE | APR_CREATE |
APR_DELONCLOSE, APR_OS_DEFAULT, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_PTR_NOTNULL(tc, file1);
rv = apr_file_dup(&file3, file1, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_PTR_NOTNULL(tc, file3);
rv = apr_file_close(file1);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
/* cleanup after ourselves */
rv = apr_file_close(file3);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_stat(&finfo, FILEPATH "testdup.file", APR_FINFO_NORM, p);
ABTS_INT_EQUAL(tc, 1, APR_STATUS_IS_ENOENT(rv));
}
static void test_file_readwrite(abts_case *tc, void *data)
{
apr_file_t *file1 = NULL;
apr_file_t *file3 = NULL;
apr_status_t rv;
apr_finfo_t finfo;
apr_size_t txtlen = sizeof(TEST);
char buff[50];
apr_off_t fpos;
/* First, create a new file, empty... */
rv = apr_file_open(&file1, FILEPATH "testdup.readwrite.file",
APR_READ | APR_WRITE | APR_CREATE |
APR_DELONCLOSE, APR_OS_DEFAULT, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_PTR_NOTNULL(tc, file1);
rv = apr_file_dup(&file3, file1, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_PTR_NOTNULL(tc, file3);
rv = apr_file_write(file3, TEST, &txtlen);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_INT_EQUAL(tc, sizeof(TEST), txtlen);
fpos = 0;
rv = apr_file_seek(file1, APR_SET, &fpos);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_ASSERT(tc, "File position mismatch, expected 0", fpos == 0);
txtlen = 50;
rv = apr_file_read(file1, buff, &txtlen);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_STR_EQUAL(tc, TEST, buff);
/* cleanup after ourselves */
rv = apr_file_close(file1);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_file_close(file3);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_stat(&finfo, FILEPATH "testdup.readwrite.file", APR_FINFO_NORM, p);
ABTS_INT_EQUAL(tc, 1, APR_STATUS_IS_ENOENT(rv));
}
static void test_dup2(abts_case *tc, void *data)
{
apr_file_t *testfile = NULL;
apr_file_t *errfile = NULL;
apr_file_t *saveerr = NULL;
apr_status_t rv;
rv = apr_file_open(&testfile, FILEPATH "testdup2.file",
APR_READ | APR_WRITE | APR_CREATE |
APR_DELONCLOSE, APR_OS_DEFAULT, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_PTR_NOTNULL(tc, testfile);
rv = apr_file_open_stderr(&errfile, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
/* Set aside the real errfile */
rv = apr_file_dup(&saveerr, errfile, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_PTR_NOTNULL(tc, saveerr);
rv = apr_file_dup2(errfile, testfile, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_PTR_NOTNULL(tc, errfile);
apr_file_close(testfile);
rv = apr_file_dup2(errfile, saveerr, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_PTR_NOTNULL(tc, errfile);
}
static void test_dup2_readwrite(abts_case *tc, void *data)
{
apr_file_t *errfile = NULL;
apr_file_t *testfile = NULL;
apr_file_t *saveerr = NULL;
apr_status_t rv;
apr_size_t txtlen = sizeof(TEST);
char buff[50];
apr_off_t fpos;
rv = apr_file_open(&testfile, FILEPATH "testdup2.readwrite.file",
APR_READ | APR_WRITE | APR_CREATE |
APR_DELONCLOSE, APR_OS_DEFAULT, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_PTR_NOTNULL(tc, testfile);
rv = apr_file_open_stderr(&errfile, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
/* Set aside the real errfile */
rv = apr_file_dup(&saveerr, errfile, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_PTR_NOTNULL(tc, saveerr);
rv = apr_file_dup2(errfile, testfile, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_PTR_NOTNULL(tc, errfile);
txtlen = sizeof(TEST2);
rv = apr_file_write(errfile, TEST2, &txtlen);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_INT_EQUAL(tc, sizeof(TEST2), txtlen);
fpos = 0;
rv = apr_file_seek(testfile, APR_SET, &fpos);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_ASSERT(tc, "File position mismatch, expected 0", fpos == 0);
txtlen = 50;
rv = apr_file_read(testfile, buff, &txtlen);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_STR_EQUAL(tc, TEST2, buff);
apr_file_close(testfile);
rv = apr_file_dup2(errfile, saveerr, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_PTR_NOTNULL(tc, errfile);
}
abts_suite *testdup(abts_suite *suite)
{
suite = ADD_SUITE(suite)
abts_run_test(suite, test_file_dup, NULL);
abts_run_test(suite, test_file_readwrite, NULL);
abts_run_test(suite, test_dup2, NULL);
abts_run_test(suite, test_dup2_readwrite, NULL);
return suite;
}
| 001-log4cxx | trunk/src/apr/test/testdup.c | C | asf20 | 6,097 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#ifndef TESTGLOBALMUTEX_H
#define TESTGLOBALMUTEX_H
/* set this to 255 so that the child processes can return it successfully. */
#define MAX_ITER 255
#define MAX_COUNTER (MAX_ITER * 4)
#define LOCKNAME "data/apr_globalmutex.lock"
#endif
| 001-log4cxx | trunk/src/apr/test/testglobalmutex.h | C | asf20 | 1,042 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "testutil.h"
#include "apr.h"
#include "apr_strings.h"
#include "apr_general.h"
#include "apr_pools.h"
#include "apr_hash.h"
static void dump_hash(apr_pool_t *p, apr_hash_t *h, char *str)
{
apr_hash_index_t *hi;
char *val, *key;
apr_ssize_t len;
int i = 0;
str[0] = '\0';
for (hi = apr_hash_first(p, h); hi; hi = apr_hash_next(hi)) {
apr_hash_this(hi,(void*) &key, &len, (void*) &val);
apr_snprintf(str, 8196, "%sKey %s (%" APR_SSIZE_T_FMT ") Value %s\n",
str, key, len, val);
i++;
}
apr_snprintf(str, 8196, "%s#entries %d\n", str, i);
}
static void sum_hash(apr_pool_t *p, apr_hash_t *h, int *pcount, int *keySum, int *valSum)
{
apr_hash_index_t *hi;
void *val, *key;
int count = 0;
*keySum = 0;
*valSum = 0;
*pcount = 0;
for (hi = apr_hash_first(p, h); hi; hi = apr_hash_next(hi)) {
apr_hash_this(hi, (void*)&key, NULL, &val);
*valSum += *(int *)val;
*keySum += *(int *)key;
count++;
}
*pcount=count;
}
static void hash_make(abts_case *tc, void *data)
{
apr_hash_t *h = NULL;
h = apr_hash_make(p);
ABTS_PTR_NOTNULL(tc, h);
}
static void hash_set(abts_case *tc, void *data)
{
apr_hash_t *h = NULL;
char *result = NULL;
h = apr_hash_make(p);
ABTS_PTR_NOTNULL(tc, h);
apr_hash_set(h, "key", APR_HASH_KEY_STRING, "value");
result = apr_hash_get(h, "key", APR_HASH_KEY_STRING);
ABTS_STR_EQUAL(tc, "value", result);
}
static void hash_reset(abts_case *tc, void *data)
{
apr_hash_t *h = NULL;
char *result = NULL;
h = apr_hash_make(p);
ABTS_PTR_NOTNULL(tc, h);
apr_hash_set(h, "key", APR_HASH_KEY_STRING, "value");
result = apr_hash_get(h, "key", APR_HASH_KEY_STRING);
ABTS_STR_EQUAL(tc, "value", result);
apr_hash_set(h, "key", APR_HASH_KEY_STRING, "new");
result = apr_hash_get(h, "key", APR_HASH_KEY_STRING);
ABTS_STR_EQUAL(tc, "new", result);
}
static void same_value(abts_case *tc, void *data)
{
apr_hash_t *h = NULL;
char *result = NULL;
h = apr_hash_make(p);
ABTS_PTR_NOTNULL(tc, h);
apr_hash_set(h, "same1", APR_HASH_KEY_STRING, "same");
result = apr_hash_get(h, "same1", APR_HASH_KEY_STRING);
ABTS_STR_EQUAL(tc, "same", result);
apr_hash_set(h, "same2", APR_HASH_KEY_STRING, "same");
result = apr_hash_get(h, "same2", APR_HASH_KEY_STRING);
ABTS_STR_EQUAL(tc, "same", result);
}
static unsigned int hash_custom( const char *key, apr_ssize_t *klen)
{
unsigned int hash = 0;
while( *klen ) {
(*klen) --;
hash = hash * 33 + key[ *klen ];
}
return hash;
}
static void same_value_custom(abts_case *tc, void *data)
{
apr_hash_t *h = NULL;
char *result = NULL;
h = apr_hash_make_custom(p, hash_custom);
ABTS_PTR_NOTNULL(tc, h);
apr_hash_set(h, "same1", 5, "same");
result = apr_hash_get(h, "same1", 5);
ABTS_STR_EQUAL(tc, "same", result);
apr_hash_set(h, "same2", 5, "same");
result = apr_hash_get(h, "same2", 5);
ABTS_STR_EQUAL(tc, "same", result);
}
static void key_space(abts_case *tc, void *data)
{
apr_hash_t *h = NULL;
char *result = NULL;
h = apr_hash_make(p);
ABTS_PTR_NOTNULL(tc, h);
apr_hash_set(h, "key with space", APR_HASH_KEY_STRING, "value");
result = apr_hash_get(h, "key with space", APR_HASH_KEY_STRING);
ABTS_STR_EQUAL(tc, "value", result);
}
/* This is kind of a hack, but I am just keeping an existing test. This is
* really testing apr_hash_first, apr_hash_next, and apr_hash_this which
* should be tested in three separate tests, but this will do for now.
*/
static void hash_traverse(abts_case *tc, void *data)
{
apr_hash_t *h;
char str[8196];
h = apr_hash_make(p);
ABTS_PTR_NOTNULL(tc, h);
apr_hash_set(h, "OVERWRITE", APR_HASH_KEY_STRING, "should not see this");
apr_hash_set(h, "FOO3", APR_HASH_KEY_STRING, "bar3");
apr_hash_set(h, "FOO3", APR_HASH_KEY_STRING, "bar3");
apr_hash_set(h, "FOO1", APR_HASH_KEY_STRING, "bar1");
apr_hash_set(h, "FOO2", APR_HASH_KEY_STRING, "bar2");
apr_hash_set(h, "FOO4", APR_HASH_KEY_STRING, "bar4");
apr_hash_set(h, "SAME1", APR_HASH_KEY_STRING, "same");
apr_hash_set(h, "SAME2", APR_HASH_KEY_STRING, "same");
apr_hash_set(h, "OVERWRITE", APR_HASH_KEY_STRING, "Overwrite key");
dump_hash(p, h, str);
ABTS_STR_EQUAL(tc, "Key FOO1 (4) Value bar1\n"
"Key FOO2 (4) Value bar2\n"
"Key OVERWRITE (9) Value Overwrite key\n"
"Key FOO3 (4) Value bar3\n"
"Key SAME1 (5) Value same\n"
"Key FOO4 (4) Value bar4\n"
"Key SAME2 (5) Value same\n"
"#entries 7\n", str);
}
/* This is kind of a hack, but I am just keeping an existing test. This is
* really testing apr_hash_first, apr_hash_next, and apr_hash_this which
* should be tested in three separate tests, but this will do for now.
*/
static void summation_test(abts_case *tc, void *data)
{
apr_hash_t *h;
int sumKeys, sumVal, trySumKey, trySumVal;
int i, j, *val, *key;
h =apr_hash_make(p);
ABTS_PTR_NOTNULL(tc, h);
sumKeys = 0;
sumVal = 0;
trySumKey = 0;
trySumVal = 0;
for (i = 0; i < 100; i++) {
j = i * 10 + 1;
sumKeys += j;
sumVal += i;
key = apr_palloc(p, sizeof(int));
*key = j;
val = apr_palloc(p, sizeof(int));
*val = i;
apr_hash_set(h, key, sizeof(int), val);
}
sum_hash(p, h, &i, &trySumKey, &trySumVal);
ABTS_INT_EQUAL(tc, 100, i);
ABTS_INT_EQUAL(tc, sumVal, trySumVal);
ABTS_INT_EQUAL(tc, sumKeys, trySumKey);
}
static void delete_key(abts_case *tc, void *data)
{
apr_hash_t *h = NULL;
char *result = NULL;
h = apr_hash_make(p);
ABTS_PTR_NOTNULL(tc, h);
apr_hash_set(h, "key", APR_HASH_KEY_STRING, "value");
apr_hash_set(h, "key2", APR_HASH_KEY_STRING, "value2");
result = apr_hash_get(h, "key", APR_HASH_KEY_STRING);
ABTS_STR_EQUAL(tc, "value", result);
result = apr_hash_get(h, "key2", APR_HASH_KEY_STRING);
ABTS_STR_EQUAL(tc, "value2", result);
apr_hash_set(h, "key", APR_HASH_KEY_STRING, NULL);
result = apr_hash_get(h, "key", APR_HASH_KEY_STRING);
ABTS_PTR_EQUAL(tc, NULL, result);
result = apr_hash_get(h, "key2", APR_HASH_KEY_STRING);
ABTS_STR_EQUAL(tc, "value2", result);
}
static void hash_count_0(abts_case *tc, void *data)
{
apr_hash_t *h = NULL;
int count;
h = apr_hash_make(p);
ABTS_PTR_NOTNULL(tc, h);
count = apr_hash_count(h);
ABTS_INT_EQUAL(tc, 0, count);
}
static void hash_count_1(abts_case *tc, void *data)
{
apr_hash_t *h = NULL;
int count;
h = apr_hash_make(p);
ABTS_PTR_NOTNULL(tc, h);
apr_hash_set(h, "key", APR_HASH_KEY_STRING, "value");
count = apr_hash_count(h);
ABTS_INT_EQUAL(tc, 1, count);
}
static void hash_count_5(abts_case *tc, void *data)
{
apr_hash_t *h = NULL;
int count;
h = apr_hash_make(p);
ABTS_PTR_NOTNULL(tc, h);
apr_hash_set(h, "key1", APR_HASH_KEY_STRING, "value1");
apr_hash_set(h, "key2", APR_HASH_KEY_STRING, "value2");
apr_hash_set(h, "key3", APR_HASH_KEY_STRING, "value3");
apr_hash_set(h, "key4", APR_HASH_KEY_STRING, "value4");
apr_hash_set(h, "key5", APR_HASH_KEY_STRING, "value5");
count = apr_hash_count(h);
ABTS_INT_EQUAL(tc, 5, count);
}
static void overlay_empty(abts_case *tc, void *data)
{
apr_hash_t *base = NULL;
apr_hash_t *overlay = NULL;
apr_hash_t *result = NULL;
int count;
char str[8196];
base = apr_hash_make(p);
overlay = apr_hash_make(p);
ABTS_PTR_NOTNULL(tc, base);
ABTS_PTR_NOTNULL(tc, overlay);
apr_hash_set(base, "key1", APR_HASH_KEY_STRING, "value1");
apr_hash_set(base, "key2", APR_HASH_KEY_STRING, "value2");
apr_hash_set(base, "key3", APR_HASH_KEY_STRING, "value3");
apr_hash_set(base, "key4", APR_HASH_KEY_STRING, "value4");
apr_hash_set(base, "key5", APR_HASH_KEY_STRING, "value5");
result = apr_hash_overlay(p, overlay, base);
count = apr_hash_count(result);
ABTS_INT_EQUAL(tc, 5, count);
dump_hash(p, result, str);
ABTS_STR_EQUAL(tc, "Key key1 (4) Value value1\n"
"Key key2 (4) Value value2\n"
"Key key3 (4) Value value3\n"
"Key key4 (4) Value value4\n"
"Key key5 (4) Value value5\n"
"#entries 5\n", str);
}
static void overlay_2unique(abts_case *tc, void *data)
{
apr_hash_t *base = NULL;
apr_hash_t *overlay = NULL;
apr_hash_t *result = NULL;
int count;
char str[8196];
base = apr_hash_make(p);
overlay = apr_hash_make(p);
ABTS_PTR_NOTNULL(tc, base);
ABTS_PTR_NOTNULL(tc, overlay);
apr_hash_set(base, "base1", APR_HASH_KEY_STRING, "value1");
apr_hash_set(base, "base2", APR_HASH_KEY_STRING, "value2");
apr_hash_set(base, "base3", APR_HASH_KEY_STRING, "value3");
apr_hash_set(base, "base4", APR_HASH_KEY_STRING, "value4");
apr_hash_set(base, "base5", APR_HASH_KEY_STRING, "value5");
apr_hash_set(overlay, "overlay1", APR_HASH_KEY_STRING, "value1");
apr_hash_set(overlay, "overlay2", APR_HASH_KEY_STRING, "value2");
apr_hash_set(overlay, "overlay3", APR_HASH_KEY_STRING, "value3");
apr_hash_set(overlay, "overlay4", APR_HASH_KEY_STRING, "value4");
apr_hash_set(overlay, "overlay5", APR_HASH_KEY_STRING, "value5");
result = apr_hash_overlay(p, overlay, base);
count = apr_hash_count(result);
ABTS_INT_EQUAL(tc, 10, count);
dump_hash(p, result, str);
/* I don't know why these are out of order, but they are. I would probably
* consider this a bug, but others should comment.
*/
ABTS_STR_EQUAL(tc, "Key base5 (5) Value value5\n"
"Key overlay1 (8) Value value1\n"
"Key overlay2 (8) Value value2\n"
"Key overlay3 (8) Value value3\n"
"Key overlay4 (8) Value value4\n"
"Key overlay5 (8) Value value5\n"
"Key base1 (5) Value value1\n"
"Key base2 (5) Value value2\n"
"Key base3 (5) Value value3\n"
"Key base4 (5) Value value4\n"
"#entries 10\n", str);
}
static void overlay_same(abts_case *tc, void *data)
{
apr_hash_t *base = NULL;
apr_hash_t *result = NULL;
int count;
char str[8196];
base = apr_hash_make(p);
ABTS_PTR_NOTNULL(tc, base);
apr_hash_set(base, "base1", APR_HASH_KEY_STRING, "value1");
apr_hash_set(base, "base2", APR_HASH_KEY_STRING, "value2");
apr_hash_set(base, "base3", APR_HASH_KEY_STRING, "value3");
apr_hash_set(base, "base4", APR_HASH_KEY_STRING, "value4");
apr_hash_set(base, "base5", APR_HASH_KEY_STRING, "value5");
result = apr_hash_overlay(p, base, base);
count = apr_hash_count(result);
ABTS_INT_EQUAL(tc, 5, count);
dump_hash(p, result, str);
/* I don't know why these are out of order, but they are. I would probably
* consider this a bug, but others should comment.
*/
ABTS_STR_EQUAL(tc, "Key base5 (5) Value value5\n"
"Key base1 (5) Value value1\n"
"Key base2 (5) Value value2\n"
"Key base3 (5) Value value3\n"
"Key base4 (5) Value value4\n"
"#entries 5\n", str);
}
abts_suite *testhash(abts_suite *suite)
{
suite = ADD_SUITE(suite)
abts_run_test(suite, hash_make, NULL);
abts_run_test(suite, hash_set, NULL);
abts_run_test(suite, hash_reset, NULL);
abts_run_test(suite, same_value, NULL);
abts_run_test(suite, same_value_custom, NULL);
abts_run_test(suite, key_space, NULL);
abts_run_test(suite, delete_key, NULL);
abts_run_test(suite, hash_count_0, NULL);
abts_run_test(suite, hash_count_1, NULL);
abts_run_test(suite, hash_count_5, NULL);
abts_run_test(suite, hash_traverse, NULL);
abts_run_test(suite, summation_test, NULL);
abts_run_test(suite, overlay_empty, NULL);
abts_run_test(suite, overlay_2unique, NULL);
abts_run_test(suite, overlay_same, NULL);
return suite;
}
| 001-log4cxx | trunk/src/apr/test/testhash.c | C | asf20 | 13,333 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "testutil.h"
#include "apr_thread_proc.h"
#include "apr_errno.h"
#include "apr_general.h"
#include "apr_lib.h"
#include "apr_strings.h"
#if APR_HAS_OTHER_CHILD
static char reasonstr[256];
static void ocmaint(int reason, void *data, int status)
{
switch (reason) {
case APR_OC_REASON_DEATH:
apr_cpystrn(reasonstr, "APR_OC_REASON_DEATH",
strlen("APR_OC_REASON_DEATH") + 1);
break;
case APR_OC_REASON_LOST:
apr_cpystrn(reasonstr, "APR_OC_REASON_LOST",
strlen("APR_OC_REASON_LOST") + 1);
break;
case APR_OC_REASON_UNWRITABLE:
apr_cpystrn(reasonstr, "APR_OC_REASON_UNWRITEABLE",
strlen("APR_OC_REASON_UNWRITEABLE") + 1);
break;
case APR_OC_REASON_RESTART:
apr_cpystrn(reasonstr, "APR_OC_REASON_RESTART",
strlen("APR_OC_REASON_RESTART") + 1);
break;
}
}
#ifndef SIGKILL
#define SIGKILL 1
#endif
/* It would be great if we could stress this stuff more, and make the test
* more granular.
*/
static void test_child_kill(abts_case *tc, void *data)
{
apr_file_t *std = NULL;
apr_proc_t newproc;
apr_procattr_t *procattr = NULL;
const char *args[3];
apr_status_t rv;
args[0] = apr_pstrdup(p, "occhild" EXTENSION);
args[1] = apr_pstrdup(p, "-X");
args[2] = NULL;
rv = apr_procattr_create(&procattr, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_procattr_io_set(procattr, APR_FULL_BLOCK, APR_NO_PIPE,
APR_NO_PIPE);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_proc_create(&newproc, "./occhild" EXTENSION, args, NULL, procattr, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_PTR_NOTNULL(tc, newproc.in);
ABTS_PTR_EQUAL(tc, NULL, newproc.out);
ABTS_PTR_EQUAL(tc, NULL, newproc.err);
std = newproc.in;
apr_proc_other_child_register(&newproc, ocmaint, NULL, std, p);
apr_sleep(apr_time_from_sec(1));
rv = apr_proc_kill(&newproc, SIGKILL);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
/* allow time for things to settle... */
apr_sleep(apr_time_from_sec(3));
apr_proc_other_child_refresh_all(APR_OC_REASON_RUNNING);
ABTS_STR_EQUAL(tc, "APR_OC_REASON_DEATH", reasonstr);
}
#else
static void oc_not_impl(abts_case *tc, void *data)
{
ABTS_NOT_IMPL(tc, "Other child logic not implemented on this platform");
}
#endif
abts_suite *testoc(abts_suite *suite)
{
suite = ADD_SUITE(suite)
#if !APR_HAS_OTHER_CHILD
abts_run_test(suite, oc_not_impl, NULL);
#else
abts_run_test(suite, test_child_kill, NULL);
#endif
return suite;
}
| 001-log4cxx | trunk/src/apr/test/testoc.c | C | asf20 | 3,466 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "apr_file_io.h"
#include "apr_file_info.h"
#include "apr_errno.h"
#include "apr_general.h"
#include "apr_lib.h"
#include "testutil.h"
static void test_mkdir(abts_case *tc, void *data)
{
apr_status_t rv;
apr_finfo_t finfo;
rv = apr_dir_make("data/testdir", APR_UREAD | APR_UWRITE | APR_UEXECUTE, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_stat(&finfo, "data/testdir", APR_FINFO_TYPE, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_INT_EQUAL(tc, APR_DIR, finfo.filetype);
}
static void test_mkdir_recurs(abts_case *tc, void *data)
{
apr_status_t rv;
apr_finfo_t finfo;
rv = apr_dir_make_recursive("data/one/two/three",
APR_UREAD | APR_UWRITE | APR_UEXECUTE, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_stat(&finfo, "data/one", APR_FINFO_TYPE, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_INT_EQUAL(tc, APR_DIR, finfo.filetype);
rv = apr_stat(&finfo, "data/one/two", APR_FINFO_TYPE, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_INT_EQUAL(tc, APR_DIR, finfo.filetype);
rv = apr_stat(&finfo, "data/one/two/three", APR_FINFO_TYPE, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_INT_EQUAL(tc, APR_DIR, finfo.filetype);
}
static void test_remove(abts_case *tc, void *data)
{
apr_status_t rv;
apr_finfo_t finfo;
rv = apr_dir_remove("data/testdir", p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_stat(&finfo, "data/testdir", APR_FINFO_TYPE, p);
ABTS_INT_EQUAL(tc, 1, APR_STATUS_IS_ENOENT(rv));
}
static void test_removeall_fail(abts_case *tc, void *data)
{
apr_status_t rv;
rv = apr_dir_remove("data/one", p);
ABTS_INT_EQUAL(tc, 1, APR_STATUS_IS_ENOTEMPTY(rv));
}
static void test_removeall(abts_case *tc, void *data)
{
apr_status_t rv;
rv = apr_dir_remove("data/one/two/three", p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_dir_remove("data/one/two", p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_dir_remove("data/one", p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
}
static void test_remove_notthere(abts_case *tc, void *data)
{
apr_status_t rv;
rv = apr_dir_remove("data/notthere", p);
ABTS_INT_EQUAL(tc, 1, APR_STATUS_IS_ENOENT(rv));
}
static void test_mkdir_twice(abts_case *tc, void *data)
{
apr_status_t rv;
rv = apr_dir_make("data/testdir", APR_UREAD | APR_UWRITE | APR_UEXECUTE, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_dir_make("data/testdir", APR_UREAD | APR_UWRITE | APR_UEXECUTE, p);
ABTS_INT_EQUAL(tc, 1, APR_STATUS_IS_EEXIST(rv));
rv = apr_dir_remove("data/testdir", p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
}
static void test_opendir(abts_case *tc, void *data)
{
apr_status_t rv;
apr_dir_t *dir;
rv = apr_dir_open(&dir, "data", p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
apr_dir_close(dir);
}
static void test_opendir_notthere(abts_case *tc, void *data)
{
apr_status_t rv;
apr_dir_t *dir;
rv = apr_dir_open(&dir, "notthere", p);
ABTS_INT_EQUAL(tc, 1, APR_STATUS_IS_ENOENT(rv));
}
static void test_closedir(abts_case *tc, void *data)
{
apr_status_t rv;
apr_dir_t *dir;
rv = apr_dir_open(&dir, "data", p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_dir_close(dir);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
}
static void test_rewind(abts_case *tc, void *data)
{
apr_dir_t *dir;
apr_finfo_t first, second;
APR_ASSERT_SUCCESS(tc, "apr_dir_open failed", apr_dir_open(&dir, "data", p));
APR_ASSERT_SUCCESS(tc, "apr_dir_read failed",
apr_dir_read(&first, APR_FINFO_DIRENT, dir));
APR_ASSERT_SUCCESS(tc, "apr_dir_rewind failed", apr_dir_rewind(dir));
APR_ASSERT_SUCCESS(tc, "second apr_dir_read failed",
apr_dir_read(&second, APR_FINFO_DIRENT, dir));
APR_ASSERT_SUCCESS(tc, "apr_dir_close failed", apr_dir_close(dir));
ABTS_STR_EQUAL(tc, first.name, second.name);
}
/* Test for a (fixed) bug in apr_dir_read(). This bug only happened
in threadless cases. */
static void test_uncleared_errno(abts_case *tc, void *data)
{
apr_file_t *thefile = NULL;
apr_finfo_t finfo;
apr_int32_t finfo_flags = APR_FINFO_TYPE | APR_FINFO_NAME;
apr_dir_t *this_dir;
apr_status_t rv;
rv = apr_dir_make("dir1", APR_OS_DEFAULT, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_dir_make("dir2", APR_OS_DEFAULT, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_file_open(&thefile, "dir1/file1",
APR_READ | APR_WRITE | APR_CREATE, APR_OS_DEFAULT, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_file_close(thefile);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
/* Try to remove dir1. This should fail because it's not empty.
However, on a platform with threads disabled (such as FreeBSD),
`errno' will be set as a result. */
rv = apr_dir_remove("dir1", p);
ABTS_INT_EQUAL(tc, 1, APR_STATUS_IS_ENOTEMPTY(rv));
/* Read `.' and `..' out of dir2. */
rv = apr_dir_open(&this_dir, "dir2", p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_dir_read(&finfo, finfo_flags, this_dir);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_dir_read(&finfo, finfo_flags, this_dir);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
/* Now, when we attempt to do a third read of empty dir2, and the
underlying system readdir() returns NULL, the old value of
errno shouldn't cause a false alarm. We should get an ENOENT
back from apr_dir_read, and *not* the old errno. */
rv = apr_dir_read(&finfo, finfo_flags, this_dir);
ABTS_INT_EQUAL(tc, 1, APR_STATUS_IS_ENOENT(rv));
rv = apr_dir_close(this_dir);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
/* Cleanup */
rv = apr_file_remove("dir1/file1", p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_dir_remove("dir1", p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_dir_remove("dir2", p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
}
static void test_rmkdir_nocwd(abts_case *tc, void *data)
{
char *cwd, *path;
apr_status_t rv;
APR_ASSERT_SUCCESS(tc, "make temp dir",
apr_dir_make("dir3", APR_OS_DEFAULT, p));
APR_ASSERT_SUCCESS(tc, "obtain cwd", apr_filepath_get(&cwd, 0, p));
APR_ASSERT_SUCCESS(tc, "determine path to temp dir",
apr_filepath_merge(&path, cwd, "dir3", 0, p));
APR_ASSERT_SUCCESS(tc, "change to temp dir", apr_filepath_set(path, p));
rv = apr_dir_remove(path, p);
/* Some platforms cannot remove a directory which is in use. */
if (rv == APR_SUCCESS) {
ABTS_ASSERT(tc, "fail to create dir",
apr_dir_make_recursive("foobar", APR_OS_DEFAULT,
p) != APR_SUCCESS);
}
APR_ASSERT_SUCCESS(tc, "restore cwd", apr_filepath_set(cwd, p));
if (rv) {
apr_dir_remove(path, p);
ABTS_NOT_IMPL(tc, "cannot remove in-use directory");
}
}
abts_suite *testdir(abts_suite *suite)
{
suite = ADD_SUITE(suite)
abts_run_test(suite, test_mkdir, NULL);
abts_run_test(suite, test_mkdir_recurs, NULL);
abts_run_test(suite, test_remove, NULL);
abts_run_test(suite, test_removeall_fail, NULL);
abts_run_test(suite, test_removeall, NULL);
abts_run_test(suite, test_remove_notthere, NULL);
abts_run_test(suite, test_mkdir_twice, NULL);
abts_run_test(suite, test_rmkdir_nocwd, NULL);
abts_run_test(suite, test_rewind, NULL);
abts_run_test(suite, test_opendir, NULL);
abts_run_test(suite, test_opendir_notthere, NULL);
abts_run_test(suite, test_closedir, NULL);
abts_run_test(suite, test_uncleared_errno, NULL);
return suite;
}
| 001-log4cxx | trunk/src/apr/test/testdir.c | C | asf20 | 8,640 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "apr_general.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include "testutil.h"
static void rand_exists(abts_case *tc, void *data)
{
#if !APR_HAS_RANDOM
ABTS_NOT_IMPL(tc, "apr_generate_random_bytes");
#else
unsigned char c[42];
/* There must be a better way to test random-ness, but I don't know
* what it is right now.
*/
APR_ASSERT_SUCCESS(tc, "apr_generate_random_bytes failed",
apr_generate_random_bytes(c, sizeof c));
#endif
}
abts_suite *testrand(abts_suite *suite)
{
suite = ADD_SUITE(suite)
abts_run_test(suite, rand_exists, NULL);
return suite;
}
| 001-log4cxx | trunk/src/apr/test/testrand.c | C | asf20 | 1,452 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "testutil.h"
#include "apr_file_io.h"
#include "apr_file_info.h"
#include "apr_errno.h"
#include "apr_pools.h"
static void copy_helper(abts_case *tc, const char *from, const char * to,
apr_fileperms_t perms, int append, apr_pool_t *p)
{
apr_status_t rv;
apr_status_t dest_rv;
apr_finfo_t copy;
apr_finfo_t orig;
apr_finfo_t dest;
dest_rv = apr_stat(&dest, to, APR_FINFO_SIZE, p);
if (!append) {
rv = apr_file_copy(from, to, perms, p);
}
else {
rv = apr_file_append(from, to, perms, p);
}
APR_ASSERT_SUCCESS(tc, "Error copying file", rv);
rv = apr_stat(&orig, from, APR_FINFO_SIZE, p);
APR_ASSERT_SUCCESS(tc, "Couldn't stat original file", rv);
rv = apr_stat(©, to, APR_FINFO_SIZE, p);
APR_ASSERT_SUCCESS(tc, "Couldn't stat copy file", rv);
if (!append) {
ABTS_ASSERT(tc, "File size differs", orig.size == copy.size);
}
else {
ABTS_ASSERT(tc, "File size differs",
((dest_rv == APR_SUCCESS)
? dest.size : 0) + orig.size == copy.size);
}
}
static void copy_short_file(abts_case *tc, void *data)
{
apr_status_t rv;
/* make absolutely sure that the dest file doesn't exist. */
apr_file_remove("data/file_copy.txt", p);
copy_helper(tc, "data/file_datafile.txt", "data/file_copy.txt",
APR_FILE_SOURCE_PERMS, 0, p);
rv = apr_file_remove("data/file_copy.txt", p);
APR_ASSERT_SUCCESS(tc, "Couldn't remove copy file", rv);
}
static void copy_over_existing(abts_case *tc, void *data)
{
apr_status_t rv;
/* make absolutely sure that the dest file doesn't exist. */
apr_file_remove("data/file_copy.txt", p);
/* This is a cheat. I don't want to create a new file, so I just copy
* one file, then I copy another. If the second copy succeeds, then
* this works.
*/
copy_helper(tc, "data/file_datafile.txt", "data/file_copy.txt",
APR_FILE_SOURCE_PERMS, 0, p);
copy_helper(tc, "data/mmap_datafile.txt", "data/file_copy.txt",
APR_FILE_SOURCE_PERMS, 0, p);
rv = apr_file_remove("data/file_copy.txt", p);
APR_ASSERT_SUCCESS(tc, "Couldn't remove copy file", rv);
}
static void append_nonexist(abts_case *tc, void *data)
{
apr_status_t rv;
/* make absolutely sure that the dest file doesn't exist. */
apr_file_remove("data/file_copy.txt", p);
copy_helper(tc, "data/file_datafile.txt", "data/file_copy.txt",
APR_FILE_SOURCE_PERMS, 0, p);
rv = apr_file_remove("data/file_copy.txt", p);
APR_ASSERT_SUCCESS(tc, "Couldn't remove copy file", rv);
}
static void append_exist(abts_case *tc, void *data)
{
apr_status_t rv;
/* make absolutely sure that the dest file doesn't exist. */
apr_file_remove("data/file_copy.txt", p);
/* This is a cheat. I don't want to create a new file, so I just copy
* one file, then I copy another. If the second copy succeeds, then
* this works.
*/
copy_helper(tc, "data/file_datafile.txt", "data/file_copy.txt",
APR_FILE_SOURCE_PERMS, 0, p);
copy_helper(tc, "data/mmap_datafile.txt", "data/file_copy.txt",
APR_FILE_SOURCE_PERMS, 1, p);
rv = apr_file_remove("data/file_copy.txt", p);
APR_ASSERT_SUCCESS(tc, "Couldn't remove copy file", rv);
}
abts_suite *testfilecopy(abts_suite *suite)
{
suite = ADD_SUITE(suite)
abts_run_test(suite, copy_short_file, NULL);
abts_run_test(suite, copy_over_existing, NULL);
abts_run_test(suite, append_nonexist, NULL);
abts_run_test(suite, append_exist, NULL);
return suite;
}
| 001-log4cxx | trunk/src/apr/test/testfilecopy.c | C | asf20 | 4,566 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "testutil.h"
#include "apr.h"
#include "apr_portable.h"
#include "apr_strings.h"
static void ssize_t_fmt(abts_case *tc, void *data)
{
char buf[100];
apr_ssize_t var = 0;
sprintf(buf, "%" APR_SSIZE_T_FMT, var);
ABTS_STR_EQUAL(tc, "0", buf);
apr_snprintf(buf, sizeof(buf), "%" APR_SSIZE_T_FMT, var);
ABTS_STR_EQUAL(tc, "0", buf);
}
static void size_t_fmt(abts_case *tc, void *data)
{
char buf[100];
apr_size_t var = 0;
sprintf(buf, "%" APR_SIZE_T_FMT, var);
ABTS_STR_EQUAL(tc, "0", buf);
apr_snprintf(buf, sizeof(buf), "%" APR_SIZE_T_FMT, var);
ABTS_STR_EQUAL(tc, "0", buf);
}
static void off_t_fmt(abts_case *tc, void *data)
{
char buf[100];
apr_off_t var = 0;
sprintf(buf, "%" APR_OFF_T_FMT, var);
ABTS_STR_EQUAL(tc, "0", buf);
apr_snprintf(buf, sizeof(buf), "%" APR_OFF_T_FMT, var);
ABTS_STR_EQUAL(tc, "0", buf);
}
static void pid_t_fmt(abts_case *tc, void *data)
{
char buf[100];
pid_t var = 0;
sprintf(buf, "%" APR_PID_T_FMT, var);
ABTS_STR_EQUAL(tc, "0", buf);
apr_snprintf(buf, sizeof(buf), "%" APR_PID_T_FMT, var);
ABTS_STR_EQUAL(tc, "0", buf);
}
static void int64_t_fmt(abts_case *tc, void *data)
{
char buf[100];
apr_int64_t var = 0;
sprintf(buf, "%" APR_INT64_T_FMT, var);
ABTS_STR_EQUAL(tc, "0", buf);
apr_snprintf(buf, sizeof(buf), "%" APR_INT64_T_FMT, var);
ABTS_STR_EQUAL(tc, "0", buf);
}
static void uint64_t_fmt(abts_case *tc, void *data)
{
char buf[100];
apr_uint64_t var = APR_UINT64_C(14000000);
sprintf(buf, "%" APR_UINT64_T_FMT, var);
ABTS_STR_EQUAL(tc, "14000000", buf);
apr_snprintf(buf, sizeof(buf), "%" APR_UINT64_T_FMT, var);
ABTS_STR_EQUAL(tc, "14000000", buf);
}
static void uint64_t_hex_fmt(abts_case *tc, void *data)
{
char buf[100];
apr_uint64_t var = APR_UINT64_C(14000000);
sprintf(buf, "%" APR_UINT64_T_HEX_FMT, var);
ABTS_STR_EQUAL(tc, "d59f80", buf);
apr_snprintf(buf, sizeof(buf), "%" APR_UINT64_T_HEX_FMT, var);
ABTS_STR_EQUAL(tc, "d59f80", buf);
}
static void more_int64_fmts(abts_case *tc, void *data)
{
char buf[100];
apr_int64_t i = APR_INT64_C(-42);
apr_int64_t ibig = APR_INT64_C(-314159265358979323);
apr_uint64_t ui = APR_UINT64_C(42);
apr_uint64_t big = APR_UINT64_C(3141592653589793238);
apr_snprintf(buf, sizeof buf, "%" APR_INT64_T_FMT, i);
ABTS_STR_EQUAL(tc, buf, "-42");
apr_snprintf(buf, sizeof buf, "%" APR_UINT64_T_FMT, ui);
ABTS_STR_EQUAL(tc, buf, "42");
apr_snprintf(buf, sizeof buf, "%" APR_UINT64_T_FMT, big);
ABTS_STR_EQUAL(tc, buf, "3141592653589793238");
apr_snprintf(buf, sizeof buf, "%" APR_INT64_T_FMT, ibig);
ABTS_STR_EQUAL(tc, buf, "-314159265358979323");
}
abts_suite *testfmt(abts_suite *suite)
{
suite = ADD_SUITE(suite)
abts_run_test(suite, ssize_t_fmt, NULL);
abts_run_test(suite, size_t_fmt, NULL);
abts_run_test(suite, off_t_fmt, NULL);
abts_run_test(suite, pid_t_fmt, NULL);
abts_run_test(suite, int64_t_fmt, NULL);
abts_run_test(suite, uint64_t_fmt, NULL);
abts_run_test(suite, uint64_t_hex_fmt, NULL);
abts_run_test(suite, more_int64_fmts, NULL);
return suite;
}
| 001-log4cxx | trunk/src/apr/test/testfmt.c | C | asf20 | 4,031 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "apr_general.h"
#include "apr_pools.h"
#include "apr_errno.h"
#include "apr_file_io.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#if APR_HAVE_UNISTD_H
#include <unistd.h>
#endif
#include "testutil.h"
#define ALLOC_BYTES 1024
static apr_pool_t *pmain = NULL;
static apr_pool_t *pchild = NULL;
static void alloc_bytes(abts_case *tc, void *data)
{
int i;
char *alloc;
alloc = apr_palloc(pmain, ALLOC_BYTES);
ABTS_PTR_NOTNULL(tc, alloc);
for (i=0;i<ALLOC_BYTES;i++) {
char *ptr = alloc + i;
*ptr = 0xa;
}
/* This is just added to get the positive. If this test fails, the
* suite will seg fault.
*/
ABTS_TRUE(tc, 1);
}
static void calloc_bytes(abts_case *tc, void *data)
{
int i;
char *alloc;
alloc = apr_pcalloc(pmain, ALLOC_BYTES);
ABTS_PTR_NOTNULL(tc, alloc);
for (i=0;i<ALLOC_BYTES;i++) {
char *ptr = alloc + i;
ABTS_TRUE(tc, *ptr == '\0');
}
}
static void parent_pool(abts_case *tc, void *data)
{
apr_status_t rv;
rv = apr_pool_create(&pmain, NULL);
ABTS_INT_EQUAL(tc, rv, APR_SUCCESS);
ABTS_PTR_NOTNULL(tc, pmain);
}
static void child_pool(abts_case *tc, void *data)
{
apr_status_t rv;
rv = apr_pool_create(&pchild, pmain);
ABTS_INT_EQUAL(tc, rv, APR_SUCCESS);
ABTS_PTR_NOTNULL(tc, pchild);
}
static void test_ancestor(abts_case *tc, void *data)
{
ABTS_INT_EQUAL(tc, 1, apr_pool_is_ancestor(pmain, pchild));
}
static void test_notancestor(abts_case *tc, void *data)
{
ABTS_INT_EQUAL(tc, 0, apr_pool_is_ancestor(pchild, pmain));
}
static apr_status_t success_cleanup(void *data)
{
return APR_SUCCESS;
}
static char *checker_data = "Hello, world.";
static apr_status_t checker_cleanup(void *data)
{
return data == checker_data ? APR_SUCCESS : APR_EGENERAL;
}
static void test_cleanups(abts_case *tc, void *data)
{
apr_status_t rv;
int n;
/* do this several times to test the cleanup freelist handling. */
for (n = 0; n < 5; n++) {
apr_pool_cleanup_register(pchild, NULL, success_cleanup,
success_cleanup);
apr_pool_cleanup_register(pchild, checker_data, checker_cleanup,
success_cleanup);
apr_pool_cleanup_register(pchild, NULL, checker_cleanup,
success_cleanup);
rv = apr_pool_cleanup_run(p, NULL, success_cleanup);
ABTS_ASSERT(tc, "nullop cleanup run OK", rv == APR_SUCCESS);
rv = apr_pool_cleanup_run(p, checker_data, checker_cleanup);
ABTS_ASSERT(tc, "cleanup passed correct data", rv == APR_SUCCESS);
rv = apr_pool_cleanup_run(p, NULL, checker_cleanup);
ABTS_ASSERT(tc, "cleanup passed correct data", rv == APR_EGENERAL);
if (n == 2) {
/* clear the pool to check that works */
apr_pool_clear(pchild);
}
if (n % 2 == 0) {
/* throw another random cleanup into the mix */
apr_pool_cleanup_register(pchild, NULL,
apr_pool_cleanup_null,
apr_pool_cleanup_null);
}
}
}
abts_suite *testpool(abts_suite *suite)
{
suite = ADD_SUITE(suite)
abts_run_test(suite, parent_pool, NULL);
abts_run_test(suite, child_pool, NULL);
abts_run_test(suite, test_ancestor, NULL);
abts_run_test(suite, test_notancestor, NULL);
abts_run_test(suite, alloc_bytes, NULL);
abts_run_test(suite, calloc_bytes, NULL);
abts_run_test(suite, test_cleanups, NULL);
return suite;
}
| 001-log4cxx | trunk/src/apr/test/testpools.c | C | asf20 | 4,441 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "testutil.h"
#include "apr_shm.h"
#include "apr_errno.h"
#include "apr_general.h"
#include "apr_lib.h"
#include "apr_strings.h"
#include "apr_thread_proc.h"
#include "apr_time.h"
#include "testshm.h"
#include "apr.h"
#if APR_HAVE_STDLIB_H
#include <stdlib.h>
#endif
#if APR_HAS_SHARED_MEMORY
static int msgwait(int sleep_sec, int first_box, int last_box)
{
int i;
int recvd = 0;
apr_time_t start = apr_time_now();
apr_interval_time_t sleep_duration = apr_time_from_sec(sleep_sec);
while (apr_time_now() - start < sleep_duration) {
for (i = first_box; i < last_box; i++) {
if (boxes[i].msgavail && !strcmp(boxes[i].msg, MSG)) {
recvd++;
boxes[i].msgavail = 0; /* reset back to 0 */
/* reset the msg field. 1024 is a magic number and it should
* be a macro, but I am being lazy.
*/
memset(boxes[i].msg, 0, 1024);
}
}
apr_sleep(apr_time_make(0, 10000)); /* 10ms */
}
return recvd;
}
static void msgput(int boxnum, char *msg)
{
apr_cpystrn(boxes[boxnum].msg, msg, strlen(msg) + 1);
boxes[boxnum].msgavail = 1;
}
static void test_anon_create(abts_case *tc, void *data)
{
apr_status_t rv;
apr_shm_t *shm = NULL;
rv = apr_shm_create(&shm, SHARED_SIZE, NULL, p);
APR_ASSERT_SUCCESS(tc, "Error allocating shared memory block", rv);
ABTS_PTR_NOTNULL(tc, shm);
rv = apr_shm_destroy(shm);
APR_ASSERT_SUCCESS(tc, "Error destroying shared memory block", rv);
}
static void test_check_size(abts_case *tc, void *data)
{
apr_status_t rv;
apr_shm_t *shm = NULL;
apr_size_t retsize;
rv = apr_shm_create(&shm, SHARED_SIZE, NULL, p);
APR_ASSERT_SUCCESS(tc, "Error allocating shared memory block", rv);
ABTS_PTR_NOTNULL(tc, shm);
retsize = apr_shm_size_get(shm);
ABTS_INT_EQUAL(tc, SHARED_SIZE, retsize);
rv = apr_shm_destroy(shm);
APR_ASSERT_SUCCESS(tc, "Error destroying shared memory block", rv);
}
static void test_shm_allocate(abts_case *tc, void *data)
{
apr_status_t rv;
apr_shm_t *shm = NULL;
rv = apr_shm_create(&shm, SHARED_SIZE, NULL, p);
APR_ASSERT_SUCCESS(tc, "Error allocating shared memory block", rv);
ABTS_PTR_NOTNULL(tc, shm);
boxes = apr_shm_baseaddr_get(shm);
ABTS_PTR_NOTNULL(tc, boxes);
rv = apr_shm_destroy(shm);
APR_ASSERT_SUCCESS(tc, "Error destroying shared memory block", rv);
}
#if APR_HAS_FORK
static void test_anon(abts_case *tc, void *data)
{
apr_proc_t proc;
apr_status_t rv;
apr_shm_t *shm;
apr_size_t retsize;
int cnt, i;
int recvd;
rv = apr_shm_create(&shm, SHARED_SIZE, NULL, p);
APR_ASSERT_SUCCESS(tc, "Error allocating shared memory block", rv);
ABTS_PTR_NOTNULL(tc, shm);
retsize = apr_shm_size_get(shm);
ABTS_INT_EQUAL(tc, SHARED_SIZE, retsize);
boxes = apr_shm_baseaddr_get(shm);
ABTS_PTR_NOTNULL(tc, boxes);
rv = apr_proc_fork(&proc, p);
if (rv == APR_INCHILD) { /* child */
int num = msgwait(5, 0, N_BOXES);
/* exit with the number of messages received so that the parent
* can check that all messages were received.
*/
exit(num);
}
else if (rv == APR_INPARENT) { /* parent */
i = N_BOXES;
cnt = 0;
while (cnt++ < N_MESSAGES) {
if ((i-=3) < 0) {
i += N_BOXES; /* start over at the top */
}
msgput(i, MSG);
apr_sleep(apr_time_make(0, 10000));
}
}
else {
ABTS_FAIL(tc, "apr_proc_fork failed");
}
/* wait for the child */
rv = apr_proc_wait(&proc, &recvd, NULL, APR_WAIT);
ABTS_INT_EQUAL(tc, N_MESSAGES, recvd);
rv = apr_shm_destroy(shm);
APR_ASSERT_SUCCESS(tc, "Error destroying shared memory block", rv);
}
#endif
static void test_named(abts_case *tc, void *data)
{
apr_status_t rv;
apr_shm_t *shm = NULL;
apr_size_t retsize;
apr_proc_t pidproducer, pidconsumer;
apr_procattr_t *attr1 = NULL, *attr2 = NULL;
int sent, received;
apr_exit_why_e why;
const char *args[4];
apr_shm_remove(SHARED_FILENAME, p);
rv = apr_shm_create(&shm, SHARED_SIZE, SHARED_FILENAME, p);
APR_ASSERT_SUCCESS(tc, "Error allocating shared memory block", rv);
if (rv != APR_SUCCESS) {
return;
}
ABTS_PTR_NOTNULL(tc, shm);
retsize = apr_shm_size_get(shm);
ABTS_INT_EQUAL(tc, SHARED_SIZE, retsize);
boxes = apr_shm_baseaddr_get(shm);
ABTS_PTR_NOTNULL(tc, boxes);
rv = apr_procattr_create(&attr1, p);
ABTS_PTR_NOTNULL(tc, attr1);
APR_ASSERT_SUCCESS(tc, "Couldn't create attr1", rv);
args[0] = apr_pstrdup(p, "testshmproducer" EXTENSION);
args[1] = NULL;
rv = apr_proc_create(&pidproducer, "./testshmproducer" EXTENSION, args,
NULL, attr1, p);
APR_ASSERT_SUCCESS(tc, "Couldn't launch producer", rv);
rv = apr_procattr_create(&attr2, p);
ABTS_PTR_NOTNULL(tc, attr2);
APR_ASSERT_SUCCESS(tc, "Couldn't create attr2", rv);
args[0] = apr_pstrdup(p, "testshmconsumer" EXTENSION);
rv = apr_proc_create(&pidconsumer, "./testshmconsumer" EXTENSION, args,
NULL, attr2, p);
APR_ASSERT_SUCCESS(tc, "Couldn't launch consumer", rv);
rv = apr_proc_wait(&pidconsumer, &received, &why, APR_WAIT);
ABTS_INT_EQUAL(tc, APR_CHILD_DONE, rv);
ABTS_INT_EQUAL(tc, APR_PROC_EXIT, why);
rv = apr_proc_wait(&pidproducer, &sent, &why, APR_WAIT);
ABTS_INT_EQUAL(tc, APR_CHILD_DONE, rv);
ABTS_INT_EQUAL(tc, APR_PROC_EXIT, why);
/* Cleanup before testing that producer and consumer worked correctly.
* This way, if they didn't succeed, we can just run this test again
* without having to cleanup manually.
*/
APR_ASSERT_SUCCESS(tc, "Error destroying shared memory",
apr_shm_destroy(shm));
ABTS_INT_EQUAL(tc, sent, received);
}
static void test_named_remove(abts_case *tc, void *data)
{
apr_status_t rv;
apr_shm_t *shm;
apr_shm_remove(SHARED_FILENAME, p);
rv = apr_shm_create(&shm, SHARED_SIZE, SHARED_FILENAME, p);
APR_ASSERT_SUCCESS(tc, "Error allocating shared memory block", rv);
if (rv != APR_SUCCESS) {
return;
}
ABTS_PTR_NOTNULL(tc, shm);
rv = apr_shm_remove(SHARED_FILENAME, p);
APR_ASSERT_SUCCESS(tc, "Error removing shared memory block", rv);
if (rv != APR_SUCCESS) {
return ;
}
rv = apr_shm_create(&shm, SHARED_SIZE, SHARED_FILENAME, p);
APR_ASSERT_SUCCESS(tc, "Error allocating shared memory block", rv);
if (rv != APR_SUCCESS) {
return;
}
ABTS_PTR_NOTNULL(tc, shm);
rv = apr_shm_destroy(shm);
APR_ASSERT_SUCCESS(tc, "Error destroying shared memory block", rv);
}
#endif
abts_suite *testshm(abts_suite *suite)
{
suite = ADD_SUITE(suite)
#if APR_HAS_SHARED_MEMORY
abts_run_test(suite, test_anon_create, NULL);
abts_run_test(suite, test_check_size, NULL);
abts_run_test(suite, test_shm_allocate, NULL);
#if APR_HAS_FORK
abts_run_test(suite, test_anon, NULL);
#endif
abts_run_test(suite, test_named, NULL);
abts_run_test(suite, test_named_remove, NULL);
#endif
return suite;
}
| 001-log4cxx | trunk/src/apr/test/testshm.c | C | asf20 | 8,125 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "apr_shm.h"
#include "apr_errno.h"
#include "apr_general.h"
#include "apr_lib.h"
#include "apr_strings.h"
#include "apr_time.h"
#include "testshm.h"
#include "apr.h"
#if APR_HAVE_STDLIB_H
#include <stdlib.h>
#endif
#if APR_HAS_SHARED_MEMORY
static int msgwait(int sleep_sec, int first_box, int last_box)
{
int i;
int recvd = 0;
apr_time_t start = apr_time_now();
apr_interval_time_t sleep_duration = apr_time_from_sec(sleep_sec);
while (apr_time_now() - start < sleep_duration) {
for (i = first_box; i < last_box; i++) {
if (boxes[i].msgavail && !strcmp(boxes[i].msg, MSG)) {
recvd++;
boxes[i].msgavail = 0; /* reset back to 0 */
memset(boxes[i].msg, 0, 1024);
}
}
apr_sleep(apr_time_from_sec(1));
}
return recvd;
}
int main(void)
{
apr_status_t rv;
apr_pool_t *pool;
apr_shm_t *shm;
int recvd;
apr_initialize();
if (apr_pool_create(&pool, NULL) != APR_SUCCESS) {
exit(-1);
}
rv = apr_shm_attach(&shm, SHARED_FILENAME, pool);
if (rv != APR_SUCCESS) {
exit(-2);
}
boxes = apr_shm_baseaddr_get(shm);
/* consume messages on all of the boxes */
recvd = msgwait(30, 0, N_BOXES); /* wait for 30 seconds for messages */
rv = apr_shm_detach(shm);
if (rv != APR_SUCCESS) {
exit(-3);
}
return recvd;
}
#else /* APR_HAS_SHARED_MEMORY */
int main(void)
{
/* Just return, this program will never be called, so we don't need
* to print a message
*/
return 0;
}
#endif /* APR_HAS_SHARED_MEMORY */
| 001-log4cxx | trunk/src/apr/test/testshmconsumer.c | C | asf20 | 2,446 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "testutil.h"
#include "apr_errno.h"
#include "apr_general.h"
#include "apr_user.h"
#if APR_HAS_USER
static void uid_current(abts_case *tc, void *data)
{
apr_uid_t uid;
apr_gid_t gid;
APR_ASSERT_SUCCESS(tc, "apr_uid_current failed",
apr_uid_current(&uid, &gid, p));
}
static void username(abts_case *tc, void *data)
{
apr_uid_t uid;
apr_gid_t gid;
apr_uid_t retreived_uid;
apr_gid_t retreived_gid;
char *uname = NULL;
APR_ASSERT_SUCCESS(tc, "apr_uid_current failed",
apr_uid_current(&uid, &gid, p));
APR_ASSERT_SUCCESS(tc, "apr_uid_name_get failed",
apr_uid_name_get(&uname, uid, p));
ABTS_PTR_NOTNULL(tc, uname);
APR_ASSERT_SUCCESS(tc, "apr_uid_get failed",
apr_uid_get(&retreived_uid, &retreived_gid, uname, p));
APR_ASSERT_SUCCESS(tc, "apr_uid_compare failed",
apr_uid_compare(uid, retreived_uid));
#ifdef WIN32
/* ### this fudge was added for Win32 but makes the test return NotImpl
* on Unix if run as root, when !gid is also true. */
if (!gid || !retreived_gid) {
/* The function had no way to recover the gid (this would have been
* an ENOTIMPL if apr_uid_ functions didn't try to double-up and
* also return apr_gid_t values, which was bogus.
*/
if (!gid) {
ABTS_NOT_IMPL(tc, "Groups from apr_uid_current");
}
else {
ABTS_NOT_IMPL(tc, "Groups from apr_uid_get");
}
}
else {
#endif
APR_ASSERT_SUCCESS(tc, "apr_gid_compare failed",
apr_gid_compare(gid, retreived_gid));
#ifdef WIN32
}
#endif
}
static void groupname(abts_case *tc, void *data)
{
apr_uid_t uid;
apr_gid_t gid;
apr_gid_t retreived_gid;
char *gname = NULL;
APR_ASSERT_SUCCESS(tc, "apr_uid_current failed",
apr_uid_current(&uid, &gid, p));
APR_ASSERT_SUCCESS(tc, "apr_gid_name_get failed",
apr_gid_name_get(&gname, gid, p));
ABTS_PTR_NOTNULL(tc, gname);
APR_ASSERT_SUCCESS(tc, "apr_gid_get failed",
apr_gid_get(&retreived_gid, gname, p));
APR_ASSERT_SUCCESS(tc, "apr_gid_compare failed",
apr_gid_compare(gid, retreived_gid));
}
#ifndef WIN32
static void fail_userinfo(abts_case *tc, void *data)
{
apr_uid_t uid;
apr_gid_t gid;
apr_status_t rv;
char *tmp;
errno = 0;
gid = uid = 9999999;
tmp = NULL;
rv = apr_uid_name_get(&tmp, uid, p);
ABTS_ASSERT(tc, "apr_uid_name_get should fail or "
"return a user name",
rv != APR_SUCCESS || tmp != NULL);
errno = 0;
tmp = NULL;
rv = apr_gid_name_get(&tmp, gid, p);
ABTS_ASSERT(tc, "apr_gid_name_get should fail or "
"return a group name",
rv != APR_SUCCESS || tmp != NULL);
gid = 424242;
errno = 0;
rv = apr_gid_get(&gid, "I_AM_NOT_A_GROUP", p);
ABTS_ASSERT(tc, "apr_gid_get should fail or "
"set a group number",
rv != APR_SUCCESS || gid == 424242);
gid = uid = 424242;
errno = 0;
rv = apr_uid_get(&uid, &gid, "I_AM_NOT_A_USER", p);
ABTS_ASSERT(tc, "apr_gid_get should fail or "
"set a user and group number",
rv != APR_SUCCESS || uid == 424242 || gid == 4242442);
errno = 0;
tmp = NULL;
rv = apr_uid_homepath_get(&tmp, "I_AM_NOT_A_USER", p);
ABTS_ASSERT(tc, "apr_uid_homepath_get should fail or "
"set a path name",
rv != APR_SUCCESS || tmp != NULL);
}
#else
static void fail_userinfo(abts_case *tc, void *data)
{
ABTS_NOT_IMPL(tc, "Users are not opaque integers on this platform");
}
#endif
#else
static void users_not_impl(abts_case *tc, void *data)
{
ABTS_NOT_IMPL(tc, "Users not implemented on this platform");
}
#endif
abts_suite *testuser(abts_suite *suite)
{
suite = ADD_SUITE(suite)
#if !APR_HAS_USER
abts_run_test(suite, users_not_impl, NULL);
#else
abts_run_test(suite, uid_current, NULL);
abts_run_test(suite, username, NULL);
abts_run_test(suite, groupname, NULL);
abts_run_test(suite, fail_userinfo, NULL);
#endif
return suite;
}
| 001-log4cxx | trunk/src/apr/test/testuser.c | C | asf20 | 5,137 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "apr_thread_proc.h"
#include "apr_file_io.h"
#include "apr_thread_mutex.h"
#include "apr_thread_rwlock.h"
#include "apr_thread_cond.h"
#include "apr_errno.h"
#include "apr_general.h"
#include "apr_getopt.h"
#include "testutil.h"
#if APR_HAS_THREADS
#define MAX_ITER 40000
#define MAX_COUNTER 100000
#define MAX_RETRY 5
static void *APR_THREAD_FUNC thread_rwlock_func(apr_thread_t *thd, void *data);
static void *APR_THREAD_FUNC thread_mutex_function(apr_thread_t *thd, void *data);
static void *APR_THREAD_FUNC thread_cond_producer(apr_thread_t *thd, void *data);
static void *APR_THREAD_FUNC thread_cond_consumer(apr_thread_t *thd, void *data);
static apr_thread_mutex_t *thread_mutex;
static apr_thread_rwlock_t *rwlock;
static int i = 0, x = 0;
static int buff[MAX_COUNTER];
struct {
apr_thread_mutex_t *mutex;
int nput;
int nval;
} put;
struct {
apr_thread_mutex_t *mutex;
apr_thread_cond_t *cond;
int nready;
} nready;
static apr_thread_mutex_t *timeout_mutex;
static apr_thread_cond_t *timeout_cond;
static void *APR_THREAD_FUNC thread_rwlock_func(apr_thread_t *thd, void *data)
{
int exitLoop = 1;
while (1)
{
apr_thread_rwlock_rdlock(rwlock);
if (i == MAX_ITER)
exitLoop = 0;
apr_thread_rwlock_unlock(rwlock);
if (!exitLoop)
break;
apr_thread_rwlock_wrlock(rwlock);
if (i != MAX_ITER)
{
i++;
x++;
}
apr_thread_rwlock_unlock(rwlock);
}
return NULL;
}
static void *APR_THREAD_FUNC thread_mutex_function(apr_thread_t *thd, void *data)
{
int exitLoop = 1;
/* slight delay to allow things to settle */
apr_sleep (1);
while (1)
{
apr_thread_mutex_lock(thread_mutex);
if (i == MAX_ITER)
exitLoop = 0;
else
{
i++;
x++;
}
apr_thread_mutex_unlock(thread_mutex);
if (!exitLoop)
break;
}
return NULL;
}
static void *APR_THREAD_FUNC thread_cond_producer(apr_thread_t *thd, void *data)
{
for (;;) {
apr_thread_mutex_lock(put.mutex);
if (put.nput >= MAX_COUNTER) {
apr_thread_mutex_unlock(put.mutex);
return NULL;
}
buff[put.nput] = put.nval;
put.nput++;
put.nval++;
apr_thread_mutex_unlock(put.mutex);
apr_thread_mutex_lock(nready.mutex);
if (nready.nready == 0)
apr_thread_cond_signal(nready.cond);
nready.nready++;
apr_thread_mutex_unlock(nready.mutex);
*((int *) data) += 1;
}
return NULL;
}
static void *APR_THREAD_FUNC thread_cond_consumer(apr_thread_t *thd, void *data)
{
int i;
for (i = 0; i < MAX_COUNTER; i++) {
apr_thread_mutex_lock(nready.mutex);
while (nready.nready == 0)
apr_thread_cond_wait(nready.cond, nready.mutex);
nready.nready--;
apr_thread_mutex_unlock(nready.mutex);
if (buff[i] != i)
printf("buff[%d] = %d\n", i, buff[i]);
}
return NULL;
}
static void test_thread_mutex(abts_case *tc, void *data)
{
apr_thread_t *t1, *t2, *t3, *t4;
apr_status_t s1, s2, s3, s4;
s1 = apr_thread_mutex_create(&thread_mutex, APR_THREAD_MUTEX_DEFAULT, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, s1);
ABTS_PTR_NOTNULL(tc, thread_mutex);
i = 0;
x = 0;
s1 = apr_thread_create(&t1, NULL, thread_mutex_function, NULL, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, s1);
s2 = apr_thread_create(&t2, NULL, thread_mutex_function, NULL, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, s2);
s3 = apr_thread_create(&t3, NULL, thread_mutex_function, NULL, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, s3);
s4 = apr_thread_create(&t4, NULL, thread_mutex_function, NULL, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, s4);
apr_thread_join(&s1, t1);
apr_thread_join(&s2, t2);
apr_thread_join(&s3, t3);
apr_thread_join(&s4, t4);
ABTS_INT_EQUAL(tc, MAX_ITER, x);
}
static void test_thread_rwlock(abts_case *tc, void *data)
{
apr_thread_t *t1, *t2, *t3, *t4;
apr_status_t s1, s2, s3, s4;
s1 = apr_thread_rwlock_create(&rwlock, p);
if (s1 == APR_ENOTIMPL) {
ABTS_NOT_IMPL(tc, "rwlocks not implemented");
return;
}
APR_ASSERT_SUCCESS(tc, "rwlock_create", s1);
ABTS_PTR_NOTNULL(tc, rwlock);
i = 0;
x = 0;
s1 = apr_thread_create(&t1, NULL, thread_rwlock_func, NULL, p);
APR_ASSERT_SUCCESS(tc, "create thread 1", s1);
s2 = apr_thread_create(&t2, NULL, thread_rwlock_func, NULL, p);
APR_ASSERT_SUCCESS(tc, "create thread 2", s2);
s3 = apr_thread_create(&t3, NULL, thread_rwlock_func, NULL, p);
APR_ASSERT_SUCCESS(tc, "create thread 3", s3);
s4 = apr_thread_create(&t4, NULL, thread_rwlock_func, NULL, p);
APR_ASSERT_SUCCESS(tc, "create thread 4", s4);
apr_thread_join(&s1, t1);
apr_thread_join(&s2, t2);
apr_thread_join(&s3, t3);
apr_thread_join(&s4, t4);
ABTS_INT_EQUAL(tc, MAX_ITER, x);
apr_thread_rwlock_destroy(rwlock);
}
static void test_cond(abts_case *tc, void *data)
{
apr_thread_t *p1, *p2, *p3, *p4, *c1;
apr_status_t s0, s1, s2, s3, s4;
int count1, count2, count3, count4;
int sum;
APR_ASSERT_SUCCESS(tc, "create put mutex",
apr_thread_mutex_create(&put.mutex,
APR_THREAD_MUTEX_DEFAULT, p));
ABTS_PTR_NOTNULL(tc, put.mutex);
APR_ASSERT_SUCCESS(tc, "create nready mutex",
apr_thread_mutex_create(&nready.mutex,
APR_THREAD_MUTEX_DEFAULT, p));
ABTS_PTR_NOTNULL(tc, nready.mutex);
APR_ASSERT_SUCCESS(tc, "create condvar",
apr_thread_cond_create(&nready.cond, p));
ABTS_PTR_NOTNULL(tc, nready.cond);
count1 = count2 = count3 = count4 = 0;
put.nput = put.nval = 0;
nready.nready = 0;
i = 0;
x = 0;
s0 = apr_thread_create(&p1, NULL, thread_cond_producer, &count1, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, s0);
s1 = apr_thread_create(&p2, NULL, thread_cond_producer, &count2, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, s1);
s2 = apr_thread_create(&p3, NULL, thread_cond_producer, &count3, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, s2);
s3 = apr_thread_create(&p4, NULL, thread_cond_producer, &count4, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, s3);
s4 = apr_thread_create(&c1, NULL, thread_cond_consumer, NULL, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, s4);
apr_thread_join(&s0, p1);
apr_thread_join(&s1, p2);
apr_thread_join(&s2, p3);
apr_thread_join(&s3, p4);
apr_thread_join(&s4, c1);
APR_ASSERT_SUCCESS(tc, "destroy condvar",
apr_thread_cond_destroy(nready.cond));
sum = count1 + count2 + count3 + count4;
/*
printf("count1 = %d count2 = %d count3 = %d count4 = %d\n",
count1, count2, count3, count4);
*/
ABTS_INT_EQUAL(tc, MAX_COUNTER, sum);
}
static void test_timeoutcond(abts_case *tc, void *data)
{
apr_status_t s;
apr_interval_time_t timeout;
apr_time_t begin, end;
int i;
s = apr_thread_mutex_create(&timeout_mutex, APR_THREAD_MUTEX_DEFAULT, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, s);
ABTS_PTR_NOTNULL(tc, timeout_mutex);
s = apr_thread_cond_create(&timeout_cond, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, s);
ABTS_PTR_NOTNULL(tc, timeout_cond);
timeout = apr_time_from_sec(5);
for (i = 0; i < MAX_RETRY; i++) {
apr_thread_mutex_lock(timeout_mutex);
begin = apr_time_now();
s = apr_thread_cond_timedwait(timeout_cond, timeout_mutex, timeout);
end = apr_time_now();
apr_thread_mutex_unlock(timeout_mutex);
if (s != APR_SUCCESS && !APR_STATUS_IS_TIMEUP(s)) {
continue;
}
ABTS_INT_EQUAL(tc, 1, APR_STATUS_IS_TIMEUP(s));
ABTS_ASSERT(tc, "Timer returned too late", end - begin - timeout < 100000);
break;
}
ABTS_ASSERT(tc, "Too many retries", i < MAX_RETRY);
APR_ASSERT_SUCCESS(tc, "Unable to destroy the conditional",
apr_thread_cond_destroy(timeout_cond));
}
#endif /* !APR_HAS_THREADS */
#if !APR_HAS_THREADS
static void threads_not_impl(abts_case *tc, void *data)
{
ABTS_NOT_IMPL(tc, "Threads not implemented on this platform");
}
#endif
abts_suite *testlock(abts_suite *suite)
{
suite = ADD_SUITE(suite)
#if !APR_HAS_THREADS
abts_run_test(suite, threads_not_impl, NULL);
#else
abts_run_test(suite, test_thread_mutex, NULL);
abts_run_test(suite, test_thread_rwlock, NULL);
abts_run_test(suite, test_cond, NULL);
abts_run_test(suite, test_timeoutcond, NULL);
#endif
return suite;
}
| 001-log4cxx | trunk/src/apr/test/testlock.c | C | asf20 | 9,670 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <stdlib.h>
#include "apr_file_io.h"
int main(int argc, char *argv[])
{
apr_file_t *in, *out;
apr_size_t nbytes, total_bytes;
apr_pool_t *p;
char buf[128];
apr_status_t rv;
apr_initialize();
atexit(apr_terminate);
apr_pool_create(&p, NULL);
apr_file_open_stdin(&in, p);
apr_file_open_stdout(&out, p);
total_bytes = 0;
nbytes = sizeof(buf);
while ((rv = apr_file_read(in, buf, &nbytes)) == APR_SUCCESS) {
total_bytes += nbytes;
nbytes = sizeof(buf);
}
apr_file_printf(out, "%" APR_SIZE_T_FMT " bytes were read\n",
total_bytes);
return 0;
}
| 001-log4cxx | trunk/src/apr/test/readchild.c | C | asf20 | 1,457 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <stdlib.h>
#include "testsock.h"
#include "apr_network_io.h"
#include "apr_pools.h"
int main(int argc, char *argv[])
{
apr_pool_t *p;
apr_socket_t *sock;
apr_status_t rv;
apr_sockaddr_t *remote_sa;
apr_initialize();
atexit(apr_terminate);
apr_pool_create(&p, NULL);
if (argc < 2) {
exit(-1);
}
rv = apr_sockaddr_info_get(&remote_sa, "127.0.0.1", APR_UNSPEC, 8021, 0, p);
if (rv != APR_SUCCESS) {
exit(-1);
}
if (apr_socket_create(&sock, remote_sa->family, SOCK_STREAM, 0,
p) != APR_SUCCESS) {
exit(-1);
}
rv = apr_socket_timeout_set(sock, apr_time_from_sec(3));
if (rv) {
exit(-1);
}
apr_socket_connect(sock, remote_sa);
if (!strcmp("read", argv[1])) {
char datarecv[STRLEN];
apr_size_t length = STRLEN;
apr_status_t rv;
memset(datarecv, 0, STRLEN);
rv = apr_socket_recv(sock, datarecv, &length);
apr_socket_close(sock);
if (APR_STATUS_IS_TIMEUP(rv)) {
exit(SOCKET_TIMEOUT);
}
if (strcmp(datarecv, DATASTR)) {
exit(-1);
}
exit(length);
}
else if (!strcmp("write", argv[1])) {
apr_size_t length = strlen(DATASTR);
apr_socket_send(sock, DATASTR, &length);
apr_socket_close(sock);
exit(length);
}
exit(-1);
}
| 001-log4cxx | trunk/src/apr/test/sockchild.c | C | asf20 | 2,228 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "apr_strings.h"
#include "apr_pools.h"
#include "apr_general.h"
#include "apr_hash.h"
#include "apr_lib.h"
#include "apr_time.h"
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char** argv) {
apr_pool_t *context;
regex_t regex;
int rc;
int i;
int iters;
apr_time_t now;
apr_time_t end;
apr_hash_t *h;
if (argc !=4 ) {
fprintf(stderr, "Usage %s match string #iterations\n",argv[0]);
return -1;
}
iters = atoi( argv[3]);
apr_initialize() ;
atexit(apr_terminate);
if (apr_pool_create(&context, NULL) != APR_SUCCESS) {
fprintf(stderr, "Something went wrong\n");
exit(-1);
}
rc = regcomp( ®ex, argv[1], REG_EXTENDED|REG_NOSUB);
if (rc) {
char errbuf[2000];
regerror(rc, ®ex,errbuf,2000);
fprintf(stderr,"Couldn't compile regex ;(\n%s\n ",errbuf);
return -1;
}
if ( regexec( ®ex, argv[2], 0, NULL,0) == 0 ) {
fprintf(stderr,"Match\n");
}
else {
fprintf(stderr,"No Match\n");
}
now = apr_time_now();
for (i=0;i<iters;i++) {
regexec( ®ex, argv[2], 0, NULL,0) ;
}
end=apr_time_now();
puts(apr_psprintf( context, "Time to run %d regex's %8lld\n",iters,end-now));
h = apr_hash_make( context);
for (i=0;i<70;i++) {
apr_hash_set(h,apr_psprintf(context, "%dkey",i),APR_HASH_KEY_STRING,"1");
}
now = apr_time_now();
for (i=0;i<iters;i++) {
apr_hash_get( h, argv[2], APR_HASH_KEY_STRING);
}
end=apr_time_now();
puts(apr_psprintf( context, "Time to run %d hash (no find)'s %8lld\n",iters,end-now));
apr_hash_set(h, argv[2],APR_HASH_KEY_STRING,"1");
now = apr_time_now();
for (i=0;i<iters;i++) {
apr_hash_get( h, argv[2], APR_HASH_KEY_STRING);
}
end=apr_time_now();
puts(apr_psprintf( context, "Time to run %d hash (find)'s %8lld\n",iters,end-now));
return 0;
}
| 001-log4cxx | trunk/src/apr/test/internal/testregex.c | C | asf20 | 2,816 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "apr.h"
#include "arch/win32/apr_arch_utf8.h"
#include <wchar.h>
#include <string.h>
struct testval {
unsigned char n[8];
wchar_t w[4];
int nl;
int wl;
};
void displaynw(struct testval *f, struct testval *l)
{
char x[80], *t = x;
int i;
for (i = 0; i < f->nl; ++i)
t += sprintf(t, "%02X ", f->n[i]);
*(t++) = '-';
for (i = 0; i < l->nl; ++i)
t += sprintf(t, " %02X", l->n[i]);
*(t++) = ' ';
*(t++) = '=';
*(t++) = ' ';
for (i = 0; i < f->wl; ++i)
t += sprintf(t, "%04X ", f->w[i]);
*(t++) = '-';
for (i = 0; i < l->wl; ++i)
t += sprintf(t, " %04X", l->w[i]);
puts(x);
}
/*
* Test every possible byte value.
* If the test passes or fails at this byte value we are done.
* Otherwise iterate test_nrange again, appending another byte.
*/
void test_nrange(struct testval *p)
{
struct testval f, l, s;
apr_status_t rc;
int success = 0;
memcpy (&s, p, sizeof(s));
++s.nl;
do {
apr_size_t nl = s.nl, wl = sizeof(s.w) / 2;
rc = apr_conv_utf8_to_ucs2(s.n, &nl, s.w, &wl);
s.wl = (sizeof(s.w) / 2) - wl;
if (!nl && rc == APR_SUCCESS) {
if (!success) {
memcpy(&f, &s, sizeof(s));
success = -1;
}
else {
if (s.wl != l.wl
|| memcmp(s.w, l.w, (s.wl - 1) * 2) != 0
|| s.w[s.wl - 1] != l.w[l.wl - 1] + 1) {
displaynw(&f, &l);
memcpy(&f, &s, sizeof(s));
}
}
memcpy(&l, &s, sizeof(s));
}
else {
if (success) {
displaynw(&f, &l);
success = 0;
}
if (rc == APR_INCOMPLETE) {
test_nrange(&s);
}
}
} while (++s.n[s.nl - 1]);
if (success) {
displaynw(&f, &l);
success = 0;
}
}
/*
* Test every possible word value.
* Once we are finished, retest every possible word value.
* if the test fails on the following null word, iterate test_nrange
* again, appending another word.
* This assures the output order of the two tests are in sync.
*/
void test_wrange(struct testval *p)
{
struct testval f, l, s;
apr_status_t rc;
int success = 0;
memcpy (&s, p, sizeof(s));
++s.wl;
do {
apr_size_t nl = sizeof(s.n), wl = s.wl;
rc = apr_conv_ucs2_to_utf8(s.w, &wl, s.n, &nl);
s.nl = sizeof(s.n) - nl;
if (!wl && rc == APR_SUCCESS) {
if (!success) {
memcpy(&f, &s, sizeof(s));
success = -1;
}
else {
if (s.nl != l.nl
|| memcmp(s.n, l.n, s.nl - 1) != 0
|| s.n[s.nl - 1] != l.n[l.nl - 1] + 1) {
displaynw(&f, &l);
memcpy(&f, &s, sizeof(s));
}
}
memcpy(&l, &s, sizeof(s));
}
else {
if (success) {
displaynw(&f, &l);
success = 0;
}
}
} while (++s.w[s.wl - 1]);
if (success) {
displaynw(&f, &l);
success = 0;
}
do {
int wl = s.wl, nl = sizeof(s.n);
rc = apr_conv_ucs2_to_utf8(s.w, &wl, s.n, &nl);
s.nl = sizeof(s.n) - s.nl;
if (rc == APR_INCOMPLETE) {
test_wrange(&s);
}
} while (++s.w[s.wl - 1]);
}
/*
* Syntax: testucs [w|n]
*
* If arg is not recognized, run both tests.
*/
int main(int argc, char **argv)
{
struct testval s;
memset (&s, 0, sizeof(s));
if (argc < 2 || apr_tolower(*argv[1]) != 'w') {
printf ("\n\nTesting Narrow Char Ranges\n");
test_nrange(&s);
}
if (argc < 2 || apr_tolower(*argv[1]) != 'n') {
printf ("\n\nTesting Wide Char Ranges\n");
test_wrange(&s);
}
return 0;
}
| 001-log4cxx | trunk/src/apr/test/internal/testucs.c | C | asf20 | 4,834 |
srcdir = @srcdir@
VPATH = @srcdir@
NONPORTABLE = \
testregex@EXEEXT@
PROGRAMS = \
TARGETS = $(PROGRAMS) $(NONPORTABLE)
# bring in rules.mk for standard functionality
@INCLUDE_RULES@
LOCAL_LIBS=../../lib@APR_LIBNAME@.la
CLEAN_TARGETS = testregex@EXEEXT@
INCDIR=../../include
INCLUDES=-I$(INCDIR)
CFLAGS=$(MY_CFLAGS)
all: $(PROGRAMS) $(NONPORTABLE)
check: $(PROGRAMS) $(NONPORTABLE)
for prog in $(PROGRAMS) $(NONPORTABLE); do \
./$$prog; \
if test $$i = 255; then \
echo "$$prog failed"; \
break; \
fi \
done
testregex@EXEEXT@: testregex.lo $(LOCAL_LIBS)
$(LINK) testregex.lo $(LOCAL_LIBS) $(ALL_LIBS)
# DO NOT REMOVE
| 001-log4cxx | trunk/src/apr/test/internal/Makefile.in | Makefile | asf20 | 644 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "apr_thread_proc.h"
#include "apr_errno.h"
#include "apr_general.h"
#include "errno.h"
#include "apr_time.h"
#include "testutil.h"
#if APR_HAS_THREADS
static apr_thread_mutex_t *thread_lock;
static apr_thread_once_t *control = NULL;
static int x = 0;
static int value = 0;
static apr_thread_t *t1;
static apr_thread_t *t2;
static apr_thread_t *t3;
static apr_thread_t *t4;
/* just some made up number to check on later */
static apr_status_t exit_ret_val = 123;
static void init_func(void)
{
value++;
}
static void * APR_THREAD_FUNC thread_func1(apr_thread_t *thd, void *data)
{
int i;
apr_thread_once(control, init_func);
for (i = 0; i < 10000; i++) {
apr_thread_mutex_lock(thread_lock);
x++;
apr_thread_mutex_unlock(thread_lock);
}
apr_thread_exit(thd, exit_ret_val);
return NULL;
}
static void thread_init(abts_case *tc, void *data)
{
apr_status_t rv;
rv = apr_thread_once_init(&control, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_thread_mutex_create(&thread_lock, APR_THREAD_MUTEX_DEFAULT, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
}
static void create_threads(abts_case *tc, void *data)
{
apr_status_t rv;
rv = apr_thread_create(&t1, NULL, thread_func1, NULL, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_thread_create(&t2, NULL, thread_func1, NULL, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_thread_create(&t3, NULL, thread_func1, NULL, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_thread_create(&t4, NULL, thread_func1, NULL, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
}
static void join_threads(abts_case *tc, void *data)
{
apr_status_t s;
apr_thread_join(&s, t1);
ABTS_INT_EQUAL(tc, exit_ret_val, s);
apr_thread_join(&s, t2);
ABTS_INT_EQUAL(tc, exit_ret_val, s);
apr_thread_join(&s, t3);
ABTS_INT_EQUAL(tc, exit_ret_val, s);
apr_thread_join(&s, t4);
ABTS_INT_EQUAL(tc, exit_ret_val, s);
}
static void check_locks(abts_case *tc, void *data)
{
ABTS_INT_EQUAL(tc, 40000, x);
}
static void check_thread_once(abts_case *tc, void *data)
{
ABTS_INT_EQUAL(tc, 1, value);
}
#else
static void threads_not_impl(abts_case *tc, void *data)
{
ABTS_NOT_IMPL(tc, "Threads not implemented on this platform");
}
#endif
abts_suite *testthread(abts_suite *suite)
{
suite = ADD_SUITE(suite)
#if !APR_HAS_THREADS
abts_run_test(suite, threads_not_impl, NULL);
#else
abts_run_test(suite, thread_init, NULL);
abts_run_test(suite, create_threads, NULL);
abts_run_test(suite, join_threads, NULL);
abts_run_test(suite, check_locks, NULL);
abts_run_test(suite, check_thread_once, NULL);
#endif
return suite;
}
| 001-log4cxx | trunk/src/apr/test/testthread.c | C | asf20 | 3,534 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "apr_network_io.h"
#include "apr_errno.h"
#include "apr_general.h"
#include "apr_lib.h"
#include "testutil.h"
static apr_socket_t *sock = NULL;
static void create_socket(abts_case *tc, void *data)
{
apr_status_t rv;
rv = apr_socket_create(&sock, APR_INET, SOCK_STREAM, 0, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_PTR_NOTNULL(tc, sock);
}
static void set_keepalive(abts_case *tc, void *data)
{
apr_status_t rv;
apr_int32_t ck;
rv = apr_socket_opt_set(sock, APR_SO_KEEPALIVE, 1);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_socket_opt_get(sock, APR_SO_KEEPALIVE, &ck);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_INT_EQUAL(tc, 1, ck);
}
static void set_debug(abts_case *tc, void *data)
{
apr_status_t rv1, rv2;
apr_int32_t ck;
/* On some platforms APR_SO_DEBUG can only be set as root; just test
* for get/set consistency of this option. */
rv1 = apr_socket_opt_set(sock, APR_SO_DEBUG, 1);
rv2 = apr_socket_opt_get(sock, APR_SO_DEBUG, &ck);
APR_ASSERT_SUCCESS(tc, "get SO_DEBUG option", rv2);
if (rv1 == APR_SUCCESS) {
ABTS_INT_EQUAL(tc, 1, ck);
} else {
ABTS_INT_EQUAL(tc, 0, ck);
}
}
static void remove_keepalive(abts_case *tc, void *data)
{
apr_status_t rv;
apr_int32_t ck;
rv = apr_socket_opt_get(sock, APR_SO_KEEPALIVE, &ck);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_INT_EQUAL(tc, 1, ck);
rv = apr_socket_opt_set(sock, APR_SO_KEEPALIVE, 0);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_socket_opt_get(sock, APR_SO_KEEPALIVE, &ck);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_INT_EQUAL(tc, 0, ck);
}
static void corkable(abts_case *tc, void *data)
{
#if !APR_HAVE_CORKABLE_TCP
ABTS_NOT_IMPL(tc, "TCP isn't corkable");
#else
apr_status_t rv;
apr_int32_t ck;
rv = apr_socket_opt_set(sock, APR_TCP_NODELAY, 1);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_socket_opt_get(sock, APR_TCP_NODELAY, &ck);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_INT_EQUAL(tc, 1, ck);
rv = apr_socket_opt_set(sock, APR_TCP_NOPUSH, 1);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_socket_opt_get(sock, APR_TCP_NOPUSH, &ck);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_INT_EQUAL(tc, 1, ck);
rv = apr_socket_opt_get(sock, APR_TCP_NODELAY, &ck);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
/* TCP_NODELAY is now in an unknown state; it may be zero if
* TCP_NOPUSH and TCP_NODELAY are mutually exclusive on this
* platform, e.g. Linux < 2.6. */
rv = apr_socket_opt_set(sock, APR_TCP_NOPUSH, 0);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_socket_opt_get(sock, APR_TCP_NODELAY, &ck);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_INT_EQUAL(tc, 1, ck);
#endif
}
static void close_socket(abts_case *tc, void *data)
{
apr_status_t rv;
rv = apr_socket_close(sock);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
}
abts_suite *testsockopt(abts_suite *suite)
{
suite = ADD_SUITE(suite)
abts_run_test(suite, create_socket, NULL);
abts_run_test(suite, set_keepalive, NULL);
abts_run_test(suite, set_debug, NULL);
abts_run_test(suite, remove_keepalive, NULL);
abts_run_test(suite, corkable, NULL);
abts_run_test(suite, close_socket, NULL);
return suite;
}
| 001-log4cxx | trunk/src/apr/test/testsockopt.c | C | asf20 | 4,127 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "apr_thread_proc.h"
#include "apr_errno.h"
#include "apr_general.h"
#include "apr_lib.h"
#include "apr_strings.h"
#include "testutil.h"
#define TESTSTR "This is a test"
static apr_proc_t newproc;
static void test_create_proc(abts_case *tc, void *data)
{
const char *args[2];
apr_procattr_t *attr;
apr_file_t *testfile = NULL;
apr_status_t rv;
apr_size_t length;
char *buf;
rv = apr_procattr_create(&attr, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_procattr_io_set(attr, APR_FULL_BLOCK, APR_FULL_BLOCK,
APR_NO_PIPE);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_procattr_dir_set(attr, "data");
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_procattr_cmdtype_set(attr, APR_PROGRAM);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
args[0] = "proc_child" EXTENSION;
args[1] = NULL;
rv = apr_proc_create(&newproc, "../proc_child" EXTENSION, args, NULL,
attr, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
testfile = newproc.in;
length = strlen(TESTSTR);
rv = apr_file_write(testfile, TESTSTR, &length);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_INT_EQUAL(tc, strlen(TESTSTR), length);
testfile = newproc.out;
length = 256;
buf = apr_pcalloc(p, length);
rv = apr_file_read(testfile, buf, &length);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_STR_EQUAL(tc, TESTSTR, buf);
}
static void test_proc_wait(abts_case *tc, void *data)
{
apr_status_t rv;
rv = apr_proc_wait(&newproc, NULL, NULL, APR_WAIT);
ABTS_INT_EQUAL(tc, APR_CHILD_DONE, rv);
}
static void test_file_redir(abts_case *tc, void *data)
{
apr_file_t *testout = NULL;
apr_file_t *testerr = NULL;
apr_off_t offset;
apr_status_t rv;
const char *args[2];
apr_procattr_t *attr;
apr_file_t *testfile = NULL;
apr_size_t length;
char *buf;
testfile = NULL;
rv = apr_file_open(&testfile, "data/stdin",
APR_READ | APR_WRITE | APR_CREATE | APR_EXCL,
APR_OS_DEFAULT, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_file_open(&testout, "data/stdout",
APR_READ | APR_WRITE | APR_CREATE | APR_EXCL,
APR_OS_DEFAULT, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_file_open(&testerr, "data/stderr",
APR_READ | APR_WRITE | APR_CREATE | APR_EXCL,
APR_OS_DEFAULT, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
length = strlen(TESTSTR);
apr_file_write(testfile, TESTSTR, &length);
offset = 0;
rv = apr_file_seek(testfile, APR_SET, &offset);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_ASSERT(tc, "File position mismatch, expected 0", offset == 0);
rv = apr_procattr_create(&attr, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_procattr_child_in_set(attr, testfile, NULL);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_procattr_child_out_set(attr, testout, NULL);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_procattr_child_err_set(attr, testerr, NULL);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_procattr_dir_set(attr, "data");
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_procattr_cmdtype_set(attr, APR_PROGRAM);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
args[0] = "proc_child";
args[1] = NULL;
rv = apr_proc_create(&newproc, "../proc_child" EXTENSION, args, NULL,
attr, p);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_proc_wait(&newproc, NULL, NULL, APR_WAIT);
ABTS_INT_EQUAL(tc, APR_CHILD_DONE, rv);
offset = 0;
rv = apr_file_seek(testout, APR_SET, &offset);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
length = 256;
buf = apr_pcalloc(p, length);
rv = apr_file_read(testout, buf, &length);
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
ABTS_STR_EQUAL(tc, TESTSTR, buf);
apr_file_close(testfile);
apr_file_close(testout);
apr_file_close(testerr);
rv = apr_file_remove("data/stdin", p);;
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_file_remove("data/stdout", p);;
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
rv = apr_file_remove("data/stderr", p);;
ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
}
abts_suite *testproc(abts_suite *suite)
{
suite = ADD_SUITE(suite)
abts_run_test(suite, test_create_proc, NULL);
abts_run_test(suite, test_proc_wait, NULL);
abts_run_test(suite, test_file_redir, NULL);
return suite;
}
| 001-log4cxx | trunk/src/apr/test/testproc.c | C | asf20 | 5,349 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "apr_strings.h"
void print_hello(char str[256]);
int count_reps(int reps);
void print_hello(char str[256])
{
apr_cpystrn(str, "Hello - I'm a DSO!\n", strlen("Hello - I'm a DSO!\n") + 1);
}
int count_reps(int reps)
{
int i = 0;
for (i = 0;i < reps; i++);
return i;
}
| 001-log4cxx | trunk/src/apr/test/mod_test.c | C | asf20 | 1,094 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "apr_shm.h"
#include "apr_errno.h"
#include "apr_general.h"
#include "apr_lib.h"
#include "apr_strings.h"
#include "apr_time.h"
#include "testshm.h"
#include "apr.h"
#if APR_HAVE_STDLIB_H
#include <stdlib.h>
#endif
#if APR_HAS_SHARED_MEMORY
static void msgput(int boxnum, char *msg)
{
apr_cpystrn(boxes[boxnum].msg, msg, strlen(msg) + 1);
boxes[boxnum].msgavail = 1;
}
int main(void)
{
apr_status_t rv;
apr_pool_t *pool;
apr_shm_t *shm;
int i;
int sent = 0;
apr_initialize();
if (apr_pool_create(&pool, NULL) != APR_SUCCESS) {
exit(-1);
}
rv = apr_shm_attach(&shm, SHARED_FILENAME, pool);
if (rv != APR_SUCCESS) {
exit(-2);
}
boxes = apr_shm_baseaddr_get(shm);
/* produce messages on all of the boxes, in descending order,
* Yes, we could just return N_BOXES, but I want to have a double-check
* in this code. The original code actually sent N_BOXES - 1 messages,
* so rather than rely on possibly buggy code, this way we know that we
* are returning the right number.
*/
for (i = N_BOXES - 1, sent = 0; i >= 0; i--, sent++) {
msgput(i, MSG);
apr_sleep(apr_time_from_sec(1));
}
rv = apr_shm_detach(shm);
if (rv != APR_SUCCESS) {
exit(-3);
}
return sent;
}
#else /* APR_HAS_SHARED_MEMORY */
int main(void)
{
/* Just return, this program will never be launched, so there is no
* reason to print a message.
*/
return 0;
}
#endif /* APR_HAS_SHARED_MEMORY */
| 001-log4cxx | trunk/src/apr/test/testshmproducer.c | C | asf20 | 2,350 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <stdio.h>
#include <stdlib.h>
#include "abts.h"
#include "testutil.h"
#include "apr_pools.h"
apr_pool_t *p;
void apr_assert_success(abts_case* tc, const char* context, apr_status_t rv,
int lineno)
{
if (rv == APR_ENOTIMPL) {
abts_not_impl(tc, context, lineno);
} else if (rv != APR_SUCCESS) {
char buf[STRING_MAX], ebuf[128];
sprintf(buf, "%s (%d): %s\n", context, rv,
apr_strerror(rv, ebuf, sizeof ebuf));
abts_fail(tc, buf, lineno);
}
}
void initialize(void) {
apr_initialize();
atexit(apr_terminate);
apr_pool_create(&p, NULL);
}
| 001-log4cxx | trunk/src/apr/test/testutil.c | C | asf20 | 1,449 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "apr_time.h"
#include "apr_errno.h"
#include "apr_general.h"
#include "apr_lib.h"
#include "testutil.h"
#include "apr_strings.h"
#include <time.h>
#define STR_SIZE 45
/* The time value is used throughout the tests, so just make this a global.
* Also, we need a single value that we can test for the positive tests, so
* I chose the number below, it corresponds to:
* 2002-08-14 12:05:36.186711 -25200 [257 Sat].
* Which happens to be when I wrote the new tests.
*/
static apr_time_t now = APR_INT64_C(1032030336186711);
static char* print_time (apr_pool_t *pool, const apr_time_exp_t *xt)
{
return apr_psprintf (pool,
"%04d-%02d-%02d %02d:%02d:%02d.%06d %+05d [%d %s]%s",
xt->tm_year + 1900,
xt->tm_mon,
xt->tm_mday,
xt->tm_hour,
xt->tm_min,
xt->tm_sec,
xt->tm_usec,
xt->tm_gmtoff,
xt->tm_yday + 1,
apr_day_snames[xt->tm_wday],
(xt->tm_isdst ? " DST" : ""));
}
static void test_now(abts_case *tc, void *data)
{
apr_time_t timediff;
apr_time_t current;
time_t os_now;
current = apr_time_now();
time(&os_now);
timediff = os_now - (current / APR_USEC_PER_SEC);
/* Even though these are called so close together, there is the chance
* that the time will be slightly off, so accept anything between -1 and
* 1 second.
*/
ABTS_ASSERT(tc, "apr_time and OS time do not agree",
(timediff > -2) && (timediff < 2));
}
static void test_gmtstr(abts_case *tc, void *data)
{
apr_status_t rv;
apr_time_exp_t xt;
rv = apr_time_exp_gmt(&xt, now);
if (rv == APR_ENOTIMPL) {
ABTS_NOT_IMPL(tc, "apr_time_exp_gmt");
}
ABTS_TRUE(tc, rv == APR_SUCCESS);
ABTS_STR_EQUAL(tc, "2002-08-14 19:05:36.186711 +0000 [257 Sat]",
print_time(p, &xt));
}
static void test_exp_lt(abts_case *tc, void *data)
{
apr_status_t rv;
apr_time_exp_t xt;
time_t posix_secs = (time_t)apr_time_sec(now);
struct tm *posix_exp = localtime(&posix_secs);
rv = apr_time_exp_lt(&xt, now);
if (rv == APR_ENOTIMPL) {
ABTS_NOT_IMPL(tc, "apr_time_exp_lt");
}
ABTS_TRUE(tc, rv == APR_SUCCESS);
#define CHK_FIELD(f) \
ABTS_ASSERT(tc, "Mismatch in " #f, posix_exp->f == xt.f)
CHK_FIELD(tm_sec);
CHK_FIELD(tm_min);
CHK_FIELD(tm_hour);
CHK_FIELD(tm_mday);
CHK_FIELD(tm_mon);
CHK_FIELD(tm_year);
CHK_FIELD(tm_wday);
CHK_FIELD(tm_yday);
CHK_FIELD(tm_isdst);
#undef CHK_FIELD
}
static void test_exp_get_gmt(abts_case *tc, void *data)
{
apr_status_t rv;
apr_time_exp_t xt;
apr_time_t imp;
apr_int64_t hr_off_64;
rv = apr_time_exp_gmt(&xt, now);
ABTS_TRUE(tc, rv == APR_SUCCESS);
rv = apr_time_exp_get(&imp, &xt);
if (rv == APR_ENOTIMPL) {
ABTS_NOT_IMPL(tc, "apr_time_exp_get");
}
ABTS_TRUE(tc, rv == APR_SUCCESS);
hr_off_64 = (apr_int64_t) xt.tm_gmtoff * APR_USEC_PER_SEC;
ABTS_TRUE(tc, now + hr_off_64 == imp);
}
static void test_exp_get_lt(abts_case *tc, void *data)
{
apr_status_t rv;
apr_time_exp_t xt;
apr_time_t imp;
apr_int64_t hr_off_64;
rv = apr_time_exp_lt(&xt, now);
ABTS_TRUE(tc, rv == APR_SUCCESS);
rv = apr_time_exp_get(&imp, &xt);
if (rv == APR_ENOTIMPL) {
ABTS_NOT_IMPL(tc, "apr_time_exp_get");
}
ABTS_TRUE(tc, rv == APR_SUCCESS);
hr_off_64 = (apr_int64_t) xt.tm_gmtoff * APR_USEC_PER_SEC;
ABTS_TRUE(tc, now + hr_off_64 == imp);
}
static void test_imp_gmt(abts_case *tc, void *data)
{
apr_status_t rv;
apr_time_exp_t xt;
apr_time_t imp;
rv = apr_time_exp_gmt(&xt, now);
ABTS_TRUE(tc, rv == APR_SUCCESS);
rv = apr_time_exp_gmt_get(&imp, &xt);
if (rv == APR_ENOTIMPL) {
ABTS_NOT_IMPL(tc, "apr_time_exp_gmt_get");
}
ABTS_TRUE(tc, rv == APR_SUCCESS);
ABTS_TRUE(tc, now == imp);
}
static void test_rfcstr(abts_case *tc, void *data)
{
apr_status_t rv;
char str[STR_SIZE];
rv = apr_rfc822_date(str, now);
if (rv == APR_ENOTIMPL) {
ABTS_NOT_IMPL(tc, "apr_rfc822_date");
}
ABTS_TRUE(tc, rv == APR_SUCCESS);
ABTS_STR_EQUAL(tc, "Sat, 14 Sep 2002 19:05:36 GMT", str);
}
static void test_ctime(abts_case *tc, void *data)
{
apr_status_t rv;
char apr_str[STR_SIZE];
char libc_str[STR_SIZE];
apr_time_t now_sec = apr_time_sec(now);
time_t posix_sec = (time_t) now_sec;
rv = apr_ctime(apr_str, now);
if (rv == APR_ENOTIMPL) {
ABTS_NOT_IMPL(tc, "apr_ctime");
}
ABTS_TRUE(tc, rv == APR_SUCCESS);
strcpy(libc_str, ctime(&posix_sec));
*strchr(libc_str, '\n') = '\0';
ABTS_STR_EQUAL(tc, libc_str, apr_str);
}
static void test_strftime(abts_case *tc, void *data)
{
apr_status_t rv;
apr_time_exp_t xt;
char *str = NULL;
apr_size_t sz;
rv = apr_time_exp_gmt(&xt, now);
str = apr_palloc(p, STR_SIZE + 1);
rv = apr_strftime(str, &sz, STR_SIZE, "%R %A %d %B %Y", &xt);
if (rv == APR_ENOTIMPL) {
ABTS_NOT_IMPL(tc, "apr_strftime");
}
ABTS_TRUE(tc, rv == APR_SUCCESS);
ABTS_STR_EQUAL(tc, "19:05 Saturday 14 September 2002", str);
}
static void test_strftimesmall(abts_case *tc, void *data)
{
apr_status_t rv;
apr_time_exp_t xt;
char str[STR_SIZE];
apr_size_t sz;
rv = apr_time_exp_gmt(&xt, now);
rv = apr_strftime(str, &sz, STR_SIZE, "%T", &xt);
if (rv == APR_ENOTIMPL) {
ABTS_NOT_IMPL(tc, "apr_strftime");
}
ABTS_TRUE(tc, rv == APR_SUCCESS);
ABTS_STR_EQUAL(tc, "19:05:36", str);
}
static void test_exp_tz(abts_case *tc, void *data)
{
apr_status_t rv;
apr_time_exp_t xt;
apr_int32_t hr_off = -5 * 3600; /* 5 hours in seconds */
rv = apr_time_exp_tz(&xt, now, hr_off);
if (rv == APR_ENOTIMPL) {
ABTS_NOT_IMPL(tc, "apr_time_exp_tz");
}
ABTS_TRUE(tc, rv == APR_SUCCESS);
ABTS_TRUE(tc, (xt.tm_usec == 186711) &&
(xt.tm_sec == 36) &&
(xt.tm_min == 5) &&
(xt.tm_hour == 14) &&
(xt.tm_mday == 14) &&
(xt.tm_mon == 8) &&
(xt.tm_year == 102) &&
(xt.tm_wday == 6) &&
(xt.tm_yday == 256));
}
static void test_strftimeoffset(abts_case *tc, void *data)
{
apr_status_t rv;
apr_time_exp_t xt;
char str[STR_SIZE];
apr_size_t sz;
apr_int32_t hr_off = -5 * 3600; /* 5 hours in seconds */
apr_time_exp_tz(&xt, now, hr_off);
rv = apr_strftime(str, &sz, STR_SIZE, "%T", &xt);
if (rv == APR_ENOTIMPL) {
ABTS_NOT_IMPL(tc, "apr_strftime");
}
ABTS_TRUE(tc, rv == APR_SUCCESS);
}
/* 0.9.4 and earlier rejected valid dates in 2038 */
static void test_2038(abts_case *tc, void *data)
{
apr_time_exp_t xt;
apr_time_t t;
/* 2038-01-19T03:14:07.000000Z */
xt.tm_year = 138;
xt.tm_mon = 0;
xt.tm_mday = 19;
xt.tm_hour = 3;
xt.tm_min = 14;
xt.tm_sec = 7;
APR_ASSERT_SUCCESS(tc, "explode January 19th, 2038",
apr_time_exp_get(&t, &xt));
}
abts_suite *testtime(abts_suite *suite)
{
suite = ADD_SUITE(suite)
abts_run_test(suite, test_now, NULL);
abts_run_test(suite, test_gmtstr, NULL);
abts_run_test(suite, test_exp_lt, NULL);
abts_run_test(suite, test_exp_get_gmt, NULL);
abts_run_test(suite, test_exp_get_lt, NULL);
abts_run_test(suite, test_imp_gmt, NULL);
abts_run_test(suite, test_rfcstr, NULL);
abts_run_test(suite, test_ctime, NULL);
abts_run_test(suite, test_strftime, NULL);
abts_run_test(suite, test_strftimesmall, NULL);
abts_run_test(suite, test_exp_tz, NULL);
abts_run_test(suite, test_strftimeoffset, NULL);
abts_run_test(suite, test_2038, NULL);
return suite;
}
| 001-log4cxx | trunk/src/apr/test/testtime.c | C | asf20 | 8,863 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <assert.h>
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include "apr_network_io.h"
#include "apr_errno.h"
#include "apr_general.h"
#include "apr_poll.h"
#if !APR_HAS_SENDFILE
int main(void)
{
fprintf(stderr,
"This program won't work on this platform because there is no "
"support for sendfile().\n");
return 0;
}
#else /* !APR_HAS_SENDFILE */
#define FILE_LENGTH 200000
#define FILE_DATA_CHAR '0'
#define HDR1 "1234567890ABCD\n"
#define HDR2 "EFGH\n"
#define HDR3_LEN 80000
#define HDR3_CHAR '^'
#define TRL1 "IJKLMNOPQRSTUVWXYZ\n"
#define TRL2 "!@#$%&*()\n"
#define TRL3_LEN 90000
#define TRL3_CHAR '@'
#define TESTSF_PORT 8021
#define TESTFILE "testsf.dat"
typedef enum {BLK, NONBLK, TIMEOUT} client_socket_mode_t;
static void apr_setup(apr_pool_t **p, apr_socket_t **sock, int *family)
{
char buf[120];
apr_status_t rv;
rv = apr_initialize();
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_initialize()->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
atexit(apr_terminate);
rv = apr_pool_create(p, NULL);
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_pool_create()->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
*sock = NULL;
rv = apr_socket_create(sock, *family, SOCK_STREAM, 0, *p);
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_socket_create()->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
if (*family == APR_UNSPEC) {
apr_sockaddr_t *localsa;
rv = apr_socket_addr_get(&localsa, APR_LOCAL, *sock);
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_socket_addr_get()->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
*family = localsa->family;
}
}
static void create_testfile(apr_pool_t *p, const char *fname)
{
apr_file_t *f = NULL;
apr_status_t rv;
char buf[120];
int i;
apr_finfo_t finfo;
printf("Creating a test file...\n");
rv = apr_file_open(&f, fname,
APR_CREATE | APR_WRITE | APR_TRUNCATE | APR_BUFFERED,
APR_UREAD | APR_UWRITE, p);
if (rv) {
fprintf(stderr, "apr_file_open()->%d/%s\n",
rv, apr_strerror(rv, buf, sizeof buf));
exit(1);
}
buf[0] = FILE_DATA_CHAR;
buf[1] = '\0';
for (i = 0; i < FILE_LENGTH; i++) {
/* exercise apr_file_putc() and apr_file_puts() on buffered files */
if ((i % 2) == 0) {
rv = apr_file_putc(buf[0], f);
if (rv) {
fprintf(stderr, "apr_file_putc()->%d/%s\n",
rv, apr_strerror(rv, buf, sizeof buf));
exit(1);
}
}
else {
rv = apr_file_puts(buf, f);
if (rv) {
fprintf(stderr, "apr_file_puts()->%d/%s\n",
rv, apr_strerror(rv, buf, sizeof buf));
exit(1);
}
}
}
rv = apr_file_close(f);
if (rv) {
fprintf(stderr, "apr_file_close()->%d/%s\n",
rv, apr_strerror(rv, buf, sizeof buf));
exit(1);
}
rv = apr_stat(&finfo, fname, APR_FINFO_NORM, p);
if (rv != APR_SUCCESS && rv != APR_INCOMPLETE) {
fprintf(stderr, "apr_stat()->%d/%s\n",
rv, apr_strerror(rv, buf, sizeof buf));
exit(1);
}
if (finfo.size != FILE_LENGTH) {
fprintf(stderr,
"test file %s should be %ld-bytes long\n"
"instead it is %ld-bytes long\n",
fname,
(long int)FILE_LENGTH,
(long int)finfo.size);
exit(1);
}
}
static int client(client_socket_mode_t socket_mode, char *host)
{
apr_status_t rv, tmprv;
apr_socket_t *sock;
apr_pool_t *p;
char buf[120];
apr_file_t *f = NULL;
apr_size_t len;
apr_size_t expected_len;
apr_off_t current_file_offset;
apr_hdtr_t hdtr;
struct iovec headers[3];
struct iovec trailers[3];
apr_size_t bytes_read;
apr_pollset_t *pset;
apr_int32_t nsocks;
int i;
int family;
apr_sockaddr_t *destsa;
family = APR_INET;
apr_setup(&p, &sock, &family);
create_testfile(p, TESTFILE);
rv = apr_file_open(&f, TESTFILE, APR_READ, 0, p);
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_file_open()->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
if (!host) {
host = "127.0.0.1";
}
rv = apr_sockaddr_info_get(&destsa, host, family, TESTSF_PORT, 0, p);
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_sockaddr_info_get()->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
rv = apr_socket_connect(sock, destsa);
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_socket_connect()->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
switch(socket_mode) {
case BLK:
/* leave it blocking */
break;
case NONBLK:
/* set it non-blocking */
rv = apr_socket_opt_set(sock, APR_SO_NONBLOCK, 1);
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_socket_opt_set(APR_SO_NONBLOCK)->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
break;
case TIMEOUT:
/* set a timeout */
rv = apr_socket_timeout_set(sock, 100 * APR_USEC_PER_SEC);
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_socket_opt_set(APR_SO_NONBLOCK)->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
break;
default:
assert(1 != 1);
}
printf("Sending the file...\n");
hdtr.headers = headers;
hdtr.numheaders = 3;
hdtr.headers[0].iov_base = HDR1;
hdtr.headers[0].iov_len = strlen(hdtr.headers[0].iov_base);
hdtr.headers[1].iov_base = HDR2;
hdtr.headers[1].iov_len = strlen(hdtr.headers[1].iov_base);
hdtr.headers[2].iov_base = malloc(HDR3_LEN);
assert(hdtr.headers[2].iov_base);
memset(hdtr.headers[2].iov_base, HDR3_CHAR, HDR3_LEN);
hdtr.headers[2].iov_len = HDR3_LEN;
hdtr.trailers = trailers;
hdtr.numtrailers = 3;
hdtr.trailers[0].iov_base = TRL1;
hdtr.trailers[0].iov_len = strlen(hdtr.trailers[0].iov_base);
hdtr.trailers[1].iov_base = TRL2;
hdtr.trailers[1].iov_len = strlen(hdtr.trailers[1].iov_base);
hdtr.trailers[2].iov_base = malloc(TRL3_LEN);
memset(hdtr.trailers[2].iov_base, TRL3_CHAR, TRL3_LEN);
assert(hdtr.trailers[2].iov_base);
hdtr.trailers[2].iov_len = TRL3_LEN;
expected_len =
strlen(HDR1) + strlen(HDR2) + HDR3_LEN +
strlen(TRL1) + strlen(TRL2) + TRL3_LEN +
FILE_LENGTH;
if (socket_mode == BLK) {
current_file_offset = 0;
len = FILE_LENGTH;
rv = apr_socket_sendfile(sock, f, &hdtr, ¤t_file_offset, &len, 0);
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_socket_sendfile()->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
printf("apr_socket_sendfile() updated offset with %ld\n",
(long int)current_file_offset);
printf("apr_socket_sendfile() updated len with %ld\n",
(long int)len);
printf("bytes really sent: %" APR_SIZE_T_FMT "\n",
expected_len);
if (len != expected_len) {
fprintf(stderr, "apr_socket_sendfile() didn't report the correct "
"number of bytes sent!\n");
exit(1);
}
}
else {
/* non-blocking... wooooooo */
apr_size_t total_bytes_sent;
apr_pollfd_t pfd;
pset = NULL;
rv = apr_pollset_create(&pset, 1, p, 0);
assert(!rv);
pfd.p = p;
pfd.desc_type = APR_POLL_SOCKET;
pfd.reqevents = APR_POLLOUT;
pfd.rtnevents = 0;
pfd.desc.s = sock;
pfd.client_data = NULL;
rv = apr_pollset_add(pset, &pfd);
assert(!rv);
total_bytes_sent = 0;
current_file_offset = 0;
len = FILE_LENGTH;
do {
apr_size_t tmplen;
tmplen = len; /* bytes remaining to send from the file */
printf("Calling apr_socket_sendfile()...\n");
printf("Headers (%d):\n", hdtr.numheaders);
for (i = 0; i < hdtr.numheaders; i++) {
printf("\t%ld bytes (%c)\n",
(long)hdtr.headers[i].iov_len,
*(char *)hdtr.headers[i].iov_base);
}
printf("File: %ld bytes from offset %ld\n",
(long)tmplen, (long)current_file_offset);
printf("Trailers (%d):\n", hdtr.numtrailers);
for (i = 0; i < hdtr.numtrailers; i++) {
printf("\t%ld bytes\n",
(long)hdtr.trailers[i].iov_len);
}
rv = apr_socket_sendfile(sock, f, &hdtr, ¤t_file_offset, &tmplen, 0);
printf("apr_socket_sendfile()->%d, sent %ld bytes\n", rv, (long)tmplen);
if (rv) {
if (APR_STATUS_IS_EAGAIN(rv)) {
assert(tmplen == 0);
nsocks = 1;
tmprv = apr_pollset_poll(pset, -1, &nsocks, NULL);
assert(!tmprv);
assert(nsocks == 1);
/* continue; */
}
}
total_bytes_sent += tmplen;
/* Adjust hdtr to compensate for partially-written
* data.
*/
/* First, skip over any header data which might have
* been written.
*/
while (tmplen && hdtr.numheaders) {
if (tmplen >= hdtr.headers[0].iov_len) {
tmplen -= hdtr.headers[0].iov_len;
--hdtr.numheaders;
++hdtr.headers;
}
else {
hdtr.headers[0].iov_len -= tmplen;
hdtr.headers[0].iov_base =
(char*) hdtr.headers[0].iov_base + tmplen;
tmplen = 0;
}
}
/* Now, skip over any file data which might have been
* written.
*/
if (tmplen <= len) {
current_file_offset += tmplen;
len -= tmplen;
tmplen = 0;
}
else {
tmplen -= len;
len = 0;
current_file_offset = 0;
}
/* Last, skip over any trailer data which might have
* been written.
*/
while (tmplen && hdtr.numtrailers) {
if (tmplen >= hdtr.trailers[0].iov_len) {
tmplen -= hdtr.trailers[0].iov_len;
--hdtr.numtrailers;
++hdtr.trailers;
}
else {
hdtr.trailers[0].iov_len -= tmplen;
hdtr.trailers[0].iov_base =
(char *)hdtr.trailers[0].iov_base + tmplen;
tmplen = 0;
}
}
} while (total_bytes_sent < expected_len &&
(rv == APR_SUCCESS ||
(APR_STATUS_IS_EAGAIN(rv) && socket_mode != TIMEOUT)));
if (total_bytes_sent != expected_len) {
fprintf(stderr,
"client problem: sent %ld of %ld bytes\n",
(long)total_bytes_sent, (long)expected_len);
exit(1);
}
if (rv) {
fprintf(stderr,
"client problem: rv %d\n",
rv);
exit(1);
}
}
current_file_offset = 0;
rv = apr_file_seek(f, APR_CUR, ¤t_file_offset);
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_file_seek()->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
printf("After apr_socket_sendfile(), the kernel file pointer is "
"at offset %ld.\n",
(long int)current_file_offset);
rv = apr_socket_shutdown(sock, APR_SHUTDOWN_WRITE);
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_socket_shutdown()->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
/* in case this is the non-blocking test, set socket timeout;
* we're just waiting for EOF */
rv = apr_socket_timeout_set(sock, apr_time_from_sec(3));
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_socket_timeout_set()->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
bytes_read = 1;
rv = apr_socket_recv(sock, buf, &bytes_read);
if (rv != APR_EOF) {
fprintf(stderr, "apr_socket_recv()->%d/%s (expected APR_EOF)\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
if (bytes_read != 0) {
fprintf(stderr, "We expected to get 0 bytes read with APR_EOF\n"
"but instead we read %ld bytes.\n",
(long int)bytes_read);
exit(1);
}
printf("client: apr_socket_sendfile() worked as expected!\n");
rv = apr_file_remove(TESTFILE, p);
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_file_remove()->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
return 0;
}
static int server(void)
{
apr_status_t rv;
apr_socket_t *sock;
apr_pool_t *p;
char buf[120];
int i;
apr_socket_t *newsock = NULL;
apr_size_t bytes_read;
apr_sockaddr_t *localsa;
int family;
family = APR_UNSPEC;
apr_setup(&p, &sock, &family);
rv = apr_socket_opt_set(sock, APR_SO_REUSEADDR, 1);
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_socket_opt_set()->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
rv = apr_sockaddr_info_get(&localsa, NULL, family, TESTSF_PORT, 0, p);
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_sockaddr_info_get()->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
rv = apr_socket_bind(sock, localsa);
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_socket_bind()->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
rv = apr_socket_listen(sock, 5);
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_socket_listen()->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
printf("Waiting for a client to connect...\n");
rv = apr_socket_accept(&newsock, sock, p);
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_socket_accept()->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
printf("Processing a client...\n");
assert(sizeof buf > strlen(HDR1));
bytes_read = strlen(HDR1);
rv = apr_socket_recv(newsock, buf, &bytes_read);
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_socket_recv()->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
if (bytes_read != strlen(HDR1)) {
fprintf(stderr, "wrong data read (1)\n");
exit(1);
}
if (memcmp(buf, HDR1, strlen(HDR1))) {
fprintf(stderr, "wrong data read (2)\n");
fprintf(stderr, "received: `%.*s'\nexpected: `%s'\n",
(int)bytes_read, buf, HDR1);
exit(1);
}
assert(sizeof buf > strlen(HDR2));
bytes_read = strlen(HDR2);
rv = apr_socket_recv(newsock, buf, &bytes_read);
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_socket_recv()->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
if (bytes_read != strlen(HDR2)) {
fprintf(stderr, "wrong data read (3)\n");
exit(1);
}
if (memcmp(buf, HDR2, strlen(HDR2))) {
fprintf(stderr, "wrong data read (4)\n");
fprintf(stderr, "received: `%.*s'\nexpected: `%s'\n",
(int)bytes_read, buf, HDR2);
exit(1);
}
for (i = 0; i < HDR3_LEN; i++) {
bytes_read = 1;
rv = apr_socket_recv(newsock, buf, &bytes_read);
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_socket_recv()->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
if (bytes_read != 1) {
fprintf(stderr, "apr_socket_recv()->%ld bytes instead of 1\n",
(long int)bytes_read);
exit(1);
}
if (buf[0] != HDR3_CHAR) {
fprintf(stderr,
"problem with data read (byte %d of hdr 3):\n",
i);
fprintf(stderr, "read `%c' (0x%x) from client; expected "
"`%c'\n",
buf[0], buf[0], HDR3_CHAR);
exit(1);
}
}
for (i = 0; i < FILE_LENGTH; i++) {
bytes_read = 1;
rv = apr_socket_recv(newsock, buf, &bytes_read);
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_socket_recv()->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
if (bytes_read != 1) {
fprintf(stderr, "apr_socket_recv()->%ld bytes instead of 1\n",
(long int)bytes_read);
exit(1);
}
if (buf[0] != FILE_DATA_CHAR) {
fprintf(stderr,
"problem with data read (byte %d of file):\n",
i);
fprintf(stderr, "read `%c' (0x%x) from client; expected "
"`%c'\n",
buf[0], buf[0], FILE_DATA_CHAR);
exit(1);
}
}
assert(sizeof buf > strlen(TRL1));
bytes_read = strlen(TRL1);
rv = apr_socket_recv(newsock, buf, &bytes_read);
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_socket_recv()->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
if (bytes_read != strlen(TRL1)) {
fprintf(stderr, "wrong data read (5)\n");
exit(1);
}
if (memcmp(buf, TRL1, strlen(TRL1))) {
fprintf(stderr, "wrong data read (6)\n");
fprintf(stderr, "received: `%.*s'\nexpected: `%s'\n",
(int)bytes_read, buf, TRL1);
exit(1);
}
assert(sizeof buf > strlen(TRL2));
bytes_read = strlen(TRL2);
rv = apr_socket_recv(newsock, buf, &bytes_read);
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_socket_recv()->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
if (bytes_read != strlen(TRL2)) {
fprintf(stderr, "wrong data read (7)\n");
exit(1);
}
if (memcmp(buf, TRL2, strlen(TRL2))) {
fprintf(stderr, "wrong data read (8)\n");
fprintf(stderr, "received: `%.*s'\nexpected: `%s'\n",
(int)bytes_read, buf, TRL2);
exit(1);
}
for (i = 0; i < TRL3_LEN; i++) {
bytes_read = 1;
rv = apr_socket_recv(newsock, buf, &bytes_read);
if (rv != APR_SUCCESS) {
fprintf(stderr, "apr_socket_recv()->%d/%s\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
if (bytes_read != 1) {
fprintf(stderr, "apr_socket_recv()->%ld bytes instead of 1\n",
(long int)bytes_read);
exit(1);
}
if (buf[0] != TRL3_CHAR) {
fprintf(stderr,
"problem with data read (byte %d of trl 3):\n",
i);
fprintf(stderr, "read `%c' (0x%x) from client; expected "
"`%c'\n",
buf[0], buf[0], TRL3_CHAR);
exit(1);
}
}
bytes_read = 1;
rv = apr_socket_recv(newsock, buf, &bytes_read);
if (rv != APR_EOF) {
fprintf(stderr, "apr_socket_recv()->%d/%s (expected APR_EOF)\n",
rv,
apr_strerror(rv, buf, sizeof buf));
exit(1);
}
if (bytes_read != 0) {
fprintf(stderr, "We expected to get 0 bytes read with APR_EOF\n"
"but instead we read %ld bytes (%c).\n",
(long int)bytes_read, buf[0]);
exit(1);
}
printf("server: apr_socket_sendfile() worked as expected!\n");
return 0;
}
int main(int argc, char *argv[])
{
#ifdef SIGPIPE
signal(SIGPIPE, SIG_IGN);
#endif
/* Gee whiz this is goofy logic but I wanna drive sendfile right now,
* not dork around with the command line!
*/
if (argc >= 3 && !strcmp(argv[1], "client")) {
char *host = 0;
if (argv[3]) {
host = argv[3];
}
if (!strcmp(argv[2], "blocking")) {
return client(BLK, host);
}
else if (!strcmp(argv[2], "timeout")) {
return client(TIMEOUT, host);
}
else if (!strcmp(argv[2], "nonblocking")) {
return client(NONBLK, host);
}
}
else if (argc == 2 && !strcmp(argv[1], "server")) {
return server();
}
fprintf(stderr,
"Usage: %s client {blocking|nonblocking|timeout}\n"
" %s server\n",
argv[0], argv[0]);
return -1;
}
#endif /* !APR_HAS_SENDFILE */
| 001-log4cxx | trunk/src/apr/test/sendfile.c | C | asf20 | 22,854 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "testutil.h"
#include "apr_general.h"
#include "apr_network_io.h"
#include "apr_errno.h"
static void test_bad_input(abts_case *tc, void *data)
{
struct {
const char *ipstr;
const char *mask;
apr_status_t expected_rv;
} testcases[] =
{
/* so we have a few good inputs in here; sue me */
{"my.host.name", NULL, APR_EINVAL}
,{"127.0.0.256", NULL, APR_EBADIP}
,{"127.0.0.1", NULL, APR_SUCCESS}
,{"127.0.0.1", "32", APR_SUCCESS}
,{"127.0.0.1", "1", APR_SUCCESS}
,{"127.0.0.1", "15", APR_SUCCESS}
,{"127.0.0.1", "-1", APR_EBADMASK}
,{"127.0.0.1", "0", APR_EBADMASK}
,{"127.0.0.1", "33", APR_EBADMASK}
,{"127.0.0.1", "255.0.0.0", APR_SUCCESS}
,{"127.0.0.1", "255.0", APR_EBADMASK}
,{"127.0.0.1", "255.255.256.0", APR_EBADMASK}
,{"127.0.0.1", "abc", APR_EBADMASK}
,{"127", NULL, APR_SUCCESS}
,{"127.0.0.1.2", NULL, APR_EBADIP}
,{"127.0.0.1.2", "8", APR_EBADIP}
,{"127", "255.0.0.0", APR_EBADIP} /* either EBADIP or EBADMASK seems fine */
#if APR_HAVE_IPV6
,{"::1", NULL, APR_SUCCESS}
,{"::1", "20", APR_SUCCESS}
,{"::ffff:9.67.113.15", NULL, APR_EBADIP} /* yes, this is goodness */
,{"fe80::", "16", APR_SUCCESS}
,{"fe80::", "255.0.0.0", APR_EBADMASK}
,{"fe80::1", "0", APR_EBADMASK}
,{"fe80::1", "-1", APR_EBADMASK}
,{"fe80::1", "1", APR_SUCCESS}
,{"fe80::1", "33", APR_SUCCESS}
,{"fe80::1", "128", APR_SUCCESS}
,{"fe80::1", "129", APR_EBADMASK}
#else
/* do some IPv6 stuff and verify that it fails with APR_EBADIP */
,{"::ffff:9.67.113.15", NULL, APR_EBADIP}
#endif
};
int i;
apr_ipsubnet_t *ipsub;
apr_status_t rv;
for (i = 0; i < (sizeof testcases / sizeof testcases[0]); i++) {
rv = apr_ipsubnet_create(&ipsub, testcases[i].ipstr, testcases[i].mask, p);
ABTS_INT_EQUAL(tc, rv, testcases[i].expected_rv);
}
}
static void test_singleton_subnets(abts_case *tc, void *data)
{
const char *v4addrs[] = {
"127.0.0.1", "129.42.18.99", "63.161.155.20", "207.46.230.229", "64.208.42.36",
"198.144.203.195", "192.18.97.241", "198.137.240.91", "62.156.179.119",
"204.177.92.181"
};
apr_ipsubnet_t *ipsub;
apr_sockaddr_t *sa;
apr_status_t rv;
int i, j, rc;
for (i = 0; i < sizeof v4addrs / sizeof v4addrs[0]; i++) {
rv = apr_ipsubnet_create(&ipsub, v4addrs[i], NULL, p);
ABTS_TRUE(tc, rv == APR_SUCCESS);
for (j = 0; j < sizeof v4addrs / sizeof v4addrs[0]; j++) {
rv = apr_sockaddr_info_get(&sa, v4addrs[j], APR_INET, 0, 0, p);
ABTS_TRUE(tc, rv == APR_SUCCESS);
rc = apr_ipsubnet_test(ipsub, sa);
if (!strcmp(v4addrs[i], v4addrs[j])) {
ABTS_TRUE(tc, rc != 0);
}
else {
ABTS_TRUE(tc, rc == 0);
}
}
}
/* same for v6? */
}
static void test_interesting_subnets(abts_case *tc, void *data)
{
struct {
const char *ipstr, *mask;
int family;
char *in_subnet, *not_in_subnet;
} testcases[] =
{
{"9.67", NULL, APR_INET, "9.67.113.15", "10.1.2.3"}
,{"9.67.0.0", "16", APR_INET, "9.67.113.15", "10.1.2.3"}
,{"9.67.0.0", "255.255.0.0", APR_INET, "9.67.113.15", "10.1.2.3"}
,{"9.67.113.99", "16", APR_INET, "9.67.113.15", "10.1.2.3"}
,{"9.67.113.99", "255.255.255.0", APR_INET, "9.67.113.15", "10.1.2.3"}
#if APR_HAVE_IPV6
,{"fe80::", "8", APR_INET6, "fe80::1", "ff01::1"}
,{"ff01::", "8", APR_INET6, "ff01::1", "fe80::1"}
,{"3FFE:8160::", "28", APR_INET6, "3ffE:816e:abcd:1234::1", "3ffe:8170::1"}
,{"127.0.0.1", NULL, APR_INET6, "::ffff:127.0.0.1", "fe80::1"}
,{"127.0.0.1", "8", APR_INET6, "::ffff:127.0.0.1", "fe80::1"}
#endif
};
apr_ipsubnet_t *ipsub;
apr_sockaddr_t *sa;
apr_status_t rv;
int i, rc;
for (i = 0; i < sizeof testcases / sizeof testcases[0]; i++) {
rv = apr_ipsubnet_create(&ipsub, testcases[i].ipstr, testcases[i].mask, p);
ABTS_TRUE(tc, rv == APR_SUCCESS);
rv = apr_sockaddr_info_get(&sa, testcases[i].in_subnet, testcases[i].family, 0, 0, p);
ABTS_TRUE(tc, rv == APR_SUCCESS);
rc = apr_ipsubnet_test(ipsub, sa);
ABTS_TRUE(tc, rc != 0);
rv = apr_sockaddr_info_get(&sa, testcases[i].not_in_subnet, testcases[i].family, 0, 0, p);
ABTS_TRUE(tc, rv == APR_SUCCESS);
rc = apr_ipsubnet_test(ipsub, sa);
ABTS_TRUE(tc, rc == 0);
}
}
static void test_badmask_str(abts_case *tc, void *data)
{
char buf[128];
ABTS_STR_EQUAL(tc, apr_strerror(APR_EBADMASK, buf, sizeof buf),
"The specified network mask is invalid.");
}
static void test_badip_str(abts_case *tc, void *data)
{
char buf[128];
ABTS_STR_EQUAL(tc, apr_strerror(APR_EBADIP, buf, sizeof buf),
"The specified IP address is invalid.");
}
abts_suite *testipsub(abts_suite *suite)
{
suite = ADD_SUITE(suite)
abts_run_test(suite, test_bad_input, NULL);
abts_run_test(suite, test_singleton_subnets, NULL);
abts_run_test(suite, test_interesting_subnets, NULL);
abts_run_test(suite, test_badmask_str, NULL);
abts_run_test(suite, test_badip_str, NULL);
return suite;
}
| 001-log4cxx | trunk/src/apr/test/testipsub.c | C | asf20 | 7,132 |