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.
#
SUBDIRS = input witness
EXTRA_DIST = L7D_en_US.properties L7D_fr_CH.properties L7D_fr.properties
# if we are building in a separate build tree, then copy all necessary files
all-local:
@if test "$(top_srcdir)" != "$(top_builddir)"; then \
echo "Copying test suite data files ..." ; \
list='$(EXTRA_DIST)'; for file in $$list; do \
cp -p $(srcdir)/$$file . ; \
done \
fi
prepare:
@if test ! -d "output"; then \
mkdir output; \
fi;
@rm -rf log4j.xml
@rm -rf log4j.properties
@rm -rf log4cxx.xml
@rm -rf log4cxx.properties
build: check-recursive prepare
cleanOutputDir:
@rm -rf output/*
check: prepare run-unittest DefaultInit
run-unittest: build cleanOutputDir
@export TOTO=wonderful; \
export key1=value1; \
export key2=value2; \
../cpp/testsuite -v
DefaultInit: build cleanOutputDir
../cpp/testsuite -v testcase1
@cp input/xml/defaultInit.xml log4j.xml
../cpp/testsuite -v testcase2
@rm -f log4j.xml
@cp input/defaultInit3.properties log4j.properties
../cpp/testsuite -v testcase3
@rm -f log4j.properties
@cp input/defaultInit3.properties log4j.properties
@cp input/xml/defaultInit.xml log4j.xml
../cpp/testsuite -v testcase4
@rm -f log4j.xml
@rm -f log4j.properties
SocketServer: build cleanOutputDir
../cpp/testsuite -v socketservertestcase
| 001-log4cxx | trunk/src/test/resources/Makefile.am | Makefile | asf20 | 2,083 |
Hello---0
Hello---1
Hello---2
Hello---3
Hello---4
Hello---5
Hello---6
Hello---7
Hello---8
Hello---9
| 001-log4cxx | trunk/src/test/resources/output/manual-test2.log.2 | Roff Manpage | asf20 | 100 |
sQthread=\"[0-9A-Fa-fXx]*Qthread=\"mainQg
sQ[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*QXXXQg
| 001-log4cxx | trunk/src/test/resources/output/temp.xmlLayout.1.sed | sed | asf20 | 102 |
Hello--10
Hello--11
Hello--12
Hello--13
Hello--14
Hello--15
Hello--16
Hello--17
Hello--18
Hello--19
| 001-log4cxx | trunk/src/test/resources/output/obsoleteRFA-test2.log.1 | Roff Manpage | asf20 | 100 |
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="XXX" level="DEBUG" thread="main">
<log4j:message><![CDATA[Hello]]></log4j:message>
<log4j:properties>
<log4j:data name="key1" value="val1"/>
<log4j:data name="key2" value="val2"/>
</log4j:properties>
</log4j:event>
| 001-log4cxx | trunk/src/test/resources/output/filtered.xmlLayout.mdc.1 | Roff Manpage | asf20 | 296 |
sQC:\\log4cxx\\src\\test\\cpp\\patternlayouttest.cppQpatternlayouttest.cppQg
sQ\[[0-9A-Fa-fXx]*]Q\[main]Qg
sQ [^ ]*[\\]Q Qg
sQ([0-9]*)Q(X)Qg
| 001-log4cxx | trunk/src/test/resources/output/temp.sed | sed | asf20 | 141 |
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="XXX" level="TRACE" thread="main">
<log4j:message><![CDATA[Message with embedded <![CDATA[<hello>hi</hello>]]>]]><![CDATA[.]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="testCDATA" file="XMLLayoutTestCase.java" line="X"/>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="XXX" level="DEBUG" thread="main">
<log4j:message><![CDATA[Message with embedded <![CDATA[<hello>hi</hello>]]>]]><![CDATA[.]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="testCDATA" file="XMLLayoutTestCase.java" line="X"/>
</log4j:event>
| 001-log4cxx | trunk/src/test/resources/output/filtered.xmlLayout.3 | Roff Manpage | asf20 | 688 |
Hello--10
Hello--11
Hello--12
Hello--13
Hello--14
Hello--15
Hello--16
Hello--17
Hello--18
Hello--19
| 001-log4cxx | trunk/src/test/resources/output/manual-test2.log.1 | Roff Manpage | asf20 | 100 |
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="1213947943660" level="DEBUG" thread="0x000004c8">
<log4j:message><![CDATA[Hello]]></log4j:message>
<log4j:properties>
<log4j:data name="key1" value="val1"/>
<log4j:data name="key2" value="val2"/>
</log4j:properties>
</log4j:event>
| 001-log4cxx | trunk/src/test/resources/output/temp.xmlLayout.mdc.1 | Roff Manpage | asf20 | 312 |
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase$X" timestamp="1213947943530" level="INFO" thread="0x000004c8">
<log4j:message><![CDATA[in X() constructor]]></log4j:message>
<log4j:locationInfo class="X" method="X" file="C:\log4cxx\src\test\cpp\xml\xmllayouttestcase.cpp" line="55"/>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="1213947943530" level="TRACE" thread="0x000004c8">
<log4j:message><![CDATA[Message 0]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="C:\log4cxx\src\test\cpp\xml\xmllayouttestcase.cpp" line="324"/>
</log4j:event>
<log4j:event logger="root" timestamp="1213947943530" level="TRACE" thread="0x000004c8">
<log4j:message><![CDATA[Message 0]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="C:\log4cxx\src\test\cpp\xml\xmllayouttestcase.cpp" line="325"/>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="1213947943530" level="DEBUG" thread="0x000004c8">
<log4j:message><![CDATA[Message 1]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="C:\log4cxx\src\test\cpp\xml\xmllayouttestcase.cpp" line="328"/>
</log4j:event>
<log4j:event logger="root" timestamp="1213947943530" level="DEBUG" thread="0x000004c8">
<log4j:message><![CDATA[Message 1]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="C:\log4cxx\src\test\cpp\xml\xmllayouttestcase.cpp" line="329"/>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="1213947943530" level="INFO" thread="0x000004c8">
<log4j:message><![CDATA[Message 2]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="C:\log4cxx\src\test\cpp\xml\xmllayouttestcase.cpp" line="332"/>
</log4j:event>
<log4j:event logger="root" timestamp="1213947943530" level="INFO" thread="0x000004c8">
<log4j:message><![CDATA[Message 2]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="C:\log4cxx\src\test\cpp\xml\xmllayouttestcase.cpp" line="333"/>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="1213947943530" level="WARN" thread="0x000004c8">
<log4j:message><![CDATA[Message 3]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="C:\log4cxx\src\test\cpp\xml\xmllayouttestcase.cpp" line="336"/>
</log4j:event>
<log4j:event logger="root" timestamp="1213947943530" level="WARN" thread="0x000004c8">
<log4j:message><![CDATA[Message 3]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="C:\log4cxx\src\test\cpp\xml\xmllayouttestcase.cpp" line="337"/>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="1213947943540" level="ERROR" thread="0x000004c8">
<log4j:message><![CDATA[Message 4]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="C:\log4cxx\src\test\cpp\xml\xmllayouttestcase.cpp" line="340"/>
</log4j:event>
<log4j:event logger="root" timestamp="1213947943540" level="ERROR" thread="0x000004c8">
<log4j:message><![CDATA[Message 4]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="C:\log4cxx\src\test\cpp\xml\xmllayouttestcase.cpp" line="341"/>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="1213947943540" level="FATAL" thread="0x000004c8">
<log4j:message><![CDATA[Message 5]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="C:\log4cxx\src\test\cpp\xml\xmllayouttestcase.cpp" line="344"/>
</log4j:event>
<log4j:event logger="root" timestamp="1213947943540" level="FATAL" thread="0x000004c8">
<log4j:message><![CDATA[Message 5]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="C:\log4cxx\src\test\cpp\xml\xmllayouttestcase.cpp" line="345"/>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="1213947943540" level="DEBUG" thread="0x000004c8">
<log4j:message><![CDATA[Message 6]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="C:\log4cxx\src\test\cpp\xml\xmllayouttestcase.cpp" line="348"/>
</log4j:event>
<log4j:event logger="root" timestamp="1213947943540" level="DEBUG" thread="0x000004c8">
<log4j:message><![CDATA[Message 6]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="C:\log4cxx\src\test\cpp\xml\xmllayouttestcase.cpp" line="349"/>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="1213947943540" level="ERROR" thread="0x000004c8">
<log4j:message><![CDATA[Message 7]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="C:\log4cxx\src\test\cpp\xml\xmllayouttestcase.cpp" line="352"/>
</log4j:event>
<log4j:event logger="root" timestamp="1213947943540" level="ERROR" thread="0x000004c8">
<log4j:message><![CDATA[Message 7]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="C:\log4cxx\src\test\cpp\xml\xmllayouttestcase.cpp" line="353"/>
</log4j:event>
| 001-log4cxx | trunk/src/test/resources/output/temp.xmlLayout.2 | Roff Manpage | asf20 | 5,288 |
Hello--10
Hello--11
Hello--12
Hello--13
Hello--14
Hello--15
Hello--16
Hello--17
Hello--18
Hello--19
| 001-log4cxx | trunk/src/test/resources/output/manual-test1.1 | Roff Manpage | asf20 | 100 |
Hello---0
Hello---1
Hello---2
Hello---3
Hello---4
Hello---5
Hello---6
Hello---7
Hello---8
Hello---9
| 001-log4cxx | trunk/src/test/resources/output/sizeBased-test5.1 | Roff Manpage | asf20 | 100 |
Hello---0
Hello---1
Hello---2
Hello---3
Hello---4
Hello---5
Hello---6
Hello---7
Hello---8
Hello---9
| 001-log4cxx | trunk/src/test/resources/output/manual-test5.1 | Roff Manpage | asf20 | 100 |
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="1213947943580" level="TRACE" thread="0x000004c8">
<log4j:message><![CDATA[Message with embedded <![CDATA[<hello>hi</hello>]]>]]><![CDATA[.]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="testCDATA" file="C:\log4cxx\src\test\cpp\xml\xmllayouttestcase.cpp" line="172"/>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="1213947943580" level="DEBUG" thread="0x000004c8">
<log4j:message><![CDATA[Message with embedded <![CDATA[<hello>hi</hello>]]>]]><![CDATA[.]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="testCDATA" file="C:\log4cxx\src\test\cpp\xml\xmllayouttestcase.cpp" line="174"/>
</log4j:event>
| 001-log4cxx | trunk/src/test/resources/output/temp.xmlLayout.3 | Roff Manpage | asf20 | 778 |
sQ\[[0-9A-Fa-fXx]*]Q\[main]Qg
sQ[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\} [0-9]\{2\}:[0-9]\{2\}:[0-9]\{2\},[0-9]\{3\}QQg
| 001-log4cxx | trunk/src/test/resources/output/temp.A2.sed | sed | asf20 | 112 |
Hello---0
Hello---1
Hello---2
Hello---3
Hello---4
Hello---5
Hello---6
Hello---7
Hello---8
Hello---9
| 001-log4cxx | trunk/src/test/resources/output/sizeBased-test2.1 | Roff Manpage | asf20 | 100 |
sQ[0-9]\{1,2\} .* 200[0-9] [0-9]\{2\}:[0-9]\{2\}:[0-9]\{2\},[0-9]\{3\}QQg
sQ\[[0-9A-Fa-fXx]*]Q\[main]Qg
| 001-log4cxx | trunk/src/test/resources/output/ttcc.sed | sed | asf20 | 104 |
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase$X" timestamp="XXX" level="INFO" thread="main">
<log4j:message><![CDATA[in X() constructor]]></log4j:message>
<log4j:locationInfo class="X" method="X" file="XMLLayoutTestCase.java" line="X"/>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="XXX" level="TRACE" thread="main">
<log4j:message><![CDATA[Message 0]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="XMLLayoutTestCase.java" line="X"/>
</log4j:event>
<log4j:event logger="root" timestamp="XXX" level="TRACE" thread="main">
<log4j:message><![CDATA[Message 0]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="XMLLayoutTestCase.java" line="X"/>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="XXX" level="DEBUG" thread="main">
<log4j:message><![CDATA[Message 1]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="XMLLayoutTestCase.java" line="X"/>
</log4j:event>
<log4j:event logger="root" timestamp="XXX" level="DEBUG" thread="main">
<log4j:message><![CDATA[Message 1]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="XMLLayoutTestCase.java" line="X"/>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="XXX" level="INFO" thread="main">
<log4j:message><![CDATA[Message 2]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="XMLLayoutTestCase.java" line="X"/>
</log4j:event>
<log4j:event logger="root" timestamp="XXX" level="INFO" thread="main">
<log4j:message><![CDATA[Message 2]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="XMLLayoutTestCase.java" line="X"/>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="XXX" level="WARN" thread="main">
<log4j:message><![CDATA[Message 3]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="XMLLayoutTestCase.java" line="X"/>
</log4j:event>
<log4j:event logger="root" timestamp="XXX" level="WARN" thread="main">
<log4j:message><![CDATA[Message 3]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="XMLLayoutTestCase.java" line="X"/>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="XXX" level="ERROR" thread="main">
<log4j:message><![CDATA[Message 4]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="XMLLayoutTestCase.java" line="X"/>
</log4j:event>
<log4j:event logger="root" timestamp="XXX" level="ERROR" thread="main">
<log4j:message><![CDATA[Message 4]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="XMLLayoutTestCase.java" line="X"/>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="XXX" level="FATAL" thread="main">
<log4j:message><![CDATA[Message 5]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="XMLLayoutTestCase.java" line="X"/>
</log4j:event>
<log4j:event logger="root" timestamp="XXX" level="FATAL" thread="main">
<log4j:message><![CDATA[Message 5]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="XMLLayoutTestCase.java" line="X"/>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="XXX" level="DEBUG" thread="main">
<log4j:message><![CDATA[Message 6]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="XMLLayoutTestCase.java" line="X"/>
</log4j:event>
<log4j:event logger="root" timestamp="XXX" level="DEBUG" thread="main">
<log4j:message><![CDATA[Message 6]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="XMLLayoutTestCase.java" line="X"/>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="XXX" level="ERROR" thread="main">
<log4j:message><![CDATA[Message 7]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="XMLLayoutTestCase.java" line="X"/>
</log4j:event>
<log4j:event logger="root" timestamp="XXX" level="ERROR" thread="main">
<log4j:message><![CDATA[Message 7]]></log4j:message>
<log4j:locationInfo class="XMLLayoutTestCase" method="common" file="XMLLayoutTestCase.java" line="X"/>
</log4j:event>
| 001-log4cxx | trunk/src/test/resources/output/filtered.xmlLayout.2 | Roff Manpage | asf20 | 4,524 |
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase$X" timestamp="1213947943220" level="INFO" thread="0x000004c8">
<log4j:message><![CDATA[in X() constructor]]></log4j:message>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="1213947943220" level="TRACE" thread="0x000004c8">
<log4j:message><![CDATA[Message 0]]></log4j:message>
</log4j:event>
<log4j:event logger="root" timestamp="1213947943220" level="TRACE" thread="0x000004c8">
<log4j:message><![CDATA[Message 0]]></log4j:message>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="1213947943220" level="DEBUG" thread="0x000004c8">
<log4j:message><![CDATA[Message 1]]></log4j:message>
</log4j:event>
<log4j:event logger="root" timestamp="1213947943220" level="DEBUG" thread="0x000004c8">
<log4j:message><![CDATA[Message 1]]></log4j:message>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="1213947943220" level="INFO" thread="0x000004c8">
<log4j:message><![CDATA[Message 2]]></log4j:message>
</log4j:event>
<log4j:event logger="root" timestamp="1213947943220" level="INFO" thread="0x000004c8">
<log4j:message><![CDATA[Message 2]]></log4j:message>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="1213947943230" level="WARN" thread="0x000004c8">
<log4j:message><![CDATA[Message 3]]></log4j:message>
</log4j:event>
<log4j:event logger="root" timestamp="1213947943230" level="WARN" thread="0x000004c8">
<log4j:message><![CDATA[Message 3]]></log4j:message>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="1213947943230" level="ERROR" thread="0x000004c8">
<log4j:message><![CDATA[Message 4]]></log4j:message>
</log4j:event>
<log4j:event logger="root" timestamp="1213947943230" level="ERROR" thread="0x000004c8">
<log4j:message><![CDATA[Message 4]]></log4j:message>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="1213947943230" level="FATAL" thread="0x000004c8">
<log4j:message><![CDATA[Message 5]]></log4j:message>
</log4j:event>
<log4j:event logger="root" timestamp="1213947943230" level="FATAL" thread="0x000004c8">
<log4j:message><![CDATA[Message 5]]></log4j:message>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="1213947943230" level="DEBUG" thread="0x000004c8">
<log4j:message><![CDATA[Message 6]]></log4j:message>
</log4j:event>
<log4j:event logger="root" timestamp="1213947943230" level="DEBUG" thread="0x000004c8">
<log4j:message><![CDATA[Message 6]]></log4j:message>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="1213947943230" level="ERROR" thread="0x000004c8">
<log4j:message><![CDATA[Message 7]]></log4j:message>
</log4j:event>
<log4j:event logger="root" timestamp="1213947943230" level="ERROR" thread="0x000004c8">
<log4j:message><![CDATA[Message 7]]></log4j:message>
</log4j:event>
| 001-log4cxx | trunk/src/test/resources/output/temp.xmlLayout.1 | Roff Manpage | asf20 | 3,049 |
DEBUG xml.DOMTestCase - Message 0
DEBUG xml.DOMTestCase - Message 0
DEBUG root - Message 0
INFO xml.DOMTestCase - Message 1
INFO xml.DOMTestCase - Message 1
INFO root - Message 1
WARN xml.DOMTestCase - Message 2
WARN xml.DOMTestCase - Message 2
WARN root - Message 2
ERROR xml.DOMTestCase - Message 3
ERROR xml.DOMTestCase - Message 3
ERROR root - Message 3
FATAL xml.DOMTestCase - Message 4
FATAL xml.DOMTestCase - Message 4
FATAL root - Message 4
| 001-log4cxx | trunk/src/test/resources/output/filtered.A1.2 | Roff | asf20 | 470 |
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="XXX" level="DEBUG" thread="main">
<log4j:message><![CDATA[Hello]]></log4j:message>
<log4j:properties>
<log4j:data name="<blahKey value='blah'/>" value="blahValue"/>
<log4j:data name="blahAttribute" value="<blah value='blah'>"/>
</log4j:properties>
</log4j:event>
| 001-log4cxx | trunk/src/test/resources/output/filtered.xmlLayout.mdc.2 | Roff Manpage | asf20 | 356 |
sQC:\\log4cxx\\src\\test\\cpp\\xml\\xmllayouttestcase.cppQXMLLayoutTestCase.javaQg
sQthread=\"[0-9A-Fa-fXx]*Qthread=\"mainQg
sQ[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*QXXXQg
sQ1[0-9][0-9]QXQg
| 001-log4cxx | trunk/src/test/resources/output/temp.xmlLayout.3.sed | sed | asf20 | 203 |
Hello--10
Hello--11
Hello--12
Hello--13
Hello--14
Hello--15
Hello--16
Hello--17
Hello--18
Hello--19
| 001-log4cxx | trunk/src/test/resources/output/sizeBased-test1.1 | Roff Manpage | asf20 | 100 |
Hello---0
Hello---1
Hello---2
Hello---3
Hello---4
Hello---5
Hello---6
Hello---7
Hello---8
Hello---9
| 001-log4cxx | trunk/src/test/resources/output/filterBased-test1.1 | Roff Manpage | asf20 | 110 |
Hello---0
Hello---1
Hello---2
Hello---3
Hello---4
Hello---5
Hello---6
Hello---7
Hello---8
Hello---9
| 001-log4cxx | trunk/src/test/resources/output/sizeBased-test1.2 | Roff Manpage | asf20 | 100 |
Hello---0
Hello---1
Hello---2
Hello---3
Hello---4
Hello---5
Hello---6
Hello---7
Hello---8
Hello---9
| 001-log4cxx | trunk/src/test/resources/output/manual-test1.2 | Roff Manpage | asf20 | 100 |
sQthread=\"[0-9A-Fa-fXx]*Qthread=\"mainQg
sQ[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*QXXXQg
| 001-log4cxx | trunk/src/test/resources/output/temp.xmlLayout.mdc.1.sed | sed | asf20 | 102 |
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase$X" timestamp="XXX" level="INFO" thread="main">
<log4j:message><![CDATA[in X() constructor]]></log4j:message>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="XXX" level="TRACE" thread="main">
<log4j:message><![CDATA[Message 0]]></log4j:message>
</log4j:event>
<log4j:event logger="root" timestamp="XXX" level="TRACE" thread="main">
<log4j:message><![CDATA[Message 0]]></log4j:message>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="XXX" level="DEBUG" thread="main">
<log4j:message><![CDATA[Message 1]]></log4j:message>
</log4j:event>
<log4j:event logger="root" timestamp="XXX" level="DEBUG" thread="main">
<log4j:message><![CDATA[Message 1]]></log4j:message>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="XXX" level="INFO" thread="main">
<log4j:message><![CDATA[Message 2]]></log4j:message>
</log4j:event>
<log4j:event logger="root" timestamp="XXX" level="INFO" thread="main">
<log4j:message><![CDATA[Message 2]]></log4j:message>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="XXX" level="WARN" thread="main">
<log4j:message><![CDATA[Message 3]]></log4j:message>
</log4j:event>
<log4j:event logger="root" timestamp="XXX" level="WARN" thread="main">
<log4j:message><![CDATA[Message 3]]></log4j:message>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="XXX" level="ERROR" thread="main">
<log4j:message><![CDATA[Message 4]]></log4j:message>
</log4j:event>
<log4j:event logger="root" timestamp="XXX" level="ERROR" thread="main">
<log4j:message><![CDATA[Message 4]]></log4j:message>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="XXX" level="FATAL" thread="main">
<log4j:message><![CDATA[Message 5]]></log4j:message>
</log4j:event>
<log4j:event logger="root" timestamp="XXX" level="FATAL" thread="main">
<log4j:message><![CDATA[Message 5]]></log4j:message>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="XXX" level="DEBUG" thread="main">
<log4j:message><![CDATA[Message 6]]></log4j:message>
</log4j:event>
<log4j:event logger="root" timestamp="XXX" level="DEBUG" thread="main">
<log4j:message><![CDATA[Message 6]]></log4j:message>
</log4j:event>
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="XXX" level="ERROR" thread="main">
<log4j:message><![CDATA[Message 7]]></log4j:message>
</log4j:event>
<log4j:event logger="root" timestamp="XXX" level="ERROR" thread="main">
<log4j:message><![CDATA[Message 7]]></log4j:message>
</log4j:event>
| 001-log4cxx | trunk/src/test/resources/output/filtered.xmlLayout.1 | Roff Manpage | asf20 | 2,777 |
[main] DEBUG org.apache.log4j.xml.DOMTestCase - Message 0
[main] DEBUG root - Message 0
[main] INFO org.apache.log4j.xml.DOMTestCase - Message 1
[main] INFO root - Message 1
[main] WARN org.apache.log4j.xml.DOMTestCase - Message 2
[main] WARN root - Message 2
[main] ERROR org.apache.log4j.xml.DOMTestCase - Message 3
[main] ERROR root - Message 3
[main] FATAL org.apache.log4j.xml.DOMTestCase - Message 4
[main] FATAL root - Message 4
| 001-log4cxx | trunk/src/test/resources/output/filtered.A2.2 | Roff | asf20 | 456 |
sQC:\\log4cxx\\src\\test\\cpp\\xml\\xmllayouttestcase.cppQXMLLayoutTestCase.javaQg
sQthread=\"[0-9A-Fa-fXx]*Qthread=\"mainQg
sQ[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*QXXXQg
sQ[23][0-9][0-9]QXQg
sQ5[0-9]QXQg
| 001-log4cxx | trunk/src/test/resources/output/temp.xmlLayout.2.sed | sed | asf20 | 219 |
sQthread=\"[0-9A-Fa-fXx]*Qthread=\"mainQg
sQ[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*QXXXQg
| 001-log4cxx | trunk/src/test/resources/output/temp.xmlLayout.mdc.2.sed | sed | asf20 | 102 |
sQthread=\"[0-9A-Fa-fXx]*Qthread=\"mainQg
sQ[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*QXXXQg
| 001-log4cxx | trunk/src/test/resources/output/temp.xmlLayout.null.sed | sed | asf20 | 102 |
DEBUG xml.DOMTestCase - Message 0
DEBUG xml.DOMTestCase - Message 0
DEBUG root - Message 0
INFO xml.DOMTestCase - Message 1
INFO xml.DOMTestCase - Message 1
INFO root - Message 1
WARN xml.DOMTestCase - Message 2
WARN xml.DOMTestCase - Message 2
WARN root - Message 2
ERROR xml.DOMTestCase - Message 3
ERROR xml.DOMTestCase - Message 3
ERROR root - Message 3
FATAL xml.DOMTestCase - Message 4
FATAL xml.DOMTestCase - Message 4
FATAL root - Message 4
| 001-log4cxx | trunk/src/test/resources/output/temp.A1.2 | Roff | asf20 | 470 |
<log4j:event logger="org.apache.log4j.xml.XMLLayoutTestCase" timestamp="1213947943690" level="DEBUG" thread="0x000004c8">
<log4j:message><![CDATA[Hello]]></log4j:message>
<log4j:properties>
<log4j:data name="<blahKey value='blah'/>" value="blahValue"/>
<log4j:data name="blahAttribute" value="<blah value='blah'>"/>
</log4j:properties>
</log4j:event>
| 001-log4cxx | trunk/src/test/resources/output/temp.xmlLayout.mdc.2 | Roff Manpage | asf20 | 372 |
Hello--10nHello--11nHello--12nHello--13nHello--14nHello--15nHello--16nHello--17nHello--18nHello--19n | 001-log4cxx | trunk/src/test/resources/output/obsoleteRFA-test1.log.1 | Roff Manpage | asf20 | 100 |
Hello---0
Hello---1
Hello---2
Hello---3
Hello---4
Hello---5
Hello---6
Hello---7
Hello---8
Hello---9
| 001-log4cxx | trunk/src/test/resources/output/filterBased-test2.1 | Roff Manpage | asf20 | 100 |
2008-06-20 00:46:10,559 [0x000004c8] DEBUG org.apache.log4j.xml.DOMTestCase - Message 0
2008-06-20 00:46:10,559 [0x000004c8] DEBUG root - Message 0
2008-06-20 00:46:10,559 [0x000004c8] INFO org.apache.log4j.xml.DOMTestCase - Message 1
2008-06-20 00:46:10,559 [0x000004c8] INFO root - Message 1
2008-06-20 00:46:10,559 [0x000004c8] WARN org.apache.log4j.xml.DOMTestCase - Message 2
2008-06-20 00:46:10,559 [0x000004c8] WARN root - Message 2
2008-06-20 00:46:10,559 [0x000004c8] ERROR org.apache.log4j.xml.DOMTestCase - Message 3
2008-06-20 00:46:10,559 [0x000004c8] ERROR root - Message 3
2008-06-20 00:46:10,559 [0x000004c8] FATAL org.apache.log4j.xml.DOMTestCase - Message 4
2008-06-20 00:46:10,559 [0x000004c8] FATAL root - Message 4
| 001-log4cxx | trunk/src/test/resources/output/temp.A2.2 | Roff | asf20 | 746 |
starting mdc pattern test
empty mdc, no key specified in pattern : {}
empty mdc, key1 in pattern :
empty mdc, key2 in pattern :
empty mdc, key3 in pattern :
empty mdc, key1, key2, and key3 in pattern : ,,
filled mdc, no key specified in pattern : {{key1,value1}{key2,value2}}
filled mdc, key1 in pattern : value1
filled mdc, key2 in pattern : value2
filled mdc, key3 in pattern :
filled mdc, key1, key2, and key3 in pattern : value1,value2,
finished mdc pattern test
| 001-log4cxx | trunk/src/test/resources/output/patternLayout.mdc.2 | Roff Manpage | asf20 | 483 |
sQ\[[0-9A-Fa-fXx]*]Q\[main]Qg
sQ[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\} [0-9]\{2\}:[0-9]\{2\}:[0-9]\{2\},[0-9]\{3\}QQg
| 001-log4cxx | trunk/src/test/resources/output/temp.A2.2.sed | sed | asf20 | 112 |
/*
* 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 <vector>
#include <log4cxx/spi/loggingevent.h>
namespace log4cxx
{
/**
An appender that appends logging events to a vector.
*/
class VectorAppender : public AppenderSkeleton
{
public:
DECLARE_LOG4CXX_OBJECT(VectorAppender)
BEGIN_LOG4CXX_CAST_MAP()
LOG4CXX_CAST_ENTRY(VectorAppender)
LOG4CXX_CAST_ENTRY_CHAIN(AppenderSkeleton)
END_LOG4CXX_CAST_MAP()
std::vector<spi::LoggingEventPtr> vector;
/**
This method is called by the AppenderSkeleton#doAppend
method.
*/
void append(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p);
const std::vector<spi::LoggingEventPtr>& getVector() const
{ return vector; }
void close();
bool isClosed() const
{ return closed; }
bool requiresLayout() const
{ return false; }
};
typedef helpers::ObjectPtrT<VectorAppender> VectorAppenderPtr;
}
| 001-log4cxx | trunk/src/test/cpp/vectorappender.h | C++ | asf20 | 2,038 |
/*
* 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(LOG4CXX_TEST_INSERT_WIDE)
#define LOG4CXX_TEST_INSERT_WIDE 1
#include <ostream>
#include <string>
#if LOG4CXX_WCHAR_T_API
std::ostream& operator<<(std::ostream& os,
const std::wstring& str);
#endif
#if LOG4CXX_LOGCHAR_IS_UNICHAR || LOG4CXX_UNICHAR_API || LOG4CXX_CFSTRING_API
std::ostream& operator<<(std::ostream& os,
const std::basic_string<log4cxx::UniChar>& str);
#endif
#endif
| 001-log4cxx | trunk/src/test/cpp/insertwide.h | C++ | asf20 | 1,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 "../logunit.h"
#include <log4cxx/logmanager.h>
#include <log4cxx/logger.h>
using namespace log4cxx;
LOGUNIT_CLASS(TestCase1)
{
LOGUNIT_TEST_SUITE(TestCase1);
LOGUNIT_TEST(noneTest);
LOGUNIT_TEST_SUITE_END();
public:
void setUp()
{
}
void tearDown()
{
LogManager::shutdown();
}
void noneTest()
{
LoggerPtr root = Logger::getRootLogger();
LOG4CXX_DEBUG(root, "Hello, world");
bool rootIsConfigured = !root->getAllAppenders().empty();
LOGUNIT_ASSERT(!rootIsConfigured);
}
};
LOGUNIT_TEST_SUITE_REGISTRATION_DISABLED(TestCase1)
| 001-log4cxx | trunk/src/test/cpp/defaultinit/testcase1.cpp | C++ | asf20 | 1,422 |
/*
* 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 <log4cxx/logmanager.h>
#include <log4cxx/logger.h>
#include "../insertwide.h"
#include "../logunit.h"
using namespace log4cxx;
LOGUNIT_CLASS(TestCase2)
{
LOGUNIT_TEST_SUITE(TestCase2);
LOGUNIT_TEST(xmlTest);
LOGUNIT_TEST_SUITE_END();
public:
void setUp()
{
}
void tearDown()
{
LogManager::shutdown();
}
void xmlTest()
{
LoggerPtr root = Logger::getRootLogger();
LOG4CXX_DEBUG(root, "Hello, world");
bool rootIsConfigured = !root->getAllAppenders().empty();
LOGUNIT_ASSERT(rootIsConfigured);
AppenderList list = root->getAllAppenders();
AppenderPtr appender = list.front();
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("D1"), appender->getName());
}
};
LOGUNIT_TEST_SUITE_REGISTRATION_DISABLED(TestCase2)
| 001-log4cxx | trunk/src/test/cpp/defaultinit/testcase2.cpp | C++ | asf20 | 1,683 |
/*
* 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 <log4cxx/logmanager.h>
#include <log4cxx/logger.h>
#include "../insertwide.h"
#include "../logunit.h"
using namespace log4cxx;
LOGUNIT_CLASS(TestCase4)
{
LOGUNIT_TEST_SUITE(TestCase4);
LOGUNIT_TEST(combinedTest);
LOGUNIT_TEST_SUITE_END();
public:
void setUp()
{
}
void tearDown()
{
LogManager::shutdown();
}
void combinedTest()
{
LoggerPtr root = Logger::getRootLogger();
LOG4CXX_DEBUG(root, "Hello, world");
bool rootIsConfigured = !root->getAllAppenders().empty();
LOGUNIT_ASSERT(rootIsConfigured);
AppenderList list = root->getAllAppenders();
LOGUNIT_ASSERT_EQUAL((size_t) 1, list.size());
AppenderPtr appender = list.front();
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("D1"), appender->getName());
}
};
LOGUNIT_TEST_SUITE_REGISTRATION_DISABLED(TestCase4)
| 001-log4cxx | trunk/src/test/cpp/defaultinit/testcase4.cpp | C++ | asf20 | 1,745 |
/*
* 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/logmanager.h>
#include <log4cxx/logger.h>
#include "../insertwide.h"
#include "../logunit.h"
using namespace log4cxx;
LOGUNIT_CLASS(TestCase3)
{
LOGUNIT_TEST_SUITE(TestCase3);
LOGUNIT_TEST(testProperties);
LOGUNIT_TEST_SUITE_END();
public:
void setUp()
{
}
void tearDown()
{
LogManager::shutdown();
}
void testProperties()
{
LoggerPtr root = Logger::getRootLogger();
LOG4CXX_DEBUG(root, "Hello, world");
bool rootIsConfigured = !root->getAllAppenders().empty();
LOGUNIT_ASSERT(rootIsConfigured);
AppenderList list = root->getAllAppenders();
AppenderPtr appender = list.front();
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("D3"), appender->getName());
}
};
LOGUNIT_TEST_SUITE_REGISTRATION_DISABLED(TestCase3)
| 001-log4cxx | trunk/src/test/cpp/defaultinit/testcase3.cpp | C++ | asf20 | 1,625 |
/*
* 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/propertyconfigurator.h>
#include "util/compare.h"
#include "xml/xlevel.h"
#include "logunit.h"
#include "testchar.h"
#include <log4cxx/spi/loggerrepository.h>
using namespace log4cxx;
/**
Test the configuration of the hierarchy-wide threshold.
*/
LOGUNIT_CLASS(HierarchyThresholdTestCase)
{
LOGUNIT_TEST_SUITE(HierarchyThresholdTestCase);
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();
public:
void setUp()
{
}
void tearDown()
{
logger->getLoggerRepository()->resetConfiguration();
}
void test1()
{
PropertyConfigurator::configure(LOG4CXX_FILE("input/hierarchyThreshold1.properties"));
common();
LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/hierarchyThreshold.1")));
}
void test2()
{
PropertyConfigurator::configure(LOG4CXX_FILE("input/hierarchyThreshold2.properties"));
common();
LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/hierarchyThreshold.2")));
}
void test3()
{
PropertyConfigurator::configure(LOG4CXX_FILE("input/hierarchyThreshold3.properties"));
common();
LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/hierarchyThreshold.3")));
}
void test4()
{
PropertyConfigurator::configure(LOG4CXX_FILE("input/hierarchyThreshold4.properties"));
common();
LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/hierarchyThreshold.4")));
}
void test5()
{
PropertyConfigurator::configure(LOG4CXX_FILE("input/hierarchyThreshold5.properties"));
common();
LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/hierarchyThreshold.5")));
}
void test6()
{
PropertyConfigurator::configure(LOG4CXX_FILE("input/hierarchyThreshold6.properties"));
common();
LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/hierarchyThreshold.6")));
}
void test7()
{
PropertyConfigurator::configure(LOG4CXX_FILE("input/hierarchyThreshold7.properties"));
common();
LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/hierarchyThreshold.7")));
}
void test8()
{
PropertyConfigurator::configure(LOG4CXX_FILE("input/hierarchyThreshold8.properties"));
common();
LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/hierarchyThreshold.8")));
}
static void common()
{
logger->log(XLevel::getTrace(), LOG4CXX_TEST_STR("m0"));
logger->debug(LOG4CXX_TEST_STR("m1"));
logger->info(LOG4CXX_TEST_STR("m2"));
logger->warn(LOG4CXX_TEST_STR("m3"));
logger->error(LOG4CXX_TEST_STR("m4"));
logger->fatal(LOG4CXX_TEST_STR("m5"));
}
private:
static File TEMP;
static LoggerPtr logger;
};
File HierarchyThresholdTestCase::TEMP(LOG4CXX_FILE("output/temp"));
LoggerPtr HierarchyThresholdTestCase::logger =
Logger::getLogger(LOG4CXX_TEST_STR("HierarchyThresholdTestCase"));
LOGUNIT_TEST_SUITE_REGISTRATION(HierarchyThresholdTestCase);
| 001-log4cxx | trunk/src/test/cpp/hierarchythresholdtestcase.cpp | C++ | asf20 | 4,020 |
/*
* 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/ndc.h>
#include <log4cxx/file.h>
#include <log4cxx/logger.h>
#include <log4cxx/propertyconfigurator.h>
#include "insertwide.h"
#include "logunit.h"
#include "util/compare.h"
using namespace log4cxx;
LOGUNIT_CLASS(NDCTestCase)
{
static File TEMP;
static LoggerPtr logger;
LOGUNIT_TEST_SUITE(NDCTestCase);
LOGUNIT_TEST(testPushPop);
LOGUNIT_TEST(test1);
LOGUNIT_TEST(testInherit);
LOGUNIT_TEST_SUITE_END();
public:
void setUp() {
}
void tearDown() {
logger->getLoggerRepository()->resetConfiguration();
}
/**
* Push and pop a value from the NDC
*/
void testPushPop()
{
NDC::push("trivial context");
LogString actual(NDC::pop());
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("trivial context"), actual);
}
void test1() {
PropertyConfigurator::configure(File("input/ndc/NDC1.properties"));
common();
LOGUNIT_ASSERT(Compare::compare(TEMP, File("witness/ndc/NDC.1")));
}
static void common() {
commonLog();
NDC::push("n1");
commonLog();
NDC::push("n2");
NDC::push("n3");
commonLog();
NDC::pop();
commonLog();
NDC::clear();
commonLog();
}
static void commonLog() {
LOG4CXX_DEBUG(logger, "m1");
LOG4CXX_INFO(logger, "m2");
LOG4CXX_WARN(logger, "m3");
LOG4CXX_ERROR(logger, "m4");
LOG4CXX_FATAL(logger, "m5");
}
void testInherit() {
NDC::push("hello");
NDC::push("world");
NDC::Stack* clone = NDC::cloneStack();
NDC::clear();
NDC::push("discard");
NDC::inherit(clone);
LogString expected1(LOG4CXX_STR("world"));
LOGUNIT_ASSERT_EQUAL(expected1, NDC::pop());
LogString expected2(LOG4CXX_STR("hello"));
LOGUNIT_ASSERT_EQUAL(expected2, NDC::pop());
LogString expected3;
LOGUNIT_ASSERT_EQUAL(expected3, NDC::pop());
}
};
File NDCTestCase::TEMP("output/temp");
LoggerPtr NDCTestCase::logger(Logger::getLogger("org.apache.log4j.NDCTestCase"));
LOGUNIT_TEST_SUITE_REGISTRATION(NDCTestCase);
| 001-log4cxx | trunk/src/test/cpp/ndctestcase.cpp | C++ | asf20 | 3,262 |
/*
* 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/spi/loggingevent.h>
#include "../util/serializationtesthelper.h"
#include <log4cxx/logmanager.h>
#include <log4cxx/ndc.h>
#include <log4cxx/mdc.h>
#include "../logunit.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::util;
using namespace log4cxx::spi;
using namespace std;
/**
Unit tests for LoggingEvent
*/
LOGUNIT_CLASS(LoggingEventTest)
{
LOGUNIT_TEST_SUITE(LoggingEventTest);
LOGUNIT_TEST(testSerializationSimple);
LOGUNIT_TEST(testSerializationWithLocation);
LOGUNIT_TEST(testSerializationNDC);
LOGUNIT_TEST(testSerializationMDC);
LOGUNIT_TEST_SUITE_END();
public:
void setUp() {
NDC::clear();
MDC::clear();
}
void tearDown()
{
LogManager::shutdown();
}
/**
* Serialize a simple logging event and check it against
* a witness.
* @throws Exception if exception during test.
*/
void testSerializationSimple() {
LoggingEventPtr event =
new LoggingEvent(
LOG4CXX_STR("root"), Level::getInfo(), LOG4CXX_STR("Hello, world."), LocationInfo::getLocationUnavailable());
LOGUNIT_ASSERT_EQUAL(true, SerializationTestHelper::compare(
"witness/serialization/simple.bin", event, 237));
}
/**
* Serialize a logging event with an exception and check it against
* a witness.
* @throws Exception if exception during test.
*
*/
void testSerializationWithLocation() {
LoggingEventPtr event =
new LoggingEvent(
LOG4CXX_STR("root"), Level::getInfo(), LOG4CXX_STR("Hello, world."), LOG4CXX_LOCATION);
LOGUNIT_ASSERT_EQUAL(true, SerializationTestHelper::compare(
"witness/serialization/location.bin", event, 237));
}
/**
* Serialize a logging event with ndc.
* @throws Exception if exception during test.
*
*/
void testSerializationNDC() {
NDC::push("ndc test");
LoggingEventPtr event =
new LoggingEvent(
LOG4CXX_STR("root"), Level::getInfo(), LOG4CXX_STR("Hello, world."), LocationInfo::getLocationUnavailable());
LOGUNIT_ASSERT_EQUAL(true, SerializationTestHelper::compare(
"witness/serialization/ndc.bin", event, 237));
}
/**
* Serialize a logging event with mdc.
* @throws Exception if exception during test.
*
*/
void testSerializationMDC() {
MDC::put("mdckey", "mdcvalue");
LoggingEventPtr event =
new LoggingEvent(
LOG4CXX_STR("root"), Level::getInfo(), LOG4CXX_STR("Hello, world."), LocationInfo::getLocationUnavailable());
LOGUNIT_ASSERT_EQUAL(true, SerializationTestHelper::compare(
"witness/serialization/mdc.bin", event, 237));
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(LoggingEventTest);
| 001-log4cxx | trunk/src/test/cpp/spi/loggingeventtest.cpp | C++ | asf20 | 3,651 |
/*
* 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(_LOG4CXX_LOGUNIT_H)
#define _LOG4CXX_LOGUNIT_H
#if defined(_MSC_VER)
#pragma warning (push)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include "abts.h"
#include <exception>
#include <map>
#include <string>
#include <vector>
#include <log4cxx/logstring.h>
namespace LogUnit {
class TestException : public std::exception {
public:
TestException();
TestException(const TestException&);
TestException& operator=(const TestException&);
};
class AssertException : public std::exception {
public:
AssertException(std::string msg, int lineno);
AssertException(bool expected, const char* actualExpr, int lineno);
AssertException(const AssertException&);
AssertException& operator=(const AssertException&);
virtual ~AssertException() throw();
std::string getMessage() const;
int getLine() const;
private:
std::string msg;
int lineno;
};
class TestFixture {
public:
TestFixture();
virtual ~TestFixture();
void setCase(abts_case* tc);
virtual void setUp();
virtual void tearDown();
void assertEquals(const int expected, const int actual, int lineno);
void assertEquals(const std::string expected,
const std::string actual,
const char* expectedExpr,
const char* actualExpr,
int lineno);
void assertEquals(const char* expected,
const char* actual,
const char* expectedExpr,
const char* actualExpr,
int lineno);
#if LOG4CXX_LOGCHAR_IS_WCHAR || LOG4CXX_WCHAR_T_API
void assertEquals(const std::wstring expected,
const std::wstring actual,
const char* expectedExpr,
const char* actualExpr,
int lineno);
#endif
#if LOG4CXX_LOGCHAR_IS_UNICHAR || LOG4CXX_UNICHAR_API || LOG4CXX_CFSTRING_API
void assertEquals(const std::basic_string<log4cxx::UniChar> expected,
const std::basic_string<log4cxx::UniChar> actual,
const char* expectedExpr,
const char* actualExpr, int lineno);
#endif
template<class T>
void assertEquals(const T& expected,
const T& actual,
const char* expectedExpr,
const char* actualExpr,
int lineno) {
if (expected != actual) {
std::string msg(expectedExpr);
msg.append(" != ");
msg.append(actualExpr);
abts_fail(tc, msg.c_str(), lineno);
}
}
private:
TestFixture(const TestFixture&);
TestFixture& operator=(const TestFixture&);
abts_case* tc;
};
template<class T>
void runTest(abts_case* tc, void (T::*func)()) {
T ti;
ti.setCase(tc);
ti.setUp();
try {
(ti.*func)();
} catch(TestException&) {
} catch(AssertException& fx) {
abts_fail(tc, fx.getMessage().c_str(), fx.getLine());
} catch(...) {
abts_fail(tc, "Unexpected exception", -1);
}
ti.tearDown();
}
template<class T, class X>
void runTestWithException(abts_case* tc, void (T::*func)()) {
T ti;
ti.setCase(tc);
ti.setUp();
try {
(ti.*func)();
} catch(TestException&) {
} catch(AssertException& fx) {
abts_fail(tc, fx.getMessage().c_str(), fx.getLine());
} catch(X&) {
} catch(...) {
abts_fail(tc, "Unexpected exception", -1);
}
ti.tearDown();
}
class TestSuite {
public:
TestSuite(const char* filename);
void addTest(const char* testName, test_func func);
abts_suite* run(abts_suite* suite) const;
std::string getName() const;
void setDisabled(bool newVal);
bool isDisabled() const;
private:
TestSuite(const TestSuite&);
TestSuite& operator=(const TestSuite&);
typedef std::vector<test_func> TestList;
TestList test_funcs;
std::string filename;
bool disabled;
};
typedef std::vector< std::pair<std::string, const TestSuite*> > SuiteList;
SuiteList& getAllSuites();
template<class T>
class RegisterSuite {
public:
RegisterSuite() {
T::populateSuite();
TestSuite* suite = T::getSuite();
LogUnit::getAllSuites().push_back(SuiteList::value_type(suite->getName(), suite));
}
};
template<class T>
class RegisterDisabledSuite {
public:
RegisterDisabledSuite() {
T::populateSuite();
TestSuite* suite = T::getSuite();
suite->setDisabled(true);
LogUnit::getAllSuites().push_back(SuiteList::value_type(suite->getName(), suite));
}
};
}
#define LOGUNIT_CLASS(x) class x : public LogUnit::TestFixture
#define LOGUNIT_TEST_SUITE(TF) \
public: \
static LogUnit::TestSuite* getSuite() { \
static LogUnit::TestSuite suite(__FILE__); \
return &suite; \
} \
private: \
class RegisterSuite { \
public: \
typedef TF ThisFixture;
#define LOGUNIT_TEST(testName) \
class testName ## Registration { \
public: \
testName ## Registration() { \
ThisFixture::getSuite()->addTest(#testName, &testName ## Registration :: run); \
} \
static void run(abts_case* tc, void*) { \
LogUnit::runTest<ThisFixture>(tc, &ThisFixture::testName); \
} \
} register ## testName;
#define LOGUNIT_TEST_EXCEPTION(testName, Exception) \
class testName ## Registration { \
public: \
testName ## Registration() { \
ThisFixture::getSuite()->addTest(#testName, &testName ## Registration :: run); \
} \
static void run(abts_case* tc, void*) { \
LogUnit::runTestWithException<ThisFixture, Exception>(tc, &ThisFixture::testName); \
} \
} register ## testName;
#define LOGUNIT_TEST_SUITE_END() \
}; \
public: \
static void populateSuite() { \
static RegisterSuite registration; \
}
#define LOGUNIT_TEST_SUITE_REGISTRATION(TF) \
static LogUnit::RegisterSuite<TF> registration;
#define LOGUNIT_TEST_SUITE_REGISTRATION_DISABLED(TF) \
static LogUnit::RegisterDisabledSuite<TF> registration;
#define LOGUNIT_ASSERT(x) { if (!(x)) throw LogUnit::AssertException(true, #x, __LINE__); }
#define LOGUNIT_ASSERT_EQUAL(expected, actual) assertEquals(expected, actual, #expected, #actual, __LINE__)
#define LOGUNIT_FAIL(msg) throw LogUnit::AssertException(msg, __LINE__)
#if defined(_MSC_VER)
#pragma warning (pop)
#endif
#endif
| 001-log4cxx | trunk/src/test/cpp/logunit.h | C++ | asf20 | 8,196 |
/*
* 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/inetaddress.h>
#include "../logunit.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
LOGUNIT_CLASS(InetAddressTestCase)
{
LOGUNIT_TEST_SUITE(InetAddressTestCase);
LOGUNIT_TEST(testGetLocalHost);
LOGUNIT_TEST(testByNameLocal);
LOGUNIT_TEST(testAllByNameLocal);
LOGUNIT_TEST(testUnreachable);
LOGUNIT_TEST_SUITE_END();
public:
/**
* Tests the InetAddress::getLocalHost() method.
*/
void testGetLocalHost() {
InetAddressPtr addr = InetAddress::getLocalHost();
LOGUNIT_ASSERT(addr->getHostAddress() == LOG4CXX_STR("127.0.0.1"));
LOGUNIT_ASSERT(!addr->getHostName().empty());
}
/**
* Tests the InetAddress::getByName() method with the
* "localhost" host name.
*/
void testByNameLocal() {
InetAddressPtr addr = InetAddress::getByName(LOG4CXX_STR("localhost"));
LOGUNIT_ASSERT(addr->getHostAddress() == LOG4CXX_STR("127.0.0.1"));
LOGUNIT_ASSERT(!addr->getHostName().empty());
}
/**
* Tests the InetAddress::getAllByName() method with the
* "localhost" host name.
*/
void testAllByNameLocal() {
std::vector<InetAddressPtr> addr = InetAddress::getAllByName(LOG4CXX_STR("localhost"));
LOGUNIT_ASSERT(addr.size() > 0);
}
/**
* Tests the UnknownHostException.
*/
void testUnknownHost() {
InetAddressPtr addr = InetAddress::getByName(LOG4CXX_STR("unknown.invalid"));
}
/**
* Tests an (likely) unreachable address.
*/
void testUnreachable() {
InetAddressPtr addr(InetAddress::getByName(LOG4CXX_STR("192.168.10.254")));
LogString addrStr(addr->toString());
LOGUNIT_ASSERT_EQUAL(addrStr.size() - 15, addrStr.find(LOG4CXX_STR("/192.168.10.254")));
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(InetAddressTestCase);
| 001-log4cxx | trunk/src/test/cpp/helpers/inetaddresstestcase.cpp | C++ | asf20 | 2,860 |
/*
* 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/helpers/syslogwriter.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
LOGUNIT_CLASS(SyslogWriterTest)
{
LOGUNIT_TEST_SUITE(SyslogWriterTest);
LOGUNIT_TEST(testUnknownHost);
LOGUNIT_TEST_SUITE_END();
public:
/**
* Tests writing to an unknown host.
*/
void testUnknownHost() {
SyslogWriter writer(LOG4CXX_STR("unknown.invalid"));
writer.write(LOG4CXX_STR("Hello, Unknown World."));
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(SyslogWriterTest);
| 001-log4cxx | trunk/src/test/cpp/helpers/syslogwritertest.cpp | C++ | asf20 | 1,405 |
/*
* 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/charsetdecoder.h>
#include "../logunit.h"
#include "../insertwide.h"
#include <log4cxx/helpers/bytebuffer.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
#define APR_SUCCESS ((log4cxx_status_t) 0)
LOGUNIT_CLASS(CharsetDecoderTestCase)
{
LOGUNIT_TEST_SUITE(CharsetDecoderTestCase);
LOGUNIT_TEST(decode1);
LOGUNIT_TEST(decode2);
LOGUNIT_TEST(decode8);
LOGUNIT_TEST_SUITE_END();
enum { BUFSIZE = 256 };
public:
void decode1() {
char buf[] = "Hello, World";
ByteBuffer src(buf, strlen(buf));
CharsetDecoderPtr dec(CharsetDecoder::getDefaultDecoder());
LogString greeting;
log4cxx_status_t stat = dec->decode(src, greeting);
LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat);
stat = dec->decode(src, greeting);
LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat);
LOGUNIT_ASSERT_EQUAL((size_t) 12, src.position());
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("Hello, World"), greeting);
}
void decode2() {
char buf[BUFSIZE + 6];
memset(buf, 'A', BUFSIZE);
buf[BUFSIZE - 3] = 0;
#if defined(__STDC_LIB_EXT1__) || defined(__STDC_SECURE_LIB__)
strcat_s(buf, sizeof buf, "Hello");
#else
strcat(buf, "Hello");
#endif
ByteBuffer src(buf, strlen(buf));
CharsetDecoderPtr dec(CharsetDecoder::getDefaultDecoder());
LogString greeting;
log4cxx_status_t stat = dec->decode(src, greeting);
LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat);
LOGUNIT_ASSERT_EQUAL((size_t) 0, src.remaining());
stat = dec->decode(src, greeting);
LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat);
LogString manyAs(BUFSIZE - 3, LOG4CXX_STR('A'));
LOGUNIT_ASSERT_EQUAL(manyAs, greeting.substr(0, BUFSIZE - 3));
LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("Hello")), greeting.substr(BUFSIZE - 3));
}
void decode8() {
char buf[] = { 'H', 'e', 'l', 'l', 'o', ',', 0, 'W', 'o', 'r', 'l', 'd'};
ByteBuffer src(buf, 12);
CharsetDecoderPtr dec(CharsetDecoder::getDefaultDecoder());
LogString greeting;
log4cxx_status_t stat = dec->decode(src, greeting);
LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat);
stat = dec->decode(src, greeting);
LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat);
LOGUNIT_ASSERT_EQUAL((size_t) 12, src.position());
const logchar expected[] = { 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x2C, 0x00, 0x57, 0x6F, 0x72, 0x6C, 0x64 };
LOGUNIT_ASSERT_EQUAL(LogString(expected, 12), greeting);
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(CharsetDecoderTestCase);
| 001-log4cxx | trunk/src/test/cpp/helpers/charsetdecodertestcase.cpp | C++ | asf20 | 3,620 |
/*
* 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/messagebuffer.h>
#include <iomanip>
#include "../insertwide.h"
#include "../logunit.h"
#include <log4cxx/logstring.h>
#if LOG4CXX_CFSTRING_API
#include <CoreFoundation/CFString.h>
#endif
using namespace log4cxx;
using namespace log4cxx::helpers;
/**
* Test MessageBuffer.
*/
LOGUNIT_CLASS(MessageBufferTest)
{
LOGUNIT_TEST_SUITE(MessageBufferTest);
LOGUNIT_TEST(testInsertChar);
LOGUNIT_TEST(testInsertConstStr);
LOGUNIT_TEST(testInsertStr);
LOGUNIT_TEST(testInsertString);
LOGUNIT_TEST(testInsertNull);
LOGUNIT_TEST(testInsertInt);
LOGUNIT_TEST(testInsertManipulator);
#if LOG4CXX_WCHAR_T_API
LOGUNIT_TEST(testInsertConstWStr);
LOGUNIT_TEST(testInsertWString);
LOGUNIT_TEST(testInsertWStr);
#endif
#if LOG4CXX_UNICHAR_API
LOGUNIT_TEST(testInsertConstUStr);
LOGUNIT_TEST(testInsertUString);
#endif
#if LOG4CXX_CFSTRING_API
LOGUNIT_TEST(testInsertCFString);
#endif
LOGUNIT_TEST_SUITE_END();
public:
void testInsertChar() {
MessageBuffer buf;
std::string greeting("Hello, World");
CharMessageBuffer& retval = buf << "Hello, Worl" << 'd';
LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval));
LOGUNIT_ASSERT_EQUAL(false, buf.hasStream());
}
void testInsertConstStr() {
MessageBuffer buf;
std::string greeting("Hello, World");
CharMessageBuffer& retval = buf << "Hello" << ", World";
LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval));
LOGUNIT_ASSERT_EQUAL(false, buf.hasStream());
}
void testInsertStr() {
MessageBuffer buf;
std::string greeting("Hello, World");
char* part1 = (char*) malloc(10*sizeof(wchar_t));
strcpy(part1, "Hello");
char* part2 = (char*) malloc(10*sizeof(wchar_t));
strcpy(part2, ", World");
CharMessageBuffer& retval = buf << part1 << part2;
free(part1);
free(part2);
LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval));
LOGUNIT_ASSERT_EQUAL(false, buf.hasStream());
}
void testInsertString() {
MessageBuffer buf;
std::string greeting("Hello, World");
CharMessageBuffer& retval = buf << std::string("Hello") << std::string(", World");
LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval));
LOGUNIT_ASSERT_EQUAL(false, buf.hasStream());
}
void testInsertNull() {
MessageBuffer buf;
std::string greeting("Hello, null");
CharMessageBuffer& retval = buf << "Hello, " << (const char*) 0;
LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval));
LOGUNIT_ASSERT_EQUAL(false, buf.hasStream());
}
void testInsertInt() {
MessageBuffer buf;
std::string greeting("Hello, 5");
std::ostream& retval = buf << "Hello, " << 5;
LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval));
LOGUNIT_ASSERT_EQUAL(true, buf.hasStream());
}
void testInsertManipulator() {
MessageBuffer buf;
std::string greeting("pi=3.142");
std::ostream& retval = buf << "pi=" << std::setprecision(4) << 3.1415926;
LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval));
LOGUNIT_ASSERT_EQUAL(true, buf.hasStream());
}
#if LOG4CXX_WCHAR_T_API
void testInsertConstWStr() {
MessageBuffer buf;
std::wstring greeting(L"Hello, World");
WideMessageBuffer& retval = buf << L"Hello" << L", World";
LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval));
LOGUNIT_ASSERT_EQUAL(false, buf.hasStream());
}
void testInsertWString() {
MessageBuffer buf;
std::wstring greeting(L"Hello, World");
WideMessageBuffer& retval = buf << std::wstring(L"Hello") << std::wstring(L", World");
LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval));
LOGUNIT_ASSERT_EQUAL(false, buf.hasStream());
}
void testInsertWStr() {
MessageBuffer buf;
std::wstring greeting(L"Hello, World");
wchar_t* part1 = (wchar_t*) malloc(10*sizeof(wchar_t));
wcscpy(part1, L"Hello");
wchar_t* part2 = (wchar_t*) malloc(10*sizeof(wchar_t));
wcscpy(part2, L", World");
WideMessageBuffer& retval = buf << part1 << part2;
free(part1);
free(part2);
LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval));
LOGUNIT_ASSERT_EQUAL(false, buf.hasStream());
}
#endif
#if LOG4CXX_UNICHAR_API
void testInsertConstUStr() {
MessageBuffer buf;
const log4cxx::UniChar hello[] = { 'H', 'e', 'l', 'l', 'o', 0 };
const log4cxx::UniChar world[] = { ',', ' ', 'W', 'o', 'r', 'l', 'd', 0 };
const log4cxx::UniChar greeting[] = { 'H', 'e', 'l', 'l', 'o',
',', ' ', 'W', 'o', 'r', 'l', 'd', 0 };
UniCharMessageBuffer& retval = buf << hello << world;
LOGUNIT_ASSERT_EQUAL(std::basic_string<log4cxx::UniChar>(greeting), buf.str(retval));
LOGUNIT_ASSERT_EQUAL(false, buf.hasStream());
}
void testInsertUString() {
MessageBuffer buf;
const log4cxx::UniChar hello[] = { 'H', 'e', 'l', 'l', 'o', 0 };
const log4cxx::UniChar world[] = { ',', ' ', 'W', 'o', 'r', 'l', 'd', 0 };
const log4cxx::UniChar greeting[] = { 'H', 'e', 'l', 'l', 'o',
',', ' ', 'W', 'o', 'r', 'l', 'd', 0 };
UniCharMessageBuffer& retval = buf << std::basic_string<log4cxx::UniChar>(hello)
<< std::basic_string<log4cxx::UniChar>(world);
LOGUNIT_ASSERT_EQUAL(std::basic_string<log4cxx::UniChar>(greeting), buf.str(retval));
LOGUNIT_ASSERT_EQUAL(false, buf.hasStream());
}
#endif
#if LOG4CXX_CFSTRING_API
void testInsertCFString() {
MessageBuffer buf;
const log4cxx::UniChar greeting[] = { 'H', 'e', 'l', 'l', 'o',
',', ' ', 'W', 'o', 'r', 'l', 'd', 0 };
UniCharMessageBuffer& retval = buf << CFSTR("Hello")
<< CFSTR(", World");
LOGUNIT_ASSERT_EQUAL(std::basic_string<log4cxx::UniChar>(greeting), buf.str(retval));
LOGUNIT_ASSERT_EQUAL(false, buf.hasStream());
}
#endif
};
LOGUNIT_TEST_SUITE_REGISTRATION(MessageBufferTest);
| 001-log4cxx | trunk/src/test/cpp/helpers/messagebuffertest.cpp | C++ | asf20 | 7,101 |
/*
* 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>
#include <log4cxx/helpers/timezone.h>
#include "../insertwide.h"
#include "../logunit.h"
#include <apr_time.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
//Define INT64_C for compilers that don't have it
#if (!defined(INT64_C))
#define INT64_C(value) value ## LL
#endif
/**
Unit test {@link TimeZone}.
*/
LOGUNIT_CLASS(TimeZoneTestCase) {
LOGUNIT_TEST_SUITE(TimeZoneTestCase);
LOGUNIT_TEST(test1);
LOGUNIT_TEST(test2);
#if !defined(__BORLANDC__)
LOGUNIT_TEST(test3);
#endif
LOGUNIT_TEST(test4);
LOGUNIT_TEST(test5);
LOGUNIT_TEST(test6);
LOGUNIT_TEST_SUITE_END();
#define MICROSECONDS_PER_DAY APR_INT64_C(86400000000)
public:
/**
* Checks the GMT timezone
*/
void test1() {
TimeZonePtr tz(TimeZone::getGMT());
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("GMT"), tz->getID());
}
/**
* Get "GMT-6" time zone
*/
void test2() {
TimeZonePtr tz(TimeZone::getTimeZone(LOG4CXX_STR("GMT-6")));
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("GMT-06:00"), tz->getID());
apr_time_t jan2 = MICROSECONDS_PER_DAY * 12420;
apr_time_exp_t exploded;
tz->explode(&exploded, jan2);
LOGUNIT_ASSERT_EQUAL(-6 * 3600, exploded.tm_gmtoff);
LOGUNIT_ASSERT_EQUAL(18, exploded.tm_hour);
}
/**
* Get the default timezone name
*/
void test3() {
TimeZonePtr tz(TimeZone::getDefault());
LogString tzName(tz->getID());
LOGUNIT_ASSERT(tzName.length() > 0);
}
/**
* Get "GMT+0010" time zone
*/
void test4() {
TimeZonePtr tz(TimeZone::getTimeZone(LOG4CXX_STR("GMT+0010")));
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("GMT+00:10"), tz->getID());
apr_time_t jan2 = MICROSECONDS_PER_DAY * 12420;
apr_time_exp_t exploded;
tz->explode(&exploded, jan2);
LOGUNIT_ASSERT_EQUAL(600, exploded.tm_gmtoff);
LOGUNIT_ASSERT_EQUAL(0, exploded.tm_hour);
LOGUNIT_ASSERT_EQUAL(10, exploded.tm_min);
}
/**
* Get "GMT+6" time zone
*/
void test5() {
TimeZonePtr tz(TimeZone::getTimeZone(LOG4CXX_STR("GMT+6")));
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("GMT+06:00"), tz->getID());
apr_time_t jan2 = MICROSECONDS_PER_DAY * 12420;
apr_time_exp_t exploded;
tz->explode(&exploded, jan2);
LOGUNIT_ASSERT_EQUAL(6 * 3600, exploded.tm_gmtoff);
LOGUNIT_ASSERT_EQUAL(6, exploded.tm_hour);
}
/**
* Checks the GMT timezone
*/
void test6() {
TimeZonePtr tz(TimeZone::getTimeZone(LOG4CXX_STR("GMT")));
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("GMT"), tz->getID());
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(TimeZoneTestCase);
| 001-log4cxx | trunk/src/test/cpp/helpers/timezonetestcase.cpp | C++ | asf20 | 3,430 |
/*
* 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>
#include <log4cxx/helpers/stringhelper.h>
#include "../insertwide.h"
#include "../logunit.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
/**
Unit test for StringHelper.
*/
LOGUNIT_CLASS(StringHelperTestCase)
{
LOGUNIT_TEST_SUITE( StringHelperTestCase );
LOGUNIT_TEST( testStartsWith1 );
LOGUNIT_TEST( testStartsWith2 );
LOGUNIT_TEST( testStartsWith3 );
LOGUNIT_TEST( testStartsWith4 );
LOGUNIT_TEST( testStartsWith5 );
LOGUNIT_TEST( testEndsWith1 );
LOGUNIT_TEST( testEndsWith2 );
LOGUNIT_TEST( testEndsWith3 );
LOGUNIT_TEST( testEndsWith4 );
LOGUNIT_TEST( testEndsWith5 );
LOGUNIT_TEST_SUITE_END();
public:
/**
* Check that startsWith("foobar", "foo") returns true.
*/
void testStartsWith1() {
LOGUNIT_ASSERT_EQUAL(true, StringHelper::startsWith(LOG4CXX_STR("foobar"), LOG4CXX_STR("foo")));
}
/**
* Check that startsWith("bar", "foobar") returns false.
*/
void testStartsWith2() {
LOGUNIT_ASSERT_EQUAL(false, StringHelper::startsWith(LOG4CXX_STR("foo"), LOG4CXX_STR("foobar")));
}
/**
* Check that startsWith("foobar", "foobar") returns true.
*/
void testStartsWith3() {
LOGUNIT_ASSERT_EQUAL(true, StringHelper::startsWith(LOG4CXX_STR("foobar"), LOG4CXX_STR("foobar")));
}
/**
* Check that startsWith("foobar", "") returns true.
*/
void testStartsWith4() {
LOGUNIT_ASSERT_EQUAL(true, StringHelper::startsWith(LOG4CXX_STR("foobar"), LOG4CXX_STR("")));
}
/**
* Check that startsWith("foobar", "abc") returns false.
*/
void testStartsWith5() {
LOGUNIT_ASSERT_EQUAL(false, StringHelper::startsWith(LOG4CXX_STR("foobar"), LOG4CXX_STR("abc")));
}
/**
* Check that endsWith("foobar", "bar") returns true.
*/
void testEndsWith1() {
LOGUNIT_ASSERT_EQUAL(true, StringHelper::endsWith(LOG4CXX_STR("foobar"), LOG4CXX_STR("bar")));
}
/**
* Check that endsWith("bar", "foobar") returns false.
*/
void testEndsWith2() {
LOGUNIT_ASSERT_EQUAL(false, StringHelper::endsWith(LOG4CXX_STR("bar"), LOG4CXX_STR("foobar")));
}
/**
* Check that endsWith("foobar", "foobar") returns true.
*/
void testEndsWith3() {
LOGUNIT_ASSERT_EQUAL(true, StringHelper::endsWith(LOG4CXX_STR("foobar"), LOG4CXX_STR("foobar")));
}
/**
* Check that endsWith("foobar", "") returns true.
*/
void testEndsWith4() {
LOGUNIT_ASSERT_EQUAL(true, StringHelper::endsWith(LOG4CXX_STR("foobar"), LOG4CXX_STR("")));
}
/**
* Check that endsWith("foobar", "abc") returns false.
*/
void testEndsWith5() {
LOGUNIT_ASSERT_EQUAL(false, StringHelper::startsWith(LOG4CXX_STR("foobar"), LOG4CXX_STR("abc")));
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(StringHelperTestCase);
| 001-log4cxx | trunk/src/test/cpp/helpers/stringhelpertestcase.cpp | C++ | asf20 | 3,611 |
/*
* 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/charsetencoder.h>
#include "../logunit.h"
#include "../insertwide.h"
#include <log4cxx/helpers/bytebuffer.h>
#include <log4cxx/helpers/thread.h>
#include <log4cxx/helpers/mutex.h>
#include <log4cxx/helpers/condition.h>
#include <log4cxx/helpers/synchronized.h>
#include <apr.h>
#include <apr_atomic.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
LOGUNIT_CLASS(CharsetEncoderTestCase)
{
LOGUNIT_TEST_SUITE(CharsetEncoderTestCase);
LOGUNIT_TEST(encode1);
LOGUNIT_TEST(encode2);
LOGUNIT_TEST(encode3);
LOGUNIT_TEST(encode4);
#if APR_HAS_THREADS
LOGUNIT_TEST(thread1);
#endif
LOGUNIT_TEST_SUITE_END();
enum { BUFSIZE = 256 };
public:
void encode1() {
const LogString greeting(LOG4CXX_STR("Hello, World"));
CharsetEncoderPtr enc(CharsetEncoder::getEncoder(LOG4CXX_STR("US-ASCII")));
char buf[BUFSIZE];
ByteBuffer out(buf, BUFSIZE);
LogString::const_iterator iter = greeting.begin();
log4cxx_status_t stat = enc->encode(greeting, iter, out);
LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat);
LOGUNIT_ASSERT(iter == greeting.end());
stat = enc->encode(greeting, iter, out);
LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat);
LOGUNIT_ASSERT_EQUAL((size_t) 12, out.position());
out.flip();
std::string encoded((const char*) out.data(), out.limit());
LOGUNIT_ASSERT_EQUAL((std::string) "Hello, World", encoded);
LOGUNIT_ASSERT(iter == greeting.end());
}
void encode2() {
LogString greeting(BUFSIZE - 3, LOG4CXX_STR('A'));
greeting.append(LOG4CXX_STR("Hello"));
CharsetEncoderPtr enc(CharsetEncoder::getEncoder(LOG4CXX_STR("US-ASCII")));
char buf[BUFSIZE];
ByteBuffer out(buf, BUFSIZE);
LogString::const_iterator iter = greeting.begin();
log4cxx_status_t stat = enc->encode(greeting, iter, out);
LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat);
LOGUNIT_ASSERT_EQUAL((size_t) 0, out.remaining());
LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR('o'), *(iter+1));
out.flip();
std::string encoded((char*) out.data(), out.limit());
out.clear();
stat = enc->encode(greeting, iter, out);
LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat);
LOGUNIT_ASSERT_EQUAL((size_t) 2, out.position());
LOGUNIT_ASSERT(iter == greeting.end());
stat = enc->encode(greeting, iter, out);
out.flip();
LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat);
encoded.append(out.data(), out.limit());
std::string manyAs(BUFSIZE - 3, 'A');
LOGUNIT_ASSERT_EQUAL(manyAs, encoded.substr(0, BUFSIZE - 3));
LOGUNIT_ASSERT_EQUAL(std::string("Hello"), encoded.substr(BUFSIZE - 3));
}
void encode3() {
#if LOG4CXX_LOGCHAR_IS_WCHAR || LOG4CXX_LOGCHAR_IS_UNICHAR
// arbitrary, hopefully meaningless, characters from
// Latin, Arabic, Armenian, Bengali, CJK and Cyrillic
const logchar greet[] = { L'A', 0x0605, 0x0530, 0x986, 0x4E03, 0x400, 0 };
#endif
#if LOG4CXX_LOGCHAR_IS_UTF8
const char greet[] = { 'A',
(char) 0xD8, (char) 0x85,
(char) 0xD4, (char) 0xB0,
(char) 0xE0, (char) 0xA6, (char) 0x86,
(char) 0xE4, (char) 0xB8, (char) 0x83,
(char) 0xD0, (char) 0x80,
0 };
#endif
LogString greeting(greet);
CharsetEncoderPtr enc(CharsetEncoder::getEncoder(LOG4CXX_STR("US-ASCII")));
char buf[BUFSIZE];
ByteBuffer out(buf, BUFSIZE);
LogString::const_iterator iter = greeting.begin();
log4cxx_status_t stat = enc->encode(greeting, iter, out);
out.flip();
LOGUNIT_ASSERT_EQUAL(true, CharsetEncoder::isError(stat));
LOGUNIT_ASSERT_EQUAL((size_t) 1, out.limit());
LOGUNIT_ASSERT_EQUAL(greet[1], *iter);
LOGUNIT_ASSERT_EQUAL('A', out.data()[0]);
}
void encode4() {
const char utf8_greet[] = { 'A',
(char) 0xD8, (char) 0x85,
(char) 0xD4, (char) 0xB0,
(char) 0xE0, (char) 0xA6, (char) 0x86,
(char) 0xE4, (char) 0xB8, (char) 0x83,
(char) 0xD0, (char) 0x80,
0 };
#if LOG4CXX_LOGCHAR_IS_WCHAR || LOG4CXX_LOGCHAR_IS_UNICHAR
// arbitrary, hopefully meaningless, characters from
// Latin, Arabic, Armenian, Bengali, CJK and Cyrillic
const logchar greet[] = { L'A', 0x0605, 0x0530, 0x986, 0x4E03, 0x400, 0 };
#endif
#if LOG4CXX_LOGCHAR_IS_UTF8
const logchar *greet = utf8_greet;
#endif
LogString greeting(greet);
CharsetEncoderPtr enc(CharsetEncoder::getEncoder(LOG4CXX_STR("UTF-8")));
char buf[BUFSIZE];
ByteBuffer out(buf, BUFSIZE);
LogString::const_iterator iter = greeting.begin();
log4cxx_status_t stat = enc->encode(greeting, iter, out);
LOGUNIT_ASSERT_EQUAL(false, CharsetEncoder::isError(stat));
stat = enc->encode(greeting, iter, out);
LOGUNIT_ASSERT_EQUAL(false, CharsetEncoder::isError(stat));
out.flip();
LOGUNIT_ASSERT_EQUAL((size_t) 13, out.limit());
for(size_t i = 0; i < out.limit(); i++) {
LOGUNIT_ASSERT_EQUAL((int) utf8_greet[i], (int) out.data()[i]);
}
LOGUNIT_ASSERT(iter == greeting.end());
}
#if APR_HAS_THREADS
class ThreadPackage {
public:
ThreadPackage(CharsetEncoderPtr& enc, int repetitions) :
p(), lock(p), condition(p), passCount(0), failCount(0), enc(enc), repetitions(repetitions) {
}
void await() {
synchronized sync(lock);
condition.await(lock);
}
void signalAll() {
synchronized sync(lock);
condition.signalAll();
}
void fail() {
apr_atomic_inc32(&failCount);
}
void pass() {
apr_atomic_inc32(&passCount);
}
apr_uint32_t getFail() {
return apr_atomic_read32(&failCount);
}
apr_uint32_t getPass() {
return apr_atomic_read32(&passCount);
}
int getRepetitions() {
return repetitions;
}
CharsetEncoderPtr& getEncoder() {
return enc;
}
private:
ThreadPackage(const ThreadPackage&);
ThreadPackage& operator=(ThreadPackage&);
Pool p;
Mutex lock;
Condition condition;
volatile apr_uint32_t passCount;
volatile apr_uint32_t failCount;
CharsetEncoderPtr enc;
int repetitions;
};
static void* LOG4CXX_THREAD_FUNC thread1Action(apr_thread_t* /* thread */, void* data) {
ThreadPackage* package = (ThreadPackage*) data;
#if LOG4CXX_LOGCHAR_IS_UTF8
const logchar greet[] = { 'H', 'e', 'l', 'l', 'o', ' ',
(char) 0xC2, (char) 0xA2, // cent sign
(char) 0xC2, (char) 0xA9, // copyright
(char) 0xc3, (char) 0xb4, // latin small letter o with circumflex
0 };
#endif
#if LOG4CXX_LOGCHAR_IS_WCHAR || LOG4CXX_LOGCHAR_IS_UNICHAR
// arbitrary, hopefully meaningless, characters from
// Latin, Arabic, Armenian, Bengali, CJK and Cyrillic
const logchar greet[] = { L'H', L'e', L'l', L'l', L'o', L' ',
0x00A2, 0x00A9, 0x00F4 , 0 };
#endif
const char expected[] = { 'H', 'e', 'l', 'l', 'o', ' ',
(char) 0x00A2, (char) 0x00A9, (char) 0x00F4 };
LogString greeting(greet);
package->await();
for(int i = 0; i < package->getRepetitions(); i++) {
bool pass = true;
char buf[BUFSIZE];
ByteBuffer out(buf, BUFSIZE);
LogString::const_iterator iter = greeting.begin();
log4cxx_status_t stat = package->getEncoder()->encode(greeting, iter, out);
pass = (false == CharsetEncoder::isError(stat));
if (pass) {
stat = package->getEncoder()->encode(greeting, iter, out);
pass = (false == CharsetEncoder::isError(stat));
if (pass) {
out.flip();
pass = (sizeof(expected) == out.limit());
for(size_t i = 0; i < out.limit() && pass; i++) {
pass = (expected[i] == out.data()[i]);
}
pass = pass && (iter == greeting.end());
}
}
if (pass) {
package->pass();
} else {
package->fail();
}
}
return 0;
}
void thread1() {
enum { THREAD_COUNT = 10, THREAD_REPS = 10000 };
Thread threads[THREAD_COUNT];
CharsetEncoderPtr enc(CharsetEncoder::getEncoder(LOG4CXX_STR("ISO-8859-1")));
ThreadPackage* package = new ThreadPackage(enc, THREAD_REPS);
{ for(int i = 0; i < THREAD_COUNT; i++) {
threads[i].run(thread1Action, package);
} }
//
// give time for all threads to be launched so
// we don't signal before everybody is waiting.
Thread::sleep(100);
package->signalAll();
for(int i = 0; i < THREAD_COUNT; i++) {
threads[i].join();
}
LOGUNIT_ASSERT_EQUAL((apr_uint32_t) 0, package->getFail());
LOGUNIT_ASSERT_EQUAL((apr_uint32_t) THREAD_COUNT * THREAD_REPS, package->getPass());
delete package;
}
#endif
};
LOGUNIT_TEST_SUITE_REGISTRATION(CharsetEncoderTestCase);
| 001-log4cxx | trunk/src/test/cpp/helpers/charsetencodertestcase.cpp | C++ | asf20 | 11,505 |
/*
* 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/properties.h>
#include <log4cxx/helpers/fileinputstream.h>
#include "../insertwide.h"
#include "../logunit.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
LOGUNIT_CLASS(PropertiesTestCase)
{
LOGUNIT_TEST_SUITE(PropertiesTestCase);
LOGUNIT_TEST(testLoad1);
LOGUNIT_TEST_SUITE_END();
public:
void testLoad1() {
//
// read patternLayout1.properties
FileInputStreamPtr propFile =
new FileInputStream(LOG4CXX_STR("input/patternLayout1.properties"));
Properties properties;
properties.load(propFile);
LogString pattern(properties.getProperty(LOG4CXX_STR("log4j.appender.testAppender.layout.ConversionPattern")));
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("%-5p - %m%n"), pattern);
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(PropertiesTestCase);
| 001-log4cxx | trunk/src/test/cpp/helpers/propertiestestcase.cpp | C++ | asf20 | 1,720 |
/*
* 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
#include <log4cxx/private/log4cxx_private.h>
#if LOG4CXX_HAS_STD_LOCALE
#include "localechanger.h"
#include <stdexcept>
using namespace log4cxx::helpers;
/**
* Construction attemtps to change default locale.
* @param locale locale.
*/
LocaleChanger::LocaleChanger(const char* locale) {
effective = false;
try {
std::locale newLocale(locale);
initial = std::locale::global(newLocale);
effective = true;
} catch(std::runtime_error&) {
} catch(std::exception&) {
}
}
/**
* Restores previous locale.
*/
LocaleChanger::~LocaleChanger() {
if (effective) {
std::locale::global(initial);
}
}
#endif
| 001-log4cxx | trunk/src/test/cpp/helpers/localechanger.cpp | C++ | asf20 | 1,490 |
/*
* 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>
#include <log4cxx/helpers/iso8601dateformat.h>
#include "../logunit.h"
#define LOG4CXX_TEST
#include <log4cxx/private/log4cxx_private.h>
#if LOG4CXX_HAS_STD_LOCALE
#include <locale>
#endif
#include "../insertwide.h"
#include <log4cxx/helpers/pool.h>
#include <log4cxx/helpers/date.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
/**
Unit test {@link ISO8601DateFormat}.
*/
LOGUNIT_CLASS(ISO8601DateFormatTestCase) {
LOGUNIT_TEST_SUITE( ISO8601DateFormatTestCase );
LOGUNIT_TEST( test1 );
LOGUNIT_TEST( test2 );
LOGUNIT_TEST( test3 );
LOGUNIT_TEST( test4 );
LOGUNIT_TEST( test5 );
LOGUNIT_TEST( test6 );
LOGUNIT_TEST( test7 );
LOGUNIT_TEST_SUITE_END();
/**
* Asserts that formatting the provided date results
* in the expected string.
*
* @param date Date date
* @param timeZone TimeZone timezone for conversion
* @param expected String expected string
*/
void assertFormattedTime(log4cxx_time_t date,
const TimeZonePtr& timeZone,
const LogString& expected) {
ISO8601DateFormat formatter;
formatter.setTimeZone(timeZone);
LogString actual;
Pool p;
formatter.format(actual, date, p);
LOGUNIT_ASSERT_EQUAL(expected, actual);
}
public:
/**
* Convert 02 Jan 2004 00:00:00 GMT for GMT.
*/
void test1() {
log4cxx_time_t jan2 = Date::getMicrosecondsPerDay() * 12419;
assertFormattedTime(jan2, TimeZone::getGMT(),
LOG4CXX_STR("2004-01-02 00:00:00,000"));
}
/**
* Convert 03 Jan 2004 00:00:00 GMT for America/Chicago.
*/
void test2() {
//
// 03 Jan 2004 00:00 GMT
// (asking for the same time at a different timezone
// will ignore the change of timezone)
log4cxx_time_t jan3 = Date::getMicrosecondsPerDay() * 12420;
assertFormattedTime(jan3, TimeZone::getTimeZone(LOG4CXX_STR("GMT-6")),
LOG4CXX_STR("2004-01-02 18:00:00,000"));
}
/**
* Convert 30 Jun 2004 00:00:00 GMT for GMT.
*/
void test3() {
log4cxx_time_t jun30 = Date::getMicrosecondsPerDay() * 12599;
assertFormattedTime(jun30, TimeZone::getGMT(),
LOG4CXX_STR("2004-06-30 00:00:00,000"));
}
/**
* Convert 1 Jul 2004 00:00:00 GMT for Chicago, daylight savings in effect.
*/
void test4() {
log4cxx_time_t jul1 = Date::getMicrosecondsPerDay() * 12600;
assertFormattedTime(jul1, TimeZone::getTimeZone(LOG4CXX_STR("GMT-5")),
LOG4CXX_STR("2004-06-30 19:00:00,000"));
}
/**
* Test multiple calls in close intervals.
*/
void test5() {
// subsequent calls within one minute
// are optimized to reuse previous formatted value
// make a couple of nearly spaced calls
log4cxx_time_t ticks = Date::getMicrosecondsPerDay() * 12601;
assertFormattedTime(ticks, TimeZone::getGMT(),
LOG4CXX_STR("2004-07-02 00:00:00,000"));
assertFormattedTime(ticks + 8000, TimeZone::getGMT(),
LOG4CXX_STR("2004-07-02 00:00:00,008"));
assertFormattedTime(ticks + 17000, TimeZone::getGMT(),
LOG4CXX_STR("2004-07-02 00:00:00,017"));
assertFormattedTime(ticks + 237000, TimeZone::getGMT(),
LOG4CXX_STR("2004-07-02 00:00:00,237"));
assertFormattedTime(ticks + 1415000, TimeZone::getGMT(),
LOG4CXX_STR("2004-07-02 00:00:01,415"));
}
/**
* Check that caching does not disregard timezone.
* This test would fail for revision 1.4 of DateTimeDateFormat.java.
*/
void test6() {
log4cxx_time_t jul3 = Date::getMicrosecondsPerDay() * 12602;
assertFormattedTime(jul3, TimeZone::getGMT(),
LOG4CXX_STR("2004-07-03 00:00:00,000"));
assertFormattedTime(jul3, TimeZone::getTimeZone(LOG4CXX_STR("GMT-5")),
LOG4CXX_STR("2004-07-02 19:00:00,000"));
assertFormattedTime(jul3, TimeZone::getGMT(),
LOG4CXX_STR("2004-07-03 00:00:00,000"));
}
/**
* Checks that numberFormat is implemented.
*/
void test7() {
LogString number;
ISO8601DateFormat formatter;
Pool p;
formatter.numberFormat(number, 87, p);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("87"), number);
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(ISO8601DateFormatTestCase);
| 001-log4cxx | trunk/src/test/cpp/helpers/iso8601dateformattestcase.cpp | C++ | asf20 | 5,108 |
/*
* 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_HELPERS_LOCALE_CHANGER_H
#define _LOG4CXX_HELPERS_LOCALE_CHANGER_H
#include <locale>
namespace log4cxx {
namespace helpers {
/**
* Utility class to change the locale for the duration of a test.
*
*
*
*
*/
class LocaleChanger {
public:
/**
* Construction attemtps to change default locale.
* @param locale locale.
*/
LocaleChanger(const char* locale);
/**
* Restores previous locale.
*/
~LocaleChanger();
/**
* Determines whether locale change was effective.
* @return true if effective.
*/
inline bool isEffective() { return effective; }
private:
LocaleChanger(LocaleChanger&);
LocaleChanger& operator=(LocaleChanger&);
std::locale initial;
bool effective;
};
}
}
#endif
| 001-log4cxx | trunk/src/test/cpp/helpers/localechanger.h | C++ | asf20 | 1,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 <log4cxx/helpers/transcoder.h>
#include "../insertwide.h"
#include "../logunit.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
LOGUNIT_CLASS(TranscoderTestCase)
{
LOGUNIT_TEST_SUITE(TranscoderTestCase);
LOGUNIT_TEST(decode1);
#if LOG4CXX_WCHAR_T_API
LOGUNIT_TEST(decode2);
#endif
LOGUNIT_TEST(decode3);
#if LOG4CXX_WCHAR_T_API
LOGUNIT_TEST(decode4);
#endif
LOGUNIT_TEST(decode7);
LOGUNIT_TEST(decode8);
#if LOG4CXX_WCHAR_T_API
LOGUNIT_TEST(encode1);
#endif
LOGUNIT_TEST(encode2);
#if LOG4CXX_WCHAR_T_API
LOGUNIT_TEST(encode3);
#endif
LOGUNIT_TEST(encode4);
#if LOG4CXX_WCHAR_T_API
LOGUNIT_TEST(encode5);
#endif
LOGUNIT_TEST(encode6);
LOGUNIT_TEST(testDecodeUTF8_1);
LOGUNIT_TEST(testDecodeUTF8_2);
LOGUNIT_TEST(testDecodeUTF8_3);
LOGUNIT_TEST(testDecodeUTF8_4);
#if LOG4CXX_UNICHAR_API
LOGUNIT_TEST(udecode2);
LOGUNIT_TEST(udecode4);
LOGUNIT_TEST(uencode1);
LOGUNIT_TEST(uencode3);
LOGUNIT_TEST(uencode5);
#endif
LOGUNIT_TEST_SUITE_END();
public:
void decode1() {
const char* greeting = "Hello, World";
LogString decoded(LOG4CXX_STR("foo\n"));
Transcoder::decode(greeting, decoded);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("foo\nHello, World"), decoded);
}
#if LOG4CXX_WCHAR_T_API
void decode2() {
const wchar_t* greeting = L"Hello, World";
LogString decoded(LOG4CXX_STR("foo\n"));
Transcoder::decode(greeting, decoded);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("foo\nHello, World"), decoded);
}
#endif
void decode3() {
const char* nothing = "";
LogString decoded(LOG4CXX_STR("foo\n"));
Transcoder::decode(nothing, decoded);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("foo\n"), decoded);
}
#if LOG4CXX_WCHAR_T_API
void decode4() {
const wchar_t* nothing = L"";
LogString decoded(LOG4CXX_STR("foo\n"));
Transcoder::decode(nothing, decoded);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("foo\n"), decoded);
}
#endif
enum { BUFSIZE = 255 };
void decode7() {
//
// normal characters striding over a buffer boundary
//
std::string longMsg(BUFSIZE - 2, 'A');
longMsg.append("Hello");
LogString decoded;
Transcoder::decode(longMsg, decoded);
LOGUNIT_ASSERT_EQUAL((size_t) BUFSIZE + 3, decoded.length());
LOGUNIT_ASSERT_EQUAL(LogString(BUFSIZE -2, LOG4CXX_STR('A')),
decoded.substr(0, BUFSIZE - 2));
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("Hello"),
decoded.substr(BUFSIZE -2 ));
}
void decode8() {
std::string msg("Hello, World.");
LogString actual;
Transcoder::decode(msg, actual);
LogString expected(LOG4CXX_STR("Hello, World."));
LOGUNIT_ASSERT_EQUAL(expected, actual);
}
#if LOG4CXX_WCHAR_T_API
void encode1() {
const LogString greeting(LOG4CXX_STR("Hello, World"));
std::wstring encoded;
Transcoder::encode(greeting, encoded);
LOGUNIT_ASSERT_EQUAL((std::wstring) L"Hello, World", encoded);
}
#endif
void encode2() {
const LogString greeting(LOG4CXX_STR("Hello, World"));
std::string encoded;
Transcoder::encode(greeting, encoded);
LOGUNIT_ASSERT_EQUAL((std::string) "Hello, World", encoded);
}
#if LOG4CXX_WCHAR_T_API
void encode3() {
LogString greeting(BUFSIZE - 3, LOG4CXX_STR('A'));
greeting.append(LOG4CXX_STR("Hello"));
std::wstring encoded;
Transcoder::encode(greeting, encoded);
std::wstring manyAs(BUFSIZE - 3, L'A');
LOGUNIT_ASSERT_EQUAL(manyAs, encoded.substr(0, BUFSIZE - 3));
LOGUNIT_ASSERT_EQUAL(std::wstring(L"Hello"), encoded.substr(BUFSIZE - 3));
}
#endif
void encode4() {
LogString greeting(BUFSIZE - 3, LOG4CXX_STR('A'));
greeting.append(LOG4CXX_STR("Hello"));
std::string encoded;
Transcoder::encode(greeting, encoded);
std::string manyAs(BUFSIZE - 3, 'A');
LOGUNIT_ASSERT_EQUAL(manyAs, encoded.substr(0, BUFSIZE - 3));
LOGUNIT_ASSERT_EQUAL(std::string("Hello"), encoded.substr(BUFSIZE - 3));
}
#if LOG4CXX_WCHAR_T_API
void encode5() {
// arbitrary, hopefully meaningless, characters from
// Latin, Arabic, Armenian, Bengali, CJK and Cyrillic
const wchar_t greeting[] = { L'A', 0x0605, 0x0530, 0x984, 0x40E3, 0x400, 0 };
//
// decode to LogString (UTF-16 or UTF-8)
//
LogString decoded;
Transcoder::decode(greeting, decoded);
//
// decode to wstring
//
std::wstring encoded;
Transcoder::encode(decoded, encoded);
//
// should be lossless
//
LOGUNIT_ASSERT_EQUAL((std::wstring) greeting, encoded);
}
#endif
void encode6() {
#if LOG4CXX_LOGCHAR_IS_WCHAR || LOG4CXX_LOGCHAR_IS_UNICHAR
// arbitrary, hopefully meaningless, characters from
// Latin, Arabic, Armenian, Bengali, CJK and Cyrillic
const logchar greeting[] = { L'A', 0x0605, 0x0530, 0x984, 0x40E3, 0x400, 0 };
#endif
#if LOG4CXX_LOGCHAR_IS_UTF8
const char greeting[] = { 'A',
(char) 0xD8, (char) 0x85,
(char) 0xD4, (char) 0xB0,
(char) 0xE0, (char) 0xCC, (char) 0x84,
(char) 0xE8, (char) 0x87, (char) 0x83,
(char) 0xD0, (char) 0x80,
0 };
#endif
//
// decode to LogString (UTF-16 or UTF-8)
//
LogString decoded;
Transcoder::decode(greeting, decoded);
//
// decode to wstring
//
std::string encoded;
//
// likely 'A\u0605\u0530\u0984\u40E3\u0400'
//
Transcoder::encode(decoded, encoded);
}
void testDecodeUTF8_1() {
std::string src("a");
LogString out;
Transcoder::decodeUTF8(src, out);
LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("a")), out);
}
void testDecodeUTF8_2() {
std::string src(1, 0x80);
LogString out;
Transcoder::decodeUTF8(src, out);
LOGUNIT_ASSERT_EQUAL(LogString(1, Transcoder::LOSSCHAR), out);
}
void testDecodeUTF8_3() {
std::string src("\xC2");
LogString out;
Transcoder::decodeUTF8(src, out);
LOGUNIT_ASSERT_EQUAL(LogString(1, Transcoder::LOSSCHAR), out);
}
void testDecodeUTF8_4() {
std::string src("\xC2\xA9");
LogString out;
Transcoder::decodeUTF8(src, out);
LogString::const_iterator iter = out.begin();
unsigned int sv = Transcoder::decode(out, iter);
LOGUNIT_ASSERT_EQUAL((unsigned int) 0xA9, sv);
LOGUNIT_ASSERT_EQUAL(true, iter == out.end());
}
#if LOG4CXX_UNICHAR_API
void udecode2() {
const UniChar greeting[] = { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', 0 };
LogString decoded(LOG4CXX_STR("foo\n"));
Transcoder::decode(greeting, decoded);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("foo\nHello, World"), decoded);
}
void udecode4() {
const UniChar nothing[] = { 0 };
LogString decoded(LOG4CXX_STR("foo\n"));
Transcoder::decode(nothing, decoded);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("foo\n"), decoded);
}
void uencode1() {
const LogString greeting(LOG4CXX_STR("Hello, World"));
std::basic_string<UniChar> encoded;
Transcoder::encode(greeting, encoded);
const UniChar expected[] = { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', 0 };
LOGUNIT_ASSERT_EQUAL(std::basic_string<UniChar>(expected), encoded);
}
void uencode3() {
LogString greeting(BUFSIZE - 3, LOG4CXX_STR('A'));
greeting.append(LOG4CXX_STR("Hello"));
std::basic_string<UniChar> encoded;
Transcoder::encode(greeting, encoded);
std::basic_string<UniChar> manyAs(BUFSIZE - 3, 'A');
LOGUNIT_ASSERT_EQUAL(manyAs, encoded.substr(0, BUFSIZE - 3));
const UniChar hello[] = { 'H', 'e', 'l', 'l', 'o', 0 };
LOGUNIT_ASSERT_EQUAL(std::basic_string<UniChar>(hello), encoded.substr(BUFSIZE - 3));
}
void uencode5() {
// arbitrary, hopefully meaningless, characters from
// Latin, Arabic, Armenian, Bengali, CJK and Cyrillic
const UniChar greeting[] = { L'A', 0x0605, 0x0530, 0x984, 0x40E3, 0x400, 0 };
//
// decode to LogString (UTF-16 or UTF-8)
//
LogString decoded;
Transcoder::decode(greeting, decoded);
//
// decode to basic_string<UniChar>
//
std::basic_string<UniChar> encoded;
Transcoder::encode(decoded, encoded);
//
// should be lossless
//
LOGUNIT_ASSERT_EQUAL(std::basic_string<UniChar>(greeting), encoded);
}
#endif
};
LOGUNIT_TEST_SUITE_REGISTRATION(TranscoderTestCase);
| 001-log4cxx | trunk/src/test/cpp/helpers/transcodertestcase.cpp | C++ | asf20 | 10,769 |
/*
* 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/cacheddateformat.h>
#include "../logunit.h"
#include <log4cxx/helpers/absolutetimedateformat.h>
#include <log4cxx/helpers/relativetimedateformat.h>
#include <log4cxx/helpers/pool.h>
#include <locale>
#include "../insertwide.h"
#include <apr.h>
#include <apr_time.h>
#include "localechanger.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::pattern;
#define LOCALE_US "C"
#if defined(_WIN32)
#define LOCALE_JP "Japanese_japan"
#else
#define LOCALE_JP "ja_JP"
#endif
//Define INT64_C for compilers that don't have it
#if (!defined(INT64_C))
#define INT64_C(value) value ##LL
#endif
#define LOG4CXX_TEST 1
#include <log4cxx/private/log4cxx_private.h>
/**
Unit test {@link CachedDateFormat}.
*/
LOGUNIT_CLASS(CachedDateFormatTestCase)
{
LOGUNIT_TEST_SUITE( CachedDateFormatTestCase );
LOGUNIT_TEST( test1 );
LOGUNIT_TEST( test2 );
LOGUNIT_TEST( test3 );
LOGUNIT_TEST( test4 );
#if LOG4CXX_HAS_STD_LOCALE
LOGUNIT_TEST( test5 );
#endif
LOGUNIT_TEST( test6 );
LOGUNIT_TEST( test8 );
// Gump doesn't like this test
// LOGUNIT_TEST( test9 );
LOGUNIT_TEST( test10 );
LOGUNIT_TEST( test11);
LOGUNIT_TEST( test12 );
LOGUNIT_TEST( test13 );
LOGUNIT_TEST( test14 );
LOGUNIT_TEST( test15 );
LOGUNIT_TEST( test16 );
LOGUNIT_TEST( test17);
LOGUNIT_TEST( test18);
LOGUNIT_TEST( test19);
LOGUNIT_TEST( test20);
LOGUNIT_TEST( test21);
LOGUNIT_TEST_SUITE_END();
#define MICROSECONDS_PER_DAY APR_INT64_C(86400000000)
public:
/**
* Test multiple calls in close intervals.
*/
void test1() {
// subsequent calls within one minute
// are optimized to reuse previous formatted value
// make a couple of nearly spaced calls
DateFormatPtr baseFormatter(new AbsoluteTimeDateFormat());
CachedDateFormat gmtFormat(baseFormatter, 1000000);
gmtFormat.setTimeZone(TimeZone::getGMT());
apr_time_t jul1 = MICROSECONDS_PER_DAY * 12601L;
Pool p;
LogString actual;
gmtFormat.format(actual, jul1, p);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,000"), actual);
actual.erase(actual.begin(), actual.end());
gmtFormat.format(actual, jul1 + 8000, p);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,008"), actual);
actual.erase(actual.begin(), actual.end());
gmtFormat.format(actual, jul1 + 17000, p);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,017"), actual);
actual.erase(actual.begin(), actual.end());
gmtFormat.format(actual, jul1 + 237000, p);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,237"), actual);
actual.erase(actual.begin(), actual.end());
gmtFormat.format(actual, jul1 + 1415000, p);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:01,415"), actual);
actual.erase(actual.begin(), actual.end());
}
/**
* Check for interaction between caches.
*/
void test2() {
apr_time_t jul2 = MICROSECONDS_PER_DAY * 12602;
DateFormatPtr baseFormatter(new AbsoluteTimeDateFormat());
CachedDateFormat gmtFormat(baseFormatter, 1000000);
gmtFormat.setTimeZone(TimeZone::getGMT());
DateFormatPtr chicagoBase(new AbsoluteTimeDateFormat());
CachedDateFormat chicagoFormat(chicagoBase, 1000000);
chicagoFormat.setTimeZone(TimeZone::getTimeZone(LOG4CXX_STR("GMT-5")));
Pool p;
LogString actual;
gmtFormat.format(actual, jul2, p);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,000"), actual);
actual.erase(actual.begin(), actual.end());
chicagoFormat.format(actual, jul2, p);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("19:00:00,000"), actual);
actual.erase(actual.begin(), actual.end());
gmtFormat.format(actual, jul2, p);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,000"), actual);
}
/**
* Test multiple calls in close intervals prior to 1 Jan 1970.
*/
void test3() {
// subsequent calls within one minute
// are optimized to reuse previous formatted value
// make a couple of nearly spaced calls
DateFormatPtr baseFormatter(new AbsoluteTimeDateFormat());
CachedDateFormat gmtFormat(baseFormatter, 1000000);
gmtFormat.setTimeZone(TimeZone::getGMT());
apr_time_t ticks = MICROSECONDS_PER_DAY * -7;
Pool p;
LogString actual;
gmtFormat.format(actual, ticks, p);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,000"), actual);
actual.erase(actual.begin(), actual.end());
//
// APR's explode_time method does not properly calculate tm_usec
// prior to 1 Jan 1970 on Unix
gmtFormat.format(actual, ticks + 8000, p);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,008"), actual);
actual.erase(actual.begin(), actual.end());
gmtFormat.format(actual, ticks + 17000, p);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,017"), actual);
actual.erase(actual.begin(), actual.end());
gmtFormat.format(actual, ticks + 237000, p);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,237"), actual);
actual.erase(actual.begin(), actual.end());
gmtFormat.format(actual, ticks + 1423000, p);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:01,423"), actual);
}
void assertFormattedEquals(
const DateFormatPtr& baseFormat,
const CachedDateFormat& cachedFormat,
apr_time_t date,
Pool& p) {
LogString expected;
LogString actual;
baseFormat->format(expected, date, p);
cachedFormat.format(actual, date, p);
LOGUNIT_ASSERT_EQUAL(expected, actual);
}
void test4() {
// subsequent calls within one minute
// are optimized to reuse previous formatted value
// make a couple of nearly spaced calls
#if LOG4CXX_HAS_STD_LOCALE
std::locale loco(LOCALE_US);
std::locale* localeEN = &loco;
#else
std::locale* localeEN = NULL;
#endif
DateFormatPtr baseFormat(
new SimpleDateFormat(LOG4CXX_STR("EEE, MMM dd, HH:mm:ss.SSS Z"), localeEN));
CachedDateFormat cachedFormat(baseFormat, 1000000);
//
// use a date in 2000 to attempt to confuse the millisecond locator
apr_time_t ticks = MICROSECONDS_PER_DAY * 11141;
Pool p;
assertFormattedEquals(baseFormat, cachedFormat, ticks, p);
assertFormattedEquals(baseFormat, cachedFormat, ticks + 8000, p);
assertFormattedEquals(baseFormat, cachedFormat, ticks + 17000, p);
assertFormattedEquals(baseFormat, cachedFormat, ticks + 237000, p);
assertFormattedEquals(baseFormat, cachedFormat, ticks + 1415000, p);
}
#if LOG4CXX_HAS_STD_LOCALE
void test5() {
// subsequent calls within one minute
// are optimized to reuse previous formatted value
// make a couple of nearly spaced calls
LocaleChanger localeChange(LOCALE_JP);
if (localeChange.isEffective()) {
DateFormatPtr baseFormat(new SimpleDateFormat(
LOG4CXX_STR("EEE, MMM dd, HH:mm:ss.SSS Z")));
CachedDateFormat cachedFormat(baseFormat, 1000000);
//
// use a date in 2000 to attempt to confuse the millisecond locator
apr_time_t ticks = MICROSECONDS_PER_DAY * 11141;
Pool p;
assertFormattedEquals(baseFormat, cachedFormat, ticks, p);
assertFormattedEquals(baseFormat, cachedFormat, ticks + 8000, p);
assertFormattedEquals(baseFormat, cachedFormat, ticks + 17000, p);
assertFormattedEquals(baseFormat, cachedFormat, ticks + 237000, p);
assertFormattedEquals(baseFormat, cachedFormat, ticks + 1415000, p);
}
}
#endif
/**
* Checks that numberFormat works as expected.
*/
void test6() {
LogString numb;
Pool p;
AbsoluteTimeDateFormat formatter;
formatter.numberFormat(numb, 87, p);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("87"), numb);
}
/**
* Set time zone on cached and check that it is effective.
*/
void test8() {
DateFormatPtr baseFormat(new SimpleDateFormat(LOG4CXX_STR("yyyy-MM-dd HH:mm:ss,SSS")));
baseFormat->setTimeZone(TimeZone::getGMT());
CachedDateFormat cachedFormat(baseFormat, 1000000);
apr_time_t jul4 = MICROSECONDS_PER_DAY * 12603;
Pool p;
LogString actual;
cachedFormat.format(actual, jul4, p);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("2004-07-04 00:00:00,000"), actual);
cachedFormat.setTimeZone(TimeZone::getTimeZone(LOG4CXX_STR("GMT-6")));
actual.erase(actual.begin(), actual.end());
cachedFormat.format(actual, jul4, p);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("2004-07-03 18:00:00,000"), actual);
}
/**
* Test of caching when less than three millisecond digits are specified.
*/
void test9() {
std::locale localeUS(LOCALE_US);
DateFormatPtr baseFormat = new SimpleDateFormat(
LOG4CXX_STR("yyyy-MMMM-dd HH:mm:ss,SS Z"), &localeUS);
DateFormatPtr cachedFormat = new CachedDateFormat(baseFormat, 1000000);
TimeZonePtr cet = TimeZone::getTimeZone(LOG4CXX_STR("GMT+1"));
cachedFormat->setTimeZone(cet);
apr_time_exp_t c;
memset(&c, 0, sizeof(c));
c.tm_year = 104;
c.tm_mon = 11;
c.tm_mday = 12;
c.tm_hour = 19;
c.tm_sec = 37;
c.tm_usec = 23000;
apr_time_t dec12;
apr_status_t stat = apr_time_exp_gmt_get(&dec12, &c);
const apr_status_t statOK = 0;
LOGUNIT_ASSERT_EQUAL(statOK, stat);
Pool p;
LogString s;
cachedFormat->format(s, dec12, p);
LOGUNIT_ASSERT_EQUAL(
(LogString) LOG4CXX_STR("2004-December-12 20:00:37,23 +0100"), s);
memset(&c, 0, sizeof(c));
c.tm_year = 104;
c.tm_mon = 11;
c.tm_mday = 31;
c.tm_hour = 23;
c.tm_sec = 13;
c.tm_usec = 905000;
apr_time_t jan1;
stat = apr_time_exp_gmt_get(&jan1, &c);
LOGUNIT_ASSERT_EQUAL(statOK, stat);
s.erase(s.begin(), s.end());
cachedFormat->format(s, jan1, p);
LOGUNIT_ASSERT_EQUAL(
(LogString) LOG4CXX_STR("2005-January-01 00:00:13,905 +0100"), s);
}
/**
* Test when millisecond position moves but length remains constant.
*/
void test10() {
#if LOG4CXX_HAS_STD_LOCALE
std::locale loco("C");
std::locale* localeUS = &loco;
#else
std::locale* localeUS = NULL;
#endif
DateFormatPtr baseFormat = new SimpleDateFormat(
LOG4CXX_STR("MMMM SSS EEEEEE"), localeUS);
DateFormatPtr cachedFormat = new CachedDateFormat(baseFormat, 1000000);
TimeZonePtr cet = TimeZone::getTimeZone(LOG4CXX_STR("GMT+1"));
cachedFormat->setTimeZone(cet);
apr_time_exp_t c;
memset(&c, 0, sizeof(c));
c.tm_year = 104;
c.tm_mon = 9;
c.tm_mday = 5;
c.tm_hour = 21;
c.tm_sec = 37;
c.tm_usec = 23000;
apr_time_t oct5;
apr_status_t stat = apr_time_exp_gmt_get(&oct5, &c);
const apr_status_t statOK = 0;
LOGUNIT_ASSERT_EQUAL(statOK, stat);
Pool p;
LogString s;
cachedFormat->format(s, oct5, p);
LOGUNIT_ASSERT_EQUAL(
(LogString) LOG4CXX_STR("October 023 Tuesday"), s);
memset(&c, 0, sizeof(c));
c.tm_year = 104;
c.tm_mon = 10;
c.tm_mday = 1;
c.tm_usec = 23000;
apr_time_t nov1;
stat = apr_time_exp_gmt_get(&nov1, &c);
LOGUNIT_ASSERT_EQUAL(statOK, stat);
s.erase(s.begin(), s.end());
cachedFormat->format(s, nov1, p);
LOGUNIT_ASSERT_EQUAL(
(LogString) LOG4CXX_STR("November 023 Monday"), s);
nov1 += 961000;
s.erase(s.begin(), s.end());
cachedFormat->format(s, nov1, p);
LOGUNIT_ASSERT_EQUAL(
(LogString) LOG4CXX_STR("November 984 Monday"), s);
}
/**
* Test that tests if caching is skipped if only "SS"
* is specified.
*/
void test11() {
//
// Earlier versions could be tricked by "SS0" patterns.
//
LogString badPattern(LOG4CXX_STR("ss,SS0"));
DateFormatPtr simpleFormat = new SimpleDateFormat(badPattern);
DateFormatPtr gmtFormat = new CachedDateFormat(simpleFormat, 1000000);
gmtFormat->setTimeZone(TimeZone::getGMT());
//
// The first request has to 100 ms after an ordinal second
// to push the literal zero out of the pattern check
apr_time_t ticks = MICROSECONDS_PER_DAY * 11142L;
apr_time_t jul2 = ticks + 120000;
Pool p;
LogString s;
gmtFormat->format(s, jul2, p);
LOGUNIT_ASSERT_EQUAL(
(LogString) LOG4CXX_STR("00,1200"), s);
jul2 = ticks + 87000;
s.erase(s.begin(), s.end());
gmtFormat->format(s, jul2, p);
LOGUNIT_ASSERT_EQUAL(
(LogString) LOG4CXX_STR("00,870"), s);
}
/**
* Check pattern location for ISO8601
*/
void test12() {
DateFormatPtr df = new SimpleDateFormat(LOG4CXX_STR("yyyy-MM-dd HH:mm:ss,SSS"));
apr_time_t ticks = 11142L * MICROSECONDS_PER_DAY;
Pool p;
LogString formatted;
df->format(formatted, ticks, p);
int millisecondStart = CachedDateFormat::findMillisecondStart(ticks,
formatted, df, p);
LOGUNIT_ASSERT_EQUAL(20, millisecondStart);
}
/**
* Check pattern location for DATE
*/
void test13() {
DateFormatPtr df = new SimpleDateFormat(LOG4CXX_STR("yyyy-MM-dd"));
apr_time_t ticks = 11142L * MICROSECONDS_PER_DAY;
Pool p;
LogString formatted;
df->format(formatted, ticks, p);
int millisecondStart = CachedDateFormat::findMillisecondStart(ticks,
formatted, df, p);
LOGUNIT_ASSERT_EQUAL((int) CachedDateFormat::NO_MILLISECONDS, millisecondStart);
}
/**
* Check pattern location for ABSOLUTE
*/
void test14() {
DateFormatPtr df = new SimpleDateFormat(LOG4CXX_STR("HH:mm:ss,SSS"));
apr_time_t ticks = 11142L * MICROSECONDS_PER_DAY;
Pool p;
LogString formatted;
df->format(formatted, ticks, p);
int millisecondStart = CachedDateFormat::findMillisecondStart(ticks,
formatted, df, p);
LOGUNIT_ASSERT_EQUAL(9, millisecondStart);
}
/**
* Check pattern location for single S
*/
void test15() {
DateFormatPtr df = new SimpleDateFormat(LOG4CXX_STR("HH:mm:ss,S"));
apr_time_t ticks = 11142L * MICROSECONDS_PER_DAY;
Pool p;
LogString formatted;
df->format(formatted, ticks, p);
int millisecondStart = CachedDateFormat::findMillisecondStart(ticks,
formatted, df, p);
LOGUNIT_ASSERT_EQUAL((int) CachedDateFormat::UNRECOGNIZED_MILLISECONDS, millisecondStart);
}
/**
* Check pattern location for single SS
*/
void test16() {
DateFormatPtr df = new SimpleDateFormat(LOG4CXX_STR("HH:mm:ss,SS"));
apr_time_t ticks = 11142L * MICROSECONDS_PER_DAY;
Pool p;
LogString formatted;
df->format(formatted, ticks, p);
int millisecondStart =
CachedDateFormat::findMillisecondStart(ticks, formatted, df, p);
LOGUNIT_ASSERT_EQUAL((int) CachedDateFormat::UNRECOGNIZED_MILLISECONDS, millisecondStart);
}
/**
* Check caching when multiple SSS appear in pattern
*/
void test17() {
apr_time_t jul2 = 12602L * MICROSECONDS_PER_DAY;
LogString badPattern(LOG4CXX_STR("HH:mm:ss,SSS HH:mm:ss,SSS"));
DateFormatPtr simpleFormat = new SimpleDateFormat(badPattern);
simpleFormat->setTimeZone(TimeZone::getGMT());
DateFormatPtr cachedFormat = new CachedDateFormat(simpleFormat, 1000000);
Pool p;
LogString s;
cachedFormat->format(s, jul2, p);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,000 00:00:00,000"), s);
jul2 += 120000;
s.erase(s.begin(), s.end());
simpleFormat->format(s, jul2, p);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,120 00:00:00,120"), s);
s.erase(s.begin(), s.end());
cachedFormat->format(s, jul2, p);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,120 00:00:00,120"), s) ;
int maxValid = CachedDateFormat::getMaximumCacheValidity(badPattern);
LOGUNIT_ASSERT_EQUAL(1000, maxValid);
}
/**
* Check that patterns not containing microseconds
* are reported as being able to be cached for a full second.
*/
void test18() {
int maxValid =
CachedDateFormat::getMaximumCacheValidity(
LOG4CXX_STR("yyyy-MM-dd"));
LOGUNIT_ASSERT_EQUAL(1000000, maxValid);
}
/**
* Check that patterns not containing 3 microseconds
* are reported as being able to be cached for a full second.
*/
void test19() {
int maxValid =
CachedDateFormat::getMaximumCacheValidity(
LOG4CXX_STR("yyyy-MM-dd SSS"));
LOGUNIT_ASSERT_EQUAL(1000000, maxValid);
}
/**
* Check that patterns not containing 2 S's
* are reported as being able to be cached for only a millisecond.
*/
void test20() {
int maxValid =
CachedDateFormat::getMaximumCacheValidity(
LOG4CXX_STR("yyyy-MM-dd SS"));
LOGUNIT_ASSERT_EQUAL(1000, maxValid);
}
/**
* Check that patterns not containing multi S groups
* are reported as being able to be cached for only a millisecond.
*/
void test21() {
int maxValid =
CachedDateFormat::getMaximumCacheValidity(
LOG4CXX_STR("yyyy-MM-dd SSS SSS"));
LOGUNIT_ASSERT_EQUAL(1000, maxValid);
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(CachedDateFormatTestCase);
| 001-log4cxx | trunk/src/test/cpp/helpers/cacheddateformattestcase.cpp | C++ | asf20 | 17,699 |
/*
* 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>
#include <log4cxx/helpers/stringtokenizer.h>
#include "../logunit.h"
#include "../insertwide.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
LOGUNIT_CLASS(StringTokenizerTestCase)
{
LOGUNIT_TEST_SUITE(StringTokenizerTestCase);
LOGUNIT_TEST(testNextTokenEmptyString);
LOGUNIT_TEST(testHasMoreTokensEmptyString);
LOGUNIT_TEST(testNextTokenAllDelim);
LOGUNIT_TEST(testHasMoreTokensAllDelim);
LOGUNIT_TEST(test1);
LOGUNIT_TEST(test2);
LOGUNIT_TEST(test3);
LOGUNIT_TEST(test4);
LOGUNIT_TEST(test5);
LOGUNIT_TEST(test6);
LOGUNIT_TEST_SUITE_END();
public:
void testNextTokenEmptyString() {
LogString src;
LogString delim(LOG4CXX_STR(" "));
StringTokenizer tokenizer(src, delim);
try {
LogString token(tokenizer.nextToken());
} catch (NoSuchElementException &ex) {
return;
}
LOGUNIT_ASSERT(false);
}
void testHasMoreTokensEmptyString() {
LogString src;
LogString delim(LOG4CXX_STR(" "));
StringTokenizer tokenizer(src, delim);
LOGUNIT_ASSERT_EQUAL(false, tokenizer.hasMoreTokens());
}
void testNextTokenAllDelim() {
LogString src(LOG4CXX_STR("==="));
LogString delim(LOG4CXX_STR("="));
StringTokenizer tokenizer(src, delim);
try {
LogString token(tokenizer.nextToken());
} catch (NoSuchElementException &ex) {
return;
}
LOGUNIT_ASSERT(false);
}
void testHasMoreTokensAllDelim() {
LogString src(LOG4CXX_STR("==="));
LogString delim(LOG4CXX_STR("="));
StringTokenizer tokenizer(src, delim);
LOGUNIT_ASSERT_EQUAL(false, tokenizer.hasMoreTokens());
}
void testBody(const LogString& src, const LogString& delim) {
StringTokenizer tokenizer(src, delim);
LOGUNIT_ASSERT_EQUAL(true, tokenizer.hasMoreTokens());
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("log4j"), tokenizer.nextToken());
LOGUNIT_ASSERT_EQUAL(true, tokenizer.hasMoreTokens());
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("properties"), tokenizer.nextToken());
LOGUNIT_ASSERT_EQUAL(true, tokenizer.hasMoreTokens());
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("txt"), tokenizer.nextToken());
LOGUNIT_ASSERT_EQUAL(false, tokenizer.hasMoreTokens());
try {
LogString token(tokenizer.nextToken());
} catch (NoSuchElementException& ex) {
return;
}
LOGUNIT_ASSERT(false);
}
void test1() {
LogString src(LOG4CXX_STR("log4j.properties.txt"));
LogString delim(LOG4CXX_STR("."));
testBody(src, delim);
}
void test2() {
LogString src(LOG4CXX_STR(".log4j.properties.txt"));
LogString delim(LOG4CXX_STR("."));
testBody(src, delim);
}
void test3() {
LogString src(LOG4CXX_STR("log4j.properties.txt."));
LogString delim(LOG4CXX_STR("."));
testBody(src, delim);
}
void test4() {
LogString src(LOG4CXX_STR("log4j..properties....txt"));
LogString delim(LOG4CXX_STR("."));
testBody(src, delim);
}
void test5() {
LogString src(LOG4CXX_STR("log4j properties,txt"));
LogString delim(LOG4CXX_STR(" ,"));
testBody(src, delim);
}
void test6() {
LogString src(LOG4CXX_STR(" log4j properties,txt "));
LogString delim(LOG4CXX_STR(" ,"));
testBody(src, delim);
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(StringTokenizerTestCase);
| 001-log4cxx | trunk/src/test/cpp/helpers/stringtokenizertestcase.cpp | C++ | asf20 | 4,780 |
/*
* 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/cyclicbuffer.h>
#include "../logunit.h"
#include <log4cxx/logmanager.h>
#include <log4cxx/logger.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/spi/location/locationinfo.h>
#include "../testchar.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::spi;
#define MAX 1000
LOGUNIT_CLASS(CyclicBufferTestCase)
{
LOGUNIT_TEST_SUITE(CyclicBufferTestCase);
LOGUNIT_TEST(test0);
LOGUNIT_TEST(test1);
LOGUNIT_TEST(testResize);
LOGUNIT_TEST_SUITE_END();
LoggerPtr logger;
std::vector<LoggingEventPtr> e;
public:
void setUp()
{
e.reserve(1000);
LoggingEventPtr event;
for (int i = 0; i < MAX; i++)
{
event = new LoggingEvent(LOG4CXX_STR("x"), Level::getDebug(), LOG4CXX_STR("e"),
log4cxx::spi::LocationInfo::getLocationUnavailable());
e.push_back(event);
}
}
void tearDown()
{
LogManager::shutdown();
}
void test0()
{
int size = 2;
CyclicBuffer cb(size);
LOGUNIT_ASSERT_EQUAL(size, cb.getMaxSize());
cb.add(e[0]);
LOGUNIT_ASSERT_EQUAL(1, cb.length());
LOGUNIT_ASSERT_EQUAL(e[0], cb.get());
LOGUNIT_ASSERT_EQUAL(0, cb.length());
LOGUNIT_ASSERT(cb.get() == 0);
LOGUNIT_ASSERT_EQUAL(0, cb.length());
CyclicBuffer cb2(size);
cb2.add(e[0]);
cb2.add(e[1]);
LOGUNIT_ASSERT_EQUAL(2, cb2.length());
LOGUNIT_ASSERT_EQUAL(e[0], cb2.get());
LOGUNIT_ASSERT_EQUAL(1, cb2.length());
LOGUNIT_ASSERT_EQUAL(e[1], cb2.get());
LOGUNIT_ASSERT_EQUAL(0, cb2.length());
LOGUNIT_ASSERT(cb2.get() == 0);
LOGUNIT_ASSERT_EQUAL(0, cb2.length());
}
void test1()
{
for (int bufSize = 1; bufSize <= 128; bufSize *= 2)
doTest1(bufSize);
}
void doTest1(int size)
{
//System.out.println("Doing test with size = "+size);
CyclicBuffer cb(size);
LOGUNIT_ASSERT_EQUAL(size, cb.getMaxSize());
int i;
for (i = -(size + 10); i < (size + 10); i++)
{
LOGUNIT_ASSERT(cb.get(i) == 0);
}
for (i = 0; i < MAX; i++)
{
cb.add(e[i]);
int limit = (i < (size - 1)) ? i : (size - 1);
//System.out.println("\nLimit is " + limit + ", i="+i);
for (int j = limit; j >= 0; j--)
{
//System.out.println("i= "+i+", j="+j);
LOGUNIT_ASSERT_EQUAL(e[i - (limit - j)], cb.get(j));
}
LOGUNIT_ASSERT(cb.get(-1) == 0);
LOGUNIT_ASSERT(cb.get(limit + 1) == 0);
}
}
void testResize()
{
for (int isize = 1; isize <= 128; isize *= 2)
{
doTestResize(isize, (isize / 2) + 1, (isize / 2) + 1);
doTestResize(isize, (isize / 2) + 1, isize + 10);
doTestResize(isize, isize + 10, (isize / 2) + 1);
doTestResize(isize, isize + 10, isize + 10);
}
}
void doTestResize(int initialSize, int numberOfAdds, int newSize)
{
//System.out.println("initialSize = "+initialSize+", numberOfAdds="
// +numberOfAdds+", newSize="+newSize);
CyclicBuffer cb(initialSize);
for (int i = 0; i < numberOfAdds; i++)
{
cb.add(e[i]);
}
cb.resize(newSize);
int offset = numberOfAdds - initialSize;
if (offset < 0)
{
offset = 0;
}
int len = (newSize < numberOfAdds) ? newSize : numberOfAdds;
len = (len < initialSize) ? len : initialSize;
//System.out.println("Len = "+len+", offset="+offset);
for (int j = 0; j < len; j++)
{
LOGUNIT_ASSERT_EQUAL(e[offset + j], cb.get(j));
}
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(CyclicBufferTestCase);
| 001-log4cxx | trunk/src/test/cpp/helpers/cyclicbuffertestcase.cpp | C++ | asf20 | 4,578 |
/*
* 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>
#include <log4cxx/helpers/relativetimedateformat.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/helpers/pool.h>
#include <log4cxx/helpers/stringhelper.h>
#include "../insertwide.h"
#include "../logunit.h"
#include <log4cxx/helpers/date.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::spi;
/**
Unit test {@link RelativeTimeDateFormat} class.
*/
LOGUNIT_CLASS(RelativeTimeDateFormatTestCase) {
LOGUNIT_TEST_SUITE(RelativeTimeDateFormatTestCase);
LOGUNIT_TEST(test1);
LOGUNIT_TEST(test2);
LOGUNIT_TEST(test3);
LOGUNIT_TEST_SUITE_END();
public:
/**
* Convert 2 Jan 2004
*/
void test1() {
log4cxx_time_t jan2 = Date::getMicrosecondsPerDay() * 12419;
log4cxx_time_t preStartTime = LoggingEvent::getStartTime();
RelativeTimeDateFormat formatter;
Pool p;
LogString actual;
formatter.format(actual, jan2, p);
log4cxx_time_t elapsed = log4cxx::helpers::StringHelper::toInt64(actual);
LOGUNIT_ASSERT(preStartTime + elapsed*1000 > jan2 - 2000);
LOGUNIT_ASSERT(preStartTime + elapsed*1000 < jan2 + 2000);
}
/**
* Checks that numberFormat works as expected.
*/
void test2() {
LogString numb;
Pool p;
RelativeTimeDateFormat formatter;
formatter.numberFormat(numb, 87, p);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("87"), numb);
}
/**
* Checks that setting timezone doesn't throw an exception.
*/
void test3() {
RelativeTimeDateFormat formatter;
formatter.setTimeZone(TimeZone::getGMT());
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(RelativeTimeDateFormatTestCase);
| 001-log4cxx | trunk/src/test/cpp/helpers/relativetimedateformattestcase.cpp | C++ | asf20 | 2,535 |
/*
* 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/optionconverter.h>
#include <log4cxx/helpers/properties.h>
#include <log4cxx/helpers/system.h>
#include <log4cxx/helpers/transcoder.h>
#include <log4cxx/helpers/pool.h>
#include "../testchar.h"
#include "../insertwide.h"
#include "../logunit.h"
#include <stdlib.h>
#include <apr_pools.h>
#include <apr_file_io.h>
#include <apr_user.h>
#include <apr_env.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::spi;
#define MAX 1000
LOGUNIT_CLASS(OptionConverterTestCase)
{
LOGUNIT_TEST_SUITE(OptionConverterTestCase);
LOGUNIT_TEST(varSubstTest1);
LOGUNIT_TEST(varSubstTest2);
LOGUNIT_TEST(varSubstTest3);
LOGUNIT_TEST(varSubstTest4);
LOGUNIT_TEST(varSubstTest5);
LOGUNIT_TEST(testTmpDir);
#if APR_HAS_USER
LOGUNIT_TEST(testUserHome);
LOGUNIT_TEST(testUserName);
#endif
LOGUNIT_TEST(testUserDir);
LOGUNIT_TEST_SUITE_END();
Properties props;
Properties nullProperties;
public:
void setUp()
{
}
void tearDown()
{
}
/**
* Checks that environment variables were properly set
* before invoking tests. ::putenv not reliable.
*/
void envCheck() {
Pool p;
char* toto;
apr_status_t stat = apr_env_get(&toto, "TOTO",
p.getAPRPool());
LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat);
LOGUNIT_ASSERT_EQUAL("wonderful", toto);
char* key1;
stat = apr_env_get(&key1, "key1",
p.getAPRPool());
LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat);
LOGUNIT_ASSERT_EQUAL("value1", key1);
char* key2;
stat = apr_env_get(&key2, "key2",
p.getAPRPool());
LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat);
LOGUNIT_ASSERT_EQUAL("value2", key2);
}
void varSubstTest1()
{
envCheck();
LogString r(OptionConverter::substVars(LOG4CXX_STR("hello world."), nullProperties));
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("hello world."), r);
r = OptionConverter::substVars(LOG4CXX_STR("hello ${TOTO} world."), nullProperties);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("hello wonderful world."), r);
}
void varSubstTest2()
{
envCheck();
LogString r(OptionConverter::substVars(LOG4CXX_STR("Test2 ${key1} mid ${key2} end."),
nullProperties));
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("Test2 value1 mid value2 end."), r);
}
void varSubstTest3()
{
envCheck();
LogString r(OptionConverter::substVars(
LOG4CXX_STR("Test3 ${unset} mid ${key1} end."), nullProperties));
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("Test3 mid value1 end."), r);
}
void varSubstTest4()
{
LogString res;
LogString val(LOG4CXX_STR("Test4 ${incomplete "));
try
{
res = OptionConverter::substVars(val, nullProperties);
}
catch(IllegalArgumentException& e)
{
std::string witness("\"Test4 ${incomplete \" has no closing brace. Opening brace at position 6.");
LOGUNIT_ASSERT_EQUAL(witness, (std::string) e.what());
}
}
void varSubstTest5()
{
Properties props1;
props1.setProperty(LOG4CXX_STR("p1"), LOG4CXX_STR("x1"));
props1.setProperty(LOG4CXX_STR("p2"), LOG4CXX_STR("${p1}"));
LogString res = OptionConverter::substVars(LOG4CXX_STR("${p2}"), props1);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("x1"), res);
}
void testTmpDir()
{
LogString actual(OptionConverter::substVars(
LOG4CXX_STR("${java.io.tmpdir}"), nullProperties));
Pool p;
const char* tmpdir = NULL;
apr_status_t stat = apr_temp_dir_get(&tmpdir, p.getAPRPool());
LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat);
LogString expected;
Transcoder::decode(tmpdir, expected);
LOGUNIT_ASSERT_EQUAL(expected, actual);
}
#if APR_HAS_USER
void testUserHome() {
LogString actual(OptionConverter::substVars(
LOG4CXX_STR("${user.home}"), nullProperties));
Pool p;
apr_uid_t userid;
apr_gid_t groupid;
apr_status_t stat = apr_uid_current(&userid, &groupid, p.getAPRPool());
if (stat == APR_SUCCESS) {
char* username = NULL;
stat = apr_uid_name_get(&username, userid, p.getAPRPool());
if (stat == APR_SUCCESS) {
char* dirname = NULL;
stat = apr_uid_homepath_get(&dirname, username, p.getAPRPool());
if (stat == APR_SUCCESS) {
LogString expected;
Transcoder::decode(dirname, expected);
LOGUNIT_ASSERT_EQUAL(expected, actual);
}
}
}
}
void testUserName() {
LogString actual(OptionConverter::substVars(
LOG4CXX_STR("${user.name}"), nullProperties));
Pool p;
apr_uid_t userid;
apr_gid_t groupid;
apr_status_t stat = apr_uid_current(&userid, &groupid, p.getAPRPool());
if (stat == APR_SUCCESS) {
char* username = NULL;
stat = apr_uid_name_get(&username, userid, p.getAPRPool());
if (stat == APR_SUCCESS) {
LogString expected;
Transcoder::decode(username, expected);
LOGUNIT_ASSERT_EQUAL(expected, actual);
}
}
}
#endif
void testUserDir() {
LogString actual(OptionConverter::substVars(
LOG4CXX_STR("${user.dir}"), nullProperties));
Pool p;
char* dirname = NULL;
apr_status_t stat = apr_filepath_get(&dirname, APR_FILEPATH_NATIVE, p.getAPRPool());
LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat);
LogString expected;
Transcoder::decode(dirname, expected);
LOGUNIT_ASSERT_EQUAL(expected, actual);
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(OptionConverterTestCase);
| 001-log4cxx | trunk/src/test/cpp/helpers/optionconvertertestcase.cpp | C++ | asf20 | 6,602 |
/*
* 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 __STDC_CONSTANT_MACROS
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/datetimedateformat.h>
#include "../logunit.h"
#include <log4cxx/helpers/pool.h>
#include "../insertwide.h"
#include <apr.h>
#include <apr_time.h>
#include <sstream>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace std;
#define LOCALE_US "C"
#if defined(_WIN32)
#define LOCALE_FR "French_france"
#else
#define LOCALE_FR "fr_FR"
#endif
#define LOG4CXX_TEST 1
#include <log4cxx/private/log4cxx_private.h>
#if LOG4CXX_HAS_STD_LOCALE
#include <locale>
#include "localechanger.h"
#define MAKE_LOCALE(ptr, id) \
std::locale loco(id); \
std::locale* ptr = &loco;
#else
#define MAKE_LOCALE(ptr, id) \
std::locale* ptr = NULL;
#endif
/**
Unit test {@link DateTimeDateFormat}.
*/
LOGUNIT_CLASS(DateTimeDateFormatTestCase)
{
LOGUNIT_TEST_SUITE( DateTimeDateFormatTestCase );
LOGUNIT_TEST( test1 );
LOGUNIT_TEST( test2 );
LOGUNIT_TEST( test3 );
LOGUNIT_TEST( test4 );
LOGUNIT_TEST( test5 );
LOGUNIT_TEST( test6 );
#if LOG4CXX_HAS_STD_LOCALE
LOGUNIT_TEST( test7 );
LOGUNIT_TEST( test8 );
#endif
LOGUNIT_TEST_SUITE_END();
private:
#define MICROSECONDS_PER_DAY APR_INT64_C(86400000000)
/**
Asserts that formatting the provided date results in the expected string.
@param date Date date
@param timeZone TimeZone timezone for conversion
@param expected String expected string
*/
void assertFormattedTime( apr_time_t date, const std::locale* locale,
const TimeZonePtr& timeZone, const LogString& expected )
{
DateTimeDateFormat formatter(locale);
formatter.setTimeZone(timeZone);
LogString actual;
Pool p;
formatter.format(actual, date, p);
LOGUNIT_ASSERT_EQUAL( expected, actual );
}
public:
/** Convert 02 Jan 2004 00:00:00 GMT for GMT. */
void test1()
{
//
// 02 Jan 2004 00:00 GMT
//
apr_time_t jan2 = MICROSECONDS_PER_DAY * 12419;
MAKE_LOCALE(localeUS, LOCALE_US);
assertFormattedTime( jan2, localeUS, TimeZone::getGMT(), LOG4CXX_STR("02 Jan 2004 00:00:00,000"));
}
/** Convert 03 Jan 2004 00:00:00 GMT for America/Chicago. */
void test2()
{
//
// 03 Jan 2004 00:00 GMT
apr_time_t jan3 = MICROSECONDS_PER_DAY * 12420;
MAKE_LOCALE(localeUS, LOCALE_US);
assertFormattedTime( jan3, localeUS,
TimeZone::getTimeZone(LOG4CXX_STR("GMT-6")),
LOG4CXX_STR("02 Jan 2004 18:00:00,000"));
}
/** Convert 30 Jun 2004 00:00:00 GMT for GMT. */
void test3()
{
apr_time_t jun30 = MICROSECONDS_PER_DAY * 12599;
MAKE_LOCALE(localeUS, LOCALE_US);
assertFormattedTime( jun30, localeUS, TimeZone::getGMT(),
LOG4CXX_STR("30 Jun 2004 00:00:00,000"));
}
/** Convert 29 Jun 2004 00:00:00 GMT for Chicago, daylight savings in effect. */
void test4()
{
apr_time_t jul1 = MICROSECONDS_PER_DAY * 12600;
MAKE_LOCALE(localeUS, LOCALE_US);
assertFormattedTime( jul1, localeUS,
TimeZone::getTimeZone(LOG4CXX_STR("GMT-5")),
LOG4CXX_STR("30 Jun 2004 19:00:00,000"));
}
/** Test multiple calls in close intervals. */
void test5()
{
// subsequent calls within one minute
// are optimized to reuse previous formatted value
// make a couple of nearly spaced calls
apr_time_t ticks = MICROSECONDS_PER_DAY * 12601;
MAKE_LOCALE(localeUS, LOCALE_US);
assertFormattedTime( ticks, localeUS, TimeZone::getGMT(),
LOG4CXX_STR("02 Jul 2004 00:00:00,000"));
assertFormattedTime( ticks + 8000, localeUS, TimeZone::getGMT(),
LOG4CXX_STR("02 Jul 2004 00:00:00,008"));
assertFormattedTime( ticks + 17000, localeUS, TimeZone::getGMT(),
LOG4CXX_STR("02 Jul 2004 00:00:00,017"));
assertFormattedTime( ticks + 237000, localeUS, TimeZone::getGMT(),
LOG4CXX_STR("02 Jul 2004 00:00:00,237"));
assertFormattedTime( ticks + 1415000, localeUS, TimeZone::getGMT(),
LOG4CXX_STR("02 Jul 2004 00:00:01,415"));
}
/** Check that caching does not disregard timezone. This test would fail for revision 1.4 of DateTimeDateFormat.java. */
void test6()
{
apr_time_t jul3 = MICROSECONDS_PER_DAY * 12602;
MAKE_LOCALE(localeUS, LOCALE_US);
assertFormattedTime( jul3, localeUS, TimeZone::getGMT(),
LOG4CXX_STR("03 Jul 2004 00:00:00,000"));
assertFormattedTime( jul3, localeUS,
TimeZone::getTimeZone(LOG4CXX_STR("GMT-5")),
LOG4CXX_STR("02 Jul 2004 19:00:00,000"));
assertFormattedTime( jul3, localeUS, TimeZone::getGMT(),
LOG4CXX_STR("03 Jul 2004 00:00:00,000"));
}
#if LOG4CXX_HAS_STD_LOCALE
LogString formatDate(const std::locale& locale, const tm& date, const LogString& fmt) {
//
// output the using STL
//
std::basic_ostringstream<logchar> buffer;
#if defined(_USEFAC)
_USEFAC(locale, std::time_put<logchar>)
.put(buffer, buffer, &date, fmt.c_str(), fmt.c_str() + fmt.length());
#else
#if defined(_RWSTD_NO_TEMPLATE_ON_RETURN_TYPE)
const std::time_put<logchar>& facet = std::use_facet(locale, (std::time_put<logchar>*) 0);
#else
const std::time_put<logchar>& facet = std::use_facet<std::time_put<logchar> >(locale);
#endif
facet.put(buffer, buffer, buffer.fill(), &date, fmt.c_str(), fmt.c_str() + fmt.length());
#endif
return buffer.str();
}
/** Check that format is locale sensitive. */
void test7()
{
apr_time_t avr11 = MICROSECONDS_PER_DAY * 12519;
LocaleChanger localeChange(LOCALE_FR);
if (localeChange.isEffective()) {
LogString formatted;
Pool p;
SimpleDateFormat formatter(LOG4CXX_STR("MMM"));
formatter.format(formatted, avr11, p);
std::locale localeFR(LOCALE_FR);
struct tm avr11tm = { 0, 0, 0, 11, 03, 104 };
LogString expected(formatDate(localeFR, avr11tm, LOG4CXX_STR("%b")));
LOGUNIT_ASSERT_EQUAL(expected, formatted);
}
}
/** Check that format is locale sensitive. */
void test8()
{
apr_time_t apr11 = MICROSECONDS_PER_DAY * 12519;
LocaleChanger localeChange(LOCALE_US);
if (localeChange.isEffective()) {
LogString formatted;
Pool p;
SimpleDateFormat formatter(LOG4CXX_STR("MMM"));
formatter.setTimeZone(TimeZone::getGMT());
formatter.format(formatted, apr11, p);
std::locale localeUS(LOCALE_US);
struct tm apr11tm = { 0, 0, 0, 11, 03, 104 };
LogString expected(formatDate(localeUS, apr11tm, LOG4CXX_STR("%b")));
LOGUNIT_ASSERT_EQUAL(expected, formatted);
}
}
#endif
};
LOGUNIT_TEST_SUITE_REGISTRATION(DateTimeDateFormatTestCase);
| 001-log4cxx | trunk/src/test/cpp/helpers/datetimedateformattestcase.cpp | C++ | asf20 | 7,561 |
/*
* 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/logstring.h>
#include <log4cxx/helpers/absolutetimedateformat.h>
#include "../insertwide.h"
#include <apr.h>
#include <apr_time.h>
#include <log4cxx/helpers/pool.h>
//Define INT64_C for compilers that don't have it
#if (!defined(INT64_C))
#define INT64_C(value) value ## LL
#endif
using namespace log4cxx;
using namespace log4cxx::helpers;
/**
Unit test {@link AbsoluteTimeDateFormat}.
*/
LOGUNIT_CLASS(AbsoluteTimeDateFormatTestCase) {
LOGUNIT_TEST_SUITE(AbsoluteTimeDateFormatTestCase);
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();
public:
/**
* Asserts that formatting the provided date results
* in the expected string.
*
* @param date Date date
* @param timeZone TimeZone timezone for conversion
* @param expected String expected string
*/
private:
void assertFormattedTime(apr_time_t date,
const TimeZonePtr& timeZone,
const LogString& expected) {
AbsoluteTimeDateFormat formatter;
formatter.setTimeZone(timeZone);
LogString actual;
Pool p;
formatter.format(actual, date, p);
LOGUNIT_ASSERT_EQUAL(expected, actual);
}
#define MICROSECONDS_PER_DAY APR_INT64_C(86400000000)
public:
/**
* Convert 02 Jan 2004 00:00:00 GMT for GMT.
*/
void test1() {
//
// 02 Jan 2004 00:00 GMT
//
apr_time_t jan2 = MICROSECONDS_PER_DAY * 12419;
assertFormattedTime(jan2, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,000"));
}
/**
* Convert 03 Jan 2004 00:00:00 GMT for America/Chicago.
*/
void test2() {
//
// 03 Jan 2004 00:00 GMT
// (asking for the same time at a different timezone
// will ignore the change of timezone)
apr_time_t jan2 = MICROSECONDS_PER_DAY * 12420;
assertFormattedTime(jan2, TimeZone::getTimeZone(LOG4CXX_STR("GMT-6")), LOG4CXX_STR("18:00:00,000"));
}
/**
* Convert 29 Jun 2004 00:00:00 GMT for GMT.
*/
void test3() {
apr_time_t jun29 = MICROSECONDS_PER_DAY * 12599;
assertFormattedTime(jun29, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,000"));
}
/**
* Convert 29 Jun 2004 00:00:00 GMT for Chicago, daylight savings in effect.
*/
void test4() {
apr_time_t jun30 = MICROSECONDS_PER_DAY * 12600;
//
// log4cxx doesn't support non-fixed timezones at this time
// passing the fixed equivalent to Chicago's Daylight Savings Time
//
assertFormattedTime(jun30, TimeZone::getTimeZone(LOG4CXX_STR("GMT-5")), LOG4CXX_STR("19:00:00,000"));
}
/**
* Test multiple calls in close intervals.
*/
void test5() {
// subsequent calls within one minute
// are optimized to reuse previous formatted value
// make a couple of nearly spaced calls
apr_time_t ticks = MICROSECONDS_PER_DAY * 12601;
assertFormattedTime(ticks, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,000"));
assertFormattedTime(ticks + 8000, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,008"));
assertFormattedTime(ticks + 17000, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,017"));
assertFormattedTime(ticks + 237000, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,237"));
assertFormattedTime(ticks + 1415000, TimeZone::getGMT(), LOG4CXX_STR("00:00:01,415"));
}
/**
* Check that caching does not disregard timezone.
* This test would fail for revision 1.4 of AbsoluteTimeDateFormat.java.
*/
void test6() {
apr_time_t jul2 = MICROSECONDS_PER_DAY * 12602;
assertFormattedTime(jul2, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,000"));
assertFormattedTime(jul2, TimeZone::getTimeZone(LOG4CXX_STR("GMT-5")), LOG4CXX_STR("19:00:00,000"));
}
/**
* Test multiple calls in close intervals predating 1 Jan 1970.
*/
void test7() {
// subsequent calls within one minute
// are optimized to reuse previous formatted value
// make a couple of nearly spaced calls
apr_time_t ticks = MICROSECONDS_PER_DAY * -7;
assertFormattedTime(ticks, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,000"));
#if defined(_WIN32)
//
// These tests fail on Unix due to bug in APR's explode_time
//
// assertFormattedTime(ticks + 8000, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,008"));
// assertFormattedTime(ticks + 17000, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,017"));
// assertFormattedTime(ticks + 237000, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,237"));
// assertFormattedTime(ticks + 1415000, TimeZone::getGMT(), LOG4CXX_STR("00:00:01,415"));
#endif
}
/**
* Checks that numberFormat works as expected.
*/
void test8() {
Pool p;
LogString numb;
AbsoluteTimeDateFormat formatter;
formatter.numberFormat(numb, 87, p);
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("87"), numb);
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(AbsoluteTimeDateFormatTestCase);
| 001-log4cxx | trunk/src/test/cpp/helpers/absolutetimedateformattestcase.cpp | C++ | asf20 | 5,906 |
/*
* 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/rolling/rollingfileappender.h>
#include "fileappendertestcase.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
/**
Unit tests of log4cxx::RollingFileAppender
*/
class RollingFileAppenderTestCase : public FileAppenderAbstractTestCase
{
LOGUNIT_TEST_SUITE(RollingFileAppenderTestCase);
//
// tests inherited from AppenderSkeletonTestCase
//
LOGUNIT_TEST(testDefaultThreshold);
LOGUNIT_TEST(testSetOptionThreshold);
LOGUNIT_TEST_SUITE_END();
public:
FileAppender* createFileAppender() const {
return new log4cxx::rolling::RollingFileAppender();
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(RollingFileAppenderTestCase);
| 001-log4cxx | trunk/src/test/cpp/rollingfileappendertestcase.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 "appenderskeletontestcase.h"
#include "logunit.h"
#include <log4cxx/helpers/objectptr.h>
#include <log4cxx/appenderskeleton.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
void AppenderSkeletonTestCase::testDefaultThreshold() {
ObjectPtrT<AppenderSkeleton> appender(createAppenderSkeleton());
LevelPtr threshold(appender->getThreshold());
LOGUNIT_ASSERT_EQUAL(Level::getAll()->toInt(), threshold->toInt());
}
void AppenderSkeletonTestCase::testSetOptionThreshold() {
ObjectPtrT<AppenderSkeleton> appender(createAppenderSkeleton());
appender->setOption(LOG4CXX_STR("threshold"), LOG4CXX_STR("debug"));
LevelPtr threshold(appender->getThreshold());
LOGUNIT_ASSERT_EQUAL(Level::getDebug()->toInt(), threshold->toInt());
}
| 001-log4cxx | trunk/src/test/cpp/appenderskeletontestcase.cpp | C++ | asf20 | 1,576 |
/*
* 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 "vectorappender.h"
#include <log4cxx/helpers/thread.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(VectorAppender)
void VectorAppender::append(const spi::LoggingEventPtr& event, Pool& /*p*/)
{
try
{
Thread::sleep(100);
}
catch (Exception&)
{
}
vector.push_back(event);
}
void VectorAppender::close()
{
if (this->closed)
{
return;
}
this->closed = true;
}
| 001-log4cxx | trunk/src/test/cpp/vectorappender.cpp | C++ | asf20 | 1,330 |
/*
* 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/simplelayout.h>
#include <log4cxx/fileappender.h>
#include <log4cxx/level.h>
#include <log4cxx/filter/levelmatchfilter.h>
#include <log4cxx/filter/denyallfilter.h>
#include <log4cxx/helpers/pool.h>
#include <log4cxx/helpers/transcoder.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/spi/loggerrepository.h>
#include "../util/compare.h"
#include "../testchar.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::filter;
LOGUNIT_CLASS(LevelMatchFilterTestCase)
{
LOGUNIT_TEST_SUITE(LevelMatchFilterTestCase);
LOGUNIT_TEST(accept);
LOGUNIT_TEST(deny);
LOGUNIT_TEST_SUITE_END();
LoggerPtr root;
LoggerPtr logger;
public:
void setUp()
{
root = Logger::getRootLogger();
root->removeAllAppenders();
logger = Logger::getLogger(LOG4CXX_TEST_STR("test"));
}
void tearDown()
{
root->getLoggerRepository()->resetConfiguration();
}
void accept()
{
// set up appender
LayoutPtr layout = new SimpleLayout();
AppenderPtr appender = new FileAppender(layout, ACCEPT_FILE, false);
// create LevelMatchFilter
LevelMatchFilterPtr matchFilter = new LevelMatchFilter();
// attach match filter to appender
appender->addFilter(matchFilter);
// attach DenyAllFilter to end of filter chain to deny neutral
// (non matching) messages
spi::FilterPtr filter(new DenyAllFilter());
appender->addFilter(filter);
// set appender on root and set level to debug
root->addAppender(appender);
root->setLevel(Level::getDebug());
LevelPtr levelArray[] =
{ Level::getDebug(), Level::getInfo(), Level::getWarn(), Level::getError(), Level::getFatal() };
int length = sizeof(levelArray)/sizeof(levelArray[0]);
Pool pool;
for (int x = 0; x < length; x++)
{
// set the level to match
matchFilter->setLevelToMatch(levelArray[x]->toString());
LogString sbuf(LOG4CXX_STR("pass "));
StringHelper::toString(x, pool, sbuf);
sbuf.append(LOG4CXX_STR("; filter set to accept only "));
sbuf.append(levelArray[x]->toString());
sbuf.append(LOG4CXX_STR(" msgs"));
common(sbuf);
}
LOGUNIT_ASSERT(Compare::compare(ACCEPT_FILE, ACCEPT_WITNESS));
}
void deny()
{
// set up appender
LayoutPtr layout = new SimpleLayout();
AppenderPtr appender = new FileAppender(layout, DENY_FILE, false);
// create LevelMatchFilter, set to deny matches
LevelMatchFilterPtr matchFilter = new LevelMatchFilter();
matchFilter->setAcceptOnMatch(false);
// attach match filter to appender
appender->addFilter(matchFilter);
// set appender on root and set level to debug
root->addAppender(appender);
root->setLevel(Level::getDebug());
LevelPtr levelArray[] =
{ Level::getDebug(), Level::getInfo(), Level::getWarn(), Level::getError(), Level::getFatal() };
int length = sizeof(levelArray)/sizeof(levelArray[0]);
Pool pool;
for (int x = 0; x < length; x++)
{
// set the level to match
matchFilter->setLevelToMatch(levelArray[x]->toString());
LogString sbuf(LOG4CXX_STR("pass "));
StringHelper::toString(x, pool, sbuf);
sbuf.append(LOG4CXX_STR("; filter set to deny only "));
sbuf.append(levelArray[x]->toString());
sbuf.append(LOG4CXX_STR(" msgs"));
common(sbuf);
}
LOGUNIT_ASSERT(Compare::compare(DENY_FILE, DENY_WITNESS));
}
void common(const LogString& msg)
{
logger->debug(msg);
logger->info(msg);
logger->warn(msg);
logger->error(msg);
logger->fatal(msg);
}
private:
static const LogString ACCEPT_FILE;
static const LogString ACCEPT_WITNESS;
static const LogString DENY_FILE;
static const LogString DENY_WITNESS;
};
const LogString LevelMatchFilterTestCase::ACCEPT_FILE(LOG4CXX_STR("output/LevelMatchFilter_accept"));
const LogString LevelMatchFilterTestCase::ACCEPT_WITNESS(LOG4CXX_STR("witness/LevelMatchFilter_accept"));
const LogString LevelMatchFilterTestCase::DENY_FILE(LOG4CXX_STR("output/LevelMatchFilter_deny"));
const LogString LevelMatchFilterTestCase::DENY_WITNESS(LOG4CXX_STR("witness/LevelMatchFilter_deny"));
LOGUNIT_TEST_SUITE_REGISTRATION(LevelMatchFilterTestCase);
| 001-log4cxx | trunk/src/test/cpp/varia/levelmatchfiltertestcase.cpp | C++ | asf20 | 6,173 |
/*
* 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 <log4cxx/logger.h>
#include <log4cxx/xml/domconfigurator.h>
#include "../logunit.h"
#include "../util/transformer.h"
#include "../util/compare.h"
#include "../util/controlfilter.h"
#include "../util/threadfilter.h"
#include "../util/linenumberfilter.h"
#include <iostream>
#include <log4cxx/file.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::xml;
#define TEST1_A_PAT "FALLBACK - test - Message [0-9]"
#define TEST1_B_PAT "FALLBACK - 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\\} " \
"\\[main]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* - Message [0-9]"
LOGUNIT_CLASS(ErrorHandlerTestCase)
{
LOGUNIT_TEST_SUITE(ErrorHandlerTestCase);
LOGUNIT_TEST(test1);
LOGUNIT_TEST_SUITE_END();
LoggerPtr root;
LoggerPtr logger;
static const File TEMP;
static const File FILTERED;
public:
void setUp()
{
root = Logger::getRootLogger();
logger = Logger::getLogger("test");
}
void tearDown()
{
logger->getLoggerRepository()->resetConfiguration();
}
void test1()
{
DOMConfigurator::configure("input/xml/fallback1.xml");
common();
ControlFilter cf;
cf << TEST1_A_PAT << TEST1_B_PAT << TEST1_2_PAT;
ThreadFilter threadFilter;
LineNumberFilter lineNumberFilter;
std::vector<Filter *> filters;
filters.push_back(&cf);
filters.push_back(&threadFilter);
filters.push_back(&lineNumberFilter);
common();
try
{
Transformer::transform(TEMP, FILTERED, filters);
}
catch(UnexpectedFormatException& e)
{
std::cout << "UnexpectedFormatException :" << e.what() << std::endl;
throw;
}
const File witness("witness/fallback");
LOGUNIT_ASSERT(Compare::compare(FILTERED, witness));
}
void common()
{
int i = -1;
std::ostringstream os;
os << "Message " << ++ i;
LOG4CXX_DEBUG(logger, os.str());
LOG4CXX_DEBUG(root, os.str());
os.str("");
os << "Message " << ++i;
LOG4CXX_INFO(logger, os.str());
LOG4CXX_INFO(root, os.str());
os.str("");
os << "Message " << ++i;
LOG4CXX_WARN(logger, os.str());
LOG4CXX_WARN(root, os.str());
os.str("");
os << "Message " << ++i;
LOG4CXX_ERROR(logger, os.str());
LOG4CXX_ERROR(root, os.str());
os.str("");
os << "Message " << ++i;
LOG4CXX_FATAL(logger, os.str());
LOG4CXX_FATAL(root, os.str());
}
};
//TODO: Not sure this test ever worked. 0.9.7 didn't call common
// had nothing that attempted to dispatch any log events
//LOGUNIT_TEST_SUITE_REGISTRATION(ErrorHandlerTestCase);
const File ErrorHandlerTestCase::TEMP("output/temp");
const File ErrorHandlerTestCase::FILTERED("output/filtered");
| 001-log4cxx | trunk/src/test/cpp/varia/errorhandlertestcase.cpp | C++ | asf20 | 4,241 |
/*
* 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/simplelayout.h>
#include <log4cxx/fileappender.h>
#include <log4cxx/level.h>
#include <log4cxx/filter/levelrangefilter.h>
#include "../util/compare.h"
#include <log4cxx/helpers/pool.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/transcoder.h>
#include "../testchar.h"
#include "../logunit.h"
#include <log4cxx/spi/loggerrepository.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::filter;
LOGUNIT_CLASS(LevelRangeFilterTestCase)
{
LOGUNIT_TEST_SUITE(LevelRangeFilterTestCase);
LOGUNIT_TEST(accept);
LOGUNIT_TEST(neutral);
LOGUNIT_TEST_SUITE_END();
LoggerPtr root;
LoggerPtr logger;
public:
void setUp()
{
root = Logger::getRootLogger();
root->removeAllAppenders();
logger = Logger::getLogger(LOG4CXX_TEST_STR("test"));
}
void tearDown()
{
root->getLoggerRepository()->resetConfiguration();
}
void accept()
{
// set up appender
LayoutPtr layout = new SimpleLayout();
AppenderPtr appender = new FileAppender(layout, ACCEPT_FILE, false);
// create LevelMatchFilter
LevelRangeFilterPtr rangeFilter = new LevelRangeFilter();
// set it to accept on a match
rangeFilter->setAcceptOnMatch(true);
// attach match filter to appender
appender->addFilter(rangeFilter);
// set appender on root and set level to debug
root->addAppender(appender);
root->setLevel(Level::getDebug());
int passCount = 0;
LogString sbuf(LOG4CXX_STR("pass "));
Pool pool;
StringHelper::toString(passCount, pool, sbuf);
sbuf.append(LOG4CXX_STR("; no min or max set"));
common(sbuf);
passCount++;
// test with a min set
rangeFilter->setLevelMin(Level::getWarn());
sbuf.assign(LOG4CXX_STR("pass "));
StringHelper::toString(passCount, pool, sbuf);
sbuf.append(LOG4CXX_STR("; min set to WARN, max not set"));
common(sbuf);
passCount++;
// create a clean filter
appender->clearFilters();
rangeFilter = new LevelRangeFilter();
appender->addFilter(rangeFilter);
//test with max set
rangeFilter->setLevelMax(Level::getWarn());
sbuf.assign(LOG4CXX_STR("pass "));
StringHelper::toString(passCount, pool, sbuf);
sbuf.append(LOG4CXX_STR("; min not set, max set to WARN"));
common(sbuf);
passCount++;
LevelPtr levelArray[] =
{ Level::getDebug(), Level::getInfo(), Level::getWarn(),
Level::getError(), Level::getFatal() };
int length = sizeof(levelArray)/sizeof(levelArray[0]);
for (int x = 0; x < length; x++)
{
// set the min level to match
rangeFilter->setLevelMin(levelArray[x]);
for (int y = length - 1; y >= 0; y--)
{
// set max level to match
rangeFilter->setLevelMax(levelArray[y]);
sbuf.assign(LOG4CXX_STR("pass "));
StringHelper::toString(passCount, pool, sbuf);
sbuf.append(LOG4CXX_STR("; filter set to accept between "));
sbuf.append(levelArray[x]->toString());
sbuf.append(LOG4CXX_STR(" and "));
sbuf.append(levelArray[y]->toString());
sbuf.append(LOG4CXX_STR(" msgs"));
common(sbuf);
// increment passCount
passCount++;
}
}
LOGUNIT_ASSERT(Compare::compare(ACCEPT_FILE, ACCEPT_WITNESS));
}
void neutral()
{
// set up appender
LayoutPtr layout = new SimpleLayout();
AppenderPtr appender = new FileAppender(layout, NEUTRAL_FILE, false);
// create LevelMatchFilter
LevelRangeFilterPtr rangeFilter = new LevelRangeFilter();
// set it to accept on a match
rangeFilter->setAcceptOnMatch(true);
// attach match filter to appender
appender->addFilter(rangeFilter);
// set appender on root and set level to debug
root->addAppender(appender);
root->setLevel(Level::getDebug());
int passCount = 0;
LogString sbuf(LOG4CXX_STR("pass "));
Pool pool;
StringHelper::toString(passCount, pool, sbuf);
// test with no min or max set
sbuf.append(LOG4CXX_STR("; no min or max set"));
common(sbuf);
passCount++;
// test with a min set
rangeFilter->setLevelMin(Level::getWarn());
sbuf.assign(LOG4CXX_STR("pass "));
StringHelper::toString(passCount, pool, sbuf);
sbuf.append(LOG4CXX_STR("; min set to WARN, max not set"));
common(sbuf);
passCount++;
// create a clean filter
appender->clearFilters();
rangeFilter = new LevelRangeFilter();
appender->addFilter(rangeFilter);
//test with max set
rangeFilter->setLevelMax(Level::getWarn());
sbuf.assign(LOG4CXX_STR("pass "));
StringHelper::toString(passCount, pool, sbuf);
sbuf.append(LOG4CXX_STR("; min not set, max set to WARN"));
common(sbuf);
passCount++;
LevelPtr levelArray[] =
{ Level::getDebug(), Level::getInfo(), Level::getWarn(),
Level::getError(), Level::getFatal() };
int length = sizeof(levelArray)/sizeof(levelArray[0]);
for (int x = 0; x < length; x++)
{
// set the min level to match
rangeFilter->setLevelMin(levelArray[x]);
for (int y = length - 1; y >= 0; y--)
{
// set max level to match
rangeFilter->setLevelMax(levelArray[y]);
sbuf.assign(LOG4CXX_STR("pass "));
StringHelper::toString(passCount, pool, sbuf);
sbuf.append(LOG4CXX_STR("; filter set to accept between "));
sbuf.append(levelArray[x]->toString());
sbuf.append(LOG4CXX_STR(" and "));
sbuf.append(levelArray[y]->toString());
sbuf.append(LOG4CXX_STR(" msgs"));
common(sbuf);
// increment passCount
passCount++;
}
}
LOGUNIT_ASSERT(Compare::compare(NEUTRAL_FILE, NEUTRAL_WITNESS));
}
void common(const LogString& msg)
{
logger->debug(msg);
logger->info(msg);
logger->warn(msg);
logger->error(msg);
logger->fatal(msg);
}
private:
static const LogString ACCEPT_FILE;
static const LogString ACCEPT_WITNESS;
static const LogString NEUTRAL_FILE;
static const LogString NEUTRAL_WITNESS;
};
const LogString LevelRangeFilterTestCase::ACCEPT_FILE(LOG4CXX_STR("output/LevelRangeFilter_accept"));
const LogString LevelRangeFilterTestCase::ACCEPT_WITNESS(LOG4CXX_STR("witness/LevelRangeFilter_accept"));
const LogString LevelRangeFilterTestCase::NEUTRAL_FILE(LOG4CXX_STR("output/LevelRangeFilter_neutral"));
const LogString LevelRangeFilterTestCase::NEUTRAL_WITNESS(LOG4CXX_STR("witness/LevelRangeFilter_neutral"));
LOGUNIT_TEST_SUITE_REGISTRATION(LevelRangeFilterTestCase);
| 001-log4cxx | trunk/src/test/cpp/varia/levelrangefiltertestcase.cpp | C++ | asf20 | 9,543 |
/*
* 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(_LOG4CXX_TESTCHAR_H)
#define _LOG4CXX_TESTCHAR_H
//
// This macro and typedef lets many tests
// check either the wchar_t or char based methods.
//
#if LOG4CXX_WCHAR_T_API && defined(LOG4CXX_TEST_WCHAR)
#define LOG4CXX_TEST_STR(str) L ## str
typedef wchar_t testchar;
#else
#define LOG4CXX_TEST_STR(str) str
typedef char testchar;
#endif
#endif
| 001-log4cxx | trunk/src/test/cpp/testchar.h | C | asf20 | 1,171 |
/*
* 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 "fileappendertestcase.h"
#include <log4cxx/helpers/objectptr.h>
#include <log4cxx/fileappender.h>
#include "insertwide.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
WriterAppender* FileAppenderAbstractTestCase::createWriterAppender() const {
return createFileAppender();
}
/**
Unit tests of log4cxx::FileAppender
*/
class FileAppenderTestCase : public FileAppenderAbstractTestCase
{
LOGUNIT_TEST_SUITE(FileAppenderTestCase);
//
// tests inherited from AppenderSkeletonTestCase
//
LOGUNIT_TEST(testDefaultThreshold);
LOGUNIT_TEST(testSetOptionThreshold);
// tests defined here
LOGUNIT_TEST(testSetDoubleBackslashes);
LOGUNIT_TEST(testStripDuplicateBackslashes);
LOGUNIT_TEST_SUITE_END();
public:
FileAppender* createFileAppender() const {
return new log4cxx::FileAppender();
}
void testSetDoubleBackslashes() {
FileAppender appender;
appender.setOption(LOG4CXX_STR("FILE"), LOG4CXX_STR("output\\\\temp"));
const File& file = appender.getFile();
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("output\\temp"), file.getPath());
}
/**
* Tests that double backslashes in filespecs are stripped
* on calls to setOption.
*
*/
void testStripDoubleBackslashes() {
FileAppender appender;
appender.setOption(LOG4CXX_STR("FILE"), LOG4CXX_STR("output\\\\temp"));
const File& file = appender.getFile();
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("output\\temp"), file.getPath());
}
/**
* Tests stripDuplicateBackslashes
*
*
*/
void testStripDuplicateBackslashes() {
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("\\foo\\bar\\foo"),
FileAppender::stripDuplicateBackslashes(LOG4CXX_STR("\\foo\\bar\\foo")));
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("\\foo\\bar\\foo\\"),
FileAppender::stripDuplicateBackslashes(LOG4CXX_STR("\\\\foo\\\\bar\\\\foo\\\\")));
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("\\foo\\bar\\foo\\"),
FileAppender::stripDuplicateBackslashes(LOG4CXX_STR("\\foo\\bar\\foo\\")));
//
// UNC's should either start with two backslashes and contain additional singles
// or four back slashes and addition doubles
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("\\\\foo\\bar\\foo"),
FileAppender::stripDuplicateBackslashes(LOG4CXX_STR("\\\\\\\\foo\\\\bar\\\\foo")));
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("\\\\foo\\bar\\foo"),
FileAppender::stripDuplicateBackslashes(LOG4CXX_STR("\\\\foo\\bar\\foo")));
//
// it it starts with doubles but has no other path component
// then it is a file path
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("\\foo.log"),
FileAppender::stripDuplicateBackslashes(LOG4CXX_STR("\\\\foo.log")));
//
// it it starts with quads but has no other path component
// then it is a UNC
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("\\\\foo.log"),
FileAppender::stripDuplicateBackslashes(LOG4CXX_STR("\\\\\\\\foo.log")));
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(FileAppenderTestCase);
| 001-log4cxx | trunk/src/test/cpp/fileappendertestcase.cpp | C++ | asf20 | 4,427 |
/*
* 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/fileappender.h>
#include <log4cxx/appenderskeleton.h>
#include <log4cxx/basicconfigurator.h>
#include <log4cxx/logmanager.h>
#include <log4cxx/level.h>
#include <log4cxx/hierarchy.h>
#include <log4cxx/spi/rootlogger.h>
#include <log4cxx/helpers/propertyresourcebundle.h>
#include "insertwide.h"
#include "testchar.h"
#include "logunit.h"
#include <log4cxx/helpers/locale.h>
#include "vectorappender.h"
using namespace log4cxx;
using namespace log4cxx::spi;
using namespace log4cxx::helpers;
class CountingAppender;
typedef helpers::ObjectPtrT<CountingAppender> CountingAppenderPtr;
class CountingAppender : public AppenderSkeleton
{
public:
int counter;
CountingAppender() : counter(0)
{}
void close()
{}
void append(const spi::LoggingEventPtr& /*event*/, Pool& /*p*/)
{ counter++; }
bool requiresLayout() const
{ return true; }
};
LOGUNIT_CLASS(LoggerTestCase)
{
LOGUNIT_TEST_SUITE(LoggerTestCase);
LOGUNIT_TEST(testAppender1);
LOGUNIT_TEST(testAppender2);
LOGUNIT_TEST(testAdditivity1);
LOGUNIT_TEST(testAdditivity2);
LOGUNIT_TEST(testAdditivity3);
LOGUNIT_TEST(testDisable1);
// LOGUNIT_TEST(testRB1);
// LOGUNIT_TEST(testRB2); //TODO restore
// LOGUNIT_TEST(testRB3);
LOGUNIT_TEST(testExists);
LOGUNIT_TEST(testHierarchy1);
LOGUNIT_TEST(testTrace);
LOGUNIT_TEST(testIsTraceEnabled);
LOGUNIT_TEST_SUITE_END();
public:
void setUp()
{
}
void tearDown()
{
BasicConfigurator::resetConfiguration();
a1 = 0;
a2 = 0;
logger = 0;
}
/**
Add an appender and see if it can be retrieved.
*/
void testAppender1()
{
logger = Logger::getLogger(LOG4CXX_TEST_STR("test"));
a1 = new FileAppender();
a1->setName(LOG4CXX_STR("testAppender1"));
logger->addAppender(a1);
AppenderList list = logger->getAllAppenders();
AppenderPtr aHat = list.front();
LOGUNIT_ASSERT_EQUAL(a1, aHat);
}
/**
Add an appender X, Y, remove X and check if Y is the only
remaining appender.
*/
void testAppender2()
{
a1 = new FileAppender();
a1->setName(LOG4CXX_STR("testAppender2.1"));
a2 = new FileAppender();
a2->setName(LOG4CXX_STR("testAppender2.2"));
logger = Logger::getLogger(LOG4CXX_TEST_STR("test"));
logger->addAppender(a1);
logger->addAppender(a2);
logger->removeAppender((LogString) LOG4CXX_STR("testAppender2.1"));
AppenderList list = logger->getAllAppenders();
AppenderPtr aHat = list.front();
LOGUNIT_ASSERT_EQUAL(a2, aHat);
LOGUNIT_ASSERT(list.size() == 1);
}
/**
Test if LoggerPtr a.b inherits its appender from a.
*/
void testAdditivity1()
{
LoggerPtr a = Logger::getLogger(LOG4CXX_TEST_STR("a"));
LoggerPtr ab = Logger::getLogger(LOG4CXX_TEST_STR("a.b"));
CountingAppenderPtr ca = new CountingAppender();
a->addAppender(ca);
LOGUNIT_ASSERT_EQUAL(ca->counter, 0);
ab->debug(MSG);
LOGUNIT_ASSERT_EQUAL(ca->counter, 1);
ab->info(MSG);
LOGUNIT_ASSERT_EQUAL(ca->counter, 2);
ab->warn(MSG);
LOGUNIT_ASSERT_EQUAL(ca->counter, 3);
ab->error(MSG);
LOGUNIT_ASSERT_EQUAL(ca->counter, 4);
}
/**
Test multiple additivity.
*/
void testAdditivity2()
{
LoggerPtr a = Logger::getLogger(LOG4CXX_TEST_STR("a"));
LoggerPtr ab = Logger::getLogger(LOG4CXX_TEST_STR("a.b"));
LoggerPtr abc = Logger::getLogger(LOG4CXX_TEST_STR("a.b.c"));
LoggerPtr x = Logger::getLogger(LOG4CXX_TEST_STR("x"));
CountingAppenderPtr ca1 = new CountingAppender();
CountingAppenderPtr ca2 = new CountingAppender();
a->addAppender(ca1);
abc->addAppender(ca2);
LOGUNIT_ASSERT_EQUAL(ca1->counter, 0);
LOGUNIT_ASSERT_EQUAL(ca2->counter, 0);
ab->debug(MSG);
LOGUNIT_ASSERT_EQUAL(ca1->counter, 1);
LOGUNIT_ASSERT_EQUAL(ca2->counter, 0);
abc->debug(MSG);
LOGUNIT_ASSERT_EQUAL(ca1->counter, 2);
LOGUNIT_ASSERT_EQUAL(ca2->counter, 1);
x->debug(MSG);
LOGUNIT_ASSERT_EQUAL(ca1->counter, 2);
LOGUNIT_ASSERT_EQUAL(ca2->counter, 1);
}
/**
Test additivity flag.
*/
void testAdditivity3()
{
LoggerPtr root = Logger::getRootLogger();
LoggerPtr a = Logger::getLogger(LOG4CXX_TEST_STR("a"));
LoggerPtr ab = Logger::getLogger(LOG4CXX_TEST_STR("a.b"));
LoggerPtr abc = Logger::getLogger(LOG4CXX_TEST_STR("a.b.c"));
LoggerPtr x = Logger::getLogger(LOG4CXX_TEST_STR("x"));
CountingAppenderPtr caRoot = new CountingAppender();
CountingAppenderPtr caA = new CountingAppender();
CountingAppenderPtr caABC = new CountingAppender();
root->addAppender(caRoot);
a->addAppender(caA);
abc->addAppender(caABC);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 0);
LOGUNIT_ASSERT_EQUAL(caA->counter, 0);
LOGUNIT_ASSERT_EQUAL(caABC->counter, 0);
ab->setAdditivity(false);
a->debug(MSG);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 1);
LOGUNIT_ASSERT_EQUAL(caA->counter, 1);
LOGUNIT_ASSERT_EQUAL(caABC->counter, 0);
ab->debug(MSG);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 1);
LOGUNIT_ASSERT_EQUAL(caA->counter, 1);
LOGUNIT_ASSERT_EQUAL(caABC->counter, 0);
abc->debug(MSG);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 1);
LOGUNIT_ASSERT_EQUAL(caA->counter, 1);
LOGUNIT_ASSERT_EQUAL(caABC->counter, 1);
}
void testDisable1()
{
CountingAppenderPtr caRoot = new CountingAppender();
LoggerPtr root = Logger::getRootLogger();
root->addAppender(caRoot);
LoggerRepositoryPtr h = LogManager::getLoggerRepository();
//h.disableDebug();
h->setThreshold(Level::getInfo());
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 0);
root->debug(MSG);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 0);
root->info(MSG);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 1);
root->log(Level::getWarn(), MSG);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 2);
root->warn(MSG);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 3);
//h.disableInfo();
h->setThreshold(Level::getWarn());
root->debug(MSG);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 3);
root->info(MSG);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 3);
root->log(Level::getWarn(), MSG);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 4);
root->error(MSG);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 5);
root->log(Level::getError(), MSG);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6);
//h.disableAll();
h->setThreshold(Level::getOff());
root->debug(MSG);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6);
root->info(MSG);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6);
root->log(Level::getWarn(), MSG);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6);
root->error(MSG);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6);
root->log(Level::getFatal(), MSG);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6);
root->log(Level::getFatal(), MSG);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6);
//h.disable(Level::getFatalLevel());
h->setThreshold(Level::getOff());
root->debug(MSG);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6);
root->info(MSG);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6);
root->log(Level::getWarn(), MSG);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6);
root->error(MSG);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6);
root->log(Level::getWarn(), MSG);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6);
root->log(Level::getFatal(), MSG);
LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6);
}
ResourceBundlePtr getBundle(const LogString& lang, const LogString& region)
{
Locale l(lang, region);
ResourceBundlePtr bundle(
PropertyResourceBundle::getBundle(LOG4CXX_STR("L7D"),l));
LOGUNIT_ASSERT(bundle != 0);
return bundle;
}
void testRB1()
{
ResourceBundlePtr rbUS(getBundle(LOG4CXX_STR("en"), LOG4CXX_STR("US")));
ResourceBundlePtr rbFR(getBundle(LOG4CXX_STR("fr"), LOG4CXX_STR("FR")));
ResourceBundlePtr rbCH(getBundle(LOG4CXX_STR("fr"), LOG4CXX_STR("CH")));
LoggerPtr root = Logger::getRootLogger();
root->setResourceBundle(rbUS);
ResourceBundlePtr t = root->getResourceBundle();
LOGUNIT_ASSERT(t == rbUS);
LoggerPtr x = Logger::getLogger(LOG4CXX_TEST_STR("x"));
LoggerPtr x_y = Logger::getLogger(LOG4CXX_TEST_STR("x.y"));
LoggerPtr x_y_z = Logger::getLogger(LOG4CXX_TEST_STR("x.y.z"));
t = x->getResourceBundle();
LOGUNIT_ASSERT(t == rbUS);
t = x_y->getResourceBundle();
LOGUNIT_ASSERT(t == rbUS);
t = x_y_z->getResourceBundle();
LOGUNIT_ASSERT(t == rbUS);
}
void testRB2()
{
LoggerPtr root = Logger::getRootLogger();
ResourceBundlePtr rbUS(getBundle(LOG4CXX_STR("en"), LOG4CXX_STR("US")));
ResourceBundlePtr rbFR(getBundle(LOG4CXX_STR("fr"), LOG4CXX_STR("FR")));
ResourceBundlePtr rbCH(getBundle(LOG4CXX_STR("fr"), LOG4CXX_STR("CH")));
root->setResourceBundle(rbUS);
ResourceBundlePtr t = root->getResourceBundle();
LOGUNIT_ASSERT(t == rbUS);
LoggerPtr x = Logger::getLogger(LOG4CXX_TEST_STR("x"));
LoggerPtr x_y = Logger::getLogger(LOG4CXX_TEST_STR("x.y"));
LoggerPtr x_y_z = Logger::getLogger(LOG4CXX_TEST_STR("x.y.z"));
x_y->setResourceBundle(rbFR);
t = x->getResourceBundle();
LOGUNIT_ASSERT(t == rbUS);
t = x_y->getResourceBundle();
LOGUNIT_ASSERT(t == rbFR);
t = x_y_z->getResourceBundle();
LOGUNIT_ASSERT(t == rbFR);
}
void testRB3()
{
ResourceBundlePtr rbUS(getBundle(LOG4CXX_STR("en"), LOG4CXX_STR("US")));
ResourceBundlePtr rbFR(getBundle(LOG4CXX_STR("fr"), LOG4CXX_STR("FR")));
ResourceBundlePtr rbCH(getBundle(LOG4CXX_STR("fr"), LOG4CXX_STR("CH")));
LoggerPtr root = Logger::getRootLogger();
root->setResourceBundle(rbUS);
ResourceBundlePtr t = root->getResourceBundle();
LOGUNIT_ASSERT(t == rbUS);
LoggerPtr x = Logger::getLogger(LOG4CXX_TEST_STR("x"));
LoggerPtr x_y = Logger::getLogger(LOG4CXX_TEST_STR("x.y"));
LoggerPtr x_y_z = Logger::getLogger(LOG4CXX_TEST_STR("x.y.z"));
x_y->setResourceBundle(rbFR);
x_y_z->setResourceBundle(rbCH);
t = x->getResourceBundle();
LOGUNIT_ASSERT(t == rbUS);
t = x_y->getResourceBundle();
LOGUNIT_ASSERT(t == rbFR);
t = x_y_z->getResourceBundle();
LOGUNIT_ASSERT(t == rbCH);
}
void testExists()
{
LoggerPtr a = Logger::getLogger(LOG4CXX_TEST_STR("a"));
LoggerPtr a_b = Logger::getLogger(LOG4CXX_TEST_STR("a.b"));
LoggerPtr a_b_c = Logger::getLogger(LOG4CXX_TEST_STR("a.b.c"));
LoggerPtr t;
t = LogManager::exists(LOG4CXX_TEST_STR("xx"));
LOGUNIT_ASSERT(t == 0);
t = LogManager::exists(LOG4CXX_TEST_STR("a"));
LOGUNIT_ASSERT_EQUAL(a, t);
t = LogManager::exists(LOG4CXX_TEST_STR("a.b"));
LOGUNIT_ASSERT_EQUAL(a_b, t);
t = LogManager::exists(LOG4CXX_TEST_STR("a.b.c"));
LOGUNIT_ASSERT_EQUAL(a_b_c, t);
}
void testHierarchy1()
{
LoggerRepositoryPtr h = new Hierarchy();
LoggerPtr root(h->getRootLogger());
root->setLevel(Level::getError());
LoggerPtr a0 = h->getLogger(LOG4CXX_STR("a"));
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("a"), a0->getName());
LOGUNIT_ASSERT(a0->getLevel() == 0);
LOGUNIT_ASSERT(Level::getError() == a0->getEffectiveLevel());
LoggerPtr a11 = h->getLogger(LOG4CXX_STR("a"));
LOGUNIT_ASSERT_EQUAL(a0, a11);
}
void compileTestForLOGCXX202() const {
//
// prior to fix, these line would compile.
//
(*logger).info("Hello, World.");
((Logger*) logger)->info("Hello, World.");
//
// this one would not.
//
logger->info("Hello, World.");
}
/**
* Tests logger.trace(Object).
*
*/
void testTrace() {
VectorAppenderPtr appender = new VectorAppender();
LoggerPtr root = Logger::getRootLogger();
root->addAppender(appender);
root->setLevel(Level::getInfo());
LoggerPtr tracer = Logger::getLogger("com.example.Tracer");
tracer->setLevel(Level::getTrace());
LOG4CXX_TRACE(tracer, "Message 1");
LOG4CXX_TRACE(root, "Discarded Message");
LOG4CXX_TRACE(root, "Discarded Message");
std::vector<LoggingEventPtr> msgs(appender->vector);
LOGUNIT_ASSERT_EQUAL((size_t) 1, msgs.size());
LoggingEventPtr event = msgs[0];
LOGUNIT_ASSERT_EQUAL((int) Level::TRACE_INT, event->getLevel()->toInt());
LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("Message 1")), event->getMessage());
}
/**
* Tests isTraceEnabled.
*
*/
void testIsTraceEnabled() {
VectorAppenderPtr appender = new VectorAppender();
LoggerPtr root = Logger::getRootLogger();
root->addAppender(appender);
root->setLevel(Level::getInfo());
LoggerPtr tracer = Logger::getLogger("com.example.Tracer");
tracer->setLevel(Level::getTrace());
LOGUNIT_ASSERT_EQUAL(true, tracer->isTraceEnabled());
LOGUNIT_ASSERT_EQUAL(false, root->isTraceEnabled());
}
protected:
static LogString MSG;
LoggerPtr logger;
AppenderPtr a1;
AppenderPtr a2;
};
LogString LoggerTestCase::MSG(LOG4CXX_STR("M"));
LOGUNIT_TEST_SUITE_REGISTRATION(LoggerTestCase);
| 001-log4cxx | trunk/src/test/cpp/loggertestcase.cpp | C++ | asf20 | 17,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.
*/
#include <ostream>
#include <iomanip>
#include "vectorappender.h"
#include <log4cxx/logmanager.h>
#include <log4cxx/simplelayout.h>
#include <log4cxx/spi/loggingevent.h>
#include "insertwide.h"
#include "logunit.h"
#include <log4cxx/stream.h>
#if LOG4CXX_CFSTRING_API
#include <CoreFoundation/CFString.h>
#endif
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace std;
class ExceptionOnInsert {
public:
ExceptionOnInsert() {
}
};
//
// define an insertion operation that will throw an
// exception to test that evaluation was short
// circuited
//
template<class Elem, class Tr>
::std::basic_ostream<Elem, Tr>& operator<<(
::std::basic_ostream<Elem, Tr>&,
const ExceptionOnInsert&) {
throw std::exception();
}
/**
Unit tests for the optional stream-like interface for log4cxx
*/
LOGUNIT_CLASS(StreamTestCase)
{
LOGUNIT_TEST_SUITE(StreamTestCase);
LOGUNIT_TEST(testSimple);
LOGUNIT_TEST(testMultiple);
LOGUNIT_TEST(testShortCircuit);
LOGUNIT_TEST_EXCEPTION(testInsertException, std::exception);
LOGUNIT_TEST(testScientific);
LOGUNIT_TEST(testPrecision);
LOGUNIT_TEST(testWidth);
#if LOG4CXX_WCHAR_T_API
LOGUNIT_TEST(testWide);
LOGUNIT_TEST(testWideAppend);
LOGUNIT_TEST(testWideWidth);
#endif
LOGUNIT_TEST(testBaseFlags);
LOGUNIT_TEST(testBasePrecisionAndWidth);
LOGUNIT_TEST(testLogStreamSimple);
LOGUNIT_TEST(testLogStreamMultiple);
LOGUNIT_TEST(testLogStreamShortCircuit);
LOGUNIT_TEST_EXCEPTION(testLogStreamInsertException, std::exception);
LOGUNIT_TEST(testLogStreamScientific);
LOGUNIT_TEST(testLogStreamPrecision);
LOGUNIT_TEST(testLogStreamWidth);
LOGUNIT_TEST(testLogStreamDelegate);
LOGUNIT_TEST(testLogStreamFormattingPersists);
LOGUNIT_TEST(testSetWidthInsert);
#if LOG4CXX_WCHAR_T_API
LOGUNIT_TEST(testWLogStreamSimple);
LOGUNIT_TEST(testWLogStreamMultiple);
LOGUNIT_TEST(testWLogStreamShortCircuit);
LOGUNIT_TEST_EXCEPTION(testWLogStreamInsertException, std::exception);
LOGUNIT_TEST(testWLogStreamScientific);
LOGUNIT_TEST(testWLogStreamPrecision);
LOGUNIT_TEST(testWLogStreamWidth);
LOGUNIT_TEST(testWLogStreamDelegate);
LOGUNIT_TEST(testWLogStreamFormattingPersists);
LOGUNIT_TEST(testWSetWidthInsert);
#endif
#if LOG4CXX_UNICHAR_API
LOGUNIT_TEST(testUniChar);
LOGUNIT_TEST(testUniCharAppend);
// LOGUNIT_TEST(testUniCharWidth);
LOGUNIT_TEST(testULogStreamSimple);
LOGUNIT_TEST(testULogStreamMultiple);
LOGUNIT_TEST(testULogStreamShortCircuit);
LOGUNIT_TEST_EXCEPTION(testULogStreamInsertException, std::exception);
// LOGUNIT_TEST(testULogStreamScientific);
// LOGUNIT_TEST(testULogStreamPrecision);
// LOGUNIT_TEST(testULogStreamWidth);
LOGUNIT_TEST(testULogStreamDelegate);
// LOGUNIT_TEST(testULogStreamFormattingPersists);
// LOGUNIT_TEST(testUSetWidthInsert);
#endif
#if LOG4CXX_CFSTRING_API
LOGUNIT_TEST(testCFString);
LOGUNIT_TEST(testCFStringAppend);
LOGUNIT_TEST(testULogStreamCFString);
LOGUNIT_TEST(testULogStreamCFString2);
#endif
LOGUNIT_TEST_SUITE_END();
VectorAppenderPtr vectorAppender;
public:
void setUp() {
LoggerPtr root(Logger::getRootLogger());
LayoutPtr layout(new SimpleLayout());
vectorAppender = new VectorAppender();
root->addAppender(vectorAppender);
}
void tearDown()
{
LogManager::shutdown();
}
void testSimple() {
LoggerPtr root(Logger::getRootLogger());
LOG4CXX_INFO(root, "This is a test");
LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size());
}
void testMultiple() {
LoggerPtr root(Logger::getRootLogger());
LOG4CXX_INFO(root, "This is a test" << ": Details to follow");
LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size());
}
void testShortCircuit() {
LoggerPtr logger(Logger::getLogger("StreamTestCase.shortCircuit"));
logger->setLevel(Level::getInfo());
ExceptionOnInsert someObj;
LOG4CXX_DEBUG(logger, someObj);
LOGUNIT_ASSERT_EQUAL((size_t) 0, vectorAppender->getVector().size());
}
void testInsertException() {
LoggerPtr logger(Logger::getLogger("StreamTestCase.insertException"));
ExceptionOnInsert someObj;
LOG4CXX_INFO(logger, someObj);
}
void testScientific() {
LoggerPtr root(Logger::getRootLogger());
LOG4CXX_INFO(root, std::scientific << 0.000001115);
spi::LoggingEventPtr event(vectorAppender->getVector()[0]);
LogString msg(event->getMessage());
LOGUNIT_ASSERT(msg.find(LOG4CXX_STR("e-")) != LogString::npos ||
msg.find(LOG4CXX_STR("E-")) != LogString::npos);
}
void testPrecision() {
LoggerPtr root(Logger::getRootLogger());
LOG4CXX_INFO(root, std::setprecision(4) << 1.000001);
spi::LoggingEventPtr event(vectorAppender->getVector()[0]);
LogString msg(event->getMessage());
LOGUNIT_ASSERT(msg.find(LOG4CXX_STR("1.00000")) == LogString::npos);
}
void testWidth() {
LoggerPtr root(Logger::getRootLogger());
LOG4CXX_INFO(root, '[' << std::fixed << std::setprecision(2) << std::setw(7) << std::right << std::setfill('_') << 10.0 << ']');
spi::LoggingEventPtr event(vectorAppender->getVector()[0]);
LogString msg(event->getMessage());
LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("[__10.00]")), msg);
}
void testBaseFlags() {
logstream base1(Logger::getRootLogger(), Level::getInfo());
logstream base2(Logger::getRootLogger(), Level::getInfo());
base1 << std::boolalpha;
base2 << std::noboolalpha;
std::ostringstream os1a, os1b, os2a, os2b;
os1a << std::boolalpha;
int fillchar;
if (base1.set_stream_state(os1b, fillchar)) {
os1b.fill(fillchar);
}
LOGUNIT_ASSERT_EQUAL(os1a.flags(), os1b.flags());
os2a << std::noboolalpha;
if (base2.set_stream_state(os2b, fillchar)) {
os2b.fill(fillchar);
}
LOGUNIT_ASSERT_EQUAL(os2a.flags(), os2b.flags());
}
void testBasePrecisionAndWidth() {
logstream base(Logger::getRootLogger(), Level::getInfo());
base.precision(2);
base.width(5);
std::ostringstream os1, os2;
os1.precision(2);
os1.width(5);
os1 << 3.1415926;
int fillchar;
if (base.set_stream_state(os2, fillchar)) {
os2.fill(fillchar);
}
os2 << 3.1415926;
string expected(os1.str());
string actual(os2.str());
LOGUNIT_ASSERT_EQUAL(expected, actual);
}
void testLogStreamSimple() {
logstream root(Logger::getRootLogger(), Level::getInfo());
root << "This is a test" << LOG4CXX_ENDMSG;
LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size());
}
void testLogStreamMultiple() {
logstream root(Logger::getRootLogger(), Level::getInfo());
root << "This is a test" << ": Details to follow" << LOG4CXX_ENDMSG;
LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size());
}
void testLogStreamShortCircuit() {
LoggerPtr logger(Logger::getLogger("StreamTestCase.shortCircuit"));
logger->setLevel(Level::getInfo());
logstream os(logger, Level::getDebug());
ExceptionOnInsert someObj;
os << someObj << LOG4CXX_ENDMSG;
LOGUNIT_ASSERT_EQUAL((size_t) 0, vectorAppender->getVector().size());
}
void testLogStreamInsertException() {
LoggerPtr logger(Logger::getLogger("StreamTestCase.insertException"));
ExceptionOnInsert someObj;
logstream os(logger, Level::getInfo());
os << someObj << LOG4CXX_ENDMSG;
}
void testLogStreamScientific() {
LoggerPtr root(Logger::getRootLogger());
logstream os(root, Level::getInfo());
os << std::scientific << 0.000001115 << LOG4CXX_ENDMSG;
spi::LoggingEventPtr event(vectorAppender->getVector()[0]);
LogString msg(event->getMessage());
LOGUNIT_ASSERT(msg.find(LOG4CXX_STR("e-")) != LogString::npos ||
msg.find(LOG4CXX_STR("E-")) != LogString::npos);
}
void testLogStreamPrecision() {
LoggerPtr root(Logger::getRootLogger());
logstream os(root, Level::getInfo());
os << std::setprecision(4) << 1.000001 << LOG4CXX_ENDMSG;
spi::LoggingEventPtr event(vectorAppender->getVector()[0]);
LogString msg(event->getMessage());
LOGUNIT_ASSERT(msg.find(LOG4CXX_STR("1.00000")) == LogString::npos);
}
void testLogStreamWidth() {
LoggerPtr root(Logger::getRootLogger());
logstream os(root, Level::getInfo());
os << '[' << std::fixed << std::setprecision(2) << std::setw(7) << std::right << std::setfill('_') << 10.0 << ']' << LOG4CXX_ENDMSG;
spi::LoggingEventPtr event(vectorAppender->getVector()[0]);
LogString msg(event->getMessage());
LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("[__10.00]")), msg);
}
void report(std::ostream& os) {
os << "This just in: \n";
os << "Use logstream in places that expect a std::ostream.\n";
}
void testLogStreamDelegate() {
logstream root(Logger::getRootLogger(), Level::getInfo());
report(root);
root << LOG4CXX_ENDMSG;
LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size());
}
void testLogStreamFormattingPersists() {
LoggerPtr root(Logger::getRootLogger());
root->setLevel(Level::getInfo());
logstream os(root, Level::getDebug());
os << std::hex << 20 << LOG4CXX_ENDMSG;
os << Level::getInfo() << 16 << LOG4CXX_ENDMSG;
spi::LoggingEventPtr event(vectorAppender->getVector()[0]);
LogString msg(event->getMessage());
LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("10")), msg);
}
void testSetWidthInsert() {
LoggerPtr root(Logger::getRootLogger());
root->setLevel(Level::getInfo());
logstream os(root, Level::getInfo());
os << std::setw(5);
LOGUNIT_ASSERT_EQUAL(5, os.width());
}
#if LOG4CXX_WCHAR_T_API
void testWide() {
LoggerPtr root(Logger::getRootLogger());
LOG4CXX_INFO(root, L"This is a test");
LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size());
}
void testWideAppend() {
LoggerPtr root(Logger::getRootLogger());
LOG4CXX_INFO(root, L"This is a test" << L": Details to follow");
LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size());
}
void testWideWidth() {
LoggerPtr root(Logger::getRootLogger());
LOG4CXX_INFO(root, L'[' << std::fixed << std::setprecision(2) << std::setw(7) << std::right << std::setfill(L'_') << 10.0 << L"]");
spi::LoggingEventPtr event(vectorAppender->getVector()[0]);
LogString msg(event->getMessage());
LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("[__10.00]")), msg);
}
void testWLogStreamSimple() {
wlogstream root(Logger::getRootLogger(), Level::getInfo());
root << L"This is a test" << LOG4CXX_ENDMSG;
LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size());
}
void testWLogStreamMultiple() {
wlogstream root(Logger::getRootLogger(), Level::getInfo());
root << L"This is a test" << L": Details to follow" << LOG4CXX_ENDMSG;
LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size());
}
void testWLogStreamShortCircuit() {
LoggerPtr logger(Logger::getLogger("StreamTestCase.shortCircuit"));
logger->setLevel(Level::getInfo());
wlogstream os(logger, Level::getDebug());
ExceptionOnInsert someObj;
os << someObj << LOG4CXX_ENDMSG;
LOGUNIT_ASSERT_EQUAL((size_t) 0, vectorAppender->getVector().size());
}
void testWLogStreamInsertException() {
LoggerPtr logger(Logger::getLogger("StreamTestCase.insertException"));
ExceptionOnInsert someObj;
wlogstream os(logger, Level::getInfo());
os << someObj << LOG4CXX_ENDMSG;
}
void testWLogStreamScientific() {
LoggerPtr root(Logger::getRootLogger());
wlogstream os(root, Level::getInfo());
os << std::scientific << 0.000001115 << LOG4CXX_ENDMSG;
spi::LoggingEventPtr event(vectorAppender->getVector()[0]);
LogString msg(event->getMessage());
LOGUNIT_ASSERT(msg.find(LOG4CXX_STR("e-")) != LogString::npos ||
msg.find(LOG4CXX_STR("E-")) != LogString::npos);
}
void testWLogStreamPrecision() {
LoggerPtr root(Logger::getRootLogger());
wlogstream os(root, Level::getInfo());
os << std::setprecision(4) << 1.000001 << LOG4CXX_ENDMSG;
spi::LoggingEventPtr event(vectorAppender->getVector()[0]);
LogString msg(event->getMessage());
LOGUNIT_ASSERT(msg.find(LOG4CXX_STR("1.00000")) == LogString::npos);
}
void testWLogStreamWidth() {
LoggerPtr root(Logger::getRootLogger());
wlogstream os(root, Level::getInfo());
os << L"[" << std::fixed << std::setprecision(2) << std::setw(7) << std::right << std::setfill(L'_') << 10.0 << L"]" << LOG4CXX_ENDMSG;
spi::LoggingEventPtr event(vectorAppender->getVector()[0]);
LogString msg(event->getMessage());
LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("[__10.00]")), msg);
}
void wreport(std::basic_ostream<wchar_t>& os) {
os << L"This just in: \n";
os << L"Use logstream in places that expect a std::ostream.\n";
}
void testWLogStreamDelegate() {
wlogstream root(Logger::getRootLogger(), Level::getInfo());
wreport(root);
root << LOG4CXX_ENDMSG;
LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size());
}
void testWLogStreamFormattingPersists() {
LoggerPtr root(Logger::getRootLogger());
root->setLevel(Level::getInfo());
wlogstream os(root, Level::getDebug());
os << std::hex << 20 << LOG4CXX_ENDMSG;
os << Level::getInfo() << 16 << LOG4CXX_ENDMSG;
spi::LoggingEventPtr event(vectorAppender->getVector()[0]);
LogString msg(event->getMessage());
LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("10")), msg);
}
void testWSetWidthInsert() {
LoggerPtr root(Logger::getRootLogger());
root->setLevel(Level::getInfo());
wlogstream os(root, Level::getInfo());
os << std::setw(5);
LOGUNIT_ASSERT_EQUAL(5, os.width());
}
#endif
#if LOG4CXX_UNICHAR_API
void testUniChar() {
LoggerPtr root(Logger::getRootLogger());
const log4cxx::UniChar msg[] = { 'T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 0 };
LOG4CXX_INFO(root, msg);
LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size());
}
void testUniCharAppend() {
LoggerPtr root(Logger::getRootLogger());
const log4cxx::UniChar msg1[] = { 'T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 0 };
const log4cxx::UniChar msg2[] = { ':', ' ', 'D', 'e', 't', 'a', 'i', 'l', 's', ' ', 't', 'o', ' ', 'f', 'o', 'l', 'l', 'o', 'w', 0 };
LOG4CXX_INFO(root, msg1 << msg2);
LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size());
}
void testUniCharWidth() {
LoggerPtr root(Logger::getRootLogger());
const log4cxx::UniChar openBracket[] = { '[', 0 };
const log4cxx::UniChar closeBracket[] = { ']', 0 };
LOG4CXX_INFO(root, openBracket << std::fixed << std::setprecision(2) << std::setw(7) << std::right << std::setfill((log4cxx::UniChar) '_') << 10.0 << closeBracket);
spi::LoggingEventPtr event(vectorAppender->getVector()[0]);
LogString msg(event->getMessage());
LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("[__10.00]")), msg);
}
void testULogStreamSimple() {
ulogstream root(Logger::getRootLogger(), Level::getInfo());
const log4cxx::UniChar msg[] = { 'T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 0 };
root << msg << LOG4CXX_ENDMSG;
LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size());
}
void testULogStreamMultiple() {
ulogstream root(Logger::getRootLogger(), Level::getInfo());
const log4cxx::UniChar msg1[] = { 'T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 0 };
const log4cxx::UniChar msg2[] = { ':', ' ', 'D', 'e', 't', 'a', 'i', 'l', 's', ' ', 't', 'o', ' ', 'f', 'o', 'l', 'l', 'o', 'w', 0 };
root << msg1 << msg2 << LOG4CXX_ENDMSG;
LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size());
}
void testULogStreamShortCircuit() {
LoggerPtr logger(Logger::getLogger("StreamTestCase.shortCircuit"));
logger->setLevel(Level::getInfo());
ulogstream os(logger, Level::getDebug());
ExceptionOnInsert someObj;
os << someObj << LOG4CXX_ENDMSG;
LOGUNIT_ASSERT_EQUAL((size_t) 0, vectorAppender->getVector().size());
}
void testULogStreamInsertException() {
LoggerPtr logger(Logger::getLogger("StreamTestCase.insertException"));
ExceptionOnInsert someObj;
ulogstream os(logger, Level::getInfo());
os << someObj << LOG4CXX_ENDMSG;
}
void testULogStreamScientific() {
LoggerPtr root(Logger::getRootLogger());
ulogstream os(root, Level::getInfo());
os << std::scientific << 0.000001115 << LOG4CXX_ENDMSG;
LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size());
spi::LoggingEventPtr event(vectorAppender->getVector()[0]);
LogString msg(event->getMessage());
LOGUNIT_ASSERT(msg.find(LOG4CXX_STR("e-")) != LogString::npos ||
msg.find(LOG4CXX_STR("E-")) != LogString::npos);
}
void testULogStreamPrecision() {
LoggerPtr root(Logger::getRootLogger());
ulogstream os(root, Level::getInfo());
os << std::setprecision(4) << 1.000001 << LOG4CXX_ENDMSG;
LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size());
spi::LoggingEventPtr event(vectorAppender->getVector()[0]);
LogString msg(event->getMessage());
LOGUNIT_ASSERT(msg.find(LOG4CXX_STR("1.00000")) == LogString::npos);
}
void testULogStreamWidth() {
LoggerPtr root(Logger::getRootLogger());
ulogstream os(root, Level::getInfo());
const log4cxx::UniChar openBracket[] = { '[', 0 };
const log4cxx::UniChar closeBracket[] = { ']', 0 };
os << openBracket << std::fixed << std::setprecision(2) << std::setw(7) << std::right
<< std::setfill((log4cxx::UniChar) '_') << 10.0 << closeBracket << LOG4CXX_ENDMSG;
LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size());
spi::LoggingEventPtr event(vectorAppender->getVector()[0]);
LogString msg(event->getMessage());
LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("[__10.00]")), msg);
}
void ureport(std::basic_ostream<log4cxx::UniChar>& os) {
const log4cxx::UniChar msg1[] = { 'T', 'h', 'i', 's', ' ', 'j', 'u', 's', 't', ' ' , 'i', 'n', ':', ' ' , '\n', 0 };
const log4cxx::UniChar msg2[] = { 'U', 's', 'e', ' ', 'l', 'o', 'g', 's', 't', 'r', 'e', 'a', 'm', '\n', 0 };
os << msg1;
os << msg2;
}
void testULogStreamDelegate() {
ulogstream root(Logger::getRootLogger(), Level::getInfo());
ureport(root);
root << LOG4CXX_ENDMSG;
LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size());
}
void testULogStreamFormattingPersists() {
LoggerPtr root(Logger::getRootLogger());
root->setLevel(Level::getInfo());
ulogstream os(root, Level::getDebug());
os << std::hex << 20 << LOG4CXX_ENDMSG;
os << Level::getInfo() << 16 << LOG4CXX_ENDMSG;
LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size());
spi::LoggingEventPtr event(vectorAppender->getVector()[0]);
LogString msg(event->getMessage());
LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("10")), msg);
}
void testUSetWidthInsert() {
LoggerPtr root(Logger::getRootLogger());
root->setLevel(Level::getInfo());
ulogstream os(root, Level::getInfo());
os << std::setw(5);
LOGUNIT_ASSERT_EQUAL(5, os.width());
}
#endif
#if LOG4CXX_CFSTRING_API
void testCFString() {
LoggerPtr root(Logger::getRootLogger());
LOG4CXX_INFO(root, CFSTR("This is a test"));
LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size());
}
void testCFStringAppend() {
LoggerPtr root(Logger::getRootLogger());
LOG4CXX_INFO(root, CFSTR("This is a test") << CFSTR(": Details to follow"));
LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size());
}
void testULogStreamCFString() {
ulogstream root(Logger::getRootLogger(), Level::getInfo());
root << CFSTR("This is a test") << LOG4CXX_ENDMSG;
LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size());
}
void testULogStreamCFString2() {
ulogstream root(Logger::getRootLogger(), Level::getInfo());
root << CFSTR("This is a test") << CFSTR(": Details to follow") << LOG4CXX_ENDMSG;
LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size());
}
#endif
};
LOGUNIT_TEST_SUITE_REGISTRATION(StreamTestCase);
#if !LOG4CXX_USE_GLOBAL_SCOPE_TEMPLATE
//
// The following code tests compilation errors
// around bug LOGCXX-150 and is not intended to be executed.
// Skipped for VC6 since it can't handle having the
// templated operator<< in class scope.s
namespace foo
{
class Bar
{
void fn();
};
std::ostream &operator<<(std::ostream &o, Bar const &b)
{
return o << "Bar";
}
}
using namespace foo;
namespace
{
log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("foo"));
log4cxx::logstream lout(logger, log4cxx::Level::getDebug());
}
void Bar::fn()
{
lout << "hi" << LOG4CXX_ENDMSG;
}
#endif
| 001-log4cxx | trunk/src/test/cpp/streamtestcase.cpp | C++ | asf20 | 25,007 |
/* Copyright 2000-2004 Ryan Bloom
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef __cplusplus
extern "C" {
#endif
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef WIN32
#include <io.h>
#else
#include <unistd.h>
#endif
#ifndef ABTS_H
#define ABTS_H
#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE 1
#endif
struct sub_suite {
const char *name;
int num_test;
int failed;
int not_run;
int not_impl;
struct sub_suite *next;
};
typedef struct sub_suite sub_suite;
struct abts_suite {
sub_suite *head;
sub_suite *tail;
};
typedef struct abts_suite abts_suite;
struct abts_case {
int failed;
sub_suite *suite;
};
typedef struct abts_case abts_case;
typedef void (*test_func)(abts_case *tc, void *data);
#define ADD_SUITE(suite) abts_add_suite(suite, __FILE__);
abts_suite *abts_add_suite(abts_suite *suite, const char *suite_name);
void abts_run_test(abts_suite *ts, test_func f, void *value);
void abts_log_message(const char *fmt, ...);
void abts_int_equal(abts_case *tc, const int expected, const int actual, int lineno);
void abts_int_nequal(abts_case *tc, const int expected, const int actual, int lineno);
void abts_str_equal(abts_case *tc, const char *expected, const char *actual, int lineno);
void abts_str_nequal(abts_case *tc, const char *expected, const char *actual,
size_t n, int lineno);
void abts_ptr_notnull(abts_case *tc, const void *ptr, int lineno);
void abts_ptr_equal(abts_case *tc, const void *expected, const void *actual, int lineno);
void abts_true(abts_case *tc, int condition, int lineno);
void abts_fail(abts_case *tc, const char *message, int lineno);
void abts_not_impl(abts_case *tc, const char *message, int lineno);
void abts_assert(abts_case *tc, const char *message, int condition, int lineno);
void abts_size_equal(abts_case *tc, size_t expected, size_t actual, int lineno);
/* Convenience macros. Ryan hates these! */
#define ABTS_INT_EQUAL(a, b, c) abts_int_equal(a, b, c, __LINE__)
#define ABTS_INT_NEQUAL(a, b, c) abts_int_nequal(a, b, c, __LINE__)
#define ABTS_STR_EQUAL(a, b, c) abts_str_equal(a, b, c, __LINE__)
#define ABTS_STR_NEQUAL(a, b, c, d) abts_str_nequal(a, b, c, d, __LINE__)
#define ABTS_PTR_NOTNULL(a, b) abts_ptr_notnull(a, b, __LINE__)
#define ABTS_PTR_EQUAL(a, b, c) abts_ptr_equal(a, b, c, __LINE__)
#define ABTS_TRUE(a, b) abts_true(a, b, __LINE__);
#define ABTS_FAIL(a, b) abts_fail(a, b, __LINE__);
#define ABTS_NOT_IMPL(a, b) abts_not_impl(a, b, __LINE__);
#define ABTS_ASSERT(a, b, c) abts_assert(a, b, c, __LINE__);
#define ABTS_SIZE_EQUAL(a, b, c) abts_size_equal(a, b, c, __LINE__)
abts_suite *run_tests(abts_suite *suite);
abts_suite *run_tests1(abts_suite *suite);
#endif
#ifdef __cplusplus
}
#endif
| 001-log4cxx | trunk/src/test/cpp/abts.h | C | asf20 | 3,380 |
/*
* 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/simplelayout.h>
#include <log4cxx/ttcclayout.h>
#include <log4cxx/fileappender.h>
#include <log4cxx/helpers/absolutetimedateformat.h>
#include "util/compare.h"
#include "util/transformer.h"
#include "util/linenumberfilter.h"
#include "util/controlfilter.h"
#include "util/absolutedateandtimefilter.h"
#include "util/threadfilter.h"
#include <log4cxx/file.h>
#include <iostream>
#include <log4cxx/helpers/pool.h>
#include <apr_strings.h>
#include "testchar.h"
#include <log4cxx/spi/loggerrepository.h>
#include <log4cxx/helpers/stringhelper.h>
#include <apr_strings.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
#define TTCC_PAT \
ABSOLUTE_DATE_AND_TIME_PAT \
" \\[0x[0-9A-F]*]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* - Message [0-9]\\{1,2\\}"
#define TTCC2_PAT \
ABSOLUTE_DATE_AND_TIME_PAT \
" \\[0x[0-9A-F]*]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* - " \
"Messages should bear numbers 0 through 23\\."
LOGUNIT_CLASS(MinimumTestCase)
{
LOGUNIT_TEST_SUITE(MinimumTestCase);
LOGUNIT_TEST(simple);
LOGUNIT_TEST(ttcc);
LOGUNIT_TEST_SUITE_END();
public:
void setUp()
{
root = Logger::getRootLogger();
root->removeAllAppenders();
}
void tearDown()
{
root->getLoggerRepository()->resetConfiguration();
}
void simple()
{
LayoutPtr layout = new SimpleLayout();
AppenderPtr appender = new FileAppender(layout, LOG4CXX_STR("output/simple"), false);
root->addAppender(appender);
common();
LOGUNIT_ASSERT(Compare::compare(LOG4CXX_FILE("output/simple"), LOG4CXX_FILE("witness/simple")));
}
void ttcc()
{
LayoutPtr layout =
new TTCCLayout(LOG4CXX_STR("DATE"));
AppenderPtr appender = new FileAppender(layout, LOG4CXX_STR("output/ttcc"), false);
root->addAppender(appender);
common();
ControlFilter filter1;
filter1 << TTCC_PAT << TTCC2_PAT;
AbsoluteDateAndTimeFilter filter2;
ThreadFilter filter3;
std::vector<Filter *> filters;
filters.push_back(&filter1);
filters.push_back(&filter2);
filters.push_back(&filter3);
try
{
const File output("output/ttcc");
Transformer::transform(output, FILTERED, filters);
}
catch(std::exception& e)
{
std::cout << "UnexpectedFormatException :" << e.what() << std::endl;
throw;
}
const File witness("witness/ttcc");
LOGUNIT_ASSERT(Compare::compare(FILTERED, witness));
}
std::string createMessage(int i, Pool& pool) {
std::string msg("Message ");
msg.append(pool.itoa(i));
return msg;
}
void common()
{
int i = 0;
// In the lines below, the logger names are chosen as an aid in
// remembering their level values. In general, the logger names
// have no bearing to level values.
LoggerPtr ERRlogger = Logger::getLogger(LOG4CXX_TEST_STR("ERR"));
ERRlogger->setLevel(Level::getError());
LoggerPtr INF = Logger::getLogger(LOG4CXX_TEST_STR("INF"));
INF->setLevel(Level::getInfo());
LoggerPtr INF_ERR = Logger::getLogger(LOG4CXX_TEST_STR("INF.ERR"));
INF_ERR->setLevel(Level::getError());
LoggerPtr DEB = Logger::getLogger(LOG4CXX_TEST_STR("DEB"));
DEB->setLevel(Level::getDebug());
// Note: categories with undefined level
LoggerPtr INF_UNDEF = Logger::getLogger(LOG4CXX_TEST_STR("INF.UNDEF"));
LoggerPtr INF_ERR_UNDEF = Logger::getLogger(LOG4CXX_TEST_STR("INF.ERR.UNDEF"));
LoggerPtr UNDEF = Logger::getLogger(LOG4CXX_TEST_STR("UNDEF"));
std::string msg("Message ");
Pool pool;
// These should all log.----------------------------
LOG4CXX_FATAL(ERRlogger, createMessage(i, pool));
i++; //0
LOG4CXX_ERROR(ERRlogger, createMessage(i, pool));
i++;
LOG4CXX_FATAL(INF, createMessage(i, pool));
i++; // 2
LOG4CXX_ERROR(INF, createMessage(i, pool));
i++;
LOG4CXX_WARN(INF, createMessage(i, pool));
i++;
LOG4CXX_INFO(INF, createMessage(i, pool));
i++;
LOG4CXX_FATAL(INF_UNDEF, createMessage(i, pool));
i++; //6
LOG4CXX_ERROR(INF_UNDEF, createMessage(i, pool));
i++;
LOG4CXX_WARN(INF_UNDEF, createMessage(i, pool));
i++;
LOG4CXX_INFO(INF_UNDEF, createMessage(i, pool));
i++;
LOG4CXX_FATAL(INF_ERR, createMessage(i, pool));
i++; // 10
LOG4CXX_ERROR(INF_ERR, createMessage(i, pool));
i++;
LOG4CXX_FATAL(INF_ERR_UNDEF, createMessage(i, pool));
i++;
LOG4CXX_ERROR(INF_ERR_UNDEF, createMessage(i, pool));
i++;
LOG4CXX_FATAL(DEB, createMessage(i, pool));
i++; //14
LOG4CXX_ERROR(DEB, createMessage(i, pool));
i++;
LOG4CXX_WARN(DEB, createMessage(i, pool));
i++;
LOG4CXX_INFO(DEB, createMessage(i, pool));
i++;
LOG4CXX_DEBUG(DEB, createMessage(i, pool));
i++;
// defaultLevel=DEBUG
LOG4CXX_FATAL(UNDEF, createMessage(i, pool));
i++; // 19
LOG4CXX_ERROR(UNDEF, createMessage(i, pool));
i++;
LOG4CXX_WARN(UNDEF, createMessage(i, pool));
i++;
LOG4CXX_INFO(UNDEF, createMessage(i, pool));
i++;
LOG4CXX_DEBUG(UNDEF, createMessage(i, pool));
i++;
// -------------------------------------------------
// The following should not log
LOG4CXX_WARN(ERRlogger, createMessage(i, pool));
i++;
LOG4CXX_INFO(ERRlogger, createMessage(i, pool));
i++;
LOG4CXX_DEBUG(ERRlogger, createMessage(i, pool));
i++;
LOG4CXX_DEBUG(INF, createMessage(i, pool));
i++;
LOG4CXX_DEBUG(INF_UNDEF, createMessage(i, pool));
i++;
LOG4CXX_WARN(INF_ERR, createMessage(i, pool));
i++;
LOG4CXX_INFO(INF_ERR, createMessage(i, pool));
i++;
LOG4CXX_DEBUG(INF_ERR, createMessage(i, pool));
i++;
LOG4CXX_WARN(INF_ERR_UNDEF, createMessage(i, pool));
i++;
LOG4CXX_INFO(INF_ERR_UNDEF, createMessage(i, pool));
i++;
LOG4CXX_DEBUG(INF_ERR_UNDEF, createMessage(i, pool));
i++;
// -------------------------------------------------
LOG4CXX_INFO(INF, LOG4CXX_TEST_STR("Messages should bear numbers 0 through 23."));
}
LoggerPtr root;
LoggerPtr logger;
private:
static const File FILTERED;
};
const File MinimumTestCase::FILTERED("output/filtered");
LOGUNIT_TEST_SUITE_REGISTRATION(MinimumTestCase);
| 001-log4cxx | trunk/src/test/cpp/minimumtestcase.cpp | C++ | asf20 | 8,801 |
/*
* 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 "xlogger.h"
#include <log4cxx/xml/domconfigurator.h>
#include "../util/transformer.h"
#include "../util/compare.h"
#include <log4cxx/file.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::xml;
#define LOG4CXX_TEST_STR(x) L##x
/**
Tests handling of custom loggers.
*/
LOGUNIT_CLASS(XLoggerTestCase)
{
LOGUNIT_TEST_SUITE(XLoggerTestCase);
LOGUNIT_TEST(test1);
LOGUNIT_TEST(test2);
LOGUNIT_TEST_SUITE_END();
XLoggerPtr logger;
public:
void setUp()
{
logger = XLogger::getLogger(
LOG4CXX_STR("org.apache.log4j.customLogger.XLoggerTestCase"));
}
void tearDown()
{
logger->getLoggerRepository()->resetConfiguration();
}
void test1() { common("1"); }
void test2() { common("2"); }
void common(const char* number)
{
std::string fn("input/xml/customLogger");
fn.append(number);
fn.append(".xml");
DOMConfigurator::configure(fn);
int i = 0;
LOG4CXX_LOG(logger, log4cxx::XLevel::getTrace(), "Message " << i);
i++;
LOG4CXX_DEBUG(logger, "Message " << i);
i++;
LOG4CXX_WARN(logger, "Message " << i);
i++;
LOG4CXX_ERROR(logger, "Message " << i);
i++;
LOG4CXX_FATAL(logger, "Message " << i);
i++;
LOG4CXX_DEBUG(logger, "Message " << i);
const File OUTPUT("output/temp");
std::string witness("witness/customLogger.");
witness.append(number);
const File WITNESS(witness);
LOGUNIT_ASSERT(Compare::compare(OUTPUT, WITNESS));
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(XLoggerTestCase);
| 001-log4cxx | trunk/src/test/cpp/customlogger/xloggertestcase.cpp | C++ | asf20 | 2,565 |
/*
* 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 "../xml/xlevel.h"
#include <log4cxx/spi/loggerfactory.h>
namespace log4cxx
{
namespace spi {
namespace location {
class LocationInfo;
}
}
// Any sub-class of Logger must also have its own implementation of
// LoggerFactory.
class XFactory :
public virtual spi::LoggerFactory,
public virtual helpers::ObjectImpl
{
public:
DECLARE_ABSTRACT_LOG4CXX_OBJECT(XFactory)
BEGIN_LOG4CXX_CAST_MAP()
LOG4CXX_CAST_ENTRY(XFactory)
LOG4CXX_CAST_ENTRY(spi::LoggerFactory)
END_LOG4CXX_CAST_MAP()
XFactory();
virtual LoggerPtr makeNewLoggerInstance(
log4cxx::helpers::Pool& pool,
const LogString& name) const;
};
typedef helpers::ObjectPtrT<XFactory> XFactoryPtr;
/**
A simple example showing Logger sub-classing. It shows the
minimum steps necessary to implement one's {@link LoggerFactory}.
Note that sub-classes follow the hierarchy even if its loggers
belong to different classes.
*/
class XLogger : public Logger
{
// It's enough to instantiate a factory once and for all.
static XFactoryPtr factory;
LogString suffix;
public:
DECLARE_ABSTRACT_LOG4CXX_OBJECT(XLogger)
BEGIN_LOG4CXX_CAST_MAP()
LOG4CXX_CAST_ENTRY(XLogger)
LOG4CXX_CAST_ENTRY_CHAIN(Logger)
END_LOG4CXX_CAST_MAP()
/**
Just calls the parent constuctor.
*/
XLogger(log4cxx::helpers::Pool& pool,
const LogString& name1) : Logger(pool, name1) {}
/**
Nothing to activate.
*/
void activateOptions() {}
/**
We introduce a new printing method in order to support {@link
XLevel#LETHAL}. */
void lethal(const LogString& message, const log4cxx::spi::LocationInfo& location);
/**
We introduce a new printing method in order to support {@link
XLevel#LETHAL}. */
void lethal(const LogString& message);
static LoggerPtr getLogger(const LogString& name);
static LoggerPtr getLogger(const helpers::Class& clazz);
LogString getSuffix() const
{ return suffix; }
void setSuffix(const LogString& suffix1)
{ this->suffix = suffix1; }
/**
We introduce a new printing method that takes the TRACE level.
*/
void trace(const LogString& message, const log4cxx::spi::LocationInfo& location);
/**
We introduce a new printing method that takes the TRACE level.
*/
void trace(const LogString& message);
};
typedef helpers::ObjectPtrT<XLogger> XLoggerPtr;
}
| 001-log4cxx | trunk/src/test/cpp/customlogger/xlogger.h | C++ | asf20 | 4,132 |
/*
* 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>
#include "xlogger.h"
#include <log4cxx/level.h>
#include <log4cxx/logmanager.h>
#include <log4cxx/spi/location/locationinfo.h>
#include <log4cxx/spi/loggerrepository.h>
using namespace log4cxx;
using namespace log4cxx::spi;
IMPLEMENT_LOG4CXX_OBJECT(XLogger)
IMPLEMENT_LOG4CXX_OBJECT(XFactory)
XFactoryPtr XLogger::factory = new XFactory();
void XLogger::lethal(const LogString& message, const LocationInfo& locationInfo)
{
if (repository->isDisabled(XLevel::LETHAL_INT))
{
return;
}
if (XLevel::getLethal()->isGreaterOrEqual(this->getEffectiveLevel()))
{
forcedLog(XLevel::getLethal(), message, locationInfo);
}
}
void XLogger::lethal(const LogString& message)
{
if (repository->isDisabled(XLevel::LETHAL_INT))
{
return;
}
if (XLevel::getLethal()->isGreaterOrEqual(this->getEffectiveLevel()))
{
forcedLog(XLevel::getLethal(), message, LocationInfo::getLocationUnavailable());
}
}
LoggerPtr XLogger::getLogger(const LogString& name)
{
return LogManager::getLogger(name, factory);
}
LoggerPtr XLogger::getLogger(const helpers::Class& clazz)
{
return XLogger::getLogger(clazz.getName());
}
void XLogger::trace(const LogString& message, const LocationInfo& locationInfo)
{
if (repository->isDisabled(XLevel::TRACE_INT))
{
return;
}
if (XLevel::getTrace()->isGreaterOrEqual(this->getEffectiveLevel()))
{
forcedLog(XLevel::getTrace(), message, locationInfo);
}
}
void XLogger::trace(const LogString& message)
{
if (repository->isDisabled(XLevel::TRACE_INT))
{
return;
}
if (XLevel::getTrace()->isGreaterOrEqual(this->getEffectiveLevel()))
{
forcedLog(XLevel::getTrace(), message, LocationInfo::getLocationUnavailable());
}
}
XFactory::XFactory()
{
}
LoggerPtr XFactory::makeNewLoggerInstance(log4cxx::helpers::Pool& pool,
const LogString& name) const
{
return new XLogger(pool, name);
}
| 001-log4cxx | trunk/src/test/cpp/customlogger/xlogger.cpp | C++ | asf20 | 2,983 |
/*
* 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/db/odbcappender.h>
#include "../appenderskeletontestcase.h"
#include "../logunit.h"
#define LOG4CXX_TEST 1
#include <log4cxx/private/log4cxx_private.h>
#ifdef LOG4CXX_HAVE_ODBC
using namespace log4cxx;
using namespace log4cxx::helpers;
/**
Unit tests of log4cxx::SocketAppender
*/
class ODBCAppenderTestCase : public AppenderSkeletonTestCase
{
LOGUNIT_TEST_SUITE(ODBCAppenderTestCase);
//
// tests inherited from AppenderSkeletonTestCase
//
LOGUNIT_TEST(testDefaultThreshold);
LOGUNIT_TEST(testSetOptionThreshold);
LOGUNIT_TEST_SUITE_END();
public:
AppenderSkeleton* createAppenderSkeleton() const {
return new log4cxx::db::ODBCAppender();
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(ODBCAppenderTestCase);
#endif
| 001-log4cxx | trunk/src/test/cpp/db/odbcappendertestcase.cpp | C++ | asf20 | 1,657 |
/*
* 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 "writerappendertestcase.h"
#include <log4cxx/helpers/objectptr.h>
#include <log4cxx/writerappender.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
AppenderSkeleton* WriterAppenderTestCase::createAppenderSkeleton() const {
return createWriterAppender();
}
| 001-log4cxx | trunk/src/test/cpp/writerappendertestcase.cpp | 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 <log4cxx/logger.h>
#include <log4cxx/propertyconfigurator.h>
#include <log4cxx/helpers/propertyresourcebundle.h>
#include <log4cxx/helpers/locale.h>
#include "util/compare.h"
#include <vector>
#include <sstream>
#include "testchar.h"
#include "logunit.h"
#include <log4cxx/spi/loggerrepository.h>
typedef std::basic_ostringstream<testchar> StringBuffer;
using namespace log4cxx;
using namespace log4cxx::helpers;
LOGUNIT_CLASS(L7dTestCase)
{
LOGUNIT_TEST_SUITE(L7dTestCase);
LOGUNIT_TEST(test1);
LOGUNIT_TEST_SUITE_END();
LoggerPtr root;
ResourceBundlePtr bundles[3];
public:
void setUp()
{
Locale localeUS(LOG4CXX_STR("en"), LOG4CXX_STR("US"));
bundles[0] =
ResourceBundle::getBundle(LOG4CXX_STR("L7D"), localeUS);
LOGUNIT_ASSERT(bundles[0] != 0);
Locale localeFR(LOG4CXX_STR("fr"), LOG4CXX_STR("FR"));
bundles[1] =
ResourceBundle::getBundle(LOG4CXX_STR("L7D"), localeFR);
LOGUNIT_ASSERT(bundles[1] != 0);
Locale localeCH(LOG4CXX_STR("fr"), LOG4CXX_STR("CH"));
bundles[2] =
ResourceBundle::getBundle(LOG4CXX_STR("L7D"), localeCH);
LOGUNIT_ASSERT(bundles[2] != 0);
root = Logger::getRootLogger();
}
void tearDown()
{
root->getLoggerRepository()->resetConfiguration();
}
void test1()
{
PropertyConfigurator::configure(LOG4CXX_FILE("input/l7d1.properties"));
log4cxx::helpers::Pool pool;
for (int i = 0; i < 3; i++)
{
root->setResourceBundle(bundles[i]);
LOG4CXX_L7DLOG(root, Level::getDebug(), LOG4CXX_TEST_STR("bogus1"));
LOG4CXX_L7DLOG(root, Level::getInfo(), LOG4CXX_TEST_STR("test"));
LOG4CXX_L7DLOG(root, Level::getWarn(), LOG4CXX_TEST_STR("hello_world"));
StringBuffer os;
os << (i + 1);
LOG4CXX_L7DLOG2(root, Level::getDebug(), LOG4CXX_TEST_STR("msg1"), os.str().c_str(),
LOG4CXX_TEST_STR("log4j"));
LOG4CXX_L7DLOG2(root, Level::getError(), LOG4CXX_TEST_STR("bogusMsg"), os.str().c_str(),
LOG4CXX_TEST_STR("log4j"));
LOG4CXX_L7DLOG2(root, Level::getError(), LOG4CXX_TEST_STR("msg1"), os.str().c_str(),
LOG4CXX_TEST_STR("log4j"));
LOG4CXX_L7DLOG(root, Level::getInfo(), LOG4CXX_TEST_STR("bogus2"));
}
LOGUNIT_ASSERT(Compare::compare(LOG4CXX_FILE("output/temp"),
LOG4CXX_FILE("witness/l7d.1")));
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(L7dTestCase);
| 001-log4cxx | trunk/src/test/cpp/l7dtestcase.cpp | C++ | asf20 | 3,806 |
/*
* 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/file.h>
#include "logunit.h"
#include "insertwide.h"
#include <log4cxx/helpers/pool.h>
#include <apr_errno.h>
#include <log4cxx/helpers/exception.h>
#include <log4cxx/helpers/fileinputstream.h>
#include <log4cxx/helpers/outputstreamwriter.h>
#include <log4cxx/helpers/fileoutputstream.h>
#include <log4cxx/helpers/inputstreamreader.h>
#include <log4cxx/helpers/fileinputstream.h>
#if LOG4CXX_CFSTRING_API
#include <CoreFoundation/CFString.h>
#endif
using namespace log4cxx;
using namespace log4cxx::helpers;
LOGUNIT_CLASS(FileTestCase)
{
LOGUNIT_TEST_SUITE(FileTestCase);
LOGUNIT_TEST(defaultConstructor);
LOGUNIT_TEST(defaultExists);
LOGUNIT_TEST(defaultRead);
LOGUNIT_TEST(propertyRead);
LOGUNIT_TEST(propertyExists);
LOGUNIT_TEST(fileWrite1);
#if LOG4CXX_WCHAR_T_API
LOGUNIT_TEST(wcharConstructor);
#endif
#if LOG4CXX_UNICHAR_API
LOGUNIT_TEST(unicharConstructor);
#endif
#if LOG4CXX_CFSTRING_API
LOGUNIT_TEST(cfstringConstructor);
#endif
LOGUNIT_TEST(copyConstructor);
LOGUNIT_TEST(assignment);
LOGUNIT_TEST(deleteBackslashedFileName);
LOGUNIT_TEST_SUITE_END();
public:
void defaultConstructor() {
File defFile;
LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR(""), defFile.getPath());
}
void defaultExists() {
File defFile;
Pool pool;
bool exists = defFile.exists(pool);
LOGUNIT_ASSERT_EQUAL(false, exists);
}
// check default constructor. read() throws an exception
// if no file name was given.
void defaultRead() {
File defFile;
Pool pool;
try {
InputStreamPtr defInput = new FileInputStream(defFile);
InputStreamReaderPtr inputReader = new InputStreamReader(defInput);
LogString contents(inputReader->read(pool));
LOGUNIT_ASSERT(false);
} catch(IOException &ex) {
}
}
#if LOG4CXX_WCHAR_T_API
void wcharConstructor() {
File propFile(L"input/patternLayout1.properties");
Pool pool;
bool exists = propFile.exists(pool);
LOGUNIT_ASSERT_EQUAL(true, exists);
}
#endif
#if LOG4CXX_UNICHAR_API
void unicharConstructor() {
const log4cxx::UniChar filename[] = { 'i', 'n', 'p', 'u', 't', '/',
'p', 'a', 't', 't', 'e', 'r', 'n', 'L', 'a', 'y', 'o', 'u', 't', '1', '.',
'p', 'r', 'o', 'p', 'e', 'r', 't', 'i', 'e', 's', 0 };
File propFile(filename);
Pool pool;
bool exists = propFile.exists(pool);
LOGUNIT_ASSERT_EQUAL(true, exists);
}
#endif
#if LOG4CXX_CFSTRING_API
void cfstringConstructor() {
File propFile(CFSTR("input/patternLayout.properties"));
Pool pool;
bool exists = propFile.exists(pool);
LOGUNIT_ASSERT_EQUAL(true, exists);
}
#endif
void copyConstructor() {
File propFile("input/patternLayout1.properties");
File copy(propFile);
Pool pool;
bool exists = copy.exists(pool);
LOGUNIT_ASSERT_EQUAL(true, exists);
}
void assignment() {
File propFile("input/patternLayout1.properties");
File copy = propFile;
Pool pool;
bool exists = copy.exists(pool);
LOGUNIT_ASSERT_EQUAL(true, exists);
}
void propertyRead() {
File propFile("input/patternLayout1.properties");
Pool pool;
InputStreamPtr propStream = new FileInputStream(propFile);
InputStreamReaderPtr propReader = new InputStreamReader(propStream);
LogString props(propReader->read(pool));
LogString line1(LOG4CXX_STR("# Licensed to the Apache Software Foundation (ASF) under one or more"));
LOGUNIT_ASSERT_EQUAL(line1, props.substr(0, line1.length()));
}
void propertyExists() {
File propFile("input/patternLayout1.properties");
Pool pool;
bool exists = propFile.exists(pool);
LOGUNIT_ASSERT_EQUAL(true, exists);
}
void fileWrite1() {
OutputStreamPtr fos =
new FileOutputStream(LOG4CXX_STR("output/fileWrite1.txt"));
OutputStreamWriterPtr osw = new OutputStreamWriter(fos);
Pool pool;
LogString greeting(LOG4CXX_STR("Hello, World"));
greeting.append(LOG4CXX_EOL);
osw->write(greeting, pool);
InputStreamPtr is =
new FileInputStream(LOG4CXX_STR("output/fileWrite1.txt"));
InputStreamReaderPtr isr = new InputStreamReader(is);
LogString reply = isr->read(pool);
LOGUNIT_ASSERT_EQUAL(greeting, reply);
}
/**
* Tests conversion of backslash containing file names.
* Would cause infinite loop due to bug LOGCXX-105.
*/
void deleteBackslashedFileName() {
File file("output\\bogus.txt");
Pool pool;
/*bool deleted = */file.deleteFile(pool);
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(FileTestCase);
| 001-log4cxx | trunk/src/test/cpp/filetestcase.cpp | C++ | asf20 | 6,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.
*/
#include <log4cxx/logger.h>
#include "logunit.h"
//
// If there is no support for wchar_t logging then
// there is not a consistent way to get the test characters logged
//
#if LOG4CXX_WCHAR_T_API
#include <log4cxx/patternlayout.h>
#include <log4cxx/fileappender.h>
#include <log4cxx/level.h>
#include "util/binarycompare.h"
#include <log4cxx/file.h>
#include <log4cxx/helpers/pool.h>
using namespace log4cxx;
using namespace log4cxx::util;
using namespace log4cxx::helpers;
/**
* Tests support for encoding specification.
*
*
*/
LOGUNIT_CLASS(EncodingTest) {
LOGUNIT_TEST_SUITE(EncodingTest);
LOGUNIT_TEST(testASCII);
LOGUNIT_TEST(testLatin1);
LOGUNIT_TEST(testUtf8);
LOGUNIT_TEST(testUtf16);
LOGUNIT_TEST(testUtf16LE);
LOGUNIT_TEST(testUtf16BE);
LOGUNIT_TEST_SUITE_END();
public:
/**
* Resets configuration after each test.
*/
void tearDown() {
Logger::getRootLogger()->getLoggerRepository()->resetConfiguration();
}
/**
* Test us-ascii encoding.
*/
void testASCII() {
LoggerPtr root(Logger::getRootLogger());
configure(root, LOG4CXX_STR("output/ascii.log"), LOG4CXX_STR("US-ASCII"));
common(root);
BinaryCompare::compare("output/ascii.log", "witness/encoding/ascii.log");
}
/**
* Test iso-8859-1 encoding.
*/
void testLatin1() {
LoggerPtr root(Logger::getRootLogger());
configure(root, LOG4CXX_STR("output/latin1.log"), LOG4CXX_STR("iso-8859-1"));
common(root);
BinaryCompare::compare("output/latin1.log", "witness/encoding/latin1.log");
}
/**
* Test utf-8 encoding.
*/
void testUtf8() {
LoggerPtr root(Logger::getRootLogger());
configure(root, LOG4CXX_STR("output/UTF-8.log"), LOG4CXX_STR("UTF-8"));
common(root);
BinaryCompare::compare("output/UTF-8.log", "witness/encoding/UTF-8.log");
}
/**
* Test utf-16 encoding.
*/
void testUtf16() {
LoggerPtr root(Logger::getRootLogger());
configure(root, LOG4CXX_STR("output/UTF-16.log"), LOG4CXX_STR("UTF-16"));
common(root);
BinaryCompare::compare("output/UTF-16.log", "witness/encoding/UTF-16.log");
}
/**
* Test utf-16be encoding.
*/
void testUtf16BE() {
LoggerPtr root(Logger::getRootLogger());
configure(root, LOG4CXX_STR("output/UTF-16BE.log"), LOG4CXX_STR("UTF-16BE"));
common(root);
BinaryCompare::compare("output/UTF-16BE.log", "witness/encoding/UTF-16BE.log");
}
/**
* Test utf16-le encoding.
*/
void testUtf16LE() {
LoggerPtr root(Logger::getRootLogger());
configure(root, LOG4CXX_STR("output/UTF-16LE.log"), LOG4CXX_STR("UTF-16LE"));
common(root);
BinaryCompare::compare("output/UTF-16LE.log", "witness/encoding/UTF-16LE.log");
}
/**
* Configure logging.
* @param logger logger
* @param filename logging file name
* @param encoding encoding
*/
private:
void configure(LoggerPtr& logger,
const LogString& filename, const LogString& encoding) {
PatternLayoutPtr layout(new PatternLayout());
layout->setConversionPattern(LOG4CXX_STR("%p - %m\n"));
Pool p;
layout->activateOptions(p);
FileAppenderPtr appender(new FileAppender());
appender->setFile(filename);
appender->setEncoding(encoding);
appender->setAppend(false);
appender->setLayout(layout);
appender->activateOptions(p);
logger->addAppender(appender);
logger->setLevel(Level::getInfo());
}
/**
* Common logging requests.
* @param logger logger
*/
void common(LoggerPtr& logger) {
logger->info("Hello, World");
// pi can be encoded in iso-8859-1
const wchar_t pi[] = { 0x00B9, 0 };
logger->info(pi);
// arbitrary, hopefully meaningless, characters from
// Latin, Arabic, Armenian, Bengali, CJK and Cyrillic
const wchar_t greeting[] = { L'A', 0x0605, 0x0530, 0x986, 0x4E03, 0x400, 0 };
logger->info(greeting);
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(EncodingTest);
#endif
| 001-log4cxx | trunk/src/test/cpp/encodingtest.cpp | C++ | asf20 | 5,061 |
/*
* 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/filedatepatternconverter.h>
#include <log4cxx/pattern/integerpatternconverter.h>
#include <log4cxx/pattern/patternparser.h>
#include <log4cxx/helpers/pool.h>
#include <log4cxx/helpers/date.h>
#include <log4cxx/helpers/integer.h>
#include "../util/compare.h"
#include "../logunit.h"
#include "../insertwide.h"
#include <apr_time.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::pattern;
/**
* Tests for FileNamePattern.
*
*
*
*
*/
LOGUNIT_CLASS(FileNamePatternTestCase) {
LOGUNIT_TEST_SUITE(FileNamePatternTestCase);
LOGUNIT_TEST(testFormatInteger1);
LOGUNIT_TEST(testFormatInteger2);
LOGUNIT_TEST(testFormatInteger3);
LOGUNIT_TEST(testFormatInteger4);
LOGUNIT_TEST(testFormatInteger5);
LOGUNIT_TEST(testFormatInteger6);
LOGUNIT_TEST(testFormatInteger7);
LOGUNIT_TEST(testFormatInteger8);
LOGUNIT_TEST(testFormatInteger9);
LOGUNIT_TEST(testFormatInteger10);
LOGUNIT_TEST(testFormatInteger11);
LOGUNIT_TEST(testFormatDate1);
//
// TODO: Problem with timezone offset
// LOGUNIT_TEST(testFormatDate2);
// LOGUNIT_TEST(testFormatDate3);
LOGUNIT_TEST(testFormatDate4);
LOGUNIT_TEST(testFormatDate5);
LOGUNIT_TEST_SUITE_END();
public:
LogString format(const LogString& pattern,
const ObjectPtr& obj) {
std::vector<PatternConverterPtr> converters;
std::vector<FormattingInfoPtr> fields;
PatternMap rules;
rules.insert(PatternMap::value_type(LOG4CXX_STR("d"), (PatternConstructor) FileDatePatternConverter::newInstance));
rules.insert(PatternMap::value_type(LOG4CXX_STR("i"), (PatternConstructor) IntegerPatternConverter::newInstance));
PatternParser::parse(pattern, converters, fields, rules);
LogString result;
Pool pool;
std::vector<FormattingInfoPtr>::const_iterator fieldIter = fields.begin();
for(std::vector<PatternConverterPtr>::const_iterator converterIter = converters.begin();
converterIter != converters.end();
converterIter++, fieldIter++) {
LogString::size_type i = result.length();
(*converterIter)->format(obj, result, pool);
(*fieldIter)->format(i, result);
}
return result;
}
void assertDatePattern(const LogString& pattern,
int year,
int month,
int day, int hour,
int min,
const LogString& expected) {
apr_time_exp_t tm;
memset(&tm, 0, sizeof(tm));
tm.tm_min = min;
tm.tm_hour = hour;
tm.tm_mday = day;
tm.tm_mon = month;
tm.tm_year = year - 1900;
apr_time_t n;
/*apr_status_t stat = */apr_time_exp_get(&n, &tm);
ObjectPtr obj(new Date(n));
LOGUNIT_ASSERT_EQUAL(expected, format(pattern, obj));
}
void assertIntegerPattern(const LogString& pattern, int value,
const LogString& expected) {
ObjectPtr obj(new Integer(value));
LOGUNIT_ASSERT_EQUAL(expected, format(pattern, obj));
}
void testFormatInteger1() {
assertIntegerPattern(LOG4CXX_STR("t"), 3, LOG4CXX_STR("t"));
}
void testFormatInteger2() {
assertIntegerPattern(LOG4CXX_STR("foo"), 3, LOG4CXX_STR("foo"));
}
void testFormatInteger3() {
assertIntegerPattern(LOG4CXX_STR("foo%"), 3, LOG4CXX_STR("foo%"));
}
void testFormatInteger4() {
assertIntegerPattern(LOG4CXX_STR("%ifoo"), 3, LOG4CXX_STR("3foo"));
}
void testFormatInteger5() {
assertIntegerPattern(LOG4CXX_STR("foo%ixixo"), 3, LOG4CXX_STR("foo3xixo"));
}
void testFormatInteger6() {
assertIntegerPattern(LOG4CXX_STR("foo%i.log"), 3, LOG4CXX_STR("foo3.log"));
}
void testFormatInteger7() {
assertIntegerPattern(LOG4CXX_STR("foo.%i.log"), 3, LOG4CXX_STR("foo.3.log"));
}
void testFormatInteger8() {
assertIntegerPattern(LOG4CXX_STR("%ifoo%"), 3, LOG4CXX_STR("3foo%"));
}
void testFormatInteger9() {
assertIntegerPattern(LOG4CXX_STR("%ifoo%%"), 3, LOG4CXX_STR("3foo%"));
}
void testFormatInteger10() {
assertIntegerPattern(LOG4CXX_STR("%%foo"), 3, LOG4CXX_STR("%foo"));
}
void testFormatInteger11() {
assertIntegerPattern(LOG4CXX_STR("foo%ibar%i"), 3, LOG4CXX_STR("foo3bar3"));
}
void testFormatDate1() {
assertDatePattern(LOG4CXX_STR("foo%d{yyyy.MM.dd}"), 2003, 4, 20, 17, 55,
LOG4CXX_STR("foo2003.05.20"));
}
void testFormatDate2() {
assertDatePattern(LOG4CXX_STR("foo%d{yyyy.MM.dd HH:mm}"), 2003, 4, 20, 17, 55,
LOG4CXX_STR("foo2003.05.20 17:55"));
}
void testFormatDate3() {
assertDatePattern(LOG4CXX_STR("%d{yyyy.MM.dd HH:mm} foo"), 2003, 4, 20, 17, 55,
LOG4CXX_STR("2003.05.20 17:55 foo"));
}
void testFormatDate4() {
assertDatePattern(LOG4CXX_STR("foo%dyyyy.MM.dd}"), 2003, 4, 20, 17, 55,
LOG4CXX_STR("foo2003-05-20yyyy.MM.dd}"));
}
void testFormatDate5() {
assertDatePattern(LOG4CXX_STR("foo%d{yyyy.MM.dd"), 2003, 4, 20, 17, 55,
LOG4CXX_STR("foo2003-05-20{yyyy.MM.dd"));
}
};
//
// See bug LOGCXX-204
//
#if !defined(_MSC_VER) || _MSC_VER > 1200
LOGUNIT_TEST_SUITE_REGISTRATION(FileNamePatternTestCase);
#endif
| 001-log4cxx | trunk/src/test/cpp/rolling/filenamepatterntestcase.cpp | C++ | asf20 | 6,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.
*/
#include "../util/compare.h"
#include "../insertwide.h"
#include "../logunit.h"
#include <apr_time.h>
#include <log4cxx/logmanager.h>
#include <log4cxx/xml/domconfigurator.h>
#include <log4cxx/patternlayout.h>
#include <log4cxx/rolling/fixedwindowrollingpolicy.h>
#include <log4cxx/rolling/sizebasedtriggeringpolicy.h>
#include <log4cxx/filter/levelrangefilter.h>
#include <log4cxx/helpers/pool.h>
#include <log4cxx/logger.h>
#include <log4cxx/propertyconfigurator.h>
#include <log4cxx/rolling/rollingfileappender.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/consoleappender.h>
#include <log4cxx/helpers/exception.h>
#include <log4cxx/helpers/fileoutputstream.h>
using namespace log4cxx;
using namespace log4cxx::xml;
using namespace log4cxx::filter;
using namespace log4cxx::helpers;
using namespace log4cxx::rolling;
/**
* Tests of explicit manual rolling of RollingFileAppenders.
*
*
*
*/
LOGUNIT_CLASS(ManualRollingTest) {
LOGUNIT_TEST_SUITE(ManualRollingTest);
LOGUNIT_TEST(test1);
LOGUNIT_TEST(test2);
// TODO: Compression not yet implemented
// LOGUNIT_TEST(test3);
LOGUNIT_TEST(test4);
LOGUNIT_TEST(test5);
LOGUNIT_TEST_SUITE_END();
LoggerPtr root;
LoggerPtr logger;
public:
void setUp() {
logger = Logger::getLogger("org.apache.log4j.rolling.ManualRollingTest");
root = Logger::getRootLogger();
}
void tearDown() {
LogManager::shutdown();
}
void common(RollingFileAppenderPtr& rfa,
Pool& pool,
LoggerPtr& logger1) {
char msg[] = { 'H', 'e', 'l', 'l', 'o', '-', '-', '-', 'N', 0 };
// Write exactly 10 bytes with each log
for (int i = 0; i < 25; i++) {
if (i < 10) {
msg[8] = '0' + i;
} else if (i < 100) {
int digit = i % 10;
if (digit == 0) {
rfa->rollover(pool);
}
msg[7] = '0' + i / 10;
msg[8] = '0' + digit;
}
LOG4CXX_DEBUG(logger1, msg);
}
}
/**
* Tests that the lack of an explicit active file will use the
* low index as the active file.
*
*/
void test1() {
PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%m\n"));
RollingFileAppenderPtr rfa = new RollingFileAppender();
rfa->setName(LOG4CXX_STR("ROLLING"));
rfa->setAppend(false);
rfa->setLayout(layout);
FixedWindowRollingPolicyPtr swrp = new FixedWindowRollingPolicy();
swrp->setMinIndex(0);
swrp->setFileNamePattern(LOG4CXX_STR("output/manual-test1.%i"));
Pool p;
swrp->activateOptions(p);
rfa->setRollingPolicy(swrp);
rfa->activateOptions(p);
root->addAppender(rfa);
common(rfa, p, logger);
LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test1.0").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test1.1").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test1.2").exists(p));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test1.0"),
File("witness/rolling/sbr-test2.log")));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test1.1"),
File("witness/rolling/sbr-test2.0")));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test1.2"),
File("witness/rolling/sbr-test2.1")));
}
/**
* Test basic rolling functionality with explicit setting of FileAppender.file.
*/
void test2() {
PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%m\n"));
RollingFileAppenderPtr rfa = new RollingFileAppender();
rfa->setName(LOG4CXX_STR("ROLLING"));
rfa->setAppend(false);
rfa->setLayout(layout);
rfa->setFile(LOG4CXX_STR("output/manual-test2.log"));
Pool p;
rfa->activateOptions(p);
root->addAppender(rfa);
common(rfa, p, logger);
LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test2.log").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test2.log.1").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test2.log.2").exists(p));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test2.log"),
File("witness/rolling/sbr-test2.log")));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test2.log.1"),
File("witness/rolling/sbr-test2.0")));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test2.log.2"),
File("witness/rolling/sbr-test2.1")));
}
/**
* Same as testBasic but also with GZ compression.
*/
void test3() {
PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%m\n"));
RollingFileAppenderPtr rfa = new RollingFileAppender();
rfa->setAppend(false);
rfa->setLayout(layout);
FixedWindowRollingPolicyPtr fwrp = new FixedWindowRollingPolicy();
fwrp->setMinIndex(0);
rfa->setFile(LOG4CXX_STR("output/manual-test3.log"));
fwrp->setFileNamePattern(LOG4CXX_STR("output/sbr-test3.%i.gz"));
Pool p;
fwrp->activateOptions(p);
rfa->setRollingPolicy(fwrp);
rfa->activateOptions(p);
root->addAppender(rfa);
common(rfa, p, logger);
LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test3.log").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test3.0.gz").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test3.1.gz").exists(p));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test3.log"), File("witness/rolling/sbr-test3.log")));
LOGUNIT_ASSERT_EQUAL(File("witness/rolling/sbr-test3.0.gz").length(p), File("output/manual-test3.0.gz").length(p));
LOGUNIT_ASSERT_EQUAL(File("witness/rolling/sbr-test3.1.gz").length(p), File("output/manual-test3.1.gz").length(p));
}
/**
* Test basic rolling functionality with bogus path in file name pattern.
*/
void test4() {
PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%m\n"));
RollingFileAppenderPtr rfa = new RollingFileAppender();
rfa->setName(LOG4CXX_STR("ROLLING"));
rfa->setAppend(false);
rfa->setLayout(layout);
rfa->setFile(LOG4CXX_STR("output/manual-test4.log"));
FixedWindowRollingPolicyPtr swrp = new FixedWindowRollingPolicy();
swrp->setMinIndex(0);
//
// test4 directory should not exists. Should cause all rollover attempts to fail.
//
swrp->setFileNamePattern(LOG4CXX_STR("output/test4/manual-test4.%i"));
Pool p;
swrp->activateOptions(p);
rfa->setRollingPolicy(swrp);
rfa->activateOptions(p);
root->addAppender(rfa);
common(rfa, p, logger);
LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test4.log").exists(p));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test4.log"),
File("witness/rolling/sbr-test4.log")));
}
/**
* Checking handling of rename failures due to other access
* to the indexed files.
*/
void test5() {
PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%m\n"));
RollingFileAppenderPtr rfa = new RollingFileAppender();
rfa->setName(LOG4CXX_STR("ROLLING"));
rfa->setAppend(false);
rfa->setLayout(layout);
rfa->setFile(LOG4CXX_STR("output/manual-test5.log"));
FixedWindowRollingPolicyPtr swrp = new FixedWindowRollingPolicy();
swrp->setMinIndex(0);
swrp->setFileNamePattern(LOG4CXX_STR("output/manual-test5.%i"));
Pool p;
swrp->activateOptions(p);
rfa->setRollingPolicy(swrp);
rfa->activateOptions(p);
root->addAppender(rfa);
//
// put stray file about locked file
FileOutputStream os1(LOG4CXX_STR("output/manual-test5.1"), false);
os1.close(p);
FileOutputStream os0(LOG4CXX_STR("output/manual-test5.0"), false);
common(rfa, p, logger);
os0.close(p);
if (File("output/manual-test5.3").exists(p)) {
//
// looks like platform where open files can be renamed
//
LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test5.log").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test5.0").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test5.1").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test5.2").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test5.3").exists(p));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test5.log"),
File("witness/rolling/sbr-test2.log")));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test5.0"),
File("witness/rolling/sbr-test2.0")));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test5.1"),
File("witness/rolling/sbr-test2.1")));
} else {
//
// rollover attempts should all fail
// so initial log file should have all log content
// open file should be unaffected
// stray file should have only been moved one slot.
LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test5.log").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test5.0").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test5.2").exists(p));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test5.log"),
File("witness/rolling/sbr-test4.log")));
}
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(ManualRollingTest);
| 001-log4cxx | trunk/src/test/cpp/rolling/manualrollingtest.cpp | C++ | asf20 | 10,024 |
/*
* 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 "../util/compare.h"
#include "../insertwide.h"
#include "../logunit.h"
#include <apr_time.h>
#include <log4cxx/logmanager.h>
#include <log4cxx/xml/domconfigurator.h>
#include <log4cxx/patternlayout.h>
#include <log4cxx/rolling/rollingfileappender.h>
#include <log4cxx/rolling/fixedwindowrollingpolicy.h>
#include <log4cxx/rolling/filterbasedtriggeringpolicy.h>
#include <log4cxx/filter/levelrangefilter.h>
#include <log4cxx/helpers/pool.h>
#include <log4cxx/logger.h>
#include <log4cxx/propertyconfigurator.h>
#include <log4cxx/dailyrollingfileappender.h>
#include <log4cxx/helpers/stringhelper.h>
using namespace log4cxx;
using namespace log4cxx::rolling;
using namespace log4cxx::xml;
using namespace log4cxx::filter;
using namespace log4cxx::helpers;
/**
* Tests the emulation of org.apache.log4j.DailyRollingFileAppender
*
*
*
*/
LOGUNIT_CLASS(ObsoleteDailyRollingFileAppenderTest) {
LOGUNIT_TEST_SUITE(ObsoleteDailyRollingFileAppenderTest);
LOGUNIT_TEST(test1);
LOGUNIT_TEST(test2);
LOGUNIT_TEST_SUITE_END();
public:
void tearDown() {
LogManager::shutdown();
}
/**
* Test basic rolling functionality.
*/
void test1() {
PropertyConfigurator::configure(File("input/rolling/obsoleteDRFA1.properties"));
int preCount = getFileCount("output", LOG4CXX_STR("obsoleteDRFA-test1.log."));
LoggerPtr logger(Logger::getLogger("org.apache.log4j.ObsoleteDailyRollingFileAppenderTest"));
char msg[11];
strcpy(msg, "Hello---??");
for (int i = 0; i < 25; i++) {
apr_sleep(100000);
msg[8] = (char) ('0' + (i / 10));
msg[9] = (char) ('0' + (i % 10));
LOG4CXX_DEBUG(logger, msg);
}
int postCount = getFileCount("output", LOG4CXX_STR("obsoleteDRFA-test1.log."));
LOGUNIT_ASSERT_EQUAL(true, postCount > preCount);
}
/**
* Test basic rolling functionality.
* @deprecated Class under test is deprecated.
*/
void test2() {
PatternLayoutPtr layout(new PatternLayout(LOG4CXX_STR("%m%n")));
log4cxx::DailyRollingFileAppenderPtr rfa(new log4cxx::DailyRollingFileAppender());
rfa->setName(LOG4CXX_STR("ROLLING"));
rfa->setLayout(layout);
rfa->setAppend(false);
rfa->setFile(LOG4CXX_STR("output/obsoleteDRFA-test2.log"));
rfa->setDatePattern(LOG4CXX_STR("'.'yyyy-MM-dd-HH_mm_ss"));
Pool p;
rfa->activateOptions(p);
LoggerPtr root(Logger::getRootLogger());
root->addAppender(rfa);
LoggerPtr logger(Logger::getLogger("org.apache.log4j.ObsoleteDailyRollingAppenderTest"));
int preCount = getFileCount("output", LOG4CXX_STR("obsoleteDRFA-test2.log."));
char msg[11];
strcpy(msg, "Hello---??");
for (int i = 0; i < 25; i++) {
apr_sleep(100000);
msg[8] = (char) ('0' + i / 10);
msg[9] = (char) ('0' + i % 10);
LOG4CXX_DEBUG(logger, msg);
}
int postCount = getFileCount("output", LOG4CXX_STR("obsoleteDRFA-test2.log."));
LOGUNIT_ASSERT_EQUAL(true, postCount > preCount);
}
private:
static int getFileCount(const char* dir, const LogString& initial) {
Pool p;
std::vector<LogString> files(File(dir).list(p));
int count = 0;
for (size_t i = 0; i < files.size(); i++) {
if (StringHelper::startsWith(files[i], initial)) {
count++;
}
}
return count;
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(ObsoleteDailyRollingFileAppenderTest);
| 001-log4cxx | trunk/src/test/cpp/rolling/obsoletedailyrollingfileappendertest.cpp | C++ | asf20 | 4,196 |
/*
* 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/rolling/rollingfileappender.h>
#include <log4cxx/logger.h>
#include <log4cxx/consoleappender.h>
#include <log4cxx/logmanager.h>
#include <log4cxx/patternlayout.h>
#include <log4cxx/rolling/timebasedrollingpolicy.h>
#include <log4cxx/helpers/simpledateformat.h>
#include <iostream>
#include <log4cxx/helpers/stringhelper.h>
#include "../util/compare.h"
#include "../logunit.h"
#include <apr_strings.h>
#ifndef INT64_C
#define INT64_C(x) x ## LL
#endif
#include <apr_time.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::rolling;
/**
* A rather exhaustive set of tests. Tests include leaving the ActiveFileName
* argument blank, or setting it, with and without compression, and tests
* with or without stopping/restarting the RollingFileAppender.
*
* The regression tests log a few times using a RollingFileAppender. Then,
* they predict the names of the files which sould be generated and compare
* them with witness files.
*
* <pre>
Compression ActiveFileName Stop/Restart
Test1 NO BLANK NO
Test2 NO BLANK YES
Test3 YES BLANK NO
Test4 NO SET YES
Test5 NO SET NO
Test6 YES SET NO
* </pre>
*
*/
LOGUNIT_CLASS(TimeBasedRollingTest) {
LOGUNIT_TEST_SUITE(TimeBasedRollingTest);
LOGUNIT_TEST(test1);
LOGUNIT_TEST(test2);
LOGUNIT_TEST(test3);
LOGUNIT_TEST(test4);
LOGUNIT_TEST(test5);
LOGUNIT_TEST(test6);
LOGUNIT_TEST_SUITE_END();
static LoggerPtr logger;
public:
void setUp() {
LoggerPtr root(Logger::getRootLogger());
root->addAppender(
new ConsoleAppender(new PatternLayout(
LOG4CXX_STR("%d{ABSOLUTE} [%t] %level %c{2}#%M:%L - %m%n"))));
}
void tearDown() {
LogManager::shutdown();
}
/**
* Test rolling without compression, activeFileName left blank, no stop/start
*/
void test1() {
PatternLayoutPtr layout(new PatternLayout(LOG4CXX_STR("%c{1} - %m%n")));
RollingFileAppenderPtr rfa(new RollingFileAppender());
rfa->setLayout(layout);
LogString datePattern(LOG4CXX_STR("yyyy-MM-dd_HH_mm_ss"));
TimeBasedRollingPolicyPtr tbrp(new TimeBasedRollingPolicy());
tbrp->setFileNamePattern(LOG4CXX_STR("output/test1-%d{yyyy-MM-dd_HH_mm_ss}"));
Pool p;
tbrp->activateOptions(p);
rfa->setRollingPolicy(tbrp);
rfa->activateOptions(p);
logger->addAppender(rfa);
SimpleDateFormat sdf(datePattern);
LogString filenames[4];
Pool pool;
apr_time_t now = apr_time_now();
{ for (int i = 0; i < 4; i++) {
filenames[i] = LOG4CXX_STR("output/test1-");
sdf.format(filenames[i], now, p);
now += APR_USEC_PER_SEC;
} }
std::cout << "Waiting until next second and 100 millis.";
delayUntilNextSecond(100);
std::cout << "Done waiting.";
{ for (int i = 0; i < 5; i++) {
std::string message("Hello---");
message.append(pool.itoa(i));
LOG4CXX_DEBUG(logger, message);
apr_sleep(APR_USEC_PER_SEC/2);
} }
for (int i = 0; i < 4; i++) {
LogString witness(LOG4CXX_STR("witness/rolling/tbr-test1."));
StringHelper::toString(i, pool, witness);
LOGUNIT_ASSERT(Compare::compare(filenames[i], File(witness)));
}
}
/**
* No compression, with stop/restart, activeFileName left blank
*/
void test2() {
LogString datePattern(LOG4CXX_STR("yyyy-MM-dd_HH_mm_ss"));
PatternLayoutPtr layout1(new PatternLayout(LOG4CXX_STR("%c{1} - %m%n")));
RollingFileAppenderPtr rfa1(new RollingFileAppender());
rfa1->setLayout(layout1);
TimeBasedRollingPolicyPtr tbrp1(new TimeBasedRollingPolicy());
tbrp1->setFileNamePattern(LOG4CXX_STR("output/test2-%d{yyyy-MM-dd_HH_mm_ss}"));
Pool pool;
tbrp1->activateOptions(pool);
rfa1->setRollingPolicy(tbrp1);
rfa1->activateOptions(pool);
logger->addAppender(rfa1);
SimpleDateFormat sdf(datePattern);
LogString filenames[4];
apr_time_t now = apr_time_now();
{ for (int i = 0; i < 4; i++) {
filenames[i] = LOG4CXX_STR("output/test2-");
sdf.format(filenames[i], now, pool);
now += APR_USEC_PER_SEC;
} }
delayUntilNextSecond(100);
{ for (int i = 0; i <= 2; i++) {
std::string message("Hello---");
message.append(pool.itoa(i));
LOG4CXX_DEBUG(logger, message);
apr_sleep(APR_USEC_PER_SEC/2);
} }
logger->removeAppender(rfa1);
rfa1->close();
PatternLayoutPtr layout2(new PatternLayout(LOG4CXX_STR("%c{1} - %m%n")));
RollingFileAppenderPtr rfa2 = new RollingFileAppender();
rfa2->setLayout(layout2);
TimeBasedRollingPolicyPtr tbrp2 = new TimeBasedRollingPolicy();
tbrp2->setFileNamePattern(LOG4CXX_STR("output/test2-%d{yyyy-MM-dd_HH_mm_ss}"));
tbrp2->activateOptions(pool);
rfa2->setRollingPolicy(tbrp2);
rfa2->activateOptions(pool);
logger->addAppender(rfa2);
{ for (int i = 3; i <= 4; i++) {
std::string message("Hello---");
message.append(pool.itoa(i));
LOG4CXX_DEBUG(logger, message);
apr_sleep(APR_USEC_PER_SEC/2);
} }
for (int i = 0; i < 4; i++) {
LogString witness(LOG4CXX_STR("witness/rolling/tbr-test2."));
StringHelper::toString(i, pool, witness);
LOGUNIT_ASSERT(Compare::compare(filenames[i], File(witness)));
}
}
/**
* With compression, activeFileName left blank, no stop/restart
*/
void test3() {
Pool p;
PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%c{1} - %m%n"));
RollingFileAppenderPtr rfa = new RollingFileAppender();
rfa->setAppend(false);
rfa->setLayout(layout);
LogString datePattern = LOG4CXX_STR("yyyy-MM-dd_HH_mm_ss");
TimeBasedRollingPolicyPtr tbrp = new TimeBasedRollingPolicy();
tbrp->setFileNamePattern(LogString(LOG4CXX_STR("output/test3-%d{")) + datePattern + LogString(LOG4CXX_STR("}.gz")));
tbrp->activateOptions(p);
rfa->setRollingPolicy(tbrp);
rfa->activateOptions(p);
logger->addAppender(rfa);
DateFormatPtr sdf = new SimpleDateFormat(datePattern);
LogString filenames[4];
apr_time_t now = apr_time_now();
{ for (int i = 0; i < 4; i++) {
filenames[i] = LOG4CXX_STR("output/test3-");
sdf->format(filenames[i], now, p);
filenames[i].append(LOG4CXX_STR(".gz"));
now += APR_USEC_PER_SEC;
} }
filenames[3].resize(filenames[3].size() - 3);
delayUntilNextSecond(100);
{ for (int i = 0; i < 5; i++) {
std::string message("Hello---");
message.append(p.itoa(i));
LOG4CXX_DEBUG(logger, message);
apr_sleep(APR_USEC_PER_SEC/2);
} }
LOGUNIT_ASSERT_EQUAL(true, File(filenames[0]).exists(p));
LOGUNIT_ASSERT_EQUAL(true, File(filenames[1]).exists(p));
LOGUNIT_ASSERT_EQUAL(true, File(filenames[2]).exists(p));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File(filenames[3]), File(LOG4CXX_STR("witness/rolling/tbr-test3.3"))));
}
/**
* Without compression, activeFileName set, with stop/restart
*/
void test4() {
LogString datePattern = LOG4CXX_STR("yyyy-MM-dd_HH_mm_ss");
PatternLayoutPtr layout1 = new PatternLayout(LOG4CXX_STR("%c{1} - %m%n"));
RollingFileAppenderPtr rfa1 = new RollingFileAppender();
rfa1->setLayout(layout1);
Pool pool;
TimeBasedRollingPolicyPtr tbrp1 = new TimeBasedRollingPolicy();
rfa1->setFile(LOG4CXX_STR("output/test4.log"));
tbrp1->setFileNamePattern(LOG4CXX_STR("output/test4-%d{yyyy-MM-dd_HH_mm_ss}"));
tbrp1->activateOptions(pool);
rfa1->setRollingPolicy(tbrp1);
rfa1->activateOptions(pool);
logger->addAppender(rfa1);
SimpleDateFormat sdf(datePattern);
LogString filenames[4];
apr_time_t now = apr_time_now();
{ for (int i = 0; i < 3; i++) {
filenames[i] = LOG4CXX_STR("output/test4-");
sdf.format(filenames[i], now, pool);
now += APR_USEC_PER_SEC;
} }
filenames[3] = LOG4CXX_STR("output/test4.log");
std::cout << "Waiting until next second and 100 millis.";
delayUntilNextSecond(100);
std::cout << "Done waiting.";
{ for (int i = 0; i <= 2; i++) {
std::string message("Hello---");
message.append(pool.itoa(i));
LOG4CXX_DEBUG(logger, message);
apr_sleep(APR_USEC_PER_SEC/2);
} }
logger->removeAppender(rfa1);
rfa1->close();
PatternLayoutPtr layout2 = new PatternLayout(LOG4CXX_STR("%c{1} - %m%n"));
RollingFileAppenderPtr rfa2 = new RollingFileAppender();
rfa2->setLayout(layout2);
TimeBasedRollingPolicyPtr tbrp2 = new TimeBasedRollingPolicy();
tbrp2->setFileNamePattern(LOG4CXX_STR("output/test4-%d{yyyy-MM-dd_HH_mm_ss}"));
rfa2->setFile(LOG4CXX_STR("output/test4.log"));
tbrp2->activateOptions(pool);
rfa2->setRollingPolicy(tbrp2);
rfa2->activateOptions(pool);
logger->addAppender(rfa2);
{ for (int i = 3; i <= 4; i++) {
std::string message("Hello---");
message.append(pool.itoa(i));
LOG4CXX_DEBUG(logger, message);
apr_sleep(APR_USEC_PER_SEC/2);
} }
for (int i = 0; i < 4; i++) {
LogString witness(LOG4CXX_STR("witness/rolling/tbr-test4."));
StringHelper::toString(i, pool, witness);
LOGUNIT_ASSERT(Compare::compare(filenames[i], File(witness)));
}
}
/**
* No compression, activeFileName set, without stop/restart
*/
void test5() {
PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%c{1} - %m%n"));
RollingFileAppenderPtr rfa = new RollingFileAppender();
rfa->setLayout(layout);
LogString datePattern(LOG4CXX_STR("yyyy-MM-dd_HH_mm_ss"));
TimeBasedRollingPolicyPtr tbrp = new TimeBasedRollingPolicy();
tbrp->setFileNamePattern(LOG4CXX_STR("output/test5-%d{yyyy-MM-dd_HH_mm_ss}"));
rfa->setFile(LOG4CXX_STR("output/test5.log"));
Pool pool;
tbrp->activateOptions(pool);
rfa->setRollingPolicy(tbrp);
rfa->activateOptions(pool);
logger->addAppender(rfa);
SimpleDateFormat sdf(datePattern);
LogString filenames[4];
apr_time_t now = apr_time_now();
{ for (int i = 0; i < 3; i++) {
filenames[i] = LOG4CXX_STR("output/test5-");
sdf.format(filenames[i], now, pool);
now += APR_USEC_PER_SEC;
} }
filenames[3] = LOG4CXX_STR("output/test5.log");
std::cout << "Waiting until next second and 100 millis.";
delayUntilNextSecond(100);
std::cout << "Done waiting.";
{ for (int i = 0; i < 5; i++) {
std::string message("Hello---");
message.append(pool.itoa(i));
LOG4CXX_DEBUG(logger, message);
apr_sleep(APR_USEC_PER_SEC/2);
} }
for (int i = 0; i < 4; i++) {
LogString witness(LOG4CXX_STR("witness/rolling/tbr-test5."));
StringHelper::toString(i, pool, witness);
LOGUNIT_ASSERT(Compare::compare(filenames[i], File(witness)));
}
}
/**
* With compression, activeFileName set, no stop/restart,
*/
void test6() {
Pool p;
PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%c{1} - %m%n"));
RollingFileAppenderPtr rfa = new RollingFileAppender();
rfa->setAppend(false);
rfa->setLayout(layout);
LogString datePattern = LOG4CXX_STR("yyyy-MM-dd_HH_mm_ss");
TimeBasedRollingPolicyPtr tbrp = new TimeBasedRollingPolicy();
tbrp->setFileNamePattern(LogString(LOG4CXX_STR("output/test6-%d{")) + datePattern + LogString(LOG4CXX_STR("}.gz")));
rfa->setFile(LOG4CXX_STR("output/test6.log"));
tbrp->activateOptions(p);
rfa->setRollingPolicy(tbrp);
rfa->activateOptions(p);
logger->addAppender(rfa);
DateFormatPtr sdf = new SimpleDateFormat(datePattern);
LogString filenames[4];
apr_time_t now = apr_time_now();
{ for (int i = 0; i < 3; i++) {
filenames[i] = LOG4CXX_STR("output/test6-");
sdf->format(filenames[i], now, p);
filenames[i].append(LOG4CXX_STR(".gz"));
now += APR_USEC_PER_SEC;
} }
filenames[3] = LOG4CXX_STR("output/test6.log");
delayUntilNextSecond(100);
{ for (int i = 0; i < 5; i++) {
std::string message("Hello---");
message.append(p.itoa(i));
LOG4CXX_DEBUG(logger, message);
apr_sleep(APR_USEC_PER_SEC/2);
} }
LOGUNIT_ASSERT_EQUAL(true, File(filenames[0]).exists(p));
LOGUNIT_ASSERT_EQUAL(true, File(filenames[1]).exists(p));
LOGUNIT_ASSERT_EQUAL(true, File(filenames[2]).exists(p));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File(filenames[3]), File(LOG4CXX_STR("witness/rolling/tbr-test6.3"))));
}
void delayUntilNextSecond(int millis) {
apr_time_t now = apr_time_now();
apr_time_t next = ((now / APR_USEC_PER_SEC) + 1) * APR_USEC_PER_SEC
+ millis * 1000L;
apr_sleep(next - now);
}
void delayUntilNextMinute(int seconds) {
apr_time_t now = apr_time_now();
apr_time_t next = ((now / APR_USEC_PER_SEC) + 1) * APR_USEC_PER_SEC
+ seconds * 1000000L;
apr_sleep(next - now);
}
};
LoggerPtr TimeBasedRollingTest::logger(Logger::getLogger("org.apache.log4j.TimeBasedRollingTest"));
LOGUNIT_TEST_SUITE_REGISTRATION(TimeBasedRollingTest);
| 001-log4cxx | trunk/src/test/cpp/rolling/timebasedrollingtest.cpp | C++ | asf20 | 14,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 "../util/compare.h"
#include "../logunit.h"
#include "../insertwide.h"
#include <log4cxx/logmanager.h>
#include <log4cxx/xml/domconfigurator.h>
#include <log4cxx/patternlayout.h>
#include <log4cxx/rolling/rollingfileappender.h>
#include <log4cxx/rolling/fixedwindowrollingpolicy.h>
#include <log4cxx/rolling/filterbasedtriggeringpolicy.h>
#include <log4cxx/filter/levelrangefilter.h>
#include <log4cxx/helpers/pool.h>
#include <log4cxx/logger.h>
using namespace log4cxx;
using namespace log4cxx::rolling;
using namespace log4cxx::xml;
using namespace log4cxx::filter;
using namespace log4cxx::helpers;
/**
*
* Tests of rolling file appender with a filter based triggering policy.
*
*
*
*
*/
LOGUNIT_CLASS(FilterBasedRollingTest) {
LOGUNIT_TEST_SUITE(FilterBasedRollingTest);
LOGUNIT_TEST(test1);
LOGUNIT_TEST(test2);
LOGUNIT_TEST_SUITE_END();
public:
void tearDown() {
LogManager::getLoggerRepository()->resetConfiguration();
}
/**
* Test basic rolling functionality using configuration file.
*/
void test1() {
DOMConfigurator::configure(
"./input/rolling/filter1.xml" /*, LogManager::getLoggerRepository() */);
common(LOG4CXX_STR("output/filterBased-test1"));
}
/**
* Test basic rolling functionality using explicit configuration.
* @remarks Test fails when run immediately after test1.
*/
void test2() {
LayoutPtr layout(new PatternLayout(LOG4CXX_STR("%m\n")));
RollingFileAppenderPtr rfa(new RollingFileAppender());
rfa->setName(LOG4CXX_STR("ROLLING"));
rfa->setLayout(layout);
FixedWindowRollingPolicyPtr swrp(new FixedWindowRollingPolicy());
FilterBasedTriggeringPolicyPtr fbtp(new FilterBasedTriggeringPolicy());
LevelRangeFilterPtr rf(new LevelRangeFilter());
rf->setLevelMin(Level::getInfo());
fbtp->addFilter(rf);
Pool p;
fbtp->activateOptions(p);
swrp->setMinIndex(0);
rfa->setFile(LOG4CXX_STR("output/filterBased-test2.log"));
rfa->setAppend(false);
swrp->setFileNamePattern(LOG4CXX_STR("output/filterBased-test2.%i"));
swrp->activateOptions(p);
rfa->setRollingPolicy(swrp);
rfa->setTriggeringPolicy(fbtp);
rfa->activateOptions(p);
Logger::getRootLogger()->addAppender(rfa);
Logger::getRootLogger()->setLevel(Level::getDebug());
common(LOG4CXX_STR("output/filterBased-test2"));
}
private:
/**
* Common aspects of test1 and test2
*/
void common(const LogString& baseName) {
LoggerPtr logger(Logger::getLogger("org.apache.log4j.rolling.FilterBasedRollingTest"));
// Write exactly 10 bytes with each log
for (int i = 0; i < 25; i++) {
char msg[10];
#if defined(__STDC_LIB_EXT1__) || defined(__STDC_SECURE_LIB__)
strcpy_s(msg, sizeof msg, "Hello---?");
#else
strcpy(msg, "Hello---?");
#endif
if (i < 10) {
msg[8] = (char) ('0' + i);
LOG4CXX_DEBUG(logger, msg);
} else if (i < 100) {
msg[7] = (char) ('0' + (i / 10));
msg[8] = (char) ('0' + (i % 10));
if ((i % 10) == 0) {
LOG4CXX_WARN(logger, msg);
} else {
LOG4CXX_DEBUG(logger, msg);
}
}
}
//
// test was constructed to mimic SizeBasedRollingTest.test2
//
LOGUNIT_ASSERT_EQUAL(true,
Compare::compare(baseName + LOG4CXX_STR(".log"), LogString(LOG4CXX_STR("witness/rolling/sbr-test2.log"))));
LOGUNIT_ASSERT_EQUAL(true,
Compare::compare(baseName + LOG4CXX_STR(".0"), LogString(LOG4CXX_STR("witness/rolling/sbr-test2.0"))));
LOGUNIT_ASSERT_EQUAL(true,
Compare::compare(baseName + LOG4CXX_STR(".1"), LogString(LOG4CXX_STR("witness/rolling/sbr-test2.1"))));
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(FilterBasedRollingTest);
| 001-log4cxx | trunk/src/test/cpp/rolling/filterbasedrollingtest.cpp | C++ | asf20 | 4,562 |
/*
* 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 "../util/compare.h"
#include "../insertwide.h"
#include "../logunit.h"
#include <apr_time.h>
#include <log4cxx/logmanager.h>
#include <log4cxx/xml/domconfigurator.h>
#include <log4cxx/patternlayout.h>
#include <log4cxx/rolling/rollingfileappender.h>
#include <log4cxx/rolling/fixedwindowrollingpolicy.h>
#include <log4cxx/rolling/filterbasedtriggeringpolicy.h>
#include <log4cxx/filter/levelrangefilter.h>
#include <log4cxx/helpers/pool.h>
#include <log4cxx/logger.h>
#include <log4cxx/propertyconfigurator.h>
#include <log4cxx/rollingfileappender.h>
#include <log4cxx/helpers/stringhelper.h>
using namespace log4cxx;
using namespace log4cxx::xml;
using namespace log4cxx::filter;
using namespace log4cxx::helpers;
/**
* Tests the emulation of org.apache.log4j.RollingFileAppender
*
*
*
*/
LOGUNIT_CLASS(ObsoleteRollingFileAppenderTest) {
LOGUNIT_TEST_SUITE(ObsoleteRollingFileAppenderTest);
LOGUNIT_TEST(test1);
LOGUNIT_TEST(test2);
LOGUNIT_TEST(testIsOptionHandler);
LOGUNIT_TEST(testClassForName);
LOGUNIT_TEST_SUITE_END();
public:
void tearDown() {
LogManager::shutdown();
}
/**
* Test basic rolling functionality.
*/
void test1() {
PropertyConfigurator::configure(File("input/rolling/obsoleteRFA1.properties"));
char msg[] = { 'H', 'e', 'l', 'l', 'o', '-', '-', '-', '?', 0};
LoggerPtr logger(Logger::getLogger("org.apache.logj4.ObsoleteRollingFileAppenderTest"));
// Write exactly 10 bytes with each log
for (int i = 0; i < 25; i++) {
apr_sleep(100000);
if (i < 10) {
msg[8] = (char) ('0' + i);
LOG4CXX_DEBUG(logger, msg);
} else if (i < 100) {
msg[7] = (char) ('0' + i / 10);
msg[8] = (char) ('0' + i % 10);
LOG4CXX_DEBUG(logger, msg);
}
}
Pool p;
LOGUNIT_ASSERT_EQUAL(true, File("output/obsoleteRFA-test1.log").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/obsoleteRFA-test1.log.1").exists(p));
}
/**
* Test basic rolling functionality.
* @deprecated Class under test is deprecated.
*/
void test2() {
PatternLayoutPtr layout(new PatternLayout(LOG4CXX_STR("%m\n")));
log4cxx::RollingFileAppenderPtr rfa(
new log4cxx::RollingFileAppender());
rfa->setName(LOG4CXX_STR("ROLLING"));
rfa->setLayout(layout);
rfa->setOption(LOG4CXX_STR("append"), LOG4CXX_STR("false"));
rfa->setMaximumFileSize(100);
rfa->setFile(LOG4CXX_STR("output/obsoleteRFA-test2.log"));
Pool p;
rfa->activateOptions(p);
LoggerPtr root(Logger::getRootLogger());
root->addAppender(rfa);
char msg[] = { 'H', 'e', 'l', 'l', 'o', '-', '-', '-', '?', 0};
LoggerPtr logger(Logger::getLogger("org.apache.logj4.ObsoleteRollingFileAppenderTest"));
// Write exactly 10 bytes with each log
for (int i = 0; i < 25; i++) {
apr_sleep(100000);
if (i < 10) {
msg[8] = (char) ('0' + i);
LOG4CXX_DEBUG(logger, msg);
} else if (i < 100) {
msg[7] = (char) ('0' + i / 10);
msg[8] = (char) ('0' + i % 10);
LOG4CXX_DEBUG(logger, msg);
}
}
LOGUNIT_ASSERT_EQUAL(true, File("output/obsoleteRFA-test2.log").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/obsoleteRFA-test2.log.1").exists(p));
}
/**
* Tests if class is declared to support the OptionHandler interface.
* See LOGCXX-136.
*/
void testIsOptionHandler() {
RollingFileAppenderPtr rfa(new RollingFileAppender());
LOGUNIT_ASSERT_EQUAL(true, rfa->instanceof(log4cxx::spi::OptionHandler::getStaticClass()));
}
void testClassForName() {
LogString className(LOG4CXX_STR("org.apache.log4j.RollingFileAppender"));
const Class& myclass = Class::forName(className);
LOGUNIT_ASSERT_EQUAL(className, LogString(myclass.getName()));
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(ObsoleteRollingFileAppenderTest);
| 001-log4cxx | trunk/src/test/cpp/rolling/obsoleterollingfileappendertest.cpp | C++ | asf20 | 4,729 |
/*
* 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 "../util/compare.h"
#include "../insertwide.h"
#include "../logunit.h"
#include <apr_time.h>
#include <log4cxx/logmanager.h>
#include <log4cxx/xml/domconfigurator.h>
#include <log4cxx/patternlayout.h>
#include <log4cxx/rolling/fixedwindowrollingpolicy.h>
#include <log4cxx/rolling/sizebasedtriggeringpolicy.h>
#include <log4cxx/filter/levelrangefilter.h>
#include <log4cxx/helpers/pool.h>
#include <log4cxx/logger.h>
#include <log4cxx/propertyconfigurator.h>
#include <log4cxx/rolling/rollingfileappender.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/consoleappender.h>
#include <log4cxx/helpers/exception.h>
#include <log4cxx/helpers/fileoutputstream.h>
using namespace log4cxx;
using namespace log4cxx::xml;
using namespace log4cxx::filter;
using namespace log4cxx::helpers;
using namespace log4cxx::rolling;
/**
*
* Do not forget to call activateOptions when configuring programatically.
*
*
*
*/
LOGUNIT_CLASS(SizeBasedRollingTest) {
LOGUNIT_TEST_SUITE(SizeBasedRollingTest);
LOGUNIT_TEST(test1);
LOGUNIT_TEST(test2);
LOGUNIT_TEST(test3);
LOGUNIT_TEST(test4);
LOGUNIT_TEST(test5);
LOGUNIT_TEST(test6);
LOGUNIT_TEST_SUITE_END();
LoggerPtr root;
LoggerPtr logger;
public:
void setUp() {
PatternLayoutPtr layout(new PatternLayout(LOG4CXX_STR("%d %level %c -%m%n")));
AppenderPtr ca(new ConsoleAppender(layout));
ca->setName(LOG4CXX_STR("CONSOLE"));
root = Logger::getRootLogger();
root->addAppender(ca);
logger = Logger::getLogger("org.apache.log4j.rolling.SizeBasedRollingTest");
}
void tearDown() {
LogManager::shutdown();
}
void common(LoggerPtr& logger1, int /*sleep*/) {
char msg[] = { 'H', 'e', 'l', 'l', 'o', '-', '-', '-', 'N', 0 };
// Write exactly 10 bytes with each log
for (int i = 0; i < 25; i++) {
if (i < 10) {
msg[8] = '0' + i;
} else if (i < 100) {
msg[7] = '0' + i / 10;
msg[8] = '0' + i % 10;
}
LOG4CXX_DEBUG(logger1, msg);
}
}
/**
* Tests that the lack of an explicit active file will use the
* low index as the active file.
*
*/
void test1() {
PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%m\n"));
RollingFileAppenderPtr rfa = new RollingFileAppender();
rfa->setName(LOG4CXX_STR("ROLLING"));
rfa->setAppend(false);
rfa->setLayout(layout);
FixedWindowRollingPolicyPtr swrp = new FixedWindowRollingPolicy();
SizeBasedTriggeringPolicyPtr sbtp = new SizeBasedTriggeringPolicy();
sbtp->setMaxFileSize(100);
swrp->setMinIndex(0);
swrp->setFileNamePattern(LOG4CXX_STR("output/sizeBased-test1.%i"));
Pool p;
swrp->activateOptions(p);
rfa->setRollingPolicy(swrp);
rfa->setTriggeringPolicy(sbtp);
rfa->activateOptions(p);
root->addAppender(rfa);
common(logger, 0);
LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test1.0").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test1.1").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test1.2").exists(p));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test1.0"),
File("witness/rolling/sbr-test2.log")));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test1.1"),
File("witness/rolling/sbr-test2.0")));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test1.2"),
File("witness/rolling/sbr-test2.1")));
}
/**
* Test basic rolling functionality with explicit setting of FileAppender.file.
*/
void test2() {
PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%m\n"));
RollingFileAppenderPtr rfa = new RollingFileAppender();
rfa->setName(LOG4CXX_STR("ROLLING"));
rfa->setAppend(false);
rfa->setLayout(layout);
rfa->setFile(LOG4CXX_STR("output/sizeBased-test2.log"));
FixedWindowRollingPolicyPtr swrp = new FixedWindowRollingPolicy();
SizeBasedTriggeringPolicyPtr sbtp = new SizeBasedTriggeringPolicy();
sbtp->setMaxFileSize(100);
swrp->setMinIndex(0);
swrp->setFileNamePattern(LOG4CXX_STR("output/sizeBased-test2.%i"));
Pool p;
swrp->activateOptions(p);
rfa->setRollingPolicy(swrp);
rfa->setTriggeringPolicy(sbtp);
rfa->activateOptions(p);
root->addAppender(rfa);
common(logger, 0);
LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test2.log").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test2.0").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test2.1").exists(p));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test2.log"),
File("witness/rolling/sbr-test2.log")));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test2.0"),
File("witness/rolling/sbr-test2.0")));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test2.1"),
File("witness/rolling/sbr-test2.1")));
}
/**
* Same as testBasic but also with GZ compression.
*/
void test3() {
PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%m\n"));
RollingFileAppenderPtr rfa = new RollingFileAppender();
rfa->setAppend(false);
rfa->setLayout(layout);
FixedWindowRollingPolicyPtr fwrp = new FixedWindowRollingPolicy();
SizeBasedTriggeringPolicyPtr sbtp = new SizeBasedTriggeringPolicy();
sbtp->setMaxFileSize(100);
fwrp->setMinIndex(0);
rfa->setFile(LOG4CXX_STR("output/sbr-test3.log"));
fwrp->setFileNamePattern(LOG4CXX_STR("output/sbr-test3.%i.gz"));
Pool p;
fwrp->activateOptions(p);
rfa->setRollingPolicy(fwrp);
rfa->setTriggeringPolicy(sbtp);
rfa->activateOptions(p);
root->addAppender(rfa);
common(logger, 100);
LOGUNIT_ASSERT_EQUAL(true, File("output/sbr-test3.log").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/sbr-test3.0.gz").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/sbr-test3.1.gz").exists(p));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sbr-test3.log"), File("witness/rolling/sbr-test3.log")));
LOGUNIT_ASSERT_EQUAL(File("witness/rolling/sbr-test3.0.gz").length(p), File("output/sbr-test3.0.gz").length(p));
LOGUNIT_ASSERT_EQUAL(File("witness/rolling/sbr-test3.1.gz").length(p), File("output/sbr-test3.1.gz").length(p));
}
/**
* Test basic rolling functionality with bogus path in file name pattern.
*/
void test4() {
PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%m\n"));
RollingFileAppenderPtr rfa = new RollingFileAppender();
rfa->setName(LOG4CXX_STR("ROLLING"));
rfa->setAppend(false);
rfa->setLayout(layout);
rfa->setFile(LOG4CXX_STR("output/sizeBased-test4.log"));
FixedWindowRollingPolicyPtr swrp = new FixedWindowRollingPolicy();
SizeBasedTriggeringPolicyPtr sbtp = new SizeBasedTriggeringPolicy();
sbtp->setMaxFileSize(100);
swrp->setMinIndex(0);
//
// test4 directory should not exists. Should cause all rollover attempts to fail.
//
swrp->setFileNamePattern(LOG4CXX_STR("output/test4/sizeBased-test4.%i"));
Pool p;
swrp->activateOptions(p);
rfa->setRollingPolicy(swrp);
rfa->setTriggeringPolicy(sbtp);
rfa->activateOptions(p);
root->addAppender(rfa);
common(logger, 0);
LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test4.log").exists(p));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test4.log"),
File("witness/rolling/sbr-test4.log")));
}
/**
* Checking handling of rename failures due to other access
* to the indexed files.
*/
void test5() {
PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%m\n"));
RollingFileAppenderPtr rfa = new RollingFileAppender();
rfa->setName(LOG4CXX_STR("ROLLING"));
rfa->setAppend(false);
rfa->setLayout(layout);
rfa->setFile(LOG4CXX_STR("output/sizeBased-test5.log"));
FixedWindowRollingPolicyPtr swrp = new FixedWindowRollingPolicy();
SizeBasedTriggeringPolicyPtr sbtp = new SizeBasedTriggeringPolicy();
sbtp->setMaxFileSize(100);
swrp->setMinIndex(0);
swrp->setFileNamePattern(LOG4CXX_STR("output/sizeBased-test5.%i"));
Pool p;
swrp->activateOptions(p);
rfa->setRollingPolicy(swrp);
rfa->setTriggeringPolicy(sbtp);
rfa->activateOptions(p);
root->addAppender(rfa);
//
// put stray file about locked file
FileOutputStream os1(LOG4CXX_STR("output/sizeBased-test5.1"), false);
os1.close(p);
FileOutputStream os0(LOG4CXX_STR("output/sizeBased-test5.0"), false);
common(logger, 0);
os0.close(p);
if (File("output/sizeBased-test5.3").exists(p)) {
//
// looks like platform where open files can be renamed
//
LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test5.log").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test5.0").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test5.1").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test5.2").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test5.3").exists(p));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test5.log"),
File("witness/rolling/sbr-test2.log")));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test5.0"),
File("witness/rolling/sbr-test2.0")));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test5.1"),
File("witness/rolling/sbr-test2.1")));
} else {
//
// rollover attempts should all fail
// so initial log file should have all log content
// open file should be unaffected
// stray file should have only been moved one slot.
LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test5.log").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test5.0").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test5.2").exists(p));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test5.log"),
File("witness/rolling/sbr-test4.log")));
}
}
/**
* Same as testBasic but also with GZ compression.
*/
void test6() {
PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%m\n"));
RollingFileAppenderPtr rfa = new RollingFileAppender();
rfa->setAppend(false);
rfa->setLayout(layout);
FixedWindowRollingPolicyPtr fwrp = new FixedWindowRollingPolicy();
SizeBasedTriggeringPolicyPtr sbtp = new SizeBasedTriggeringPolicy();
sbtp->setMaxFileSize(100);
fwrp->setMinIndex(0);
rfa->setFile(LOG4CXX_STR("output/sbr-test6.log"));
fwrp->setFileNamePattern(LOG4CXX_STR("output/sbr-test6.%i.zip"));
Pool p;
fwrp->activateOptions(p);
rfa->setRollingPolicy(fwrp);
rfa->setTriggeringPolicy(sbtp);
rfa->activateOptions(p);
root->addAppender(rfa);
common(logger, 100);
LOGUNIT_ASSERT_EQUAL(true, File("output/sbr-test6.log").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/sbr-test6.0.zip").exists(p));
LOGUNIT_ASSERT_EQUAL(true, File("output/sbr-test6.1.zip").exists(p));
LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sbr-test6.log"), File("witness/rolling/sbr-test3.log")));
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(SizeBasedRollingTest);
| 001-log4cxx | trunk/src/test/cpp/rolling/sizebasedrollingtest.cpp | C++ | asf20 | 12,218 |
/*
* 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/properties.h>
#include <log4cxx/propertyconfigurator.h>
#include <log4cxx/logmanager.h>
#include "vectorappender.h"
#include "logunit.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
LOGUNIT_CLASS(PropertyConfiguratorTest)
{
LOGUNIT_TEST_SUITE(PropertyConfiguratorTest);
LOGUNIT_TEST(testInherited);
LOGUNIT_TEST(testNull);
LOGUNIT_TEST(testAppenderThreshold);
LOGUNIT_TEST_SUITE_END();
public:
void testInherited() {
Properties props;
props.put(LOG4CXX_STR("log4j.rootLogger"),LOG4CXX_STR("DEBUG,VECTOR1"));
props.put(LOG4CXX_STR("log4j.logger.org.apache.log4j.PropertyConfiguratorTest"), LOG4CXX_STR("inherited,VECTOR2"));
props.put(LOG4CXX_STR("log4j.appender.VECTOR1"), LOG4CXX_STR("org.apache.log4j.VectorAppender"));
props.put(LOG4CXX_STR("log4j.appender.VECTOR2"), LOG4CXX_STR("org.apache.log4j.VectorAppender"));
PropertyConfigurator::configure(props);
LoggerPtr logger = Logger::getLogger("org.apache.log4j.PropertyConfiguratorTest");
LOGUNIT_ASSERT_EQUAL((int) Level::DEBUG_INT,
logger->getEffectiveLevel()->toInt());
Logger::getRootLogger()->setLevel(Level::getError());
LOGUNIT_ASSERT_EQUAL((int) Level::ERROR_INT,
logger->getEffectiveLevel()->toInt());
LogManager::resetConfiguration();
}
void testNull() {
Properties props;
props.put(LOG4CXX_STR("log4j.rootLogger"),LOG4CXX_STR("DEBUG,VECTOR1"));
props.put(LOG4CXX_STR("log4j.logger.org.apache.log4j.PropertyConfiguratorTest"), LOG4CXX_STR("NuLL,VECTOR2"));
props.put(LOG4CXX_STR("log4j.appender.VECTOR1"), LOG4CXX_STR("org.apache.log4j.VectorAppender"));
props.put(LOG4CXX_STR("log4j.appender.VECTOR2"), LOG4CXX_STR("org.apache.log4j.VectorAppender"));
PropertyConfigurator::configure(props);
LoggerPtr logger = Logger::getLogger("org.apache.log4j.PropertyConfiguratorTest");
LOGUNIT_ASSERT_EQUAL((int) Level::DEBUG_INT,
logger->getEffectiveLevel()->toInt());
Logger::getRootLogger()->setLevel(Level::getError());
LOGUNIT_ASSERT_EQUAL((int) Level::ERROR_INT,
logger->getEffectiveLevel()->toInt());
LogManager::resetConfiguration();
}
void testAppenderThreshold() {
Properties props;
props.put(LOG4CXX_STR("log4j.rootLogger"), LOG4CXX_STR("ALL,VECTOR1"));
props.put(LOG4CXX_STR("log4j.appender.VECTOR1"), LOG4CXX_STR("org.apache.log4j.VectorAppender"));
props.put(LOG4CXX_STR("log4j.appender.VECTOR1.threshold"), LOG4CXX_STR("WARN"));
PropertyConfigurator::configure(props);
LoggerPtr root(Logger::getRootLogger());
VectorAppenderPtr appender(root->getAppender(LOG4CXX_STR("VECTOR1")));
LOGUNIT_ASSERT_EQUAL((int) Level::WARN_INT, appender->getThreshold()->toInt());
LOG4CXX_INFO(root, "Info message");
LOG4CXX_WARN(root, "Warn message");
LOG4CXX_WARN(root, "Error message");
LOGUNIT_ASSERT_EQUAL((size_t) 2, appender->vector.size());
LogManager::resetConfiguration();
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(PropertyConfiguratorTest);
| 001-log4cxx | trunk/src/test/cpp/propertyconfiguratortest.cpp | C++ | asf20 | 4,089 |
/* Copyright 2000-2004 Ryan Bloom
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Portions of this file were taken from testall.c in the APR test suite,
* written by members of the Apache Software Foundation.
*/
#include "abts.h"
#include "abts_tests.h"
#include "testutil.h"
#define ABTS_STAT_SIZE 6
static char status[ABTS_STAT_SIZE] = {'|', '/', '-', '|', '\\', '-'};
static int curr_char;
static int verbose = 0;
static int exclude = 0;
static int quiet = 0;
static int list_tests = 0;
const char **testlist = NULL;
// defined in logunit.cpp
abts_suite* abts_run_suites(abts_suite*);
static int find_test_name(const char *testname) {
int i;
for (i = 0; testlist[i] != NULL; i++) {
if (!strcmp(testlist[i], testname)) {
return 1;
}
}
return 0;
}
/* Determine if the test should be run at all */
static int should_test_run(const char *testname) {
int found = 0;
if (list_tests == 1) {
return 0;
}
if (testlist == NULL) {
return 1;
}
found = find_test_name(testname);
if ((found && !exclude) || (!found && exclude)) {
return 1;
}
return 0;
}
static void reset_status(void)
{
curr_char = 0;
}
static void update_status(void)
{
if (!quiet) {
curr_char = (curr_char + 1) % ABTS_STAT_SIZE;
fprintf(stdout, "\b%c", status[curr_char]);
fflush(stdout);
}
}
static void end_suite(abts_suite *suite)
{
if (suite != NULL) {
sub_suite *last = suite->tail;
if (!quiet) {
fprintf(stdout, "\b");
fflush(stdout);
}
if (last->failed == 0) {
fprintf(stdout, "SUCCESS\n");
fflush(stdout);
}
else {
fprintf(stdout, "FAILED %d of %d\n", last->failed, last->num_test);
fflush(stdout);
}
}
}
abts_suite *abts_add_suite(abts_suite *suite, const char *suite_name_full)
{
sub_suite *subsuite;
const char *p;
const char *suite_name;
curr_char = 0;
/* Only end the suite if we actually ran it */
if (suite && suite->tail &&!suite->tail->not_run) {
end_suite(suite);
}
subsuite = (sub_suite*) malloc(sizeof(*subsuite));
subsuite->num_test = 0;
subsuite->failed = 0;
subsuite->next = NULL;
/* suite_name_full may be an absolute path depending on __FILE__
* expansion */
suite_name = strrchr(suite_name_full, '/');
if (suite_name) {
suite_name++;
} else {
suite_name = suite_name_full;
}
p = strrchr(suite_name, '.');
if (p) {
subsuite->name = (const char*) memcpy(calloc(p - suite_name + 1, 1),
suite_name, p - suite_name);
}
else {
subsuite->name = suite_name;
}
if (list_tests) {
fprintf(stdout, "%s\n", subsuite->name);
}
subsuite->not_run = 0;
if (suite == NULL) {
suite = (abts_suite*) malloc(sizeof(*suite));
suite->head = subsuite;
suite->tail = subsuite;
}
else {
suite->tail->next = subsuite;
suite->tail = subsuite;
}
if (!should_test_run(subsuite->name)) {
subsuite->not_run = 1;
return suite;
}
reset_status();
fprintf(stdout, "%-20s: ", subsuite->name);
update_status();
fflush(stdout);
return suite;
}
void abts_run_test(abts_suite *ts, test_func f, void *value)
{
abts_case tc;
sub_suite *ss;
if (!should_test_run(ts->tail->name)) {
return;
}
ss = ts->tail;
tc.failed = 0;
tc.suite = ss;
ss->num_test++;
update_status();
f(&tc, value);
if (tc.failed) {
ss->failed++;
}
}
static int report(abts_suite *suite)
{
int count = 0;
sub_suite *dptr;
if (suite && suite->tail &&!suite->tail->not_run) {
end_suite(suite);
}
for (dptr = suite->head; dptr; dptr = dptr->next) {
count += dptr->failed;
}
if (list_tests) {
return 0;
}
if (count == 0) {
printf("All tests passed.\n");
return 0;
}
dptr = suite->head;
fprintf(stdout, "%-15s\t\tTotal\tFail\tFailed %%\n", "Failed Tests");
fprintf(stdout, "===================================================\n");
while (dptr != NULL) {
if (dptr->failed != 0) {
float percent = ((float)dptr->failed / (float)dptr->num_test);
fprintf(stdout, "%-15s\t\t%5d\t%4d\t%6.2f%%\n", dptr->name,
dptr->num_test, dptr->failed, percent * 100);
}
dptr = dptr->next;
}
return 1;
}
void abts_log_message(const char *fmt, ...)
{
va_list args;
update_status();
if (verbose) {
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
fprintf(stderr, "\n");
fflush(stderr);
}
}
void abts_int_equal(abts_case *tc, const int expected, const int actual, int lineno)
{
update_status();
if (tc->failed) return;
if (expected == actual) return;
tc->failed = TRUE;
if (verbose) {
fprintf(stderr, "Line %d: expected <%d>, but saw <%d>\n", lineno, expected, actual);
fflush(stderr);
}
}
void abts_int_nequal(abts_case *tc, const int expected, const int actual, int lineno)
{
update_status();
if (tc->failed) return;
if (expected != actual) return;
tc->failed = TRUE;
if (verbose) {
fprintf(stderr, "Line %d: expected <%d>, but saw <%d>\n", lineno, expected, actual);
fflush(stderr);
}
}
void abts_size_equal(abts_case *tc, size_t expected, size_t actual, int lineno)
{
update_status();
if (tc->failed) return;
if (expected == actual) return;
tc->failed = TRUE;
if (verbose) {
/* Note that the comparison is type-exact, reporting must be a best-fit */
fprintf(stderr, "Line %d: expected %lu, but saw %lu\n", lineno,
(unsigned long)expected, (unsigned long)actual);
fflush(stderr);
}
}
void abts_str_equal(abts_case *tc, const char *expected, const char *actual, int lineno)
{
update_status();
if (tc->failed) return;
if (!expected && !actual) return;
if (expected && actual)
if (!strcmp(expected, actual)) return;
tc->failed = TRUE;
if (verbose) {
fprintf(stderr, "Line %d: expected <%s>, but saw <%s>\n", lineno, expected, actual);
fflush(stderr);
}
}
void abts_str_nequal(abts_case *tc, const char *expected, const char *actual,
size_t n, int lineno)
{
update_status();
if (tc->failed) return;
if (!strncmp(expected, actual, n)) return;
tc->failed = TRUE;
if (verbose) {
fprintf(stderr, "Line %d: expected <%s>, but saw <%s>\n", lineno, expected, actual);
fflush(stderr);
}
}
void abts_ptr_notnull(abts_case *tc, const void *ptr, int lineno)
{
update_status();
if (tc->failed) return;
if (ptr != NULL) return;
tc->failed = TRUE;
if (verbose) {
fprintf(stderr, "Line %d: Expected NULL, but saw <%p>\n", lineno, ptr);
fflush(stderr);
}
}
void abts_ptr_equal(abts_case *tc, const void *expected, const void *actual, int lineno)
{
update_status();
if (tc->failed) return;
if (expected == actual) return;
tc->failed = TRUE;
if (verbose) {
fprintf(stderr, "Line %d: expected <%p>, but saw <%p>\n", lineno, expected, actual);
fflush(stderr);
}
}
void abts_fail(abts_case *tc, const char *message, int lineno)
{
update_status();
if (tc->failed) return;
tc->failed = TRUE;
if (verbose) {
fprintf(stderr, "Line %d: %s\n", lineno, message);
fflush(stderr);
}
}
void abts_assert(abts_case *tc, const char *message, int condition, int lineno)
{
update_status();
if (tc->failed) return;
if (condition) return;
tc->failed = TRUE;
if (verbose) {
fprintf(stderr, "Line %d: %s\n", lineno, message);
fflush(stderr);
}
}
void abts_true(abts_case *tc, int condition, int lineno)
{
update_status();
if (tc->failed) return;
if (condition) return;
tc->failed = TRUE;
if (verbose) {
fprintf(stderr, "Line %d: Condition is false, but expected true\n", lineno);
fflush(stderr);
}
}
void abts_not_impl(abts_case *tc, const char *message, int lineno)
{
update_status();
tc->suite->not_impl++;
if (verbose) {
fprintf(stderr, "Line %d: %s\n", lineno, message);
fflush(stderr);
}
}
int main(int argc, const char *const argv[]) {
int i;
int rv;
int list_provided = 0;
abts_suite *suite = NULL;
initialize();
#if defined(_MSC_VER)
quiet = 1;
#else
quiet = !isatty(STDOUT_FILENO);
#endif
for (i = 1; i < argc; i++) {
if (!strcmp(argv[i], "-v")) {
verbose = 1;
continue;
}
if (!strcmp(argv[i], "-x")) {
exclude = 1;
continue;
}
if (!strcmp(argv[i], "-l")) {
list_tests = 1;
continue;
}
if (!strcmp(argv[i], "-q")) {
quiet = 1;
continue;
}
if (argv[i][0] == '-') {
fprintf(stderr, "Invalid option: `%s'\n", argv[i]);
exit(1);
}
list_provided = 1;
}
if (list_provided) {
/* Waste a little space here, because it is easier than counting the
* number of tests listed. Besides it is at most three char *.
*/
testlist = (const char**) calloc(argc + 1, sizeof(char *));
for (i = 1; i < argc; i++) {
testlist[i - 1] = argv[i];
}
}
suite = abts_run_suites(suite);
if (suite == 0) {
fputs("No tests selected\n", stderr);
} else {
rv = report(suite);
//
// clean up suite
//
sub_suite* next;
for(sub_suite* head = suite->head; head != NULL; head = next) {
next = head->next;
free((void*) head->name);
free(head);
}
free(suite);
}
return rv;
}
| 001-log4cxx | trunk/src/test/cpp/abts.cpp | C++ | asf20 | 10,678 |
/*
* 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/pool.h>
#include <log4cxx/fileappender.h>
#include <log4cxx/patternlayout.h>
#include "logunit.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
/**
*
* FileAppender tests.
*/
LOGUNIT_CLASS(FileAppenderTest) {
LOGUNIT_TEST_SUITE(FileAppenderTest);
LOGUNIT_TEST(testDirectoryCreation);
LOGUNIT_TEST(testgetSetThreshold);
LOGUNIT_TEST(testIsAsSevereAsThreshold);
LOGUNIT_TEST_SUITE_END();
public:
/**
* Tests that any necessary directories are attempted to
* be created if they don't exist. See bug 9150.
*
*/
void testDirectoryCreation() {
File newFile(LOG4CXX_STR("output/newdir/temp.log"));
Pool p;
newFile.deleteFile(p);
File newDir(LOG4CXX_STR("output/newdir"));
newDir.deleteFile(p);
FileAppenderPtr wa(new FileAppender());
wa->setFile(LOG4CXX_STR("output/newdir/temp.log"));
wa->setLayout(new PatternLayout(LOG4CXX_STR("%m%n")));
wa->activateOptions(p);
LOGUNIT_ASSERT(File(LOG4CXX_STR("output/newdir/temp.log")).exists(p));
}
/**
* Tests getThreshold and setThreshold.
*/
void testgetSetThreshold() {
FileAppenderPtr appender = new FileAppender();
LevelPtr debug = Level::getDebug();
//
// different from log4j where threshold is null.
//
LOGUNIT_ASSERT_EQUAL(Level::getAll(), appender->getThreshold());
appender->setThreshold(debug);
LOGUNIT_ASSERT_EQUAL(debug, appender->getThreshold());
}
/**
* Tests isAsSevereAsThreshold.
*/
void testIsAsSevereAsThreshold() {
FileAppenderPtr appender = new FileAppender();
LevelPtr debug = Level::getDebug();
LOGUNIT_ASSERT(appender->isAsSevereAsThreshold(debug));
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(FileAppenderTest);
| 001-log4cxx | trunk/src/test/cpp/fileappendertest.cpp | C++ | asf20 | 2,602 |
/*
* 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(_WIN32) && !defined(_WIN32_WCE)
#include <log4cxx/nt/nteventlogappender.h>
#include "../appenderskeletontestcase.h"
#include "windows.h"
#include <log4cxx/logger.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/patternlayout.h>
#include "../insertwide.h"
#include "../logunit.h"
#include <log4cxx/helpers/date.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::nt;
using namespace log4cxx::spi;
/**
Unit tests of log4cxx::nt::NTEventLogAppender
*/
class NTEventLogAppenderTestCase : public AppenderSkeletonTestCase
{
LOGUNIT_TEST_SUITE(NTEventLogAppenderTestCase);
//
// tests inherited from AppenderSkeletonTestCase
//
LOGUNIT_TEST(testDefaultThreshold);
LOGUNIT_TEST(testSetOptionThreshold);
LOGUNIT_TEST(testHelloWorld);
LOGUNIT_TEST_SUITE_END();
public:
AppenderSkeleton* createAppenderSkeleton() const {
return new log4cxx::nt::NTEventLogAppender();
}
void testHelloWorld() {
DWORD expectedId = 1;
HANDLE hEventLog = ::OpenEventLogW(NULL, L"log4cxx_test");
if (hEventLog != NULL) {
BOOL stat = GetNumberOfEventLogRecords(hEventLog, &expectedId);
DWORD oldest;
if(stat) stat = GetOldestEventLogRecord(hEventLog, &oldest);
CloseEventLog(hEventLog);
LOGUNIT_ASSERT(stat);
expectedId += oldest;
}
Pool p;
Date now;
DWORD expectedTime = now.getTime() / Date::getMicrosecondsPerSecond();
{
NTEventLogAppenderPtr appender(new NTEventLogAppender());
appender->setSource(LOG4CXX_STR("log4cxx_test"));
LayoutPtr layout(new PatternLayout(LOG4CXX_STR("%c - %m%n")));
appender->setLayout(layout);
appender->activateOptions(p);
LoggingEventPtr event(new LoggingEvent(
LOG4CXX_STR("org.foobar"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION));
appender->doAppend(event, p);
}
hEventLog = ::OpenEventLogW(NULL, L"log4cxx_test");
LOGUNIT_ASSERT(hEventLog != NULL);
DWORD actualId;
BOOL stat = GetNumberOfEventLogRecords(hEventLog, &actualId);
DWORD oldest;
if (stat) stat = GetOldestEventLogRecord(hEventLog, &oldest);
actualId += oldest;
actualId--;
CloseEventLog(hEventLog);
LOGUNIT_ASSERT(stat);
LOGUNIT_ASSERT_EQUAL(expectedId, actualId);
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(NTEventLogAppenderTestCase);
#endif
| 001-log4cxx | trunk/src/test/cpp/nt/nteventlogappendertestcase.cpp | C++ | asf20 | 3,606 |
/*
* 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/propertyconfigurator.h>
#include <log4cxx/mdc.h>
#include <log4cxx/patternlayout.h>
#include <log4cxx/fileappender.h>
#include "util/compare.h"
#include "util/transformer.h"
#include "util/absolutedateandtimefilter.h"
#include "util/iso8601filter.h"
#include "util/absolutetimefilter.h"
#include "util/relativetimefilter.h"
#include "util/controlfilter.h"
#include "util/threadfilter.h"
#include "util/linenumberfilter.h"
#include "util/filenamefilter.h"
#include <iostream>
#include <log4cxx/helpers/transcoder.h>
#include <log4cxx/helpers/pool.h>
#include <apr_strings.h>
#include <log4cxx/helpers/pool.h>
#include "testchar.h"
#include "logunit.h"
#include <log4cxx/spi/loggerrepository.h>
#include <log4cxx/helpers/stringhelper.h>
#define REGEX_STR(x) x
#define PAT0 REGEX_STR("\\[[0-9A-FXx]*]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* - Message [0-9]\\{1,2\\}")
#define PAT1 ISO8601_PAT REGEX_STR(" ") PAT0
#define PAT2 ABSOLUTE_DATE_AND_TIME_PAT REGEX_STR(" ") PAT0
#define PAT3 ABSOLUTE_TIME_PAT REGEX_STR(" ") PAT0
#define PAT4 RELATIVE_TIME_PAT REGEX_STR(" ") PAT0
#define PAT5 REGEX_STR("\\[[0-9A-FXx]*]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* : Message [0-9]\\{1,2\\}")
#define PAT6 REGEX_STR("\\[[0-9A-FXx]*]\\ (DEBUG|INFO |WARN |ERROR|FATAL) .*patternlayouttest.cpp\\([0-9]\\{1,4\\}\\): Message [0-9]\\{1,3\\}")
#define PAT11a REGEX_STR("^(DEBUG|INFO |WARN |ERROR|FATAL) \\[[0-9A-FXx]*]\\ log4j.PatternLayoutTest: Message [0-9]\\{1,2\\}")
#define PAT11b REGEX_STR("^(DEBUG|INFO |WARN |ERROR|FATAL) \\[[0-9A-FXx]*]\\ root: Message [0-9]\\{1,2\\}")
#define PAT12 REGEX_STR("^\\[[0-9A-FXx]*]\\ (DEBUG|INFO |WARN |ERROR|FATAL) ")\
REGEX_STR(".*patternlayouttest.cpp([0-9]\\{1,4\\}): ")\
REGEX_STR("Message [0-9]\\{1,2\\}")
#define PAT_MDC_1 REGEX_STR("")
using namespace log4cxx;
using namespace log4cxx::helpers;
LOGUNIT_CLASS(PatternLayoutTest)
{
LOGUNIT_TEST_SUITE(PatternLayoutTest);
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(test9);
LOGUNIT_TEST(test10);
LOGUNIT_TEST(test11);
LOGUNIT_TEST(test12);
LOGUNIT_TEST(testMDC1);
LOGUNIT_TEST(testMDC2);
LOGUNIT_TEST_SUITE_END();
LoggerPtr root;
LoggerPtr logger;
public:
void setUp()
{
root = Logger::getRootLogger();
MDC::clear();
logger = Logger::getLogger(LOG4CXX_TEST_STR("java.org.apache.log4j.PatternLayoutTest"));
}
void tearDown()
{
MDC::clear();
root->getLoggerRepository()->resetConfiguration();
}
void test1()
{
PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout1.properties"));
common();
LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/patternLayout.1")));
}
void test2()
{
PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout2.properties"));
common();
ControlFilter filter1;
filter1 << PAT1;
ISO8601Filter filter2;
ThreadFilter filter3;
std::vector<Filter *> filters;
filters.push_back(&filter1);
filters.push_back(&filter2);
filters.push_back(&filter3);
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/patternLayout.2")));
}
void test3()
{
PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout3.properties"));
common();
ControlFilter filter1;
filter1 << PAT1;
ISO8601Filter filter2;
ThreadFilter filter3;
std::vector<Filter *> filters;
filters.push_back(&filter1);
filters.push_back(&filter2);
filters.push_back(&filter3);
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/patternLayout.3")));
}
// Output format:
// 06 avr. 2002 18:30:58,937 [12345] DEBUG atternLayoutTest - Message 0
void test4()
{
PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout4.properties"));
common();
ControlFilter filter1;
filter1 << PAT2;
AbsoluteDateAndTimeFilter filter2;
ThreadFilter filter3;
std::vector<Filter *> filters;
filters.push_back(&filter1);
filters.push_back(&filter2);
filters.push_back(&filter3);
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/patternLayout.4")));
}
void test5()
{
PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout5.properties"));
common();
ControlFilter filter1;
filter1 << PAT2;
AbsoluteDateAndTimeFilter filter2;
ThreadFilter filter3;
std::vector<Filter *> filters;
filters.push_back(&filter1);
filters.push_back(&filter2);
filters.push_back(&filter3);
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/patternLayout.5")));
}
void test6()
{
PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout6.properties"));
common();
ControlFilter filter1;
filter1 << PAT3;
AbsoluteTimeFilter filter2;
ThreadFilter filter3;
std::vector<Filter *> filters;
filters.push_back(&filter1);
filters.push_back(&filter2);
filters.push_back(&filter3);
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/patternLayout.6")));
}
void test7()
{
PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout7.properties"));
common();
ControlFilter filter1;
filter1 << PAT3;
AbsoluteTimeFilter filter2;
ThreadFilter filter3;
std::vector<Filter *> filters;
filters.push_back(&filter1);
filters.push_back(&filter2);
filters.push_back(&filter3);
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/patternLayout.7")));
}
void test8()
{
PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout8.properties"));
common();
ControlFilter filter1;
filter1 << PAT4;
//
// combo of relative time and thread identifier
// (the \\\\1 preserve a leading space)
Filter filter2(".*]", "[main]");
std::vector<Filter *> filters;
filters.push_back(&filter1);
filters.push_back(&filter2);
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/patternLayout.8")));
}
void test9()
{
PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout9.properties"));
common();
ControlFilter filter1;
filter1 << PAT5;
ThreadFilter filter2;
std::vector<Filter *> filters;
filters.push_back(&filter1);
filters.push_back(&filter2);
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/patternLayout.9")));
}
void test10()
{
PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout10.properties"));
common();
ControlFilter filter1;
filter1 << PAT6;
ThreadFilter filter2;
LineNumberFilter filter3;
FilenameFilter filenameFilter(__FILE__, "patternlayouttest.cpp");
std::vector<Filter *> filters;
filters.push_back(&filenameFilter);
filters.push_back(&filter1);
filters.push_back(&filter2);
filters.push_back(&filter3);
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/patternLayout.10")));
}
void test11()
{
PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout11.properties"));
common();
ControlFilter filter1;
filter1 << PAT11a << PAT11b;
ThreadFilter filter2;
std::vector<Filter *> filters;
filters.push_back(&filter1);
filters.push_back(&filter2);
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/patternLayout.11")));
}
void test12()
{
PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout12.properties"));
common();
ControlFilter filter1;
filter1 << PAT12;
ThreadFilter filter2;
LineNumberFilter filter3;
FilenameFilter filenameFilter(__FILE__, "patternlayouttest.cpp");
std::vector<Filter *> filters;
filters.push_back(&filenameFilter);
filters.push_back(&filter1);
filters.push_back(&filter2);
filters.push_back(&filter3);
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/patternLayout.12")));
}
void testMDC1()
{
PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout.mdc.1.properties"));
MDC::put(LOG4CXX_TEST_STR("key1"), LOG4CXX_TEST_STR("va11"));
MDC::put(LOG4CXX_TEST_STR("key2"), LOG4CXX_TEST_STR("va12"));
logger->debug(LOG4CXX_TEST_STR("Hello World"));
MDC::clear();
LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/patternLayout.mdc.1")));
}
void testMDC2()
{
LogString OUTPUT_FILE = LOG4CXX_STR("output/patternLayout.mdc.2");
File WITNESS_FILE = LOG4CXX_FILE("witness/patternLayout.mdc.2");
LogString mdcMsgPattern1 = LOG4CXX_STR("%m : %X%n");
LogString mdcMsgPattern2 = LOG4CXX_STR("%m : %X{key1}%n");
LogString mdcMsgPattern3 = LOG4CXX_STR("%m : %X{key2}%n");
LogString mdcMsgPattern4 = LOG4CXX_STR("%m : %X{key3}%n");
LogString mdcMsgPattern5 = LOG4CXX_STR("%m : %X{key1},%X{key2},%X{key3}%n");
// set up appender
PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%m%n"));
AppenderPtr appender = new FileAppender(layout, OUTPUT_FILE, false);
// set appender on root and set level to debug
root->addAppender(appender);
root->setLevel(Level::getDebug());
// output starting message
root->debug(LOG4CXX_TEST_STR("starting mdc pattern test"));
layout->setConversionPattern(mdcMsgPattern1);
log4cxx::helpers::Pool pool;
layout->activateOptions(pool);
root->debug(LOG4CXX_TEST_STR("empty mdc, no key specified in pattern"));
layout->setConversionPattern(mdcMsgPattern2);
layout->activateOptions(pool);
root->debug(LOG4CXX_TEST_STR("empty mdc, key1 in pattern"));
layout->setConversionPattern(mdcMsgPattern3);
layout->activateOptions(pool);
root->debug(LOG4CXX_TEST_STR("empty mdc, key2 in pattern"));
layout->setConversionPattern(mdcMsgPattern4);
layout->activateOptions(pool);
root->debug(LOG4CXX_TEST_STR("empty mdc, key3 in pattern"));
layout->setConversionPattern(mdcMsgPattern5);
layout->activateOptions(pool);
root->debug(LOG4CXX_TEST_STR("empty mdc, key1, key2, and key3 in pattern"));
MDC::put(LOG4CXX_TEST_STR("key1"), LOG4CXX_TEST_STR("value1"));
MDC::put(LOG4CXX_TEST_STR("key2"), LOG4CXX_TEST_STR("value2"));
layout->setConversionPattern(mdcMsgPattern1);
layout->activateOptions(pool);
root->debug(LOG4CXX_TEST_STR("filled mdc, no key specified in pattern"));
layout->setConversionPattern(mdcMsgPattern2);
layout->activateOptions(pool);
root->debug(LOG4CXX_TEST_STR("filled mdc, key1 in pattern"));
layout->setConversionPattern(mdcMsgPattern3);
layout->activateOptions(pool);
root->debug(LOG4CXX_TEST_STR("filled mdc, key2 in pattern"));
layout->setConversionPattern(mdcMsgPattern4);
layout->activateOptions(pool);
root->debug(LOG4CXX_TEST_STR("filled mdc, key3 in pattern"));
layout->setConversionPattern(mdcMsgPattern5);
layout->activateOptions(pool);
root->debug(LOG4CXX_TEST_STR("filled mdc, key1, key2, and key3 in pattern"));
MDC::remove(LOG4CXX_TEST_STR("key1"));
MDC::remove(LOG4CXX_TEST_STR("key2"));
layout->setConversionPattern(LOG4CXX_STR("%m%n"));
layout->activateOptions(pool);
root->debug(LOG4CXX_TEST_STR("finished mdc pattern test"));
LOGUNIT_ASSERT(Compare::compare(OUTPUT_FILE, WITNESS_FILE));
}
std::string createMessage(Pool& pool, int i) {
std::string msg("Message ");
msg.append(pool.itoa(i));
return msg;
}
void common()
{
int i = -1;
Pool pool;
LOG4CXX_DEBUG(logger, createMessage(pool, ++i));
LOG4CXX_DEBUG(root, createMessage(pool, i));
LOG4CXX_INFO(logger, createMessage(pool, ++i));
LOG4CXX_INFO(root, createMessage(pool, i));
LOG4CXX_WARN(logger, createMessage(pool, ++i));
LOG4CXX_WARN(root, createMessage(pool, i));
LOG4CXX_ERROR(logger, createMessage(pool, ++i));
LOG4CXX_ERROR(root, createMessage(pool, i));
LOG4CXX_FATAL(logger, createMessage(pool, ++i));
LOG4CXX_FATAL(root, createMessage(pool, i));
}
private:
static const LogString FILTERED;
static const LogString TEMP;
};
const LogString PatternLayoutTest::TEMP(LOG4CXX_STR("output/temp"));
const LogString PatternLayoutTest::FILTERED(LOG4CXX_STR("output/filtered"));
LOGUNIT_TEST_SUITE_REGISTRATION(PatternLayoutTest);
| 001-log4cxx | trunk/src/test/cpp/patternlayouttest.cpp | C++ | asf20 | 20,005 |