提交 449b151d authored 作者: Iñaki Baz Castillo's avatar Iñaki Baz Castillo

Improve internal doc.

上级 707a82a4
...@@ -13,7 +13,7 @@ Builds the production ready mediasoup worker binary at `worker/out/Release/`. Th ...@@ -13,7 +13,7 @@ Builds the production ready mediasoup worker binary at `worker/out/Release/`. Th
### `make Debug` ### `make Debug`
Builds a more verbose mediasoup and less optimized worker binary at `worker/out/Debug/` with some C flags enabled (such as `-g` and `-O0`) and some macros defined (such as `DEBUG`, `MS_LOG_FILE_LINE` and `MS_LOG_TRACE`). Builds a more verbose and non optimized mediasoup worker binary at `worker/out/Debug/` with some C flags enabled (such as `-g` and `-O0`) and some macros defined (such as `DEBUG`, `MS_LOG_FILE_LINE` and `MS_LOG_TRACE`).
Check the meaning of these macros in the [Logger.h](worker/include/Logger.h) header file. Check the meaning of these macros in the [Logger.h](worker/include/Logger.h) header file.
......
The following is a list of common ABBREViations in the ZUT project.
TS..........TestSuite
NLIST.......List
=========
CHECKLIST
=========
TODO: Write this up.
# Specifications for all the TEST executables.
#
# ====================================================================
# Copyright (c) 2009 Ian Blumel. All rights reserved.
#
# This software is licensed as described in the file LICENSE, which
# you should have received as part of this distribution.
# ====================================================================
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
PROJECT(FCT)
ENABLE_TESTING()
# ------------------------
# Configure Warning Levels
# ------------------------
IF (MSVC)
# Warning Level 4, Treat all warnings as errors!
IF (MSVC80)
# 64 bit warning flags are only really used in MSVC80.
SET(WARN_LEV 4)
SET(C_WARNINGS "/WX /Wp64")
SET(CXX_WARNINGS "/WX /Wp64")
ELSEIF(MSVC60)
# Treating warnings as errors for this compiler makes things unworkable
# as you get warnings about functions being inlined (who cares),
# warnings about inlined functions in the math library not being used
# (who cares), and so on. For my sanity this old compiler will get the
# warnings turned on, but we can manually choose to ignore them.
#
# Not only am I not turning on warnings, I am dialing them down to a
# "sane" level 3.
SET(WARN_LEV 3)
SET(C_WARNINGS )
SET(CXX_WARNINGS )
ELSE()
SET(WARN_LEV 4)
SET(C_WARNINGS "/WX")
SET(CXX_WARNINGS "/WX")
ENDIF()
STRING(REPLACE "/W3" "/W${WARN_LEV}" CMAKE_C_FLAGS ${CMAKE_C_FLAGS})
STRING(REPLACE "/W3" "/W${WARN_LEV}" CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS})
ELSEIF (CMAKE_COMPILER_IS_GNUCC)
set(GCC_COMMON_WARNING_FLAGS
"-Wall -Wextra -O -Werror -Wformat=2 -Wshadow -Wfloat-equal"
)
SET(C_WARNINGS "${GCC_COMMON_WARNING_FLAGS}")
set(CXX_WARNINGS "${GCC_COMMON_WARNING_FLAGS}")
ENDIF()
SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${C_WARNINGS}")
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CXX_WARNINGS}")
SET(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin)
# --------
# Delegate
# --------
ADD_SUBDIRECTORY(include)
ADD_SUBDIRECTORY(tests)
ADD_SUBDIRECTORY(examples)
# ------
# ASTYLE
# ------
# Target for standardizing the style in FCTX, if astyle.exe is
# available.
find_program(ASTYLE astyle)
if(ASTYLE)
add_custom_target(run_astyle
"${CMAKE_COMMAND}"
-E chdir "${CMAKE_CURRENT_SOURCE_DIR}"
${ASTYLE}
--options=${CMAKE_CURRENT_SOURCE_DIR}/astyle.conf
include/*.h
tests/*.c
examples/custom_logger/*.h
examples/custom_logger/*.c
)
endif()
See https://github.com/imb/fctx/graphs/contributors.
FCTest (Fast C Test) Unit Testing Framework
Copyright (c) 2008, Ian Blumel (ian.blumel@gmail.com)
All rights reserved.
This license is based on the BSD License.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of, Ian Blumel, nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
++++++++++++
FCTX Changes
++++++++++++
Whats new in FCTX 1.6.1
-----------------------
- FIX: Removes unreferenced variable, and fixes a /W4 warning with
MSVC.
- FIX: FCT_INIT removes hard coded argc/argv dependency. Previously
you had to use those variables or it wouldn't compile.
- FIX: Cast FCT_NUM_FAILED to int to avoid 64 bit warning about
down casting. This cast is safe.
Whats new in FCTX 1.6.0
-----------------------
- ENH: New fct_chk_ex will check that a C++ exception is generated within
a code block. Only in C++.
- ENH: Add new FCT_BGN_FN/FCT_END_FN to bootstrap the test framework
without using "main".
- ENH: Add new FCT_INIT, FCT_FINAL, and FCT_NUM_FAILED to allow you
to initialize and finalize FCTX within your own custom function.
Whats new in FCTX 1.5.0
-----------------------
This release focused on a rework of the fct_req check to allow it to
abort a test suite if a setup or teardown check fails. This involved
some disruptive work to the test suite structure, and warrants a
release on its own. The change should be backwards compatible.
- ENH: fct_req will now abort a test suite if it fails in a setup and
teardown block.
Whats new in FCTX 1.4.2
-----------------------
Many thanks to suggestions from Rhys Ulerich (http://github.com/RhysU)
for his patches to make FCTX better.
- ENH: Ability to use fct_chk in an if conditional. You can then
conditionally execute further checks based on the first check.
- ENH: Allow user to mutate main's argv (useful for initializing
libraries. Thanks to RhysU.
- FIX: Fix to handle simple unit test case (catches segmentation
fault).
- FIX: Warning corrections for GCC 4.3.4, Intel 11.1. Thanks to
RhysU.
- FIX: DOC - Updated Getting Started sample to use FCT_QTEST_END.
Thanks to RhysU for the fix.
Whats new in FCTX 1.4.1
-----------------------
- FIX: Compiler regression with MSV compilers. FCTX should be back to
compiling for the MSVC.
Whats new in FCTX 1.4.0
-----------------------
- ENH: Custom logger. You can now write and install a customized
logger. See the examples/custom_logger directory within the source
for details.
- ENH: Test and Test Suites grow their own duration value. Getting the
time for a particular test or test suite is a common logging
operation. In order to simplify logging the test and test suite
objects will now take care to report their durations.
- FIX: Fix warnings generated for a "blank test" (i.e. "FCT_BGN() {}
FCT_END()").
Whats new in FCTX 1.3.2
-----------------------
- FIX: Use size_t instead of int to remove some nuisance warnings on a
64 bit compiler.
Whats new in FCTX 1.3.1
-----------------------
- FIX: JUnit logger now displays the correct XML header.
Whats new in FCTX 1.3.0
-----------------------
- ENH: Add JUnit support thanks to timrule (http://github.com/timrule).
(http://github.com/imb/fctx/issues/closed#issue/10)
- ENH (#3): Add helpful string checks. These functions will produce
error messages that are relevant.
(http://github.com/imb/fctx/issues/closed#issue/3)
- New fct_chk_incl_str, will check that a string includes a
substring and report an useful error message if it does not
include the substring.
- New fct_chk_incl_istr, case insensitive variant of
fct_chk_incl_str.
- New fct_chk_excl_str, will check that a string does not include a
substring and report an useful error message if it is found.
- New fct_chk_excl_istr, case insensitive variant of
fct_chk_excl_str.
- New fct_chk_startswith_str, will check if a string starts with a
given substring, and report an helpful error otherwise. Also
introduces a fctstr_startswith backend function.
- New fct_chk_empty_str, will check if a string is empty.
- New fct_chk_full_str, will check if string is full.
- ENH: Reduced malloc's for exceptional cases. Since failed tests are,
as a rule exceptional, there was no need to allocate memory for a
list to hold error results until such time as an error occurs. This
lead to a relatively minor speed up.
Whats new in FCTX 1.2.1
-----------------------
This release is the first release using Git hosted at GitHub
(http://github.com/imb/fctx). As such a lot of the changes in this release
had to do with converting from BAZZAR to GIT. Namely normalizing the
line endings so the are standard across the Git repository.
- FIX (#11): Fixed fctcl_val2 so it will return a default value if the
option was not specified on the command line.
Whats new in FCTX 1.2
---------------------
Highlights for this release include access to a command line parser for each
EXE built with FCTX. You are now able to customize your command line to add
flags that you may require for unit testing. To help you utilize any custom
flags, conditional tests and tests suites where also added. These changes were
designed to help you run a "quick set" of tests while in development mode, but
allowing you run a full suite of tests during your continuous builds.
- ENH: (sys-command-line-parser) ability to parse and read command line
options.
- ENH: (sys-conditional-test-runs): ability to run test suites based on a
conditional. See FCT_FIXTURE_SUITE_BGN_IF and FCT_SUITE_BGN_IF macros.
- ENH: (sys-conditional-test-runs): ability to run tests based on a
conditional. See new FCT_TEST_IF and FCT_QTEST_IF macros.
- ENH: (sys-clean-up-variables): moved extra variables into a single
structure used throughout the FCTX test run, this helps to reduce the noise
in a debugger watch windows.
- FIX: (486457) #pragma down to warning level 3 for MSC during FCTMF calls.
- FIX: (501472) CMAKE now configures MSC to compile with /W4.
- FIX: (501474) GCC now compiles with higher warning levels
- FIX: (501476) Removed redundant count found in FCT_END.
- FIX: (512202) Fixed test_chk failures in CTEST due to trying to configure
CMAKE to handle multiple platforms and compilers. Adds a new
FCT_EXPECTED_FAILURES macro that has the program return 0 if the expected
number of failures matches the actual.
More details at: https://launchpad.net/fctest/+milestone/1.2
See also: http://fctx.wildbearsoftware.com
Whats new in FCTX 1.1.4
-----------------------
- FIX (499089): Handle last character truncation in prefix filter. Turns out
that a string buffer was missing a +1 for the null terminator. Also added
new test_fctkern as a place to start testing the fctkern object. Thanks to
Roel Schroeven for finding this bug.
Whats new in FCTX 1.1.3
-----------------------
- FIX (482943): handle 64 bit variables. Thanks to Raedwulf for pointing out
that the current fct_(x)chk functions may truncate a 64 bit pointer and
erroneously report false for a true result.
Whats new in FCTX 1.1.2
-----------------------
- FIX: memory leak in fct_standard_logger_t.
Whats new in FCTX 1.1.1
-----------------------
- PROJECT: Rename from "FCTest" to "FCTX". The term "FCTest" clashes too much
on the net, and things with "x" in it are cool. ;-P
- ENH: FCTMF - Removed need to call FCTMF_SUITE_DEF. The macro will remain for
backwards compatibility.
Whats new in FCT 1.1
--------------------
- Addition of fct_xchk: Allows you to customize your checking and error
reporting. Implementation of fct_chk_eq_str/int/dbl based on the fct_xchk
interface.
- CMAKE used for building the FCT tests.
- Updated all compiles to use the highest warning level and fixed compiler
warnings.
- Removed all "assert out of memory" checks and properly checked the memory
through the entire lifetime of the execution branch.
- Added fct_req: Function will abort a test block when the requirement is not
met.
- Modified fct_chk: Will continue after a failed test.
- Modified standard logger output to provide a straight continuous line of
PASS/FAIL statements. Easier to scan failures.
- BLUEPRINT: sys-multi-file. Better, more robust multi-file support. Although
it starts to take a toll on the time to code for FCTest, it does help
provide it a little more extendability to FCTest.
- Modified failure output to hopefully be less likely to wrap around by using
a new line to actually show what failed.
- Start to develop API documentation.
- #376783: Added test to make sure we continue to compile against a C++
project.
- #398286: Fixed to use _vsnprintf for Microsoft compilers.
Whats new in FCT 1.0.4
----------------------
- Bring down select changes from 1.1 Release Branch:
- Modified standard logger output to provide a straight continuous line of
PASS/FAIL statements. Easier to scan failures.
- Modified failure output to hopefully be less likely to wrap around by
using a new line to actually show what failed.
- #376783: Added test to make sure we continue to compile against a C++
project.
- #398286: Fixed to use _vsnprintf for Microsoft compilers.
Whats new in FCT 1.0.3
----------------------
- #385063: Call free on fct_test_t.
Whats new in FCT 1.0.2
----------------------
- #382628: Fix tests so tear-down gets executed. Added test case.
Whats new in FCT 1.0.1
----------------------
- #376783: Applied proper casting so the header works within a C++ project.
===============================
FCTX (FAST C XUNIT TEST) README
===============================
--------
Overview
--------
Fast C Test (FCTX) is an all in one header file that lets you create
tests fast in C/C++. With FCTX you can write and run a test as fast as
you can think about it. There is no need to write a test and register a
test. Once the test is written it will be executed at runtime. There is
no need for post-processing to generate a compilable file, you can run
and view the results. The FCTX only requires a ANSI C/C++ compiler to
run, there are no third party requirements.
Simply include, write your test, and compile.
The FCTX principle design goal is to make it possible to quickly
generate unit tests for C and C++ with little or no hassle.
It is just a header, you only need #include.
----------
What's New
----------
See the NEWS file for release notes.
---------
Licensing
---------
The official statement:
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
What that LICENSE file is essentially stating in plain English:
Please be a good, smart person, and use due diligence. I can make no
claims that what you are using will not light your computer on fire.
I can make no claims that everything written in FCTX will be 100%
correct.
All I ask is that if FCT is extended or redistributed, that the
original contributors be notified, and that a proper reference is
appreciated.
Thanks.
-----------------
Quick Start Guide
-----------------
To get you started quickly you only need to have the "fct.h" header file
somewhere handy on your system. In the distribution package, it can be
found in the "include" directory.
What follows an overly simple example of testing::
/* First include the fct framework. */
#include "fct.h"
/* Include your API. In this case we are going to test strcmp. */
#include <string.h>
/* Now lets define our testing scope. */
FCT_BGN()
{
/* A simple test case. No setup/teardown. */
FCT_SUITE_BGN(simple)
{
/* An actual test case in the test suite. */
FCT_TEST_BGN(strcmp_eq)
{
fct_chk(strcmp("durka", "durka") == 0);
}
FCT_TEST_END();
FCT_TEST_BGN(chk_neq)
{
fct_chk(strcmp("daka", "durka") !=0 );
}
FCT_TEST_END();
/* Every test suite must be closed. */
}
FCT_SUITE_END();
/* Every FCT scope has an end. */
}
FCT_END();
Now you can compile the above file and generate a new EXE. If your new
EXE was called "test.exe", you can run it with a "filtering prefix" to
limit the tests executed, for example::
test strcmp_eq
would only execute the "strcmp_eq" test.
To define a SETUP/TEARDOWN structure you would do something similar to
the above tests::
FCT_BGN()
{
/* Optionally, define a scope for you data. */
{
void *data =NULL;
FCT_FIXTURE_SUITE_BGN(Fixtures)
{
FCT_SETUP_BGN()
{
/* Initialize your data before a test is executed. */
data = malloc(sizeof(10));
}
FCT_SETUP_END();
FCT_TEARDOWN_BGN()
{
/* Clean up your data after a test is executed. */
free(data);
data = NULL;
}
FCT_TEARDOWN_END();
FCT_TEST_BGN(silly_test_for_null)
{
fct_chk( data != NULL );
}
FCT_TEST_END();
FCT_TEST_BGN(silly_test_for_null__again)
{
fct_chk( data != NULL );
}
FCT_TEST_END();
}
FCT_FIXTURE_SUITE_END();
}
}
FCT_END();
Afterwards, you can compile and run this test, and the "data" will be
setup and teared down after each test cycle.
----------------
Development Goal
----------------
To state it out loud: FCT is dedicated to reducing the overhead
associated with generating tests in C and C++.
--------
Building
--------
Build your Own Test Suite
-------------------------
To build your own test suite: Its just a header, include into your test
file, and run the compiler.
Build the FCT Tests
-------------------
To build the tests themselves: use CMAKE (http://www.cmake.org/). On Linux
or similar system do something like this (from the root source directory)::
mkdir build
cd build
cmake ../
At this point you should have a Makefile in your "build" directory.
Type "make help" for a list of targets.
On a Win32 Machine it depends what you want to ultimately work with.
The following example illustrates creating a Visual Studio 9 solution::
mkdir msw
cd msw
cmake -G"Visual Studio 9 2008" ..\
At this point you should have a FCT.sln file within your MSW directory.
If you wanted to generate a different project, type::
cmake --help
To get list of generators. For example, if you wanted to use MinGW,
you could do something like::
mkdir mingw
cmake -G"MinGW Makefiles" ..\
and now you will have a Makefile configured to compile with MinGW.
====
TODO
====
MileStone 1.3 (Command Line Args)
=================================
- (P2) Start a "boilerplate" file.
- (P1) Run only a specific test suite by name,
fct.exe --run-suite some_suite
- Write up some rules for creating your own custom logger.
Milestone 1.4 (Major Enhancements)
==================================
- (P2) Handle different languages for the built-in loggers.
- Unicode Support
- Figure out a way to have a test case without a FCT_BGN/END?
#include "fct.h"
FCT_VERY_QUICK(test1)
{
FCT_CHECK( ok ); // This should fail, with a hint!
}
FCT_VERY_QUICK_END()
FCT_VERY_QUICK(test2)
{
FCT_CHECK( ok ); // This should fail, with a hint!
}
FCT_VERY_QUICK_END()
/* Actually may be impossible. */
# Standard code format for the FCT project. You should run against astyle prior
# to a commit:
#
# astyle --options=astyle.conf include/*.h tests/*.c
#
--style=ansi
--recursive
# Specifications for building user and development documentation.
#
# ====================================================================
# Copyright (c) 2009 Ian Blumel. All rights reserved.
#
# This software is licensed as described in the file LICENSE, which
# you should have received as part of this distribution.
# ====================================================================
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
FIND_FILE( SPHINX sphinx-build.exe)
# If we are windows call to the make.bat file, otherwise rely on the Makefile
# to handle the processing.
IF(WIN32)
SET(SPHINX_MAKE make.bat)
ELSE(WIN32)
SET(SPHINX_MAKE make)
ENDIF(WIN32)
ADD_CUSTOM_TARGET(
doc_usr
COMMAND ${SPHINX_MAKE} html
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/usr
)
ADD_CUSTOM_TARGET(
doc_dev
COMMAND ${SPHINX_MAKE} html
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/dev
)
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
VERSION = 0.0.0
RELEASE = $(VERSION)
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -D version=$(VERSION) -D release=$(RELEASE) \
-d build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
.PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " html_web to make standalone HTML files for the fctx web."
@echo " dirhtml to make HTML files named index.html in directories"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf build/*
html:
$(SPHINXBUILD) -b html -D rst_epilog="" $(ALLSPHINXOPTS) build/html
@echo
@echo "Build finished. The HTML pages are in build/html."
html_web:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) build/html_web
@echo
@echo "Build finished. The HTML pages are in build/html_web."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) build/dirhtml
@echo
@echo "Build finished. The HTML pages are in build/dirhtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) build/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) build/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) build/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in build/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) build/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in build/qthelp, like this:"
@echo "# qcollectiongenerator build/qthelp/FCTest User Documenation.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile build/qthelp/FCTest User Documenation.qhc"
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) build/latex
@echo
@echo "Build finished; the LaTeX files are in build/latex."
@echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \
"run these through (pdf)latex."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) build/changes
@echo
@echo "The overview file is in build/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) build/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in build/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) build/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in build/doctest/output.txt."
========
FCTX API
========
.. module:: FCT
:platform: Unix, Windows
:synopsis: Framework, test suites, tests and checks.
Initialize/Finalize
-------------------
.. c:function:: FCT_BGN()
Initializes your test framework. Every test program needs to
begin with this declaration.
.. c:function:: FCT_BGN_FN(fname)
*New in 1.6*. Allows you to start unit tests with a function,
*fname*, other than the standard main.
.. code-block:: c
FCT_BGN_FN(myentry) {
FCT_QTEST_BGN(test_func) {
fct_chk(1);
} FCT_QTEST_END();
} FCT_END_FN();
int
main(int argc, char *argv[]) {
return myentry(argc, argv);
}
The function needs to get the standard *argc* and *argv* values.
In the example above we are simplying forwarding *argc* and
*argv*, but you could create your own argc and argv. Keep in
mind that you must mimic the program name.
.. c:function:: FCT_INIT(argc, argv)
*New in 1.6*. Provides the ability to initialize FCTX within a
function other than main.
.. code-block:: c
int
_start_test(int argc, char *argv[]) {
FCT_INIT(argc, argv);
FCT_QTEST_BGN(test_with_my_own_func) {
fct_chk(1);
} FCT_QTEST_END();
FCT_FINAL();
return FCT_NUM_FAILED();
}
int
main(int argc, char *argv[]) {
return _start_test(argc, argv);
}
The initialization needs to recieve the standard *argc* and
*argv* in order to initialize FCT. TO clean up use the
c:func:`FCT_FINAL`.
.. c:function:: FCT_END()
Finalizes your test framework. Every test program neesd to end
with this declaration.
.. c:function:: FCT_END_FN()
*New in 1.6*. Finalize your test framework started via
c:func:`FCT_BGN_FN`.
.. c:function:: FCT_EXPECTED_FAILURES(num_failed)
*New in 1.2*. Mainly used internally by FCTX to test that failures are
occurring properly. If the actual number of failed tests matches the
expected *num_failed*, this macro will cause the program to return 0
instead of a non-zero value.
.. c:function:: FCT_FINAL()
*New in 1.6*. Closes a :c:func:`FCT_INIT` block.
.. c:function:: FCT_NUM_FAILED()
*New in 1.6*. After a :c:func:`FCT_FINAL` this will have the
number of failed tests.
Test Suites
-----------
.. c:function:: FCT_FIXTURE_SUITE_BGN(name)
Using the xtest convention, every test suite starts with a
SUITE_BGN macro. By using the FIXTURE variants you are indicating
that you wish to use a SETUP and TEARDOWN fixture via the
:c:func:`FCT_SETUP_BGN`/:c:func:`FCT_SETUP_END` and
:c:func:`FCT_TEARDOWN_BGN`/:c:func:`FCT_TEARDOWN_END` macro blocks.
See also :c:func:`FCT_SUITE_BGN`, which allows you to skip a setup
and teardown block.
The following example shows calling a setup/teardown to allocate memory
to *data* structure.
.. code-block:: c
{
void *data =NULL;
FCT_FIXTURE_SUITE_BGN("1Suite")
{
FCT_SETUP_BGN()
{
data = malloc(sizeof(10));
}
FCT_SETUP_END();
FCT_TEARDOWN_BGN()
{
free(data);
data =NULL;
}
FCT_TEARDOWN_END();
FCT_TEST_BGN("1Test")
{
fct_chk( strcmp("a", "b") != 0 );
}
FCT_TEST_END();
}
FCT_FIXTURE_SUITE_END();
}
.. /* (Just fixes VIM highlighter)
.. c:function:: FCT_FIXTURE_SUITE_END()
This closes a test suite that contains fixtures. If you do not wish to
specify a setup/teardown you would use the :c:func:`FCT_SUITE_END`
function instead.
.. c:function:: FCT_SUITE_BGN(name)
Use this FCT_SUITE variant if you do not want to bother specifying a
SETUP and TEARDOWN blocks.
See also :c:func:`FCT_FIXTURE_SUITE_BGN`.
The following test suite does not have a setup/teardown method. This
is generally used for convenience, to group a set of tests under
one heading (a "suite").
.. code-block:: c
FCT_SUITE_BGN("1Suite")
{
FCT_TEST_BGN("1Test")
{
fct_chk( strcmp("a", "b") != 0 );
}
FCT_TEST_END();
}
FCT_SUITE_END();
}
.. c:function:: FCT_SUITE_END()
Closes the FCT_SUITE_BGN macro.
.. c:function:: FCT_SETUP_BGN()
Opens a SETUP block. This block is executed *before* every test.
.. c:function:: FCT_SETUP_END()
Closes the SETUP block.
.. c:function:: FCT_TEARDOWN_BGN()
Opens up a teardown block. This block is executed *after* every test.
.. c:function:: FCT_TEARDOWN_END()
Ends a teardown block.
Conditional Test Suites
-----------------------
*New in FCTX 1.2*. The following macros provide you with the ability to run a
test suite based on some condition. If the condition is TRUE (non-zero) then
the test suite and its tests will be executed.
.. c:function:: FCT_FIXTURE_SUITE_BGN_IF(condition, name)
Same as :c:func:`FCT_SUITE_BGN`, but will only run if the *condition* is
a non-zero value (TRUE).
.. c:function:: FCT_FIXTURE_SUITE_END_IF()
Closes the :c:func:`FCT_FIXTURE_SUITE_BGN_IF` macro.
.. c:function:: FCT_SUITE_BGN_IF(condition, name)
Same as :c:func:`FCT_SUITE_BGN`, but will only run if the *condition* is
a non-zero value (TRUE).
.. c:function:: FCT_SUITE_END_IF()
Closes the :c:func:`FCT_SUITE_BGN_IF` macro.
Quick Test
----------
*New in FCTX 1.1*. This allows you to write tests without any Test Suite
infrastructure. For example,
.. code-block:: c
/* First include the fct framework. */
#include "fct.h"
/* Include your API. In this case we are going to test strcmp. */
#include <string.h>
/* Now lets define our testing scope. */
FCT_BGN()
{
/* An actual test case in the test suite. */
FCT_QTEST_BGN(strcmp_eq)
{
fct_chk(strcmp("durka", "durka") == 0);
}
FCT_QTEST_END();
FCT_QTEST_BGN(chk_neq)
{
fct_chk(strcmp("daka", "durka") !=0 );
}
FCT_QTEST_END();
/* Every FCT scope has an end. */
}
FCT_END();
.. ***
The above code block lacks any test suites, and provide a convenient way to get
of the ground quickly and start writing tests.
.. c:function:: FCT_QTEST_BGN(name)
Opens the quick test block with the given *name*.
.. c:function:: FCT_QTEST_END()
Ends the quick test block.
.. c:function:: FCT_QTEST_BGN_IF(condition, name)
*New in FCTX 1.2*. Opens the quick test block with the given *name*. The
contents of the test block are only executed if the *condition* is a
non-zero (TRUE) value.
.. c:function:: FCT_QTEST_END_IF()
*New in FCTX 1.2*. Ends the conditional quick test block.
Tests
-----
These define a beginning and end of a test block. See also
:c:func:`FCT_QTEST_BGN` and :c:func:`FCT_QTEST_END`.
.. c:function:: FCT_TEST_BGN(name)
Opens a test block with the given *name*.
.. c:function:: FCT_TEST_END()
Closes a test block.
Conditional Tests
-----------------
*New in FCTX 1.2*. Use these variants to run a test based on a conditional
value.
.. c:function:: FCT_TEST_BGN_IF(condition, name)
Opens a test block with the given *name*. The test is only executed if the
*condition* is a non-zero (TRUE) value.
.. c:function:: FCT_TEST_END_IF()
Closes a test block.
Checks
------
These are used to verify that a condition is true. They are executed within
:c:func:`FCT_TEST_BGN`/:c:func:`FCT_TEST_END` blocks.
.. c:function:: fct_chk(condition)
Evaluates the *condition*, and if it is false will cause the tests to fail.
Further lines in the test block continue to execute. If you want a check to
terminate testing, then use the :c:func:`fct_req` function instead.
A feature of this check is that you can provide notes to yourself as in,
.. code-block:: c
fct_chk( it_works() && "The whoosley wazzle didn't work!");
fct_chk(!"TODO: Write tests to confirm that the ish can wish for fish.");
in both those cases if an error was generated (the second case always will
fail), you will get a message in the final error log.
.. c:function:: fct_chk_empty_str(s)
*New in FCTX 1.3*. Causes a test failure if the string, *s*, is not
empty. NULL is considered an empty string.
.. c:function:: fct_chk_eq_dbl(a, b)
*New in FCTX 1.1*. Causes a test failure if *a* != *b*. Testing for
equality is done based on an absolute floating point difference less than
the *DBL_EPISLON* defined in the standard <float.h> file.
.. c:function:: fct_chk_eq_int(a, b)
*New in FCTX 1.1*. Causes a test failure if *a* != *b*. Testing for
equality is done based on the "==" operator. An error message is generated
showing the values of *a* and *b*.
.. c:function:: fct_chk_eq_istr(a, b)
*New in FCTX 1.1*. Causes a test failure if *a* != *b* (case-insensitive).
Testing for equality is done based on first checking for NULL values, then
making a case-insensitive compare.
.. c:function:: fct_chk_eq_str(a, b)
*New in FCTX 1.1*. Causes a test failure if *a* != *b*. Testing for
equality is done based on first checking for NULL values, then making a
case-sensitive compare.
.. c:function:: fct_chk_endswith_str(s, check)
*New in FCTX 1.3* Checks that the given string, *s*, ends with the
given *check*. NULL's are treated as blank strings.
.. c:function:: fct_chk_excl_str(s, check)
*New in FCTX 1.3*. Will cause a test failure when it does find the
*check* within the given string, *s*. NULL is treated as a blank
string in this case.
.. c:function:: fct_chk_excl_istr(s, check)
*New in FCTX 1.3*. Case insensitive variant of
:c:func:`fct_chk_excl_str`.
.. c:function:: fct_chk_full_str(s)
*New in FCTX 1.3*. Fails if the string, *s*, is full. A string with
whitespace is still considered full.
.. c:function:: fct_chk_incl_str(s, check)
*New in FCTX 1.3*. Causes a test failure when it can not find *check*
within the given string, *s*. NULL is treated as a blank string in
this case, thus if *check* is NULL, all *str* will pass. Down in the
guts of this function, there is a call to the Standard C *strstr*
function.
.. c:function:: fct_chk_incl_istr(s, check)
*New in FCTX 1.3*. This is a case insensitive variant of
:c:func:`fct_chk_incl_str`.
.. c:function:: fct_chk_iendswith(s, check)
*New in FCTX 1.3*. This is a cse insensitive variant of
:c:func:`fct_chk_endswith`.
.. c:function:: fct_chk_istartswith_istr(s, check)
*New in FCTX 1.3*. Case insensitive variant of
:c:func:`fct_chk_startswith_str`.
.. c:function:: fct_chk_startswith_str(s, check)
*New in FCTX 1.3*. Will return true if the string, *s*, starts with
the given *check* string. Will output a useful error message
otherwise.
.. c:function:: fct_chk_neq_dbl(a, b)
*New in FCTX 1.1*. Causes a test failure if *a* == *b*. Testing for
inequality is done based on an absolute floating point difference that is
NOT less than the *DBL_EPISLON* defined in the standard <float.h> file.
.. c:function:: fct_chk_neq_int(a, b)
*New in FCTX 1.1*. Causes a test failure if *a* == *b*. Testing for
equality is done based on the "!=" operator. An error message is generated
showing the values of *a* and *b*.
.. c:function:: fct_chk_neq_istr(a, b)
*New in FCTX 1.1*. Causes a test failure if *a* == *b* (case-insensitive).
Testing for inequality is done based on first checking for NULL, then
making a case-insensitive compare.
.. c:function:: fct_chk_neq_str(a, b)
*New in FCTX 1.1*. Causes a test failure if *a* == *b*. Testing for
inequality is done based on first checking for NULL, then making a
case-sensitive compare.
.. c:function:: fct_xchk(condition, format_str, ...)
*New in FCTX 1.1*. Evaluates the *condition*, and if it is false will cause
the tests to fail. Further lines in the test block continue to execute.
The message reported is a function of a printf-style *format_str*, with
multiple arguments.
:c:func:`fct_xchk` can be extended to generate your own check functions. For
example, say you had a structure such as,
.. code-block:: c
typedef struct _point_t {
float x, y, z;
} point_t;
you could define a macro that checks if two points are equal based on some
epsilon value. Something that looked like this should work,
.. code-block:: c
#define point_is_eq(p1, p2, ep) \
((int)(fabs(p1.x - p2.x) < ep)) &&\
((int)(fabs(p1.y - p2.y) < ep)) &&\
((int)(fabs(p1.z - p2.z) < ep))
#define point_chk_eq(p1, p2, ep) \
fct_xchk(\
point_is_eq(p1, p2, ep), \
"failed point_is_equal:\n<Point x=%f y=%f z=%f>"\
" !=\n<Point x=%f y=%f z=%f>",\
p1.x, p1.y, p1.z, p2.x, p2.y, p2.z\
);
now your test case can utilize this to test if two points are equal, and
you will get a meaningful report if they are not.
.. code-block:: c
FCT_QTEST_BGN(chk_my_point) {
point_t point1 = {1.f, 2.f, 3.f};
point_t point2 = {1.f, 2.f, 3.f};
point_t point3 = {10.f, 20.f, 30.f};
point_chk_eq(point1, point2, DBL_EPSILON);
point_chk_eq(point1, point3, DBL_EPSILON);
}
FCT_QTEST_END();
in the above example, the second check should generate a test error.
.. c:function:: fct_xchk2(condition_str, condition, format_str, ...)
*New in FCTX 1.4.1*. Works like fct_xchk, but allows you to supply a
value for the check condition.
.. c:function:: fct_req(condition)
*New in FCTX 1.1*. Evaluates the *condition*, and if it is false it will
cause a test to fail. This differs from :c:func:`fct_chk` in so far as a
false state causes the test block to abort.
*Starting with FCTX 1.5* :c:func:`fct_req` will work within a
:c:func:`FCT_SETUP_BGN`/:c:func:`FCT_SETUP_END` block. If
a :c:func:`fct_req` call fails, the entire test suite will be aborted.
C++ Only Checks
---------------
.. c:function:: fct_chk_ex(exception, CODE_BLOCK)
*New in FCTX 1.6*. Checks for the given *exception* with in the
*CODE_BLOCK*. The *CODE_BLOCK* could be 1 or more lines.
=======================
fctcl: Command Line API
=======================
.. module:: fctcl
:platform: Unix, Windows
:synopsis: FCTX command line interface.
.. versionadded:: 1.2
Introduction
------------
To help control unit tests at runtime you may want to use command line
arguments. This modules provides access to a simple command line parser that
builds into each version FCTX unit testing application.
Built-in Options
----------------
When you build a program with FCTX, you will get a set of pre-built command
line options. The options are as follows,
.. program:: fctx_program.exe
.. cmdoption:: -v, --version
Reports the version of FCTX used to build ``your_test_program.exe``.
.. cmdoption:: -h, --help
Shows the usage for all command line options defined for
``your_test_program.exe``.
The following options are reserved, and should not be used by your custom
command line options.
.. program:: fctx_program.exe
.. cmdoption:: -l, --logger
Defines the logger to use for the testing session. Options are,
=============== ===============
Type Summary
=============== ===============
standard The standard logger that comes with fctx.
minimal Displays a series of '.' for each test and a "x" if there was a failure.
junit Output's JUnit compatible xml.
=============== ===============
to be able to define the type of logger used.
All future pre-built command line options in FCTX will all be prefixed with
a "f", as in ``--foption``.
Customizing the Command Line
----------------------------
The following steps go over how to set up your own custom command line parser
and check the results.
In our example we will test for a "flag" option called ``--use-slow``, which
when present will signal that we can execute the long running unit tests. You
could envisage using this option for a nightly run only, while day-to-day work
would avoid the long running tests.
First, lets take a look at what we have before we customize the command line
parser.
.. code-block:: c
#include "fct.h"
FCT_BGN() {
int use_slow =0; /* Toggle This Value */
FCT_QTEST_BGN(slow_test) {
if ( use_slow ) {
fct_chk( run_slow_running_process() );
}
} FCT_QTEST_END();
} FCT_END();
.. /* (Fixes VIM highlighter)
now in order to determine if you want to run the slow tests you need to toggle
the *use_slow* variable to true and re-compile. Clearly this is not a desirable
way to control the execution.
What follows is how to go about setting up a custom command line option so we
can check if the *use_slow* option should be set to true at run-time.
The first thing we will do is install our command line options. This is a NULL
terminated list of :c:type:`fctcl_init_t` entries.
.. code-block:: c
#include "fct.h"
/* Add our command line options. */
static fctcl_init_t my_cl_options[] = {
{"--use-slow", /* long_opt */
NULL, /* short_opt (optional) */
FCTCL_STORE_TRUE, /* action */
"Runs slow running unit tests" /* help */
},
FCTCL_INIT_NULL /* Sentinel */
};
FCT_BGN() {
int use_slow =0; /* Toggle This Value */
FCT_QTEST_BGN(slow_test) {
if ( use_slow ) {
fct_chk( run_slow_running_process() );
}
} FCT_QTEST_END();
} FCT_END();
.. /* (Fixes VIM highlighter)
The entry we added says: "if you encounter the long ``--use-slow`` option, then
set a true flag that we can read later."
Next we install the options with the :c:func:`fctcl_install`.
.. code-block:: c
#include "fct.h"
/* Add our command line options. */
static fctcl_init_t my_cl_options[] = {
{"--use-slow",
NULL,
FCTCL_STORE_TRUE,
"Runs slow running unit tests"},
FCTCL_INIT_NULL /* Sentinel */
};
FCT_BGN() {
int use_slow =0;
/* Install the command line options defined above. */
fctcl_install(my_cl_options);
/* Check if --use-slow was on the command line. */
use_slow = fctcl_is("--use-slow");
FCT_QTEST_BGN(slow_test) {
if ( use_slow ) {
fct_chk( run_slow_running_process() );
}
} FCT_QTEST_END();
} FCT_END();
.. /* (Fixes VIM highlighter)
After you have installed the options you can now check if a flag is set using
the :c:func:`fctcl_is` macro. If the user had entered ``--use-slow`` at the
command prompt, then the value of :c:func:`fctcl_is` would return TRUE (1).
Your last option is to use the :c:func:`FCT_QTEST_BGN_IF` macro.
.. code-block:: c
#include "fct.h"
/* Add our command line options. */
static fctcl_init_t my_cl_options[] = {
{"--use-slow",
NULL,
FCTCL_STORE_TRUE,
"Runs slow running unit tests"},
FCTCL_INIT_NULL /* Sentinel */
};
FCT_BGN() {
int use_slow =0;
/* Install the command line options defined above. */
fctcl_install(my_cl_options);
/* Check if --use-slow was on the command line. */
use_slow = fctcl_is("--use-slow");
FCT_QTEST_BGN_IF(use_slow, slow_test) {
fct_chk( run_slow_running_process() );
} FCT_QTEST_END_IF();
} FCT_END();
.. /* (Fixes VIM highlighter)
This will run the "slow_test" if the *use_slow* variable is TRUE (non-zero).
Types
-----
.. c:type:: fctcl_init_t
Use this structure to initialize your options. The structure is usually
initialized as part of a listing of command line options. Each field is
described below.
.. c:member:: char const * long_opt
Long option on the command line.
.. c:member:: char const * short_opt
Short option on the command line. This can be set to NULL if you do not
wish to have a short option available.
.. c:member:: fctcl_store_t action
When a command line option is encountered by the parser this describes
what the parser should do. If, for example, :c:macro:`FCTCL_STORE_TRUE`
is used, then a true boolean value (1) is stored. If
:c:macro:`FCTCL_STORE_VALUE` is used, then a string is stored and can be
later retrieved.
.. c:member:: char const * help
This is the help string that is displayed if the command line parser
encounters a ``-h`` or ``--help``.
.. c:type:: fctcl_store_t
Describes the action to take if a command line option is recognized by the
parser. Valid options currently are,
.. c:macro:: FCTCL_STORE_UNDEFINED
Do not use. This is the default value when we don't have an available
option.
.. c:macro:: FCTCL_STORE_TRUE
When present it signals to the command line parser that we store a true
(1) flag.
.. c:macro:: FCTCL_STORE_VALUE
When present it signals to the command line parser that we store a
string value corresponding to the next argument in the parser. For
instance,
=============== ===============
Command Line Resulting Value
=============== ===============
--use-value=xxx xxx
--use-value xxx xxx
=============== ===============
use this if you want to retrieve a value from the command line.
Functions
---------
.. c:function:: void fctcl_install(cl_options)
Installs your :c:type:`fctcl_init_t` NULL terminated array of *cl_options*
into the command line parser. The command line is then parsed at this
moment, and any subsequent queries via :c:func:`fctcl_is` or
:c:func:`fctcl_val` will return the parse results. See `Customizing
the Command Line`_ for an example of installing your own command line
options.
.. c:function:: int fctcl_is(flag)
Returns true if the *flag* has been used. The *flag* is the either the long
or short option used during the configuration stage. Use this macro to
retrieve :c:macro:`FCTCL_STORE_TRUE` command line options.
.. c:function:: const char* fctcl_val(flag)
Returns a character buffer defined by the *flag*. It will return NULL if
*flag* was not defined at the command line. Use this macro to retrieve
:c:macro:`FCTCL_STORE_VALUE` command line options.
.. c:function:: const char * fctcl_val2(flag, defval)
Returns a character buffer defiend by the *flag* or the pointer to *defval*
if the *flag* was not defined on the command line. Use this macro to
retrieve :c:macro:`FCTCL_STORE_VALUE` command line options.
# -*- coding: utf-8 -*-
#
# FCTX User Documenation documentation build configuration file, created by
# sphinx-quickstart on Sun May 17 13:42:01 2009.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.append(os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.pngmath', 'sphinx.ext.ifconfig']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'FCTX User Documenation'
copyright = u'2009, Ian Blumel'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.2'
# The full version, including alpha/beta/rc tags.
release = '1.2.0'
# This is tacked onto the end of every "web release", to help us better track
# how the documentation is doing. The regular, non-web release, will set this
# value to "" in the makefile.
rst_epilog ="""
.. raw:: html
<script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> try { var pageTracker = _gat._getTracker("UA-10742433-3"); pageTracker._trackPageview(); } catch(err) {}</script>
"""
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some # non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = []
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'borland'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'sphinxdoc'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_use_modindex = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'FCTXUserDocumenationdoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'FCTXUserDocumenation.tex', u'FCTX User Documentation',
u'Ian Blumel', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'http://docs.python.org/': None}
===============
Getting Started
===============
To get you started quickly you only need to have the "fct.h" header file
somewhere handy on your system. In the distribution package, it can be found in
the "include" directory.
What follows an overly simple example of testing.
.. code-block:: c
/* First include the fct framework. */
#include "fct.h"
/* Include your API. In this case we are going to test strcmp. */
#include <string.h>
/* Now lets define our testing scope. */
FCT_BGN()
{
/* An actual test case in the test suite. */
FCT_QTEST_BGN(strcmp_eq)
{
fct_chk(strcmp("durka", "durka") == 0);
}
FCT_QTEST_END();
FCT_QTEST_BGN(chk_neq)
{
fct_chk(strcmp("daka", "durka") !=0 );
}
FCT_QTEST_END();
/* Every FCT scope has an end. */
}
FCT_END();
Now you can compile the above file and generate a new EXE. If your new
EXE was called "test.exe", you can run it with a "filtering prefix" to
limit the tests executed, for example::
test strcmp_eq
would only execute the "strcmp_eq" test.
To define a SETUP/TEARDOWN structure you would do something similar to
the above tests but this time we would introduce a test suite.
.. code-block:: c
FCT_BGN()
{
/* Optionally, define a scope for you data. */
{
void *data =NULL;
FCT_FIXTURE_SUITE_BGN(Fixtures)
{
FCT_SETUP_BGN()
{
/* Initialize your data before a test is executed. */
data = malloc(sizeof(10));
}
FCT_SETUP_END();
FCT_TEARDOWN_BGN()
{
/* Clean up your data after a test is executed. */
free(data);
data = NULL;
}
FCT_TEARDOWN_END();
FCT_TEST_BGN(silly_test_for_null)
{
fct_chk( data != NULL );
}
FCT_TEST_END();
FCT_TEST_BGN(silly_test_for_null__again)
{
fct_chk( data != NULL );
}
FCT_TEST_END();
}
FCT_FIXTURE_SUITE_END();
}
}
FCT_END();
Afterwards, you can compile and run this test, and the "data" will be
setup and teared down after each test cycle.
FCTX User Documentation
=======================
Welcome
--------
Use Fast C XUnit Test as a lightweight tool for quickly generating unit tests in
C/C++. Simply include a header and start typing out your tests.
With FCTX you can write tests in C/C++ just like you can in other introspective
languages like Java and Python. FCTX does not require a post-processing step.
FCTX does not require registration of your functions. Declare your test and
start writing.
Contents
--------
.. toctree::
:maxdepth: 2
getting_started.rst
api_fct.rst
clapi_fct.rst
mfapi_fct.rst
strapi_fct.rst
=====================
FCTMF: Multi-file API
=====================
.. module:: FCTMF
:platform: Unix, Windows
:synopsis: FCTX across multiple files.
.. versionadded:: 1.1
The FCTX Multi-File (FCTMF) supersedes the older "include method"
described in version 1.0.
Introduction
------------
When you start unit testing with FCTX you will find that at some point
holding all your tests in one file can become unwieldy. The Multi-File api
(FCTMF) attempts to provide a minimal barrier to writing unit tests that span
multiple files.
The idea is to have one file that starts up tests defined in each of the other
files. The process of registration is a one step "call" into the other files.
Multi-File Setup
----------------
Imagine we have two files: :file:`test_main.c` and :file:`test_a.c`. In
:file:`test_main.c` we will setup and register our test that is defined in
:file:`test_a.c`.
Lets look at :file:`test_main.c`,
.. code-block:: c
/* file: test_main.c */
#include "fct.h"
FCT_BGN() {
FCTMF_SUITE_CALL(test_a_feature);
} FCT_END();
.. /* fixes vim highlighting.
there now we have set it up to call into the test suite called "test_a_feature"
defined in :file:`test_a.c`. Lets look at the contents of :file:`test_a.c`.
.. code-block:: c
/* file: test_a.c */
#include "fct.h"
FCTMF_SUITE_BGN(test_a_feature) {
FCT_TEST_BGN(sanity_check) {
fct_chk( a_feature__sanity_check() );
} FCT_TEST_END();
} FCTMF_SUITE_END();
.. /* fixes vim highlighting.
this will register a test suite called "test_a_feature" and execute a test
called "sanity_check".
If you wanted to use a test suite with fixtures (setup/teardown), you would do
the following,
.. code-block:: c
/* file: test_a.c */
#include "fct.h"
static a_object_t *obj;
FCTMF_FIXTURE_SUITE_BGN(test_a_feature) {
FCT_SETUP_BGN() {
obj = a_object_new();
} FCT_SETUP_END();
FCT_TEARDOWN_BGN() {
a_object__del(obj);
obj =NULL;
} FCT_TEARDOWN_END();
FCT_TEST_BGN(sanity_check) {
fct_chk( a_object__sanity_check(obj) );
} FCT_TEST_END()
} FCTMF_FIXTURE_SUITE_END();
.. /* (Just fixes VIM highlighter)
the only difference here being the introduction of "FIXTURE" into scope
statements as well as the SETUP and TEARDOWN fixtures themselves.
The key thing to also notice is that all the testing, checking, setup and
teardown macros follow the existing :mod:`FCT` module.
Note for MVC Compilers
----------------------
Using the FCTMF API with warning level 4 will produce the following::
warning C4210: nonstandard extension used : function given file scope
so far testing both with MVC and GCC FCTMF has yet to fail, except for this
warning level above.
So what's happening here?
The FCTMF_SUITE_CALL uses the following little trick whereby,
.. code-block:: c
FCTMF_SUITE_CALL(my_test_suite);
becomes,
.. code-block:: c
void my_test_suite(fctkern_t *fk);
my_test_suite(fctkern_ptr__);
.. /* (Just fixes VM highlighter)
where we make a "variable" and "run it", and let the linker sort it out all in
the end.
The goal here was to prevent you from having to repeatedly "register" your test
suite in order for you get up and running. To stay at warning level 4, but
quite the compiler, you can do the following,
.. code-block:: c
#if defined(_MSC_VER)
# pragma warning(push, 3)
#endif /* _MSC_VER */
FCTMF_SUITE_CALL(my_test_suite);
FCTMF_SUITE_CALL(test_fixture_suite2);
#if defined(_MSC_VER)
# pragma warning(pop)
#endif /* _MSC_VER */
.. /* (Just fixes VM highlighter)
and you will be able to continue to use /W4 with MVC as well as GCC.
Multi-File Test Suites
----------------------
.. c:function:: FCTMF_SUITE_CALL(name)
This launches the test suite defined by *name*. You would place this
call between the :c:func:`FCT_BGN()` and :c:func:`FCT_END()` scope. This
simply calls off to another file, and it does not prevent you from
having other tests within the :c:func:`FCT_BGN()` and :c:func:`FCT_END()`
scope.
For Visual Studio 6 compilers, you will need to use the
:c:func:`FCTMF_SUITE_DEF` function.
.. c:function:: FCTMF_FIXTURE_SUITE_BGN(name)
Following the xtest convention, every test suite needs to start with a
SUITE_BGN function. In by using the FIXTURE variants you are indicating
that you wish to install a SETUP and TEARDOWN fixture via the
:c:func:`FCT_SETUP_BGN` and :c:func:`FCT_SETUP_END` and
:c:func:`FCT_TEARDOWN_BGN` and :c:func:`FCT_TEARDOWN_END` functions.
See also :c:func:`FCTMF_SUITE_BGN`.
.. /* (Just fixes VIM highlighter)
.. c:function:: FCTMF_FIXTURE_SUITE_END(name)
This closes a test suite that contains fixtures. If you do not wish to
specify a setup/teardown you would use the :c:func:`FCT_SUITE_END`
function instead.
.. c:function:: FCTMF_SUITE_BGN(name)
Use this FCTMF_SUITE variant if you do not want to bother specifying a
SETUP and TEARDOWN blocks.
See also :c:func:`FCTMF_FIXTURE_SUITE_BGN`.
.. c:function:: FCTMF_SUITE_END()
Closes the :c:func:`FCTMF_SUITE_BGN` function.
.. c:function:: FCTMF_SUITE_DEF(name)
Defines a test suite with the given *name*. This is only required for
the Visual Studio 6 compilers (or if you choose to avoid the comments
in `Note for MVC Compilers`_). This call must be made *before* the
:c:func:`FCT_BGN` function. The *name* must be the same as the name in
:c:func:`FCTMF_SUITE_CALL` and :c:func:`FCTMF_SUITE_BGN`.
==================
fctstr: String API
==================
.. module:: fctstr
:platform: Unix, Windows
:synopsis: Basic string API to support unit testing.
.. versionadded:: 1.2
API for string operations that you may encounter during unit testing.
Introduction
------------
Provides an API for common string operations that you may encounter during unit
testing. This module will grow over time.
String Functions
----------------
.. c:function:: fctstr_clone(s)
Allocates new memory, and copies the contents of *s* into the result.
Callee should use the standard C Runtime Library's *free* function to
clean up the memory.
.. c:function:: fctstr_clone_lower(s)
*New in FCTX 1.3.* Same as :c:func:`fctstr_clone`, but returns the
string, *s*, as a lower case string.
.. c:function:: fctstr_eq(s1,s2)
Returns a non-zero (TRUE) if *s1* and *s2* are equal. Unlike the
standard strcmp function, this function can handle NULL values. This
function will also quit the moment one of the strings is unequal. If
*s1* and *s2* are NULL, this function will return non-zero (TRUE)
value. See :c:func:`fctstr_ieq` for a case-insensitive string compare.
.. c:function:: fctstr_endswith(s, check)
*New in FCTX 1.3*. Returns true if the string, *s*, ends with
the given *check* string.
.. c:function:: fctstr_ieq(s1,s2)
Performs a case insensitve string compare, see :c:func:`fctstr_eq` for
more details.
.. c:function:: fctstr_iendswith(s, check)
*New in FCTX 1.3.* Case insensitive variant of
:c:func:`fctstr_endswith`.
.. c:function:: fctstr_incl(s1, check)
*New in FCTX 1.3.* Returns true if the sub-string, *check*, can
be found in the string *s1*. This function will change NULL input
values for a blank string before proceeding to call the standard
C *strstr* function.
.. c:function:: fctstr_iincl(s1, check)
*New in FCTX 1.3.* Case insensitive version of
:c:func:`fctstr_incl`.
.. c:function:: fctstr_istartswith(s1, check)
*New in FCTX 1.3*. Case insensitive variant of
:c:func:`fctstr_startswith`.
.. c:function:: fctstr_startswith(s1, check)
*New in FCTX 1.3*. Returns true (1) if the string, *s1*, starts
with the given string, *check*. This will treat two NULL values
as equal, and return true (1).
# ====================================================================
# Copyright (c) 2010 Ian Blumel. All rights reserved.
#
# This software is licensed as described in the file LICENSE, which
# you should have received as part of this distribution.
# ====================================================================
ADD_SUBDIRECTORY(custom_check)
ADD_SUBDIRECTORY(custom_logger)
# ====================================================================
# Copyright (c) 2010 Ian Blumel. All rights reserved.
#
# This software is licensed as described in the file LICENSE, which
# you should have received as part of this distribution.
# ====================================================================
INCLUDE_DIRECTORIES(../../include)
ADD_EXECUTABLE(example_custom_check
example_custom_check.cpp
)
ADD_TEST(example_custom_check
${EXECUTABLE_OUTPUT_PATH}/example_custom_check
)
/*
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_1suite.c
Runs through 1 test suite. A very simple project for testing the layout
and execution of a test suite.
*/
#include <string>
#include <sstream>
#include "fct.h"
/*
--------------------------------------------------------------------
OUR TEST CLASS
--------------------------------------------------------------------
*/
/* A very simple and naive money class implementation. */
class money_t
{
friend bool operator==(const money_t &a, const money_t &b);
public:
money_t() : amount_(0), currency_(0) {};
money_t(int amount, const std::string &currency)
: amount_(amount), currency_(currency)
{};
virtual ~money_t() {};
std::string to_string() const
{
std::stringstream buf;
buf << "<money_t amount: "
<< this->amount_
<< "; currency: "
<< this->currency_
<< ">";
return buf.str();
};
void add(int amount)
{
this->amount_ += amount;
};
private:
int amount_; /* Use integers to make compares simple for now. */
std::string currency_;
};
bool operator==(const money_t &a, const money_t &b)
{
return ((a.amount_ == b.amount_)
&& (b.currency_ == b.currency_));
}
/*
--------------------------------------------------------------------
CUSTOM CHECK
--------------------------------------------------------------------
*/
#define chk_money_eq(m1, m2) \
fct_xchk(\
m1 == m2,\
"money_t not equal:\n%s != %s",\
m1.to_string().c_str(),\
m2.to_string().c_str()\
)
/*
--------------------------------------------------------------------
UNIT TESTS
--------------------------------------------------------------------
*/
FCT_BGN()
{
FCT_QTEST_BGN(test_money__no_helpful_info)
{
money_t m1(10, "USD");
money_t m2(m1);
fct_chk( m1 == m2 );
}
FCT_QTEST_END();
FCT_QTEST_BGN(test_money__with_custom_check)
{
money_t m1(10, "USD");
money_t m2(m1);
chk_money_eq(m1, m2);
}
FCT_QTEST_END();
}
FCT_END();
# ====================================================================
# Copyright (c) 2010 Ian Blumel. All rights reserved.
#
# This software is licensed as described in the file LICENSE, which
# you should have received as part of this distribution.
# ====================================================================
INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/include)
ADD_EXECUTABLE(example_custom_logger
# The 'custom header'.
custom_logger_fct.h
# The unit test
custom_logger.c
)
ADD_TEST(example_custom_logger
${EXECUTABLE_OUTPUT_PATH}/example_custom_logger
)
/*
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: custom_logger.c
*/
/* Rather than include fct, we will include our 'custom_logger_fct.h'
header. This header will be responsible for exentending the logger. */
#include "custom_logger_fct.h"
CL_FCT_BGN()
{
FCT_QTEST_BGN(custom_logger_qtest1)
{
fct_chk("pass");
}
FCT_QTEST_END();
FCT_QTEST_BGN(custom_logger_qtest2)
{
fct_chk( 1 == 1);
}
FCT_QTEST_END();
FCT_SUITE_BGN(test_suite)
{
FCT_TEST_BGN(test1)
{
fct_chk( strcmp("test1", "test1")==0 );
fct_chk( strcmp("test2", "test2")==0 );
}
FCT_TEST_END();
FCT_TEST_BGN(test_will_fail)
{
fct_chk( 0 && "This should fail.");
}
FCT_TEST_END();
}
FCT_SUITE_END();
printf("\n***TESTS ARE SUPPOSED TO REPORT FAILURES***\n");
FCT_EXPECTED_FAILURES(1);
}
CL_FCT_END();
/* Extends the fct logger.
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: custom_logger_fct.h
*/
#include "fct.h"
/* Define our custom logger object. */
struct _custlog_t
{
/* Define the common logger header. */
_fct_logger_head;
/* Add any data members you want to maintain here. Perhaps
you want to track something from event to event? */
};
/* Handles what to do when a fct_chk is made. */
static void
custlog__on_chk(fct_logger_i *l, fct_logger_evt_t const *e)
{
fctchk_t const *chk = e->chk;
fct_unused(l);
printf("on_chk: %s\n"
" - location: %s(%d)\n"
" - message: %s\n"
" - condition: %s [DEPRECATED]\n",
(fctchk__is_pass(chk)) ? "PASS" : "FAIL",
fctchk__file(chk),
fctchk__lineno(chk),
fctchk__msg(chk),
fctchk__cndtn(chk) /* This should be deprecated. */
);
}
/* Handles the start of a test, for example FCT_TEST_BGN(). */
static void
custlog__on_test_start(fct_logger_i *l, fct_logger_evt_t const *e)
{
fct_test_t const *test = e->test;
(void)l;
(void)e;
printf("on_test_start:\n"
" - name: %s\n",
fct_test__name(test)
);
}
/* Handles the end of a test, for example FCT_TEST_END(). */
static void
custlog__on_test_end(fct_logger_i *l, fct_logger_evt_t const *e)
{
fct_test_t const *test = e->test;
(void)l;
printf("on_test_end:\n"
" - name: %s\n"
" - duration: %f ms\n",
fct_test__name(test),
fct_test__duration(test)
);
}
/* Handles the start of a test suite, for example FCT_TESTSUITE_BGN(). */
static void
custlog__on_test_suite_start(fct_logger_i *l, fct_logger_evt_t const *e)
{
fct_ts_t const *test_suite = e->ts;
(void)l;
printf("on_test_suite_start:\n"
" - name: %s\n",
fct_ts__name(test_suite)
);
}
/* Handles the end of a test suite, for example FCT_TESTSUITE_END(). */
static void
custlog__on_test_suite_end(fct_logger_i *l, fct_logger_evt_t const *e)
{
fct_ts_t const *test_suite = e->ts;
int test_cnt = fct_ts__tst_cnt(test_suite);
int passed_test_cnt = fct_ts__tst_cnt(test_suite);
int failed_test_cnt = test_cnt - passed_test_cnt;
(void)l;
printf("on_test_suite_end:\n"
" - name: %s\n"
" - duration: %f ms\n"
" - tests passed: %d\n"
" - tests failed: %d\n"
" - checks: %lu\n",
fct_ts__name(test_suite),
fct_ts__duration(test_suite),
passed_test_cnt,
failed_test_cnt,
(unsigned long) fct_ts__chk_cnt(test_suite)
);
}
/* Handles the first time FCTX can offically say 'start'. */
static void
custlog__on_fctx_start(fct_logger_i *l, fct_logger_evt_t const *e)
{
(void)l;
(void)e;
printf("on_fctx_start:\n");
}
/* Handles the last time FCTX can do anything. */
static void
custlog__on_fctx_end(fct_logger_i *l, fct_logger_evt_t const *e)
{
(void)l;
(void)e;
printf("on_fctx_end:\n");
}
/* Handles a warning message produced by FCTX. */
static void
custlog__on_warn(fct_logger_i *l, fct_logger_evt_t const *e)
{
char const *message = e->msg;
(void)l;
printf("on_warn: %s\n", message);
}
/* When a conditional test suite is skipped due to conditional evaluation. */
static void
custlog__on_test_suite_skip(fct_logger_i *l, fct_logger_evt_t const *e)
{
/* Conditional evaluation on why we skipped. */
const char *condition = e->cndtn;
/* Name of test suite skipped. */
const char *name = e->name;
(void)l;
printf("on_test_suite_skip:\n"
" - name: %s\n"
" - condition: %s\n",
name,
condition
);
}
/* When a conditional test is skipped due to conditional evaluation. */
static void
custlog__on_test_skip(fct_logger_i *l, fct_logger_evt_t const *e)
{
/* Conditional evaluation on why we skipped. */
const char *condition = e->cndtn;
/* Name of test suite skipped. */
const char *name = e->name;
(void)l;
printf("on_test_suite_skip:\n"
" - name: %s\n"
" - condition: %s\n",
name,
condition
);
}
/* Handles the clean up of the logger object. Perform your special
clean up code here. */
static void
custlog__on_delete(fct_logger_i *l, fct_logger_evt_t const *e)
{
(void)e; /* Currently doesn't supply anything. */
puts("custlog__on_delete:\n");
free((struct _custlog_t*)l);
}
static fct_logger_i*
custlog_new(void)
{
struct _custlog_t *logger = (struct _custlog_t*)malloc(
sizeof(struct _custlog_t)
);
if ( logger == NULL )
{
return NULL;
}
fct_logger__init((fct_logger_i*)logger);
/* The destructor. */
logger->vtable.on_delete = custlog__on_delete;
/* The event handlers. */
logger->vtable.on_chk = custlog__on_chk;
logger->vtable.on_test_start = custlog__on_test_start;
logger->vtable.on_test_end = custlog__on_test_end;
logger->vtable.on_test_suite_start = custlog__on_test_suite_start;
logger->vtable.on_test_suite_end = custlog__on_test_suite_end;
logger->vtable.on_fctx_start = custlog__on_fctx_start;
logger->vtable.on_fctx_end = custlog__on_fctx_end;
logger->vtable.on_warn = custlog__on_warn;
logger->vtable.on_test_suite_skip = custlog__on_test_suite_skip;
logger->vtable.on_test_skip = custlog__on_test_skip;
return (fct_logger_i*)logger;
}
/* Define our custom logger structure. */
/* Define how to install the custom logger. To override the built in
ones use the same name (i.e. "standard" to override the default logger). */
static fct_logger_types_t custlogs[] =
{
{
"custlog", (fct_logger_new_fn)custlog_new,
"custom logger example, outputs everything!"
},
{NULL, (fct_logger_new_fn)NULL, NULL} /* Sentinel */
};
/* Redefine how to initialize FCT to automatically initialize our custom
logger. Define the _END macro for symmetry. */
#define CL_FCT_BGN() \
FCT_BGN() { \
fctlog_install(custlogs);
#define CL_FCT_END() } FCT_END()
# ====================================================================
# Copyright (c) 2009 Ian Blumel. All rights reserved.
#
# This software is licensed as described in the file LICENSE, which
# you should have received as part of this distribution.
# ====================================================================
# Just hold the include file in a project listing. Mainly as a convience for
# IDE generators.
ADD_CUSTOM_TARGET(include
fct.h
)
SET_SOURCE_FILES_PROPERTIES(fct.h
PROPERTIES
HEADER_FILE_ONLY 1
)
This source diff could not be displayed because it is too large. You can view the blob instead.
#!/bin/sh
#
# Taken from Linus Torvald's Linux release script. See
# http://www.kernel.org/pub/software/scm/git-core/docs/user-manual.html.
#
# Examples would be:
#
# release-script 1.2.1 1.3.0
# release-script 1.3.1 1.3.2
#
last="$1"
new="$2"
fctx_dist_dir=../fctx.dist/$new
echo "mkdir --parents $fctx_dist_dir"
echo "git tag -s -m \"FCTX v$new\" v$new"
echo "git archive --prefix=fctx-$new/ v$new | gzip -9 > $fctx_dist_dir/fctx-src-$new.tar.gz"
echo "git diff v$last v$new | gzip -9 > $fctx_dist_dir/patch-$new.gz"
echo "git log --no-merges v$new v$last > $fctx_dist_dir/ChangeLog-$new"
echo "git shortlog --no-merges v$new v$last > $fctx_dist_dir/ShortLog"
echo "git diff --stat --summary -M v$last v$new > $fctx_dist_dir/diffstat-$new"
echo "cd doc/usr"
echo "make clean html html_web VERSION=$new"
echo "tar --create --verbose --transform='s,build/html,fct-doc-$new,' build/html | gzip > ../../$fctx_dist_dir/fctx-doc-$new.tar.gz"
echo "cd ../.."
echo "cp include/fct.h $fctx_dist_dir/fct.h"
echo "cp NEWS $fctx_dist_dir/NEWS-$new"
echo "cp README.rst $fctx_dist_dir/README.rst"
echo "cp wikify.py $fctx_dist_dir/wikify.py"
# Specifications for all the TEST executables.
#
# ====================================================================
# Copyright (c) 2009 Ian Blumel. All rights reserved.
#
# This software is licensed as described in the file LICENSE, which
# you should have received as part of this distribution.
# ====================================================================
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/include)
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
MACRO(TO_CPP _NAME_)
ADD_CUSTOM_COMMAND(
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${_NAME_}.cpp
COMMAND ${CMAKE_COMMAND} -E copy
${CMAKE_CURRENT_SOURCE_DIR}/${_NAME_}.c
${CMAKE_CURRENT_BINARY_DIR}/${_NAME_}.cpp
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${_NAME_}.c
)
SET_SOURCE_FILES_PROPERTIES(
${CMAKE_CURRENT_BINARY_DIR}/${_NAME_}.cpp
PROPERTIES GENERATED 1
)
ENDMACRO(TO_CPP)
MACRO(TEST_CPP_VERSION _NAME_)
TO_CPP(${_NAME_})
ADD_EXECUTABLE(${_NAME_}_cpp ${CMAKE_CURRENT_BINARY_DIR}/${_NAME_}.cpp)
ADD_TEST(
run_${_NAME_}_cpp
${EXECUTABLE_OUTPUT_PATH}/${_NAME_}_cpp
)
ADD_TEST(
run_${_NAME_}_cpp
${EXECUTABLE_OUTPUT_PATH}/${_NAME_}_cpp
)
ENDMACRO(TEST_CPP_VERSION)
SET(SIMPLE_TESTS test_1suite
test_basic
test_call_teardown
test_chk_types
test_count
test_fctkern
test_fct_bgn_func
test_fct_xchk2
test_fct_chk_conditional
test_help_logger
test_money
test_multi_old_style
test_quick_test
test_two_names
test_clp
test_conditionals
test_chk
test_empty
test_req_in_setup_teardown
test_start_other_than_main
)
FOREACH( PROGRAM ${SIMPLE_TESTS})
ADD_EXECUTABLE(${PROGRAM} ${PROGRAM}.c)
ENDFOREACH(PROGRAM)
# This requires more than one file and doesn't fall under the "test simple"
# category.
ADD_EXECUTABLE(
test_multi
test_multi.c test_multi_suite1.c test_multi_with_fixtures_suite2.c
)
# This one will always fail.
ADD_EXECUTABLE(test_fail test_fail.c)
# TEST_BIG. This requires generating test_big.c before we can
# build test_big.exe. To generate test_big.c you need to compile
# and execute mkbigtest.c. Here is what is happening below,
#
# 1. First we say to build mkbigtest we need to compile mkbigtest.c
# 2. Then we say to build test_big you need to compile test_big.c
# 3. Then we say, well, to generate a test_big.c file you need to
# run mkbigtest.
# 4. Finally we just make it obvious that to make your test_big you
# need to make your mkbigtest. I tried to set a dependency on
# test_big.c, which seems more natural to me, but CMAKE could not
# locate a target called "test_big.c".
ADD_EXECUTABLE(mkbigtest mkbigtest.c)
ADD_CUSTOM_COMMAND(
OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/test_big.c"
COMMAND mkbigtest
DEPENDS mkbigtest
)
ADD_EXECUTABLE(test_big "${CMAKE_CURRENT_BINARY_DIR}/test_big.c")
# -------
# TESTING
# -------
FOREACH( PROGRAM ${SIMPLE_TESTS})
ADD_TEST(run_${PROGRAM}
${EXECUTABLE_OUTPUT_PATH}/${PROGRAM}
)
ADD_TEST(run_${PROGRAM}_with_junit
${EXECUTABLE_OUTPUT_PATH}/${PROGRAM}
--logger=junit
)
ADD_TEST(run_${PROGRAM}_with_minimal
${EXECUTABLE_OUTPUT_PATH}/${PROGRAM}
--logger=minimal
)
ADD_TEST(run_${PROGRAM}_help
${EXECUTABLE_OUTPUT_PATH}/${PROGRAM}
--help
)
TEST_CPP_VERSION(${PROGRAM})
ENDFOREACH(PROGRAM)
ADD_TEST(run_test_big ${EXECUTABLE_OUTPUT_PATH}/test_big)
ADD_TEST(run_test_call_teardown
${EXECUTABLE_OUTPUT_PATH}/test_call_teardown
)
TO_CPP(test_multi)
TO_CPP(test_multi_suite1)
TO_CPP(test_multi_with_fixtures_suite2)
ADD_EXECUTABLE(test_multi_cpp
${CMAKE_CURRENT_BINARY_DIR}/test_multi.cpp
${CMAKE_CURRENT_BINARY_DIR}/test_multi_suite1.cpp
${CMAKE_CURRENT_BINARY_DIR}/test_multi_with_fixtures_suite2.cpp
)
ADD_TEST(run_test_multi_cpp
${EXECUTABLE_OUTPUT_PATH}/test_multi_cpp
)
# The following tests confirm that failure happens.
ADD_TEST(run_test_fail
${EXECUTABLE_OUTPUT_PATH}/test_fail
)
SET_TESTS_PROPERTIES(run_test_fail PROPERTIES WILL_FAIL 1)
# Test money uses 'strcpy', and its just an example, so lets add a definition
# for that one program.
SET_TARGET_PROPERTIES(test_money
PROPERTIES
COMPILE_DEFINITIONS "_CRT_SECURE_NO_WARNINGS"
)
SET_TARGET_PROPERTIES(test_money_cpp
PROPERTIES
COMPILE_DEFINITIONS "_CRT_SECURE_NO_WARNINGS"
)
# Tests for the custom command line parse involve generating different
# configurations based on a common template file.
MACRO(TEST_COMMAND_LINE NAME USE_FLAG USE_VALUE)
SET(CL_PASSED_IN_VALUE "scooby-doo")
SET(CL_USE_FLAG ${USE_FLAG})
SET(CL_USE_VALUE ${USE_VALUE})
SET(CL_USE_NAME ${NAME})
CONFIGURE_FILE(
test_cl_customize.c.in
${CMAKE_CURRENT_BINARY_DIR}/test_cl_customize_${NAME}.c
)
ADD_EXECUTABLE(test_cl_customize_${NAME}
${CMAKE_CURRENT_BINARY_DIR}/test_cl_customize_${NAME}.c
)
IF(${USE_FLAG})
LIST(APPEND ARGS "--flag")
ENDIF()
IF(${USE_VALUE})
LIST(APPEND ARGS "--value" ${CL_PASSED_IN_VALUE})
ENDIF()
ADD_TEST(test_cl_customize_${NAME}
${EXECUTABLE_OUTPUT_PATH}/test_cl_customize_${NAME}
${ARGS}
)
SET(CL_PASSED_IN_VALUE )
SET(CL_USE_FLAG )
SET(CL_UES_VALUE )
SET(ARGS )
ENDMACRO()
# Truth table the combinations.
TEST_COMMAND_LINE(noflag_novalue 0 0)
TEST_COMMAND_LINE(noflag_value 0 1)
TEST_COMMAND_LINE(flag_novalue 1 0)
TEST_COMMAND_LINE(flag_value 1 1)
# C++ Only
add_executable(test_chk_ex test_chk_ex.cxx)
add_test(test_chk_ex ${EXECUTABLE_OUTPUT_PATH}/test_chk_ex)
/*
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: mkbigtest.c
This file will generate a large "unit tests" file which can be used for
load testing.
*/
/* Keep MicroSoft compilers "quiet". */
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
/* This should define a fairly reasonably large test file. Files with more
unit tests should probably be fragmented. Right now the slow down is
basically the time it takes to compile the file. */
#if defined(WIN32) && _MSC_VER >= 1200
#define MESSAGE ("Visual Studio is crippled trying to compile >256\n"\
"tests. So we are limiting it to %d tests.\n")
#define NUM_TESTS 256
#elif NDEBUG
#define MESSAGE ("Building %d tests, in release. Release spends to much time "\
"optimizing >256 tests, and gcc runs out of memory.\n")
#define NUM_TESTS 256
#else
#define MESSAGE "Building %d tests.\n"
#define NUM_TESTS 1024
#endif
#define TEST_STRING \
"This is a really, really really long string that I thought would"\
"give some meat to the tests. I could even make this longer by adding"\
"more jibberish, but that would probablly be really, really silly."\
"What I should be doing is coming up with a meater test."
#define FILE_NAME "test_big.c"
int
main(int argc, char const *argv[])
{
int test_i =0;
FILE *f = fopen(FILE_NAME, "wt");
(void)argc;
(void)argv;
if ( f == NULL )
{
fprintf(stderr, "unable to open 'test_big.c'");
return 1;
}
printf(MESSAGE, NUM_TESTS);
printf("writing '%s'...", FILE_NAME);
fprintf(f, "/* This file was generated by mkbigtest.c */\n");
fprintf(f, "#include \"fct.h\"\n\n");
fprintf(f, "FCT_BGN() {\n");
fprintf(f, " FCT_SUITE_BGN(big_one) {\n");
for (test_i =0; test_i != NUM_TESTS; ++test_i )
{
fprintf(f, " FCT_TEST_BGN(test_%d) {\n", test_i+1);
/* Want to test something with a wee bit of meat to it. */
fprintf(
f,
" fct_chk(strcmp(\"%s_%d_%s\", \"%s_%d_%s\")==0);\n",
TEST_STRING,
test_i,
TEST_STRING,
TEST_STRING,
test_i,
TEST_STRING
);
fprintf(f, " } FCT_TEST_END();\n");
}
fprintf(f, " } FCT_SUITE_END();\n");
fprintf(f, "} FCT_END();\n");
printf("OK.\n");
fclose(f);
f =NULL;
return 0;
}
/*
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_1suite.c
Runs through 1 test suite. A very simple project for testing the layout
and execution of a test suite.
*/
#include "fct.h"
FCT_BGN()
{
void *data =NULL;
FCT_FIXTURE_SUITE_BGN("1Suite")
{
FCT_SETUP_BGN()
{
data = malloc(sizeof(10));
}
FCT_SETUP_END();
FCT_TEARDOWN_BGN()
{
free(data);
data =NULL;
}
FCT_TEARDOWN_END();
FCT_TEST_BGN("1Test")
{
fct_chk( strcmp("a", "b") != 0 );
}
FCT_TEST_END();
}
FCT_FIXTURE_SUITE_END();
}
FCT_END();
/*
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_basic.c
Provides a dumping ground for basic tests of fct.
*/
#include "fct.h"
FCT_BGN()
{
/* A very simple test suite, it doesn't have any data to
setup/teardown. */
FCT_SUITE_BGN(simple)
{
/* A test, simply check that 1 is still 1. */
FCT_TEST_BGN(simple__one_is_one)
{
fct_chk(1);
}
FCT_TEST_END();
}
FCT_SUITE_END();
/* Test running with a fixture, where we need to setup and
teardown data. */
FCT_FIXTURE_SUITE_BGN(fixture)
{
int a =0;
int b =0;
int c =0;
FCT_SETUP_BGN()
{
a =1;
b =2;
c =3;
}
FCT_SETUP_END();
FCT_TEARDOWN_BGN()
{
a=0;
b=0;
c=0;
}
FCT_TEARDOWN_END();
FCT_TEST_BGN(fixture_long_name_0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789)
{
fct_chk("Verify that long names don't break the logger.");
}
FCT_TEST_END();
FCT_TEST_BGN(fixture__smoke_test)
{
// THE TEST CASE ...
char const *test_str = "test_str";
fct_chk( strcmp(test_str, "test") != 0);
fct_chk( strcmp(test_str, "test_str") == 0);
}
FCT_TEST_END();
FCT_TEST_BGN(fixture__smoke_test_again)
{
fct_chk(1);
fct_chk(a == 1);
fct_chk(b == 2);
fct_chk(c == 3);
}
FCT_TEST_END();
}
FCT_FIXTURE_SUITE_END()
/* A blank suite shouldn't cause a crash. */
FCT_SUITE_BGN(blank)
{
}
FCT_SUITE_END();
/* Test the 'filtering' API */
FCT_SUITE_BGN(filtering)
{
FCT_TEST_BGN(filtering__smoke_test)
{
int ok;
ok = fct_filter_pass("filter", "filter__smoke_test");
fct_chk( ok );
/* This is an automatic pass. */
ok = fct_filter_pass("filter", "filter");
fct_chk( ok );
/* This should fail, since the filter is LONGER than the test
string. */
ok = fct_filter_pass("filter", "fil");
fct_chk( !ok );
ok = fct_filter_pass("filter", "green_eggs_and_ham");
fct_chk( !ok );
ok = fct_filter_pass("filter", "");
fct_chk( !ok );
}
FCT_TEST_END();
FCT_TEST_BGN(filtering__blank_or_null_filter_always_passes)
{
int ok;
ok = fct_filter_pass("", "green_eggs_and_ham");
fct_chk( ok );
ok = fct_filter_pass(NULL, "green_eggs_and_ham");
fct_chk( ok );
}
FCT_TEST_END();
FCT_TEST_BGN(filtering__last_character_truncated)
{
/* See bug #499089 */
int ok;
ok = fct_filter_pass("aaaa", "aaab");
fct_chk( !ok );
}
FCT_TEST_END();
}
FCT_SUITE_END();
FCT_SUITE_BGN(test_64bit)
{
FCT_TEST_BGN(test_64bit__dont_truncate)
{
#if defined(WIN32)
__int64 sixfourval =0;
#else
unsigned long long sixfourval =0;
#endif
/* G++ compilers want to see the LLU (long long unsigned)
tag at the of the variable, Microsoft compilers are sad when
they see this. */
#if defined(_MSC_VER)
# define BACK_VAL 0x00000000ffffffff
# define FRONT_VAL 0xffffffff00000000
#else
# define BACK_VAL 0x00000000ffffffffLLU
# define FRONT_VAL 0xffffffff00000000LLU
#endif
int tv;
int is_checked =0;
sixfourval = BACK_VAL;
tv = (int)sixfourval;
/* Check the truncation and actual value. We
may or may not be truncated, depends on endianess. */
if ( !tv )
{
fct_chk(sixfourval);
is_checked =1;
}
sixfourval = FRONT_VAL;
tv = (int)sixfourval;
if ( !tv )
{
fct_chk(sixfourval);
is_checked =1;
}
fct_chk(is_checked);
}
FCT_TEST_END();
}
FCT_SUITE_END();
}
FCT_END();
/*
====================================================================
Copyright (c) 2009 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_call_teardown.c
Checks that the teardown function is executed (bug #382628).
*/
#include "fct.h"
FCT_BGN()
{
/* This value is incremented during the setup, then incremented in the
first test, it is finally decremented in the last test. Thus in the next
test suite I can test for a value of 1. */
int reference =0;
FCT_FIXTURE_SUITE_BGN("1Suite")
{
FCT_SETUP_BGN()
{
reference++;
}
FCT_SETUP_END();
FCT_TEARDOWN_BGN()
{
reference--;
}
FCT_TEARDOWN_END();
FCT_TEST_BGN(__dummy__)
{
reference++;
}
FCT_TEST_END();
}
FCT_FIXTURE_SUITE_END();
FCT_SUITE_BGN(check_teardown)
{
FCT_TEST_BGN(check_reference_count)
{
fct_chk( reference == 1 );
}
FCT_TEST_END();
}
FCT_SUITE_END();
}
FCT_END();
/*
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_basic.c
Test the Check Routines, make sure they are doing what they are supposed to do.
*/
#include "fct.h"
FCT_BGN()
{
int chk_cnt=0;
int req_cnt=0;
FCT_FIXTURE_SUITE_BGN(chk_versus_req)
{
FCT_SETUP_BGN()
{
} FCT_SETUP_END();
FCT_TEARDOWN_BGN()
{
} FCT_TEARDOWN_END();
FCT_TEST_BGN(test_chk)
{
/* The 'chk' variant should not quite the code block,
and instead should continue testing. */
fct_chk( 1 ); /* Should pass */
chk_cnt += 1;
fct_chk( 0 ); /* Fail */
chk_cnt += 1;
fct_chk( 1 ); /* Pas */
chk_cnt += 1;
/* chk_cnt should be 3 since all lines execute. */
}
FCT_TEST_END();
FCT_TEST_BGN(test_chk_not_aborted)
{
fct_chk( chk_cnt == 3 );
}
FCT_TEST_END();
FCT_TEST_BGN(test_req)
{
fct_req( 1 ); /* Should pass */
req_cnt += 1;
fct_req( 0 ); /* Fail */
req_cnt += 1; /* Should not executed past here... */
fct_req( 1 ); /* Pass */
req_cnt += 1;
}
FCT_TEST_END();
FCT_TEST_BGN(test_req_aborted)
{
fct_chk(req_cnt == 1);
}
FCT_TEST_END();
}
FCT_FIXTURE_SUITE_END();
printf("\n***TESTS ARE SUPPOSED TO REPORT FAILURES***\n");
FCT_EXPECTED_FAILURES(2);
}
FCT_END();
/*
====================================================================
Copyright (c) 2011 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_chk_ex.cxx
*/
#include "fct.h"
class err_t {};
class sub_err_t : public err_t {};
class other_err_t {};
static void throw_err() {
throw err_t();
}
static void throw_sub_err() {
throw sub_err_t();
}
static void throw_other_err() {
throw other_err_t();
}
static void not_going_to_throw() {
int j = 2+1;
char buf[32];
fct_snprintf(buf, sizeof(buf), "j=%d", j);
}
FCT_BGN()
{
FCT_QTEST_BGN(throw_err) {
fct_chk_ex(
err_t&,
throw_err()
);
} FCT_QTEST_END();
FCT_QTEST_BGN(throw_and_catch_sub_err) {
fct_chk_ex(
sub_err_t&,
throw_sub_err()
);
} FCT_QTEST_END();
FCT_QTEST_BGN(throw_and_catch_other_err__should_fail) {
/* This is checking for an exception of type "sub_err_t", but
doesn't get it. Should fail! */
fct_chk_ex(
sub_err_t&,
throw_other_err()
);
} FCT_QTEST_END();
FCT_QTEST_BGN(doesnt_throw) {
/* This is expecting the function to throw an error, but it
doesn't. */
fct_chk_ex(
err_t&,
not_going_to_throw();
);
} FCT_QTEST_END();
printf("\n***TESTS ARE SUPPOSED TO REPORT FAILURES***\n");
FCT_EXPECTED_FAILURES(2);
}
FCT_END();
/*
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_chk_types.c
*/
#include <float.h>
#include <math.h>
#include "fct.h"
/* My Own Type. */
typedef struct _point_t
{
float x,y,z;
} point_t;
#define point_is_eq(p1, p2, ep) \
((int)(fabs(p1.x - p2.x) < ep)) &&\
((int)(fabs(p1.y - p2.y) < ep)) &&\
((int)(fabs(p1.z - p2.z) < ep))
#define point_chk_eq(p1, p2, ep) \
fct_xchk(\
point_is_eq(p1, p2, ep), \
"failed point_is_equal:\n<Point x=%f y=%f z=%f>"\
" !=\n<Point x=%f y=%f z=%f>",\
p1.x, p1.y, p1.z, p2.x, p2.y, p2.z\
);
#define point_is_neq(p1, p2, ep) \
(!(int)(fabs(p1.x - p2.x) < ep)) ||\
(!(int)(fabs(p1.y - p2.y) < ep)) ||\
(!(int)(fabs(p1.z - p2.z) < ep))
#define point_chk_neq(p1, p2, ep) \
fct_xchk(\
point_is_neq(p1, p2, ep), \
"failed point_chk_neq:\n<Point x=%f y=%f z=%f>"\
" ==\n<Point x=%f y=%f z=%f>",\
p1.x, p1.y, p1.z, p2.x, p2.y, p2.z\
);
FCT_BGN()
{
FCT_QTEST_BGN(chk_dbl_eq)
{
fct_chk_eq_dbl(6123.2313,6123.2313);
}
FCT_QTEST_END();
FCT_QTEST_BGN(chk_dbl_neq)
{
fct_chk_neq_dbl(1.11111, 1.1);
}
FCT_QTEST_END();
FCT_QTEST_BGN(chk_str_eq)
{
fct_chk_eq_str("a", "a");
fct_chk_eq_str(NULL, NULL);
fct_chk_eq_str("boo", "boo");
}
FCT_QTEST_END();
FCT_QTEST_BGN(chk_neq_str)
{
fct_chk_neq_str("a", "b");
fct_chk_neq_str(NULL, "b");
fct_chk_neq_str("a", NULL);
fct_chk_neq_istr("different", "differentlengths");
fct_chk_neq_istr("differentlengths", "different");
}
FCT_QTEST_END();
FCT_QTEST_BGN(chk_eq_istr)
{
fct_chk_eq_istr("mismatch", "misMatch");
fct_chk_eq_istr("a", "a");
fct_chk_eq_istr("A", "a");
fct_chk_eq_istr(NULL, NULL);
}
FCT_QTEST_END();
FCT_QTEST_BGN(chk_neq_istr)
{
fct_chk_neq_istr("mismatch", "misMatchLength");
fct_chk_neq_istr("misMatchLength", "mismatch");
fct_chk_neq_istr("a", "b");
fct_chk_neq_istr("A", "b");
fct_chk_neq_istr(NULL, "b");
fct_chk_neq_istr("A", NULL);
}
FCT_QTEST_END();
/* ---------------------------------------------------------- */
FCT_QTEST_BGN(chk_incl_str)
{
fct_chk_incl_str("mr roboto is super", "roboto");
fct_chk_incl_str("mr ROBOTO is super", "ROBOTO");
fct_chk_incl_str(NULL, NULL); /* NULL includes NULL */
fct_chk_incl_str("mr roboto", NULL);
fct_chk_incl_str("a", "a");
fct_chk_incl_str("b", NULL);
fct_chk_incl_str("mr roboto", "");
fct_chk_incl_str("", "");
fct_chk_incl_str("", NULL);
}
FCT_QTEST_END();
/* ---------------------------------------------------------- */
FCT_QTEST_BGN(chk_incl_istr)
{
/* All the case sensitive tests should pass. */
fct_chk_incl_istr("mr roboto is super", "roboto");
fct_chk_incl_istr("mr ROBOTO is super", "ROBOTO");
fct_chk_incl_istr(NULL, NULL); /* NULL includes NULL */
fct_chk_incl_istr("mr roboto", NULL);
fct_chk_incl_istr("a", "a");
fct_chk_incl_istr("b", NULL);
fct_chk_incl_istr("mr roboto", "");
fct_chk_incl_istr("", "");
fct_chk_incl_istr("", NULL);
fct_chk_incl_istr("MR RoboTO", "RoBOtO");
}
FCT_QTEST_END();
/* ---------------------------------------------------------- */
FCT_QTEST_BGN(chk_excl_str)
{
fct_chk_excl_str("mr roboto", "ta");
fct_chk_excl_str("a", "b");
}
FCT_QTEST_END();
/* ---------------------------------------------------------- */
FCT_QTEST_BGN(chk_excl_istr)
{
fct_chk_excl_istr("mr ROboto", "ta");
fct_chk_excl_istr("a", "b");
}
FCT_QTEST_END();
/* ---------------------------------------------------------- */
FCT_QTEST_BGN(chk_startswith_str)
{
fct_chk_startswith_str("mr ROboto", "mr");
fct_chk_startswith_str(NULL, NULL);
fct_chk_startswith_str("", "");
}
FCT_QTEST_END();
/* ---------------------------------------------------------- */
FCT_QTEST_BGN(chk_startswith_istr)
{
fct_chk_startswith_istr("Mr ROboto", "mr");
fct_chk_startswith_istr(NULL, NULL);
fct_chk_startswith_istr("", "");
}
FCT_QTEST_END();
/* ---------------------------------------------------------- */
FCT_QTEST_BGN(chk_endswith_str)
{
fct_chk_endswith_str("Mr ROboto", "ROboto");
fct_chk_endswith_str(NULL, NULL);
fct_chk_endswith_str("", "");
}
FCT_QTEST_END();
/* ---------------------------------------------------------- */
FCT_QTEST_BGN(chk_iendswith_str)
{
fct_chk_iendswith_str("Mr ROboto", "roboto");
fct_chk_iendswith_str(NULL, NULL);
fct_chk_iendswith_str("", "");
}
FCT_QTEST_END();
/* ---------------------------------------------------------- */
FCT_QTEST_BGN(chk_eq_int)
{
fct_chk_eq_int(1, 1);
fct_chk_eq_int(-1, -1);
fct_chk_eq_int(0, 0);
}
FCT_QTEST_END();
/* ---------------------------------------------------------- */
FCT_QTEST_BGN(chk_str_empty)
{
fct_chk_empty_str("");
fct_chk_empty_str(NULL);
}
FCT_QTEST_END();
/* ---------------------------------------------------------- */
FCT_QTEST_BGN(chk_str_full)
{
fct_chk_full_str(" ");
fct_chk_full_str("mr roboto");
}
FCT_QTEST_END();
/* ---------------------------------------------------------- */
FCT_QTEST_BGN(chk_neq_int)
{
fct_chk_neq_int(1, 2);
fct_chk_neq_int(0, -1);
fct_chk_neq_int(-1, 2);
}
FCT_QTEST_END();
FCT_QTEST_BGN(chk_my_point)
{
point_t point1 = {1.f, 2.f, 3.f};
point_t point2 = {1.f, 2.f, 3.f};
point_t point3 = {10.f, 20.f, 30.f};
point_chk_eq(point1, point2, DBL_EPSILON);
point_chk_neq(point1, point3, DBL_EPSILON);
}
FCT_QTEST_END();
}
FCT_END();
/*
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
WARNING: This file is autogenerated from a template "test_cl_customize.c.in",
you may or may not want to edit this file.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Testing the custom command line parser. This file is a template file for
handling different configurations. We need to be able to test with and without
a configuration setting and the easiest way to do this is to generate different
files.
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_cl_customize.c.in
*/
#include "fct.h"
static fctcl_init_t my_options[] = {
{"--flag", "-f", FCTCL_STORE_TRUE, "Test boolean flag."},
{"--value", "-v", FCTCL_STORE_VALUE, "Test store value."},
FCTCL_INIT_NULL
};
/* Configuration settings configured by cmake. */
#cmakedefine CL_USE_FLAG
#cmakedefine CL_USE_VALUE
#define CL_PASSED_IN_VALUE "@CL_PASSED_IN_VALUE@"
#define CL_USE_NAME "@CL_USE_NAME@"
FCT_BGN()
{
int g_is_flag =-1;
char const *g_value =NULL;
fctcl_install(my_options);
/* Want to make sure a parse happens AFTER the my_options. */
g_is_flag = fctcl_is("--flag");
g_value = fctcl_val("--value");
/* -------------------------------------------------------------------- */
FCT_QTEST_BGN(test_flag) {
int is_flag = fctcl_is("--flag");
#if defined(CL_USE_FLAG)
fct_chk( is_flag );
fct_chk( g_is_flag );
#else
fct_chk( !is_flag);
fct_chk( !g_is_flag );
#endif /* CL_USE_FLAG */
} FCT_QTEST_END();
/* -------------------------------------------------------------------- */
FCT_QTEST_BGN(test_value) {
char const *val = fctcl_val2("--value", NULL);
#if defined(CL_USE_VALUE)
fct_chk_eq_str(val, CL_PASSED_IN_VALUE);
fct_chk_eq_str(g_value, CL_PASSED_IN_VALUE);
#else
fct_chk_neq_str(val, CL_PASSED_IN_VALUE);
fct_chk_neq_str(g_value, CL_PASSED_IN_VALUE);
#endif /* CL_USE_VALUE */
} FCT_QTEST_END();
/* -------------------------------------------------------------------- */
FCT_QTEST_BGN(test_value_def_string) {
#define DEFAULT_STRING "default_string"
char const *val = fctcl_val2("--value", DEFAULT_STRING);
#if defined(CL_USE_VALUE)
fct_chk_eq_str(val, CL_PASSED_IN_VALUE);
fct_chk_eq_str(g_value, CL_PASSED_IN_VALUE);
#else
fct_chk_eq_str(val, DEFAULT_STRING);
/* Here we need to test that value is NULL, since we acquire the
global value via the fctcl_val function, not the v2 variant that
accepts a default value. */
fct_chk( g_value == NULL );
#endif /* CL_USE_VALUE */
} FCT_QTEST_END();
}
FCT_END();
/*
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_clp.c
Runs through tests for the command line parser.
*/
#include "fct.h"
/* Test Data */
fct_clp_t clp;
fctcl_init_t options[] =
{
/* The "casting to char*" is bad mojo here. But until I
grow a "fctcl_init_t" object with constants, it will
do to quiet down C++. It turns out that you never delete
this data, so it is OK to cast it to a char*. */
{
"--help",
"-h",
FCTCL_STORE_TRUE,
"Shows this message"
},
{
"--output",
NULL,
FCTCL_STORE_VALUE,
"Name of file to store output."
},
FCTCL_INIT_NULL /* Sentinel. */
};
FCT_BGN()
{
FCT_FIXTURE_SUITE_BGN(clp__parse_scenarios)
{
FCT_SETUP_BGN()
{
fct_clp__init(&clp, options);
}
FCT_SETUP_END();
FCT_TEARDOWN_BGN()
{
fct_clp__final(&clp);
}
FCT_TEARDOWN_END();
FCT_TEST_BGN(initialization)
{
fct_chk_eq_int( fct_clp__num_clo(&clp), 2);
}
FCT_TEST_END();
FCT_TEST_BGN(parse_nothing)
{
char const *test_argv[] = {"program.exe" };
int test_argc =1;
fct_clp__parse(&clp, test_argc, test_argv);
fct_chk( !fct_clp__is(&clp, "--help") );
fct_chk( !fct_clp__is(&clp, "--output") );
}
FCT_TEST_END();
FCT_TEST_BGN(parse_store_true)
{
char const *test_argv[] = {"program.exe", "--help"};
int test_argc =2;
fct_clp__parse(&clp, test_argc, test_argv);
fct_chk( fct_clp__is(&clp, "--help") );
fct_chk( !fct_clp__is(&clp, "--output") );
}
FCT_TEST_END();
FCT_TEST_BGN(parse_store_true__short_arg)
{
char const *test_argv[] = {"program.exe", "-h"};
int test_argc =2;
fct_clp__parse(&clp, test_argc, test_argv);
fct_chk( fct_clp__is(&clp, "--help") );
fct_chk( fct_clp__is(&clp, "-h") );
fct_chk( !fct_clp__is(&clp, "--output") );
}
FCT_TEST_END();
FCT_TEST_BGN(parse_store_value__with_2nd_arg)
{
char const *test_argv[] = {"program.exe", "--output", "foo"};
int test_argc =3;
fct_clp__parse(&clp, test_argc, test_argv);
fct_chk( !fct_clp__is(&clp, "--help") );
fct_chk( fct_clp__is(&clp, "--output") );
fct_chk_eq_str(fct_clp__optval(&clp, "--output"), "foo");
}
FCT_TEST_END();
FCT_TEST_BGN(parse_store_value__with_equals)
{
char const *test_argv[] = {"program.exe", "--output=foo"};
int test_argc =2;
fct_clp__parse(&clp, test_argc, test_argv);
fct_chk( !fct_clp__is(&clp, "--help") );
fct_chk( fct_clp__is(&clp, "--output") );
fct_chk_eq_str(fct_clp__optval(&clp, "--output"), "foo");
}
FCT_TEST_END();
FCT_TEST_BGN(parse_store_value__with_equals_but_no_value)
{
char const *test_argv[] = {"program.exe", "--output="};
int test_argc =2;
fct_clp__parse(&clp, test_argc, test_argv);
fct_chk( fct_clp__is_error(&clp) );
fct_chk( !fct_clp__is(&clp, "--help") );
fct_chk( !fct_clp__is(&clp, "--output") );
}
FCT_TEST_END();
FCT_TEST_BGN(parse_store_value__without_2nd_arg)
{
char const *test_argv[] = {"program.exe", "--output"};
int test_argc =2;
fct_clp__parse(&clp, test_argc, test_argv);
fct_chk( fct_clp__is_error(&clp) );
fct_chk( !fct_clp__is(&clp, "--help") );
fct_chk( !fct_clp__is(&clp, "--output") );
}
FCT_TEST_END();
FCT_TEST_BGN(parse__check_for_invalid_value)
{
char const *test_argv[] = {"program.exe", "--output"};
int test_argc =2;
fct_clp__parse(&clp, test_argc, test_argv);
fct_chk( !fct_clp__is(&clp, "--booga") );
fct_chk( fct_clp__optval(&clp, "--booga") == NULL );
}
FCT_TEST_END();
FCT_TEST_BGN(parse_store_value__with_multiple_args)
{
char const *test_argv[] = {"program.exe", "--output", "foo", "--help"};
int test_argc =4;
fct_clp__parse(&clp, test_argc, test_argv);
fct_chk( fct_clp__is(&clp, "--help") );
fct_chk( fct_clp__is(&clp, "--output") );
fct_chk_eq_str(fct_clp__optval(&clp, "--output"), "foo");
}
FCT_TEST_END();
FCT_TEST_BGN(parse_store_value__with_multiple_args_diff_order)
{
char const *test_argv[] = {"program.exe", "--help", "--output", "xxx"};
int test_argc =4;
fct_clp__parse(&clp, test_argc, test_argv);
fct_chk( fct_clp__is(&clp, "--help") );
fct_chk( fct_clp__is(&clp, "--output") );
fct_chk_eq_str(fct_clp__optval(&clp, "--output"), "xxx");
}
FCT_TEST_END();
FCT_TEST_BGN(parse_store_value__with_params_only)
{
char const *test_argv[] = {"program.exe",
"parama",
"paramb",
"paramc"
};
int test_argc =4;
int is_error =0;
int param_cnt =0;
fct_clp__parse(&clp, test_argc, test_argv);
is_error = fct_clp__is_error(&clp);
fct_chk( !is_error );
param_cnt = fct_clp__param_cnt(&clp);
fct_chk_eq_int( param_cnt, 3);
fct_chk( fct_clp__is_param(&clp, "parama") );
fct_chk( !fct_clp__is_param(&clp, "funk") );
fct_chk( fct_clp__is_param(&clp, "paramb") );
fct_chk( fct_clp__is_param(&clp, "paramc") );
}
FCT_TEST_END();
FCT_TEST_BGN(parse_store_value__with_params_and_a_flag)
{
char const *test_argv[] = {"program.exe",
"--output=foo",
"parama",
"paramb",
"paramc"
};
int test_argc =5;
char const *optval;
char const *paramat;
fct_clp__parse(&clp, test_argc, test_argv);
fct_chk( !fct_clp__is_error(&clp) );
fct_chk_eq_int( fct_clp__param_cnt(&clp), 3);
fct_chk( fct_clp__is_param(&clp, "parama") );
fct_chk( !fct_clp__is_param(&clp, "funk") );
fct_chk( fct_clp__is_param(&clp, "paramb") );
fct_chk( fct_clp__is_param(&clp, "paramc") );
/* Parameters should be in same sequence. Not neccessarily
going to enforce this, just using the assumption for testing. */
paramat = fct_clp__param_at(&clp, 0);
fct_chk_eq_str( paramat, "parama");
paramat = fct_clp__param_at(&clp, 1);
fct_chk_eq_str( paramat, "paramb");
paramat = fct_clp__param_at(&clp, 2);
fct_chk_eq_str( paramat, "paramc");
fct_chk( fct_clp__is(&clp, "--output") );
optval = fct_clp__optval(&clp, "--output");
fct_chk_eq_str( optval, "foo" );
}
FCT_TEST_END();
}
FCT_FIXTURE_SUITE_END();
}
FCT_END();
/*
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_1suite.c
Tests that the conditionals are working correctly. Runs through a bunch of
tests to see if certain flags where set, if they where done corrrectly then the
subsequent "real" unit test will work just fine.
*/
#include "fct.h"
FCT_BGN()
{
int true_condition =1;
int false_condition =0;
int is_test_suite_fixture_if_true =0;
int is_test_suite_fixture_if_false =0;
int is_test_suite_if_true =0;
int is_test_suite_if_false =0;
int is_qtest_if_true =0;
int is_qtest_if_false =0;
int is_test_if_true =0;
int is_test_if_false =0;
/* ------------------------------------------------------------- */
FCT_FIXTURE_SUITE_BGN_IF(true_condition, test_suite_if_true)
{
FCT_SETUP_BGN()
{
} FCT_SETUP_END();
FCT_TEARDOWN_BGN()
{
} FCT_TEARDOWN_END();
FCT_TEST_BGN(run_fixture_test_if_true)
{
is_test_suite_fixture_if_true =1;
}
FCT_TEST_END();
}
FCT_FIXTURE_SUITE_END_IF();
FCT_FIXTURE_SUITE_BGN_IF(false_condition, test_suite_if_false)
{
FCT_SETUP_BGN()
{
} FCT_SETUP_END();
FCT_TEARDOWN_BGN()
{
} FCT_TEARDOWN_END();
FCT_TEST_BGN(run_fixture_test_if_false)
{
is_test_suite_fixture_if_false =1;
}
FCT_TEST_END();
}
FCT_FIXTURE_SUITE_END_IF();
/* ------------------------------------------------------------- */
FCT_SUITE_BGN_IF(true_condition, test_suite_if_true)
{
FCT_TEST_BGN(run_test_if_true)
{
is_test_suite_if_true =1;
}
FCT_TEST_END();
}
FCT_SUITE_END_IF();
FCT_SUITE_BGN_IF(false_condition, test_suite_if_false)
{
FCT_TEST_BGN(run_test_if_false)
{
is_test_suite_if_false =1;
}
FCT_TEST_END();
}
FCT_SUITE_END_IF();
/* ------------------------------------------------------------- */
FCT_QTEST_BGN_IF(true_condition, test_qtest_if_true)
{
is_qtest_if_true = 1;
}
FCT_QTEST_END_IF();
FCT_QTEST_BGN_IF(false_condition, test_qtest_if_false)
{
is_qtest_if_false = 1;
}
FCT_QTEST_END_IF();
/* ------------------------------------------------------------- */
FCT_SUITE_BGN(test_if_true)
{
FCT_TEST_BGN_IF(true_condition, run_test_if_true)
{
is_test_if_true =1;
}
FCT_TEST_END_IF();
}
FCT_SUITE_END_IF();
FCT_SUITE_BGN(test_if_false)
{
FCT_TEST_BGN_IF(false_condition, run_test_if_false)
{
is_test_if_false =1;
}
FCT_TEST_END_IF();
}
FCT_SUITE_END();
/* ------------------------------------------------------------- */
puts("--- Confirm Conditionals Worked -- \n");
FCT_QTEST_BGN(confirm_conditionals__fixture_suite)
{
fct_chk( is_test_suite_fixture_if_true );
fct_chk( !is_test_suite_fixture_if_false );
}
FCT_QTEST_END();
FCT_QTEST_BGN(confirm_conditionals__nofixture_suite)
{
fct_chk( is_test_suite_if_true );
fct_chk( !is_test_suite_if_false );
}
FCT_QTEST_END();
FCT_QTEST_BGN(confirm_conditionals__qtest)
{
fct_chk( is_qtest_if_true );
fct_chk( !is_qtest_if_false );
}
FCT_QTEST_END();
FCT_QTEST_BGN(confirm_conditionals__test)
{
fct_chk( is_test_if_true );
fct_chk( !is_test_if_false );
}
FCT_QTEST_END();
}
FCT_END();
/*
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
Tests "counting" of various elements of a unit test framework. For
example the number of tests, the number of checks, &etc.
TODO - Run this in verbose mode. This is currently waiting for
the verbose mode to be released.
*/
/* To activate some "gut check" functions that are not used normally. */
#define FCT_USE_TEST_COUNT
#include "fct.h"
FCT_BGN()
{
/* An empty test suite that doesn't have any tests within
it, then confirm that at our count is still zero. */
FCT_SUITE_BGN(empty)
{
}
FCT_SUITE_END();
_FCT_GUTCHK(fctkern__tst_cnt(fctkern_ptr__) == 0);
/* Now run a suite again, but place one test in it. Then confirm with
our gut check. */
FCT_SUITE_BGN(one_test)
{
FCT_TEST_BGN(check_one_test)
{
}
FCT_TEST_END();
}
FCT_SUITE_END();
_FCT_GUTCHK(fctkern__tst_cnt(fctkern_ptr__) == 1);
_FCT_GUTCHK(fctkern__chk_cnt(fctkern_ptr__) == 0);
/* Now again, but with two checks. The gut check should return 3 for the
number of tests. */
FCT_SUITE_BGN(one_test_again)
{
FCT_TEST_BGN(check_one_test_again)
{
fct_chk(1);
fct_chk(1);
}
FCT_TEST_END();
}
FCT_SUITE_END();
_FCT_GUTCHK(fctkern__tst_cnt(fctkern_ptr__) == 2);
_FCT_GUTCHK(fctkern__chk_cnt(fctkern_ptr__) == 2);
}
FCT_END();
/*
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_req_in_setup_teardown.c
Test compiling a 'blank' unit test.
*/
#include "fct.h"
FCT_BGN()
{
} FCT_END();
/*
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_fail.c
This code is designed to fail. It runs tests to confirm that failure conditions are failing properly.
*/
#include "fct.h"
FCT_BGN()
{
/* A very simple test suite, it doesn't have any data to
setup/teardown. */
FCT_SUITE_BGN(should_fail)
{
/* A test, simply check that 1 is still 1. */
FCT_TEST_BGN(false is fail)
{
fct_chk(0);
}
FCT_TEST_END();
}
FCT_SUITE_END();
}
FCT_END();
/*
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_fct_bgn_func.c
*/
#include "fct.h"
FCT_BGN_FN(function_entry)
{
FCT_QTEST_BGN(test_func)
{
fct_chk(1);
}
FCT_QTEST_END();
}
FCT_END_FN();
int main(int argCount, char *argVariables[])
{
/* We could supply our own argc, argv, but for testing purposes
supplying the standard ones are OK. */
return function_entry(argCount, argVariables);
}
/*
====================================================================
Copyright (c) 2010 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_fct_chk_conditional.c
This code is designed to fail. It runs tests to confirm that failure conditions are failing properly.
*/
#include "fct.h"
FCT_BGN()
{
FCT_QTEST_BGN(fct_chk_if)
{
if ( fct_chk(1) )
{
fct_chk(1);
}
}
FCT_QTEST_END();
FCT_QTEST_BGN(fct_xchk_if)
{
if ( fct_xchk(1, "") )
{
fct_chk(1);
}
}
FCT_QTEST_END();
}
FCT_END();
/*
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_fct_xchk2
*/
#include "fct.h"
FCT_BGN()
{
FCT_QTEST_BGN(three_names)
{
const char *test_names[] =
{
"test_1",
"test_2",
"test_3",
NULL
};
const char **itr;
for ( itr = test_names; *itr != NULL; ++itr )
{
fct_xchk2(
*itr,
1,
"always succeed"
);
}
}
FCT_QTEST_END();
}
FCT_END();
/*
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_fctkern.c
Tests for the fct kern(al) object.
*/
#include "fct.h"
FCT_BGN()
{
FCT_QTEST_BGN(fctkern_test_add_prefix_filter)
{
/* See bug #499089 */
char const *argv_dummy[] = {"test"};
int argc_dummy = 1;
fctkern_t k;
fctkern__init(&k, argc_dummy, argv_dummy);
fctkern__add_prefix_filter(&k, "aaaa");
fct_chk( fctkern__filter_cnt(&k) == 1 );
fct_chk( fctkern__pass_filter(&k, "aaaa") );
fct_chk( !fctkern__pass_filter(&k, "aaab") );
}
FCT_QTEST_END();
}
FCT_END();
/*
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_basic.c
Tries to catch a segmentation fault that occurs with a simple test case,
and invoking the --help option. First reported by RhysU.
*/
#include "fct.h"
FCT_BGN()
{
FCT_QTEST_BGN(debug)
{
fct_chk(1);
}
FCT_QTEST_END();
}
FCT_END();
/*
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_money.c
Emulates the testing a "Money" class. This is an example of testing
with something that is a little more "Real World". At least it
corresponds to the oft written about class.
This is build from the "JUnit Test Infected: Programmers Love Writing
Tests" paper found at the following URL,
http://junit.sourceforge.net/doc/testinfected/testing.htm.
*/
/* Include the FCT Unit Test framework. */
#include "fct.h"
/*
-----------------------------------------------------------------------
MONEY
-----------------------------------------------------------------------
Defines a "Simple" money object.
*/
/* Any currency "nickname" large than 16 must be a preversion of a
nickname. */
#define MONEY_MAX_CURR_LEN 16
typedef struct _money_t money_t;
struct _money_t
{
int amount;
char currency[MONEY_MAX_CURR_LEN];
};
static void
money__del(money_t *self)
{
if ( self == NULL )
{
return;
}
free(self);
}
static money_t *
money_new(int amount, char const *currency)
{
money_t *self =NULL;
self = (money_t*)calloc(1, sizeof(money_t));
if ( self == NULL )
{
return NULL;
}
strcpy(self->currency, currency);
self->currency[MONEY_MAX_CURR_LEN-1] = '\0';
self->amount = amount;
return self;
}
static int
money__amount(money_t const *self)
{
assert( self != NULL );
return self->amount;
}
/* Returns a reference to the "currency string". Do NOT MODIFY! */
static char const *
money___currency(money_t const *self)
{
assert( self != NULL );
return self->currency;
}
/* Creates a copy of the existing money class. */
static money_t*
money__copy(money_t const *self)
{
money_t *other = money_new(money__amount(self), money___currency(self));
return other;
}
/* Can only add the same currency to the existing currency. If you
want to decrement, use a negative number for now. */
static void
money__add_amt(money_t *self, int amt)
{
assert( self != NULL );
self->amount = self->amount + amt;
}
/* Returns 1 if m1's currency is equal to m2's currency. */
static int
money_curr_eq(money_t const *m1, money_t const *m2)
{
int is_eq =0;
/* Simple case */
if ( m1 == m2 )
{
return 1;
}
/* If money1 XOR money2 are NULL, then we kick out. */
else if ( (m1 == NULL && m2 != NULL) || (m1 != NULL && m2 == NULL) )
{
return 0;
}
is_eq =strcmp(money___currency(m1), money___currency(m2)) ==0;
return is_eq;
}
/* Returns 1 if money1 == money2 */
static int
money_eq(money_t const *money1, money_t const *money2)
{
int is_same_curr =0;
int is_same_amt =0;
/* Are they pointing to the same memory, then they are the same object.
This also catches the case when they are both NULL. */
if ( money1 == money2 )
{
return 1;
}
/* If money1 XOR money2 are NULL, then we kick out. */
if (
(money1 == NULL && money2 != NULL) \
|| (money1 != NULL && money2 == NULL)
)
{
return 0;
}
/* At this point we shouldn't have any NULL money objects. */
assert( money1 != NULL );
assert( money2 != NULL );
is_same_amt = money__amount(money1) == money__amount(money2);
if ( !is_same_amt )
{
return 0;
}
is_same_curr = money_curr_eq(money1, money2);
/* If they are the same currency, and the passed the eariler tests, then
they are the same object. */
return is_same_curr;
}
static money_t*
money_add(money_t const *money1, money_t const *money2)
{
money_t *new_amt =NULL;
assert( money1 != NULL );
assert( money2 != NULL );
/* For now we will ignore "different" currencies, and return an error. */
if ( !money_curr_eq(money1, money2) )
{
return NULL;
}
new_amt = money_new(
money__amount(money1)+money__amount(money2),
money___currency(money1)
);
return new_amt;
}
/*
-----------------------------------------------------------------------
UNIT TESTS
-----------------------------------------------------------------------
*/
FCT_BGN()
{
/* Illustrates a VERY SIMPLE unit test, without a fixture. */
FCT_SUITE_BGN(money_simple)
{
FCT_TEST_BGN(money_new_del__basic)
{
money_t *m = money_new(10, "US");
fct_chk(m != NULL);
money__del(m);
}
FCT_TEST_END();
FCT_TEST_BGN(money_del__with_null)
{
/* Supply NULL to money_del, and make sure it does nothing. */
money__del(NULL);
}
FCT_TEST_END();
FCT_TEST_BGN(money__copy__basic)
{
money_t *m = money_new(10, "USD");
money_t *other =NULL;
fct_chk( m != NULL );
other = money__copy(m);
fct_chk( other != NULL );
fct_chk( money_eq(m, other) );
money__del(other);
money__del(m);
}
FCT_TEST_END();
}
FCT_SUITE_END();
/* Creates a unit with a fixture, to help bootstrap common code between
tests. */
{
/* These objects are common to each test. */
money_t *m12CDN =NULL;
money_t *m14CDN =NULL;
money_t *m7USD =NULL;
FCT_FIXTURE_SUITE_BGN(money_fixture)
{
/* Notice we have a setup and teardown sections in our fixture test
suite. These are used to consturct and destruct our common data
defined above. */
FCT_SETUP_BGN()
{
/* Our common setup procedure. */
m12CDN = money_new(12, "CDN");
m14CDN = money_new(14, "CDN");
m7USD = money_new(7, "USD");
}
FCT_SETUP_END();
FCT_TEARDOWN_BGN()
{
/* Our common cleanup procedure. */
money__del(m12CDN);
m12CDN =NULL;
money__del(m14CDN);
m14CDN =NULL;
}
FCT_TEARDOWN_END();
FCT_TEST_BGN(money__add_amt__simple)
{
money_t *expected = money_new(32, "CDN");
money__add_amt(m14CDN, 18); /* Should be 32 now */
fct_chk( money_eq(m14CDN, expected) );
money__del(expected);
}
FCT_TEST_END();
FCT_TEST_BGN(money_add__simple)
{
money_t *expected = money_new(26, "CDN");
money_t *result = money_add(m12CDN, m14CDN);
fct_chk( money_eq(result, expected) );
money__del(result);
}
FCT_TEST_END();
FCT_TEST_BGN(money_add__diff_currency)
{
money_t *result;
result = money_add(m12CDN, m7USD);
/* Currently not implmented so NULL is returned. We can change
this test later. */
fct_chk( result == NULL );
money__del(result); /* For later */
}
FCT_TEST_END();
FCT_TEST_BGN(money_eq__simple)
{
money_t *m12CDN_prime = money_new(12, "CDN");
fct_chk( !money_eq(m12CDN, NULL) );
fct_chk( money_eq(m12CDN, m12CDN) );
fct_chk( money_eq(m12CDN, m12CDN_prime) );
fct_chk( !money_eq(m12CDN, m14CDN) );
money__del(m12CDN_prime);
}
FCT_TEST_END();
FCT_TEST_BGN(money_curr_eq__simple)
{
fct_chk( !money_curr_eq(m12CDN, m7USD) );
fct_chk( money_curr_eq(m12CDN, m14CDN) );
fct_chk( !money_curr_eq(NULL, m7USD) );
fct_chk( !money_curr_eq(m7USD, NULL) );
fct_chk( money_curr_eq(m12CDN, m12CDN) );
}
FCT_TEST_END();
}
FCT_FIXTURE_SUITE_END();
}
}
FCT_END();
/*
====================================================================
Copyright (c) 2009 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_multi.c
This code is designed to experiment with the "multi-file" support
for the FCT.
This method superscedes the test_mutli_old_style method shown in the other
test example. As it doesn't suffer from some of the foibles in that
method.
*/
#include "fct.h"
/* These no longer do anything, except for the older Visual Studio 6
compiler. */
FCTMF_SUITE_DEF(test_suite1);
FCTMF_SUITE_DEF(test_fixture_suite2);
FCT_BGN()
{
/* This suite is called *OUTSIDE* of this compilation unit. The
pragma's are to tackle a /W4 problem on MVC compilers. */
#if defined(_MSC_VER)
# pragma warning(push, 3)
#endif /* _MSC_VER */
FCTMF_SUITE_CALL(test_suite1);
FCTMF_SUITE_CALL(test_fixture_suite2);
#if defined(_MSC_VER)
# pragma warning(pop)
#endif /* _MSC_VER */
/* Provide a co-existing "embedded" version for completness. */
FCT_SUITE_BGN(test_embedded)
{
FCT_TEST_BGN(test_embedded.zero_is_zero)
{
fct_chk( 0 == 0 );
}
FCT_TEST_END();
}
FCT_SUITE_END();
}
FCT_END();
/*
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_multi_old_style.c
This method is superceded by the test_multi method as this method
suffers from some serious annoying behaviour. Namely your included
files can not themselves INCLUDE any files NOR define any helper
functions.
*/
#include "fct.h"
FCT_BGN()
{
#include "test_multi_old_style_suite_a.h"
#include "test_multi_old_style_suite_b.h"
}
FCT_END();
/*
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_multi_old_style_suite_a.h
*/
#include <string.h>
#include "fct.h"
FCT_SUITE_BGN(multi_a)
{
FCT_TEST_BGN(test_multi_a_1)
{
fct_chk(strcmp("a", "b") != 0);
}
FCT_TEST_END();
FCT_TEST_BGN(test_multi_a_2)
{
fct_chk(strcmp("a", "a") == 0);
}
FCT_TEST_END();
}
FCT_SUITE_END()
/*
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_multi_old_style_suite_b.h
*/
#include <string.h>
#include "fct.h"
FCT_SUITE_BGN(multi_b)
{
FCT_TEST_BGN(test_multi_b_1)
{
fct_chk(strcmp("a", "b") != 0);
}
FCT_TEST_END();
FCT_TEST_BGN(test_multi_b_2)
{
fct_chk(strcmp("a", "a") == 0);
}
FCT_TEST_END();
}
FCT_SUITE_END()
/*
====================================================================
Copyright (c) 2009 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_multi_suite1.c
*/
#include "fct.h"
#include <string.h>
/* Original Multi-file case would fall down on this since it would
end up including a function definition within main() {}. */
static int
streq(char const *c1, char const *c2)
{
return strcmp(c1, c2) ==0;
}
FCTMF_SUITE_BGN(test_suite1)
{
FCT_TEST_BGN(simple__one_is_one)
{
fct_chk(1);
}
FCT_TEST_END();
FCT_TEST_BGN(simple__check_streq)
{
fct_chk(streq("one", "one"));
fct_chk(!streq("one", "two"));
}
FCT_TEST_END();
}
FCTMF_SUITE_END()
/*
====================================================================
Copyright (c) 2009 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_multi_with_fixtures_suite2.c
This file has a test suite with a fixture.
*/
#include "fct.h"
#include <string.h>
/* Original Multi-file case would fall down on this since it would
end up including a function definition within main() {}. */
static int
streq(char const *c1, char const *c2)
{
return strcmp(c1, c2) ==0;
}
FCTMF_FIXTURE_SUITE_BGN(test_fixture_suite2)
{
/* Fixture Variables. */
int count =0;
FCT_SETUP_BGN()
{
++count;
}
FCT_SETUP_END();
FCT_TEARDOWN_BGN()
{
--count;
}
FCT_TEARDOWN_END();
FCT_TEST_BGN(suite2.check_one_is_one)
{
fct_chk(1);
}
FCT_TEST_END();
FCT_TEST_BGN(suite2.check_eq_str)
{
fct_chk( streq("hello", "hello") );
}
FCT_TEST_END();
FCT_TEST_BGN(suite2.check_setup_teardown)
{
/* The count should always be one if the
setup and teardown are doing their job. */
fct_chk( count == 1 );
}
FCT_TEST_END();
}
FCTMF_FIXTURE_SUITE_END();
/*
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_basic.c
Provides a dumping ground for basic tests of fct.
*/
#include "fct.h"
FCT_BGN()
{
int count =0; /* Use this to confirm the quick tests execute. */
FCT_QTEST_BGN(quick)
{
++count;
fct_chk(strcmp("quick", "is quick") != 0);
}
FCT_QTEST_END();
/* Quick should execute before quick_check, thus count should
be 1. */
FCT_QTEST_BGN(quick_check)
{
fct_chk(count == 1);
}
FCT_QTEST_END();
}
FCT_END();
/*
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_req_in_setup_teardown.c
Tests running fct_req within a setup and teardown.
*/
#include "fct.h"
FCT_BGN()
{
int is_abort_setup =1; /* Assume success unless otherwise noted. */
int is_abort_teardown =1;
FCT_FIXTURE_SUITE_BGN(check_in_setup)
{
FCT_SETUP_BGN()
{
fct_req(0 && "cause a failure during setup");
is_abort_setup =0;
}
FCT_SETUP_END();
FCT_TEARDOWN_BGN()
{
} FCT_TEARDOWN_END();
}
FCT_FIXTURE_SUITE_END();
FCT_FIXTURE_SUITE_BGN(check_in_teardown)
{
FCT_SETUP_BGN()
{
} FCT_SETUP_END();
FCT_TEARDOWN_BGN()
{
fct_req(0 && "cause a failure during teardown");
is_abort_teardown =0;
}
FCT_TEARDOWN_END();
}
FCT_FIXTURE_SUITE_END();
FCT_QTEST_BGN(verify_we_aborted_in_setup)
{
fct_chk(is_abort_setup == 1);
}
FCT_QTEST_END();
FCT_QTEST_BGN(verify_we_aborted_in_teardown)
{
fct_chk(is_abort_teardown == 1);
}
FCT_QTEST_END();
printf("\n***TESTS ARE SUPPOSED TO REPORT FAILURES***\n");
FCT_EXPECTED_FAILURES(2);
}
FCT_END();
/*
====================================================================
Copyright (c) 2011 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_start_other_than_main.c
*/
#include "fct.h"
int
_start_test(int argCount, char *argVariables[])
{
FCT_INIT(argCount, argVariables);
FCT_QTEST_BGN(test_with_my_own_func)
{
fct_chk(1);
}
FCT_QTEST_END();
FCT_FINAL();
return FCT_NUM_FAILED();
}
int
main(int argCount, char *argVariables[])
{
return _start_test(argCount, argVariables);
}
/*
====================================================================
Copyright (c) 2008 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_basic.c
Provides a dumping ground for basic tests of fct.
*/
#include "fct.h"
FCT_BGN()
{
/* These test suites share the same name. */
FCT_SUITE_BGN(simple)
{
/* A test, simply check that 1 is still 1. */
FCT_TEST_BGN(simple__one_is_one)
{
fct_chk(1);
}
FCT_TEST_END();
}
FCT_SUITE_END();
FCT_SUITE_BGN(simple)
{
/* A test, simply check that 1 is still 1. */
FCT_TEST_BGN(simple_two_is_two)
{
fct_chk(2);
}
FCT_TEST_END();
}
FCT_SUITE_END();
/* This test has two tests with the same name. */
FCT_SUITE_BGN(same_name_tests)
{
FCT_TEST_BGN(same_name)
{
fct_chk(1);
}
FCT_TEST_END();
FCT_TEST_BGN(same_name)
{
fct_chk(1);
}
FCT_TEST_END();
}
FCT_SUITE_END();
}
FCT_END();
"""Builds the download page based on the released files.
This is just a little helper to execute after building all the release files. It will generate the contents of a wiki page that I can upload to wildbear to finish off a release.
"""
import hashlib
import sys
RELEASE_LISTING = [
'fct.h',
'fctx-doc-%(ver)s.tar.gz',
'fctx-src-%(ver)s.tar.gz',
'patch-%(ver)s.gz',
'README.rst',
'NEWS-%(ver)s',
'diffstat-%(ver)s',
'ChangeLog-%(ver)s'
]
fname_args = {'ver':sys.argv[1]}
print "== %(ver)s (Stable) ==" % (fname_args)
print "||<tablestyle=\"align:right;margin:2em;\">'''Files''' ||<:>'''md5'''||"
for l in RELEASE_LISTING:
m = hashlib.md5()
fname = l % (fname_args)
m.update(open(fname).read())
digest = m.hexdigest()
args = fname_args.copy()
args["fname"] = fname
args["digest"] = digest
print "|| [[http://fctx.wildbearsoftware.com/static/fctx/download/%(ver)s/%(fname)s|%(fname)s]] || %(digest)s ||" % args
print
print
print "=== Release Notes ==="
print
release_lines = open('NEWS-%(ver)s' % args).readlines()
notes = []
start_parse = False
for line in release_lines:
# First underline in first release note section
if line.find(sys.argv[1]) >= 0:
start_parse = True
elif line.startswith("Whats"):
start_parse = False
elif start_parse and not line.startswith("-----"):
notes.append(line)
chunks =[]
chunk =""
for line in notes:
if line.strip().startswith("-"):
if bool(chunk):
chunks.append(chunk + "\n")
chunk = " " + line.replace(" - ", " * ").strip() + " "
else:
chunk += line.strip() + " "
chunks.append(chunk)
print "".join(chunks)
...@@ -30,8 +30,7 @@ ...@@ -30,8 +30,7 @@
# CMake-generated files: # CMake-generated files:
CMakeFiles/ CMakeFiles/
CTestTestFile.cmake *.cmake
cmake_install.cmake
pkg-config/jsoncpp.pc pkg-config/jsoncpp.pc
jsoncpp_lib_static.dir/ jsoncpp_lib_static.dir/
...@@ -45,6 +44,7 @@ jsoncpp_lib_static.dir/ ...@@ -45,6 +44,7 @@ jsoncpp_lib_static.dir/
/src/lib_json/Makefile /src/lib_json/Makefile
/src/test_lib_json/Makefile /src/test_lib_json/Makefile
/src/test_lib_json/jsoncpp_test /src/test_lib_json/jsoncpp_test
*.a
# eclipse project files # eclipse project files
.project .project
......
...@@ -9,8 +9,8 @@ ...@@ -9,8 +9,8 @@
install: install:
# /usr/bin/gcc is 4.6 always, but gcc-X.Y is available. # /usr/bin/gcc is 4.6 always, but gcc-X.Y is available.
- if [ "$CXX" = "g++" ]; then export CXX="g++-4.9" CC="gcc-4.9"; fi - if [ "$CXX" = "g++" ]; then export CXX="g++-4.9" CC="gcc-4.9"; fi
# /usr/bin/clang is our version already, and clang-X.Y does not exist. # /usr/bin/clang has a conflict with gcc, so use clang-X.Y.
#- if [ "$CXX" = "clang++" ]; then export CXX="clang++-3.7" CC="clang-3.7"; fi - if [ "$CXX" = "clang++" ]; then export CXX="clang++-3.5" CC="clang-3.5"; fi
- echo ${PATH} - echo ${PATH}
- ls /usr/local - ls /usr/local
- ls /usr/local/bin - ls /usr/local/bin
...@@ -22,10 +22,14 @@ addons: ...@@ -22,10 +22,14 @@ addons:
apt: apt:
sources: sources:
- ubuntu-toolchain-r-test - ubuntu-toolchain-r-test
- llvm-toolchain-precise-3.5
- george-edison55-precise-backports # cmake 3.2.3
packages: packages:
- cmake
- cmake-data
- gcc-4.9 - gcc-4.9
- g++-4.9 - g++-4.9
- clang - clang-3.5
- valgrind - valgrind
os: os:
- linux - linux
......
# vim: et ts=4 sts=4 sw=4 tw=0 # vim: et ts=4 sts=4 sw=4 tw=0
CMAKE_MINIMUM_REQUIRED(VERSION 2.8.5) CMAKE_MINIMUM_REQUIRED(VERSION 3.1)
PROJECT(jsoncpp) PROJECT(jsoncpp)
ENABLE_TESTING() ENABLE_TESTING()
...@@ -27,20 +27,10 @@ IF(APPLE) ...@@ -27,20 +27,10 @@ IF(APPLE)
SET(CMAKE_MACOSX_RPATH 1) SET(CMAKE_MACOSX_RPATH 1)
ENDIF() ENDIF()
# Adhere to GNU filesystem layout conventions
INCLUDE(GNUInstallDirs)
SET(DEBUG_LIBNAME_SUFFIX "" CACHE STRING "Optional suffix to append to the library name for a debug build") SET(DEBUG_LIBNAME_SUFFIX "" CACHE STRING "Optional suffix to append to the library name for a debug build")
SET(LIB_SUFFIX "" CACHE STRING "Optional arch-dependent suffix for the library installation directory")
SET(RUNTIME_INSTALL_DIR bin
CACHE PATH "Install dir for executables and dlls")
SET(ARCHIVE_INSTALL_DIR lib${LIB_SUFFIX}
CACHE PATH "Install dir for static libraries")
SET(LIBRARY_INSTALL_DIR lib${LIB_SUFFIX}
CACHE PATH "Install dir for shared libraries")
SET(INCLUDE_INSTALL_DIR include
CACHE PATH "Install dir for headers")
SET(PACKAGE_INSTALL_DIR lib${LIB_SUFFIX}/cmake
CACHE PATH "Install dir for cmake package config files")
MARK_AS_ADVANCED( RUNTIME_INSTALL_DIR ARCHIVE_INSTALL_DIR INCLUDE_INSTALL_DIR PACKAGE_INSTALL_DIR )
# Set variable named ${VAR_NAME} to value ${VALUE} # Set variable named ${VAR_NAME} to value ${VALUE}
FUNCTION(set_using_dynamic_name VAR_NAME VALUE) FUNCTION(set_using_dynamic_name VAR_NAME VALUE)
...@@ -69,7 +59,7 @@ ENDMACRO() ...@@ -69,7 +59,7 @@ ENDMACRO()
#SET( JSONCPP_VERSION_MAJOR X ) #SET( JSONCPP_VERSION_MAJOR X )
#SET( JSONCPP_VERSION_MINOR Y ) #SET( JSONCPP_VERSION_MINOR Y )
#SET( JSONCPP_VERSION_PATCH Z ) #SET( JSONCPP_VERSION_PATCH Z )
SET( JSONCPP_VERSION 1.7.7 ) SET( JSONCPP_VERSION 1.8.0 )
jsoncpp_parse_version( ${JSONCPP_VERSION} JSONCPP_VERSION ) jsoncpp_parse_version( ${JSONCPP_VERSION} JSONCPP_VERSION )
#IF(NOT JSONCPP_VERSION_FOUND) #IF(NOT JSONCPP_VERSION_FOUND)
# MESSAGE(FATAL_ERROR "Failed to parse version string properly. Expect X.Y.Z") # MESSAGE(FATAL_ERROR "Failed to parse version string properly. Expect X.Y.Z")
...@@ -86,70 +76,76 @@ CONFIGURE_FILE( "${PROJECT_SOURCE_DIR}/version.in" ...@@ -86,70 +76,76 @@ CONFIGURE_FILE( "${PROJECT_SOURCE_DIR}/version.in"
"${PROJECT_SOURCE_DIR}/version" "${PROJECT_SOURCE_DIR}/version"
NEWLINE_STYLE UNIX ) NEWLINE_STYLE UNIX )
macro(UseCompilationWarningAsError) MACRO(UseCompilationWarningAsError)
if ( MSVC ) IF(MSVC)
# Only enabled in debug because some old versions of VS STL generate # Only enabled in debug because some old versions of VS STL generate
# warnings when compiled in release configuration. # warnings when compiled in release configuration.
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /WX ") SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /WX ")
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") ELSEIF(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror") SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror")
if (JSONCPP_WITH_STRICT_ISO) IF(JSONCPP_WITH_STRICT_ISO)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pedantic-errors") SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pedantic-errors")
endif () ENDIF()
endif() ENDIF()
endmacro() ENDMACRO()
# Include our configuration header # Include our configuration header
INCLUDE_DIRECTORIES( ${jsoncpp_SOURCE_DIR}/include ) INCLUDE_DIRECTORIES( ${jsoncpp_SOURCE_DIR}/include )
if ( MSVC ) IF(MSVC)
# Only enabled in debug because some old versions of VS STL generate # Only enabled in debug because some old versions of VS STL generate
# unreachable code warning when compiled in release configuration. # unreachable code warning when compiled in release configuration.
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /W4 ") SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /W4 ")
endif() ENDIF()
if (CMAKE_CXX_COMPILER_ID MATCHES "Clang") # Require C++11 support, prefer ISO C++ over GNU variants,
# using regular Clang or AppleClang # as relying solely on ISO C++ is more portable.
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall -Wconversion -Wshadow -Werror=conversion -Werror=sign-compare") SET(CMAKE_CXX_STANDARD 11)
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") SET(CMAKE_CXX_STANDARD_REQUIRED ON)
# using GCC SET(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall -Wconversion -Wshadow -Wextra")
# not yet ready for -Wsign-conversion IF(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
# using regular Clang or AppleClang
if (JSONCPP_WITH_STRICT_ISO AND NOT JSONCPP_WITH_WARNING_AS_ERROR) SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wconversion -Wshadow -Werror=conversion -Werror=sign-compare")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror=conversion -pedantic") ELSEIF(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
endif () # using GCC
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Intel") SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wconversion -Wshadow -Wextra")
# using Intel compiler # not yet ready for -Wsign-conversion
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall -Wconversion -Wshadow -Wextra -Werror=conversion")
IF(JSONCPP_WITH_STRICT_ISO AND NOT JSONCPP_WITH_WARNING_AS_ERROR)
if (JSONCPP_WITH_STRICT_ISO AND NOT JSONCPP_WITH_WARNING_AS_ERROR) SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror=conversion -pedantic")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pedantic") ENDIF()
endif () ELSEIF(CMAKE_CXX_COMPILER_ID STREQUAL "Intel")
endif() # using Intel compiler
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wconversion -Wshadow -Wextra -Werror=conversion")
find_program(CCACHE_FOUND ccache)
if(CCACHE_FOUND) IF(JSONCPP_WITH_STRICT_ISO AND NOT JSONCPP_WITH_WARNING_AS_ERROR)
set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE ccache) SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pedantic")
set_property(GLOBAL PROPERTY RULE_LAUNCH_LINK ccache) ENDIF()
endif(CCACHE_FOUND) ENDIF()
FIND_PROGRAM(CCACHE_FOUND ccache)
IF(CCACHE_FOUND)
SET_PROPERTY(GLOBAL PROPERTY RULE_LAUNCH_COMPILE ccache)
SET_PROPERTY(GLOBAL PROPERTY RULE_LAUNCH_LINK ccache)
ENDIF(CCACHE_FOUND)
IF(JSONCPP_WITH_WARNING_AS_ERROR) IF(JSONCPP_WITH_WARNING_AS_ERROR)
UseCompilationWarningAsError() UseCompilationWarningAsError()
ENDIF() ENDIF()
IF(JSONCPP_WITH_PKGCONFIG_SUPPORT) IF(JSONCPP_WITH_PKGCONFIG_SUPPORT)
CONFIGURE_FILE( CONFIGURE_FILE(
"pkg-config/jsoncpp.pc.in" "pkg-config/jsoncpp.pc.in"
"pkg-config/jsoncpp.pc" "pkg-config/jsoncpp.pc"
@ONLY) @ONLY)
INSTALL(FILES "${CMAKE_CURRENT_BINARY_DIR}/pkg-config/jsoncpp.pc" INSTALL(FILES "${CMAKE_CURRENT_BINARY_DIR}/pkg-config/jsoncpp.pc"
DESTINATION "${CMAKE_INSTALL_PREFIX}/lib${LIB_SUFFIX}/pkgconfig") DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig")
ENDIF() ENDIF()
IF(JSONCPP_WITH_CMAKE_PACKAGE) IF(JSONCPP_WITH_CMAKE_PACKAGE)
INSTALL(EXPORT jsoncpp INSTALL(EXPORT jsoncpp
DESTINATION ${PACKAGE_INSTALL_DIR}/jsoncpp DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/jsoncpp
FILE jsoncppConfig.cmake) FILE jsoncppConfig.cmake)
ENDIF() ENDIF()
......
/// Json-cpp amalgated forward header (http://jsoncpp.sourceforge.net/).
/// It is intended to be used with #include "json/json-forwards.h"
/// This header provides forward declaration for all JsonCpp types.
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: LICENSE
// //////////////////////////////////////////////////////////////////////
/*
The JsonCpp library's source code, including accompanying documentation,
tests and demonstration applications, are licensed under the following
conditions...
The author (Baptiste Lepilleur) explicitly disclaims copyright in all
jurisdictions which recognize such a disclaimer. In such jurisdictions,
this software is released into the Public Domain.
In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
released under the terms of the MIT License (see below).
In jurisdictions which recognize Public Domain property, the user of this
software may choose to accept it either as 1) Public Domain, 2) under the
conditions of the MIT License (see below), or 3) under the terms of dual
Public Domain/MIT License conditions described here, as they choose.
The MIT License is about as close to Public Domain as a license can get, and is
described in clear, concise terms at:
http://en.wikipedia.org/wiki/MIT_License
The full text of the MIT License follows:
========================================================================
Copyright (c) 2007-2010 Baptiste Lepilleur
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
========================================================================
(END LICENSE TEXT)
The MIT license is compatible with both the GPL and commercial
software, affording one all of the rights of Public Domain with the
minor nuisance of being required to keep the above copyright notice
and license text in the source code. Note also that by accepting the
Public Domain "license" you can re-license your copy using whatever
license you like.
*/
// //////////////////////////////////////////////////////////////////////
// End of content of file: LICENSE
// //////////////////////////////////////////////////////////////////////
#ifndef JSON_FORWARD_AMALGATED_H_INCLUDED
# define JSON_FORWARD_AMALGATED_H_INCLUDED
/// If defined, indicates that the source file is amalgated
/// to prevent private header inclusion.
#define JSON_IS_AMALGAMATION
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: include/json/config.h
// //////////////////////////////////////////////////////////////////////
// Copyright 2007-2010 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef JSON_CONFIG_H_INCLUDED
#define JSON_CONFIG_H_INCLUDED
#include <stddef.h>
#include <string> //typedef String
#include <stdint.h> //typedef int64_t, uint64_t
/// If defined, indicates that json library is embedded in CppTL library.
//# define JSON_IN_CPPTL 1
/// If defined, indicates that json may leverage CppTL library
//# define JSON_USE_CPPTL 1
/// If defined, indicates that cpptl vector based map should be used instead of
/// std::map
/// as Value container.
//# define JSON_USE_CPPTL_SMALLMAP 1
// If non-zero, the library uses exceptions to report bad input instead of C
// assertion macros. The default is to use exceptions.
#ifndef JSON_USE_EXCEPTION
#define JSON_USE_EXCEPTION 1
#endif
/// If defined, indicates that the source file is amalgated
/// to prevent private header inclusion.
/// Remarks: it is automatically defined in the generated amalgated header.
// #define JSON_IS_AMALGAMATION
#ifdef JSON_IN_CPPTL
#include <cpptl/config.h>
#ifndef JSON_USE_CPPTL
#define JSON_USE_CPPTL 1
#endif
#endif
#ifdef JSON_IN_CPPTL
#define JSON_API CPPTL_API
#elif defined(JSON_DLL_BUILD)
#if defined(_MSC_VER) || defined(__MINGW32__)
#define JSON_API __declspec(dllexport)
#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
#endif // if defined(_MSC_VER)
#elif defined(JSON_DLL)
#if defined(_MSC_VER) || defined(__MINGW32__)
#define JSON_API __declspec(dllimport)
#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
#endif // if defined(_MSC_VER)
#endif // ifdef JSON_IN_CPPTL
#if !defined(JSON_API)
#define JSON_API
#endif
// If JSON_NO_INT64 is defined, then Json only support C++ "int" type for
// integer
// Storages, and 64 bits integer support is disabled.
// #define JSON_NO_INT64 1
#if defined(_MSC_VER) // MSVC
# if _MSC_VER <= 1200 // MSVC 6
// Microsoft Visual Studio 6 only support conversion from __int64 to double
// (no conversion from unsigned __int64).
# define JSON_USE_INT64_DOUBLE_CONVERSION 1
// Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255'
// characters in the debug information)
// All projects I've ever seen with VS6 were using this globally (not bothering
// with pragma push/pop).
# pragma warning(disable : 4786)
# endif // MSVC 6
# if _MSC_VER >= 1500 // MSVC 2008
/// Indicates that the following function is deprecated.
# define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
# endif
#endif // defined(_MSC_VER)
// In c++11 the override keyword allows you to explicity define that a function
// is intended to override the base-class version. This makes the code more
// managable and fixes a set of common hard-to-find bugs.
#if __cplusplus >= 201103L
# define JSONCPP_OVERRIDE override
#elif defined(_MSC_VER) && _MSC_VER > 1600
# define JSONCPP_OVERRIDE override
#else
# define JSONCPP_OVERRIDE
#endif
#ifndef JSON_HAS_RVALUE_REFERENCES
#if defined(_MSC_VER) && _MSC_VER >= 1600 // MSVC >= 2010
#define JSON_HAS_RVALUE_REFERENCES 1
#endif // MSVC >= 2010
#ifdef __clang__
#if __has_feature(cxx_rvalue_references)
#define JSON_HAS_RVALUE_REFERENCES 1
#endif // has_feature
#elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
#if defined(__GXX_EXPERIMENTAL_CXX0X__) || (__cplusplus >= 201103L)
#define JSON_HAS_RVALUE_REFERENCES 1
#endif // GXX_EXPERIMENTAL
#endif // __clang__ || __GNUC__
#endif // not defined JSON_HAS_RVALUE_REFERENCES
#ifndef JSON_HAS_RVALUE_REFERENCES
#define JSON_HAS_RVALUE_REFERENCES 0
#endif
#ifdef __clang__
#elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
# if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
# define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message)))
# elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
# define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__))
# endif // GNUC version
#endif // __clang__ || __GNUC__
#if !defined(JSONCPP_DEPRECATED)
#define JSONCPP_DEPRECATED(message)
#endif // if !defined(JSONCPP_DEPRECATED)
#if __GNUC__ >= 6
# define JSON_USE_INT64_DOUBLE_CONVERSION 1
#endif
#if !defined(JSON_IS_AMALGAMATION)
# include "version.h"
# if JSONCPP_USING_SECURE_MEMORY
# include "allocator.h" //typedef Allocator
# endif
#endif // if !defined(JSON_IS_AMALGAMATION)
namespace Json {
typedef int Int;
typedef unsigned int UInt;
#if defined(JSON_NO_INT64)
typedef int LargestInt;
typedef unsigned int LargestUInt;
#undef JSON_HAS_INT64
#else // if defined(JSON_NO_INT64)
// For Microsoft Visual use specific types as long long is not supported
#if defined(_MSC_VER) // Microsoft Visual Studio
typedef __int64 Int64;
typedef unsigned __int64 UInt64;
#else // if defined(_MSC_VER) // Other platforms, use long long
typedef int64_t Int64;
typedef uint64_t UInt64;
#endif // if defined(_MSC_VER)
typedef Int64 LargestInt;
typedef UInt64 LargestUInt;
#define JSON_HAS_INT64
#endif // if defined(JSON_NO_INT64)
#if JSONCPP_USING_SECURE_MEMORY
#define JSONCPP_STRING std::basic_string<char, std::char_traits<char>, Json::SecureAllocator<char> >
#define JSONCPP_OSTRINGSTREAM std::basic_ostringstream<char, std::char_traits<char>, Json::SecureAllocator<char> >
#define JSONCPP_OSTREAM std::basic_ostream<char, std::char_traits<char>>
#define JSONCPP_ISTRINGSTREAM std::basic_istringstream<char, std::char_traits<char>, Json::SecureAllocator<char> >
#define JSONCPP_ISTREAM std::istream
#else
#define JSONCPP_STRING std::string
#define JSONCPP_OSTRINGSTREAM std::ostringstream
#define JSONCPP_OSTREAM std::ostream
#define JSONCPP_ISTRINGSTREAM std::istringstream
#define JSONCPP_ISTREAM std::istream
#endif // if JSONCPP_USING_SECURE_MEMORY
} // end namespace Json
#endif // JSON_CONFIG_H_INCLUDED
// //////////////////////////////////////////////////////////////////////
// End of content of file: include/json/config.h
// //////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: include/json/forwards.h
// //////////////////////////////////////////////////////////////////////
// Copyright 2007-2010 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef JSON_FORWARDS_H_INCLUDED
#define JSON_FORWARDS_H_INCLUDED
#if !defined(JSON_IS_AMALGAMATION)
#include "config.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
namespace Json {
// writer.h
class FastWriter;
class StyledWriter;
// reader.h
class Reader;
// features.h
class Features;
// value.h
typedef unsigned int ArrayIndex;
class StaticString;
class Path;
class PathArgument;
class Value;
class ValueIteratorBase;
class ValueIterator;
class ValueConstIterator;
} // namespace Json
#endif // JSON_FORWARDS_H_INCLUDED
// //////////////////////////////////////////////////////////////////////
// End of content of file: include/json/forwards.h
// //////////////////////////////////////////////////////////////////////
#endif //ifndef JSON_FORWARD_AMALGATED_H_INCLUDED
/// Json-cpp amalgated header (http://jsoncpp.sourceforge.net/).
/// It is intended to be used with #include "json/json.h"
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: LICENSE
// //////////////////////////////////////////////////////////////////////
/*
The JsonCpp library's source code, including accompanying documentation,
tests and demonstration applications, are licensed under the following
conditions...
The author (Baptiste Lepilleur) explicitly disclaims copyright in all
jurisdictions which recognize such a disclaimer. In such jurisdictions,
this software is released into the Public Domain.
In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
released under the terms of the MIT License (see below).
In jurisdictions which recognize Public Domain property, the user of this
software may choose to accept it either as 1) Public Domain, 2) under the
conditions of the MIT License (see below), or 3) under the terms of dual
Public Domain/MIT License conditions described here, as they choose.
The MIT License is about as close to Public Domain as a license can get, and is
described in clear, concise terms at:
http://en.wikipedia.org/wiki/MIT_License
The full text of the MIT License follows:
========================================================================
Copyright (c) 2007-2010 Baptiste Lepilleur
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
========================================================================
(END LICENSE TEXT)
The MIT license is compatible with both the GPL and commercial
software, affording one all of the rights of Public Domain with the
minor nuisance of being required to keep the above copyright notice
and license text in the source code. Note also that by accepting the
Public Domain "license" you can re-license your copy using whatever
license you like.
*/
// //////////////////////////////////////////////////////////////////////
// End of content of file: LICENSE
// //////////////////////////////////////////////////////////////////////
#ifndef JSON_AMALGATED_H_INCLUDED
# define JSON_AMALGATED_H_INCLUDED
/// If defined, indicates that the source file is amalgated
/// to prevent private header inclusion.
#define JSON_IS_AMALGAMATION
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: include/json/version.h
// //////////////////////////////////////////////////////////////////////
// DO NOT EDIT. This file (and "version") is generated by CMake.
// Run CMake configure step to update it.
#ifndef JSON_VERSION_H_INCLUDED
# define JSON_VERSION_H_INCLUDED
# define JSONCPP_VERSION_STRING "1.7.7"
# define JSONCPP_VERSION_MAJOR 1
# define JSONCPP_VERSION_MINOR 7
# define JSONCPP_VERSION_PATCH 7
# define JSONCPP_VERSION_QUALIFIER
# define JSONCPP_VERSION_HEXA ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | (JSONCPP_VERSION_PATCH << 8))
#ifdef JSONCPP_USING_SECURE_MEMORY
#undef JSONCPP_USING_SECURE_MEMORY
#endif
#define JSONCPP_USING_SECURE_MEMORY 0
// If non-zero, the library zeroes any memory that it has allocated before
// it frees its memory.
#endif // JSON_VERSION_H_INCLUDED
// //////////////////////////////////////////////////////////////////////
// End of content of file: include/json/version.h
// //////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: include/json/config.h
// //////////////////////////////////////////////////////////////////////
// Copyright 2007-2010 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef JSON_CONFIG_H_INCLUDED
#define JSON_CONFIG_H_INCLUDED
#include <stddef.h>
#include <string> //typedef String
#include <stdint.h> //typedef int64_t, uint64_t
/// If defined, indicates that json library is embedded in CppTL library.
//# define JSON_IN_CPPTL 1
/// If defined, indicates that json may leverage CppTL library
//# define JSON_USE_CPPTL 1
/// If defined, indicates that cpptl vector based map should be used instead of
/// std::map
/// as Value container.
//# define JSON_USE_CPPTL_SMALLMAP 1
// If non-zero, the library uses exceptions to report bad input instead of C
// assertion macros. The default is to use exceptions.
#ifndef JSON_USE_EXCEPTION
#define JSON_USE_EXCEPTION 1
#endif
/// If defined, indicates that the source file is amalgated
/// to prevent private header inclusion.
/// Remarks: it is automatically defined in the generated amalgated header.
// #define JSON_IS_AMALGAMATION
#ifdef JSON_IN_CPPTL
#include <cpptl/config.h>
#ifndef JSON_USE_CPPTL
#define JSON_USE_CPPTL 1
#endif
#endif
#ifdef JSON_IN_CPPTL
#define JSON_API CPPTL_API
#elif defined(JSON_DLL_BUILD)
#if defined(_MSC_VER) || defined(__MINGW32__)
#define JSON_API __declspec(dllexport)
#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
#endif // if defined(_MSC_VER)
#elif defined(JSON_DLL)
#if defined(_MSC_VER) || defined(__MINGW32__)
#define JSON_API __declspec(dllimport)
#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
#endif // if defined(_MSC_VER)
#endif // ifdef JSON_IN_CPPTL
#if !defined(JSON_API)
#define JSON_API
#endif
// If JSON_NO_INT64 is defined, then Json only support C++ "int" type for
// integer
// Storages, and 64 bits integer support is disabled.
// #define JSON_NO_INT64 1
#if defined(_MSC_VER) // MSVC
# if _MSC_VER <= 1200 // MSVC 6
// Microsoft Visual Studio 6 only support conversion from __int64 to double
// (no conversion from unsigned __int64).
# define JSON_USE_INT64_DOUBLE_CONVERSION 1
// Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255'
// characters in the debug information)
// All projects I've ever seen with VS6 were using this globally (not bothering
// with pragma push/pop).
# pragma warning(disable : 4786)
# endif // MSVC 6
# if _MSC_VER >= 1500 // MSVC 2008
/// Indicates that the following function is deprecated.
# define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
# endif
#endif // defined(_MSC_VER)
// In c++11 the override keyword allows you to explicity define that a function
// is intended to override the base-class version. This makes the code more
// managable and fixes a set of common hard-to-find bugs.
#if __cplusplus >= 201103L
# define JSONCPP_OVERRIDE override
#elif defined(_MSC_VER) && _MSC_VER > 1600
# define JSONCPP_OVERRIDE override
#else
# define JSONCPP_OVERRIDE
#endif
#ifndef JSON_HAS_RVALUE_REFERENCES
#if defined(_MSC_VER) && _MSC_VER >= 1600 // MSVC >= 2010
#define JSON_HAS_RVALUE_REFERENCES 1
#endif // MSVC >= 2010
#ifdef __clang__
#if __has_feature(cxx_rvalue_references)
#define JSON_HAS_RVALUE_REFERENCES 1
#endif // has_feature
#elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
#if defined(__GXX_EXPERIMENTAL_CXX0X__) || (__cplusplus >= 201103L)
#define JSON_HAS_RVALUE_REFERENCES 1
#endif // GXX_EXPERIMENTAL
#endif // __clang__ || __GNUC__
#endif // not defined JSON_HAS_RVALUE_REFERENCES
#ifndef JSON_HAS_RVALUE_REFERENCES
#define JSON_HAS_RVALUE_REFERENCES 0
#endif
#ifdef __clang__
#elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
# if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
# define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message)))
# elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
# define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__))
# endif // GNUC version
#endif // __clang__ || __GNUC__
#if !defined(JSONCPP_DEPRECATED)
#define JSONCPP_DEPRECATED(message)
#endif // if !defined(JSONCPP_DEPRECATED)
#if __GNUC__ >= 6
# define JSON_USE_INT64_DOUBLE_CONVERSION 1
#endif
#if !defined(JSON_IS_AMALGAMATION)
# include "version.h"
# if JSONCPP_USING_SECURE_MEMORY
# include "allocator.h" //typedef Allocator
# endif
#endif // if !defined(JSON_IS_AMALGAMATION)
namespace Json {
typedef int Int;
typedef unsigned int UInt;
#if defined(JSON_NO_INT64)
typedef int LargestInt;
typedef unsigned int LargestUInt;
#undef JSON_HAS_INT64
#else // if defined(JSON_NO_INT64)
// For Microsoft Visual use specific types as long long is not supported
#if defined(_MSC_VER) // Microsoft Visual Studio
typedef __int64 Int64;
typedef unsigned __int64 UInt64;
#else // if defined(_MSC_VER) // Other platforms, use long long
typedef int64_t Int64;
typedef uint64_t UInt64;
#endif // if defined(_MSC_VER)
typedef Int64 LargestInt;
typedef UInt64 LargestUInt;
#define JSON_HAS_INT64
#endif // if defined(JSON_NO_INT64)
#if JSONCPP_USING_SECURE_MEMORY
#define JSONCPP_STRING std::basic_string<char, std::char_traits<char>, Json::SecureAllocator<char> >
#define JSONCPP_OSTRINGSTREAM std::basic_ostringstream<char, std::char_traits<char>, Json::SecureAllocator<char> >
#define JSONCPP_OSTREAM std::basic_ostream<char, std::char_traits<char>>
#define JSONCPP_ISTRINGSTREAM std::basic_istringstream<char, std::char_traits<char>, Json::SecureAllocator<char> >
#define JSONCPP_ISTREAM std::istream
#else
#define JSONCPP_STRING std::string
#define JSONCPP_OSTRINGSTREAM std::ostringstream
#define JSONCPP_OSTREAM std::ostream
#define JSONCPP_ISTRINGSTREAM std::istringstream
#define JSONCPP_ISTREAM std::istream
#endif // if JSONCPP_USING_SECURE_MEMORY
} // end namespace Json
#endif // JSON_CONFIG_H_INCLUDED
// //////////////////////////////////////////////////////////////////////
// End of content of file: include/json/config.h
// //////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: include/json/forwards.h
// //////////////////////////////////////////////////////////////////////
// Copyright 2007-2010 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef JSON_FORWARDS_H_INCLUDED
#define JSON_FORWARDS_H_INCLUDED
#if !defined(JSON_IS_AMALGAMATION)
#include "config.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
namespace Json {
// writer.h
class FastWriter;
class StyledWriter;
// reader.h
class Reader;
// features.h
class Features;
// value.h
typedef unsigned int ArrayIndex;
class StaticString;
class Path;
class PathArgument;
class Value;
class ValueIteratorBase;
class ValueIterator;
class ValueConstIterator;
} // namespace Json
#endif // JSON_FORWARDS_H_INCLUDED
// //////////////////////////////////////////////////////////////////////
// End of content of file: include/json/forwards.h
// //////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: include/json/features.h
// //////////////////////////////////////////////////////////////////////
// Copyright 2007-2010 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef CPPTL_JSON_FEATURES_H_INCLUDED
#define CPPTL_JSON_FEATURES_H_INCLUDED
#if !defined(JSON_IS_AMALGAMATION)
#include "forwards.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
namespace Json {
/** \brief Configuration passed to reader and writer.
* This configuration object can be used to force the Reader or Writer
* to behave in a standard conforming way.
*/
class JSON_API Features {
public:
/** \brief A configuration that allows all features and assumes all strings
* are UTF-8.
* - C & C++ comments are allowed
* - Root object can be any JSON value
* - Assumes Value strings are encoded in UTF-8
*/
static Features all();
/** \brief A configuration that is strictly compatible with the JSON
* specification.
* - Comments are forbidden.
* - Root object must be either an array or an object value.
* - Assumes Value strings are encoded in UTF-8
*/
static Features strictMode();
/** \brief Initialize the configuration like JsonConfig::allFeatures;
*/
Features();
/// \c true if comments are allowed. Default: \c true.
bool allowComments_;
/// \c true if root must be either an array or an object value. Default: \c
/// false.
bool strictRoot_;
/// \c true if dropped null placeholders are allowed. Default: \c false.
bool allowDroppedNullPlaceholders_;
/// \c true if numeric object key are allowed. Default: \c false.
bool allowNumericKeys_;
};
} // namespace Json
#endif // CPPTL_JSON_FEATURES_H_INCLUDED
// //////////////////////////////////////////////////////////////////////
// End of content of file: include/json/features.h
// //////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: include/json/value.h
// //////////////////////////////////////////////////////////////////////
// Copyright 2007-2010 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef CPPTL_JSON_H_INCLUDED
#define CPPTL_JSON_H_INCLUDED
#if !defined(JSON_IS_AMALGAMATION)
#include "forwards.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
#include <string>
#include <vector>
#include <exception>
#ifndef JSON_USE_CPPTL_SMALLMAP
#include <map>
#else
#include <cpptl/smallmap.h>
#endif
#ifdef JSON_USE_CPPTL
#include <cpptl/forwards.h>
#endif
//Conditional NORETURN attribute on the throw functions would:
// a) suppress false positives from static code analysis
// b) possibly improve optimization opportunities.
#if !defined(JSONCPP_NORETURN)
# if defined(_MSC_VER)
# define JSONCPP_NORETURN __declspec(noreturn)
# elif defined(__GNUC__)
# define JSONCPP_NORETURN __attribute__ ((__noreturn__))
# else
# define JSONCPP_NORETURN
# endif
#endif
// Disable warning C4251: <data member>: <type> needs to have dll-interface to
// be used by...
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#pragma warning(push)
#pragma warning(disable : 4251)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
/** \brief JSON (JavaScript Object Notation).
*/
namespace Json {
/** Base class for all exceptions we throw.
*
* We use nothing but these internally. Of course, STL can throw others.
*/
class JSON_API Exception : public std::exception {
public:
Exception(JSONCPP_STRING const& msg);
~Exception() throw() JSONCPP_OVERRIDE;
char const* what() const throw() JSONCPP_OVERRIDE;
protected:
JSONCPP_STRING msg_;
};
/** Exceptions which the user cannot easily avoid.
*
* E.g. out-of-memory (when we use malloc), stack-overflow, malicious input
*
* \remark derived from Json::Exception
*/
class JSON_API RuntimeError : public Exception {
public:
RuntimeError(JSONCPP_STRING const& msg);
};
/** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
*
* These are precondition-violations (user bugs) and internal errors (our bugs).
*
* \remark derived from Json::Exception
*/
class JSON_API LogicError : public Exception {
public:
LogicError(JSONCPP_STRING const& msg);
};
/// used internally
JSONCPP_NORETURN void throwRuntimeError(JSONCPP_STRING const& msg);
/// used internally
JSONCPP_NORETURN void throwLogicError(JSONCPP_STRING const& msg);
/** \brief Type of the value held by a Value object.
*/
enum ValueType {
nullValue = 0, ///< 'null' value
intValue, ///< signed integer value
uintValue, ///< unsigned integer value
realValue, ///< double value
stringValue, ///< UTF-8 string value
booleanValue, ///< bool value
arrayValue, ///< array value (ordered list)
objectValue ///< object value (collection of name/value pairs).
};
enum CommentPlacement {
commentBefore = 0, ///< a comment placed on the line before a value
commentAfterOnSameLine, ///< a comment just after a value on the same line
commentAfter, ///< a comment on the line after a value (only make sense for
/// root value)
numberOfCommentPlacement
};
//# ifdef JSON_USE_CPPTL
// typedef CppTL::AnyEnumerator<const char *> EnumMemberNames;
// typedef CppTL::AnyEnumerator<const Value &> EnumValues;
//# endif
/** \brief Lightweight wrapper to tag static string.
*
* Value constructor and objectValue member assignement takes advantage of the
* StaticString and avoid the cost of string duplication when storing the
* string or the member name.
*
* Example of usage:
* \code
* Json::Value aValue( StaticString("some text") );
* Json::Value object;
* static const StaticString code("code");
* object[code] = 1234;
* \endcode
*/
class JSON_API StaticString {
public:
explicit StaticString(const char* czstring) : c_str_(czstring) {}
operator const char*() const { return c_str_; }
const char* c_str() const { return c_str_; }
private:
const char* c_str_;
};
/** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
*
* This class is a discriminated union wrapper that can represents a:
* - signed integer [range: Value::minInt - Value::maxInt]
* - unsigned integer (range: 0 - Value::maxUInt)
* - double
* - UTF-8 string
* - boolean
* - 'null'
* - an ordered list of Value
* - collection of name/value pairs (javascript object)
*
* The type of the held value is represented by a #ValueType and
* can be obtained using type().
*
* Values of an #objectValue or #arrayValue can be accessed using operator[]()
* methods.
* Non-const methods will automatically create the a #nullValue element
* if it does not exist.
* The sequence of an #arrayValue will be automatically resized and initialized
* with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
*
* The get() methods can be used to obtain default value in the case the
* required element does not exist.
*
* It is possible to iterate over the list of a #objectValue values using
* the getMemberNames() method.
*
* \note #Value string-length fit in size_t, but keys must be < 2^30.
* (The reason is an implementation detail.) A #CharReader will raise an
* exception if a bound is exceeded to avoid security holes in your app,
* but the Value API does *not* check bounds. That is the responsibility
* of the caller.
*/
class JSON_API Value {
friend class ValueIteratorBase;
public:
typedef std::vector<JSONCPP_STRING> Members;
typedef ValueIterator iterator;
typedef ValueConstIterator const_iterator;
typedef Json::UInt UInt;
typedef Json::Int Int;
#if defined(JSON_HAS_INT64)
typedef Json::UInt64 UInt64;
typedef Json::Int64 Int64;
#endif // defined(JSON_HAS_INT64)
typedef Json::LargestInt LargestInt;
typedef Json::LargestUInt LargestUInt;
typedef Json::ArrayIndex ArrayIndex;
static const Value& null; ///< We regret this reference to a global instance; prefer the simpler Value().
static const Value& nullRef; ///< just a kludge for binary-compatibility; same as null
static Value const& nullSingleton(); ///< Prefer this to null or nullRef.
/// Minimum signed integer value that can be stored in a Json::Value.
static const LargestInt minLargestInt;
/// Maximum signed integer value that can be stored in a Json::Value.
static const LargestInt maxLargestInt;
/// Maximum unsigned integer value that can be stored in a Json::Value.
static const LargestUInt maxLargestUInt;
/// Minimum signed int value that can be stored in a Json::Value.
static const Int minInt;
/// Maximum signed int value that can be stored in a Json::Value.
static const Int maxInt;
/// Maximum unsigned int value that can be stored in a Json::Value.
static const UInt maxUInt;
#if defined(JSON_HAS_INT64)
/// Minimum signed 64 bits int value that can be stored in a Json::Value.
static const Int64 minInt64;
/// Maximum signed 64 bits int value that can be stored in a Json::Value.
static const Int64 maxInt64;
/// Maximum unsigned 64 bits int value that can be stored in a Json::Value.
static const UInt64 maxUInt64;
#endif // defined(JSON_HAS_INT64)
private:
#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
class CZString {
public:
enum DuplicationPolicy {
noDuplication = 0,
duplicate,
duplicateOnCopy
};
CZString(ArrayIndex index);
CZString(char const* str, unsigned length, DuplicationPolicy allocate);
CZString(CZString const& other);
#if JSON_HAS_RVALUE_REFERENCES
CZString(CZString&& other);
#endif
~CZString();
CZString& operator=(CZString other);
bool operator<(CZString const& other) const;
bool operator==(CZString const& other) const;
ArrayIndex index() const;
//const char* c_str() const; ///< \deprecated
char const* data() const;
unsigned length() const;
bool isStaticString() const;
private:
void swap(CZString& other);
struct StringStorage {
unsigned policy_: 2;
unsigned length_: 30; // 1GB max
};
char const* cstr_; // actually, a prefixed string, unless policy is noDup
union {
ArrayIndex index_;
StringStorage storage_;
};
};
public:
#ifndef JSON_USE_CPPTL_SMALLMAP
typedef std::map<CZString, Value> ObjectValues;
#else
typedef CppTL::SmallMap<CZString, Value> ObjectValues;
#endif // ifndef JSON_USE_CPPTL_SMALLMAP
#endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
public:
/** \brief Create a default Value of the given type.
This is a very useful constructor.
To create an empty array, pass arrayValue.
To create an empty object, pass objectValue.
Another Value can then be set to this one by assignment.
This is useful since clear() and resize() will not alter types.
Examples:
\code
Json::Value null_value; // null
Json::Value arr_value(Json::arrayValue); // []
Json::Value obj_value(Json::objectValue); // {}
\endcode
*/
Value(ValueType type = nullValue);
Value(Int value);
Value(UInt value);
#if defined(JSON_HAS_INT64)
Value(Int64 value);
Value(UInt64 value);
#endif // if defined(JSON_HAS_INT64)
Value(double value);
Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.)
Value(const char* begin, const char* end); ///< Copy all, incl zeroes.
/** \brief Constructs a value from a static string.
* Like other value string constructor but do not duplicate the string for
* internal storage. The given string must remain alive after the call to this
* constructor.
* \note This works only for null-terminated strings. (We cannot change the
* size of this class, so we have nowhere to store the length,
* which might be computed later for various operations.)
*
* Example of usage:
* \code
* static StaticString foo("some text");
* Json::Value aValue(foo);
* \endcode
*/
Value(const StaticString& value);
Value(const JSONCPP_STRING& value); ///< Copy data() til size(). Embedded zeroes too.
#ifdef JSON_USE_CPPTL
Value(const CppTL::ConstString& value);
#endif
Value(bool value);
/// Deep copy.
Value(const Value& other);
#if JSON_HAS_RVALUE_REFERENCES
/// Move constructor
Value(Value&& other);
#endif
~Value();
/// Deep copy, then swap(other).
/// \note Over-write existing comments. To preserve comments, use #swapPayload().
Value& operator=(Value other);
/// Swap everything.
void swap(Value& other);
/// Swap values but leave comments and source offsets in place.
void swapPayload(Value& other);
ValueType type() const;
/// Compare payload only, not comments etc.
bool operator<(const Value& other) const;
bool operator<=(const Value& other) const;
bool operator>=(const Value& other) const;
bool operator>(const Value& other) const;
bool operator==(const Value& other) const;
bool operator!=(const Value& other) const;
int compare(const Value& other) const;
const char* asCString() const; ///< Embedded zeroes could cause you trouble!
#if JSONCPP_USING_SECURE_MEMORY
unsigned getCStringLength() const; //Allows you to understand the length of the CString
#endif
JSONCPP_STRING asString() const; ///< Embedded zeroes are possible.
/** Get raw char* of string-value.
* \return false if !string. (Seg-fault if str or end are NULL.)
*/
bool getString(
char const** begin, char const** end) const;
#ifdef JSON_USE_CPPTL
CppTL::ConstString asConstString() const;
#endif
Int asInt() const;
UInt asUInt() const;
#if defined(JSON_HAS_INT64)
Int64 asInt64() const;
UInt64 asUInt64() const;
#endif // if defined(JSON_HAS_INT64)
LargestInt asLargestInt() const;
LargestUInt asLargestUInt() const;
float asFloat() const;
double asDouble() const;
bool asBool() const;
bool isNull() const;
bool isBool() const;
bool isInt() const;
bool isInt64() const;
bool isUInt() const;
bool isUInt64() const;
bool isIntegral() const;
bool isDouble() const;
bool isNumeric() const;
bool isString() const;
bool isArray() const;
bool isObject() const;
bool isConvertibleTo(ValueType other) const;
/// Number of values in array or object
ArrayIndex size() const;
/// \brief Return true if empty array, empty object, or null;
/// otherwise, false.
bool empty() const;
/// Return isNull()
bool operator!() const;
/// Remove all object members and array elements.
/// \pre type() is arrayValue, objectValue, or nullValue
/// \post type() is unchanged
void clear();
/// Resize the array to size elements.
/// New elements are initialized to null.
/// May only be called on nullValue or arrayValue.
/// \pre type() is arrayValue or nullValue
/// \post type() is arrayValue
void resize(ArrayIndex size);
/// Access an array element (zero based index ).
/// If the array contains less than index element, then null value are
/// inserted
/// in the array so that its size is index+1.
/// (You may need to say 'value[0u]' to get your compiler to distinguish
/// this from the operator[] which takes a string.)
Value& operator[](ArrayIndex index);
/// Access an array element (zero based index ).
/// If the array contains less than index element, then null value are
/// inserted
/// in the array so that its size is index+1.
/// (You may need to say 'value[0u]' to get your compiler to distinguish
/// this from the operator[] which takes a string.)
Value& operator[](int index);
/// Access an array element (zero based index )
/// (You may need to say 'value[0u]' to get your compiler to distinguish
/// this from the operator[] which takes a string.)
const Value& operator[](ArrayIndex index) const;
/// Access an array element (zero based index )
/// (You may need to say 'value[0u]' to get your compiler to distinguish
/// this from the operator[] which takes a string.)
const Value& operator[](int index) const;
/// If the array contains at least index+1 elements, returns the element
/// value,
/// otherwise returns defaultValue.
Value get(ArrayIndex index, const Value& defaultValue) const;
/// Return true if index < size().
bool isValidIndex(ArrayIndex index) const;
/// \brief Append value to array at the end.
///
/// Equivalent to jsonvalue[jsonvalue.size()] = value;
Value& append(const Value& value);
/// Access an object value by name, create a null member if it does not exist.
/// \note Because of our implementation, keys are limited to 2^30 -1 chars.
/// Exceeding that will cause an exception.
Value& operator[](const char* key);
/// Access an object value by name, returns null if there is no member with
/// that name.
const Value& operator[](const char* key) const;
/// Access an object value by name, create a null member if it does not exist.
/// \param key may contain embedded nulls.
Value& operator[](const JSONCPP_STRING& key);
/// Access an object value by name, returns null if there is no member with
/// that name.
/// \param key may contain embedded nulls.
const Value& operator[](const JSONCPP_STRING& key) const;
/** \brief Access an object value by name, create a null member if it does not
exist.
* If the object has no entry for that name, then the member name used to store
* the new entry is not duplicated.
* Example of use:
* \code
* Json::Value object;
* static const StaticString code("code");
* object[code] = 1234;
* \endcode
*/
Value& operator[](const StaticString& key);
#ifdef JSON_USE_CPPTL
/// Access an object value by name, create a null member if it does not exist.
Value& operator[](const CppTL::ConstString& key);
/// Access an object value by name, returns null if there is no member with
/// that name.
const Value& operator[](const CppTL::ConstString& key) const;
#endif
/// Return the member named key if it exist, defaultValue otherwise.
/// \note deep copy
Value get(const char* key, const Value& defaultValue) const;
/// Return the member named key if it exist, defaultValue otherwise.
/// \note deep copy
/// \note key may contain embedded nulls.
Value get(const char* begin, const char* end, const Value& defaultValue) const;
/// Return the member named key if it exist, defaultValue otherwise.
/// \note deep copy
/// \param key may contain embedded nulls.
Value get(const JSONCPP_STRING& key, const Value& defaultValue) const;
#ifdef JSON_USE_CPPTL
/// Return the member named key if it exist, defaultValue otherwise.
/// \note deep copy
Value get(const CppTL::ConstString& key, const Value& defaultValue) const;
#endif
/// Most general and efficient version of isMember()const, get()const,
/// and operator[]const
/// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
Value const* find(char const* begin, char const* end) const;
/// Most general and efficient version of object-mutators.
/// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
/// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
Value const* demand(char const* begin, char const* end);
/// \brief Remove and return the named member.
///
/// Do nothing if it did not exist.
/// \return the removed Value, or null.
/// \pre type() is objectValue or nullValue
/// \post type() is unchanged
/// \deprecated
Value removeMember(const char* key);
/// Same as removeMember(const char*)
/// \param key may contain embedded nulls.
/// \deprecated
Value removeMember(const JSONCPP_STRING& key);
/// Same as removeMember(const char* begin, const char* end, Value* removed),
/// but 'key' is null-terminated.
bool removeMember(const char* key, Value* removed);
/** \brief Remove the named map member.
Update 'removed' iff removed.
\param key may contain embedded nulls.
\return true iff removed (no exceptions)
*/
bool removeMember(JSONCPP_STRING const& key, Value* removed);
/// Same as removeMember(JSONCPP_STRING const& key, Value* removed)
bool removeMember(const char* begin, const char* end, Value* removed);
/** \brief Remove the indexed array element.
O(n) expensive operations.
Update 'removed' iff removed.
\return true iff removed (no exceptions)
*/
bool removeIndex(ArrayIndex i, Value* removed);
/// Return true if the object has a member named key.
/// \note 'key' must be null-terminated.
bool isMember(const char* key) const;
/// Return true if the object has a member named key.
/// \param key may contain embedded nulls.
bool isMember(const JSONCPP_STRING& key) const;
/// Same as isMember(JSONCPP_STRING const& key)const
bool isMember(const char* begin, const char* end) const;
#ifdef JSON_USE_CPPTL
/// Return true if the object has a member named key.
bool isMember(const CppTL::ConstString& key) const;
#endif
/// \brief Return a list of the member names.
///
/// If null, return an empty list.
/// \pre type() is objectValue or nullValue
/// \post if type() was nullValue, it remains nullValue
Members getMemberNames() const;
//# ifdef JSON_USE_CPPTL
// EnumMemberNames enumMemberNames() const;
// EnumValues enumValues() const;
//# endif
/// \deprecated Always pass len.
JSONCPP_DEPRECATED("Use setComment(JSONCPP_STRING const&) instead.")
void setComment(const char* comment, CommentPlacement placement);
/// Comments must be //... or /* ... */
void setComment(const char* comment, size_t len, CommentPlacement placement);
/// Comments must be //... or /* ... */
void setComment(const JSONCPP_STRING& comment, CommentPlacement placement);
bool hasComment(CommentPlacement placement) const;
/// Include delimiters and embedded newlines.
JSONCPP_STRING getComment(CommentPlacement placement) const;
JSONCPP_STRING toStyledString() const;
const_iterator begin() const;
const_iterator end() const;
iterator begin();
iterator end();
// Accessors for the [start, limit) range of bytes within the JSON text from
// which this value was parsed, if any.
void setOffsetStart(ptrdiff_t start);
void setOffsetLimit(ptrdiff_t limit);
ptrdiff_t getOffsetStart() const;
ptrdiff_t getOffsetLimit() const;
private:
void initBasic(ValueType type, bool allocated = false);
Value& resolveReference(const char* key);
Value& resolveReference(const char* key, const char* end);
struct CommentInfo {
CommentInfo();
~CommentInfo();
void setComment(const char* text, size_t len);
char* comment_;
};
// struct MemberNamesTransform
//{
// typedef const char *result_type;
// const char *operator()( const CZString &name ) const
// {
// return name.c_str();
// }
//};
union ValueHolder {
LargestInt int_;
LargestUInt uint_;
double real_;
bool bool_;
char* string_; // actually ptr to unsigned, followed by str, unless !allocated_
ObjectValues* map_;
} value_;
ValueType type_ : 8;
unsigned int allocated_ : 1; // Notes: if declared as bool, bitfield is useless.
// If not allocated_, string_ must be null-terminated.
CommentInfo* comments_;
// [start, limit) byte offsets in the source JSON text from which this Value
// was extracted.
ptrdiff_t start_;
ptrdiff_t limit_;
};
/** \brief Experimental and untested: represents an element of the "path" to
* access a node.
*/
class JSON_API PathArgument {
public:
friend class Path;
PathArgument();
PathArgument(ArrayIndex index);
PathArgument(const char* key);
PathArgument(const JSONCPP_STRING& key);
private:
enum Kind {
kindNone = 0,
kindIndex,
kindKey
};
JSONCPP_STRING key_;
ArrayIndex index_;
Kind kind_;
};
/** \brief Experimental and untested: represents a "path" to access a node.
*
* Syntax:
* - "." => root node
* - ".[n]" => elements at index 'n' of root node (an array value)
* - ".name" => member named 'name' of root node (an object value)
* - ".name1.name2.name3"
* - ".[0][1][2].name1[3]"
* - ".%" => member name is provided as parameter
* - ".[%]" => index is provied as parameter
*/
class JSON_API Path {
public:
Path(const JSONCPP_STRING& path,
const PathArgument& a1 = PathArgument(),
const PathArgument& a2 = PathArgument(),
const PathArgument& a3 = PathArgument(),
const PathArgument& a4 = PathArgument(),
const PathArgument& a5 = PathArgument());
const Value& resolve(const Value& root) const;
Value resolve(const Value& root, const Value& defaultValue) const;
/// Creates the "path" to access the specified node and returns a reference on
/// the node.
Value& make(Value& root) const;
private:
typedef std::vector<const PathArgument*> InArgs;
typedef std::vector<PathArgument> Args;
void makePath(const JSONCPP_STRING& path, const InArgs& in);
void addPathInArg(const JSONCPP_STRING& path,
const InArgs& in,
InArgs::const_iterator& itInArg,
PathArgument::Kind kind);
void invalidPath(const JSONCPP_STRING& path, int location);
Args args_;
};
/** \brief base class for Value iterators.
*
*/
class JSON_API ValueIteratorBase {
public:
typedef std::bidirectional_iterator_tag iterator_category;
typedef unsigned int size_t;
typedef int difference_type;
typedef ValueIteratorBase SelfType;
bool operator==(const SelfType& other) const { return isEqual(other); }
bool operator!=(const SelfType& other) const { return !isEqual(other); }
difference_type operator-(const SelfType& other) const {
return other.computeDistance(*this);
}
/// Return either the index or the member name of the referenced value as a
/// Value.
Value key() const;
/// Return the index of the referenced Value, or -1 if it is not an arrayValue.
UInt index() const;
/// Return the member name of the referenced Value, or "" if it is not an
/// objectValue.
/// \note Avoid `c_str()` on result, as embedded zeroes are possible.
JSONCPP_STRING name() const;
/// Return the member name of the referenced Value. "" if it is not an
/// objectValue.
/// \deprecated This cannot be used for UTF-8 strings, since there can be embedded nulls.
JSONCPP_DEPRECATED("Use `key = name();` instead.")
char const* memberName() const;
/// Return the member name of the referenced Value, or NULL if it is not an
/// objectValue.
/// \note Better version than memberName(). Allows embedded nulls.
char const* memberName(char const** end) const;
protected:
Value& deref() const;
void increment();
void decrement();
difference_type computeDistance(const SelfType& other) const;
bool isEqual(const SelfType& other) const;
void copy(const SelfType& other);
private:
Value::ObjectValues::iterator current_;
// Indicates that iterator is for a null value.
bool isNull_;
public:
// For some reason, BORLAND needs these at the end, rather
// than earlier. No idea why.
ValueIteratorBase();
explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
};
/** \brief const iterator for object and array value.
*
*/
class JSON_API ValueConstIterator : public ValueIteratorBase {
friend class Value;
public:
typedef const Value value_type;
//typedef unsigned int size_t;
//typedef int difference_type;
typedef const Value& reference;
typedef const Value* pointer;
typedef ValueConstIterator SelfType;
ValueConstIterator();
ValueConstIterator(ValueIterator const& other);
private:
/*! \internal Use by Value to create an iterator.
*/
explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
public:
SelfType& operator=(const ValueIteratorBase& other);
SelfType operator++(int) {
SelfType temp(*this);
++*this;
return temp;
}
SelfType operator--(int) {
SelfType temp(*this);
--*this;
return temp;
}
SelfType& operator--() {
decrement();
return *this;
}
SelfType& operator++() {
increment();
return *this;
}
reference operator*() const { return deref(); }
pointer operator->() const { return &deref(); }
};
/** \brief Iterator for object and array value.
*/
class JSON_API ValueIterator : public ValueIteratorBase {
friend class Value;
public:
typedef Value value_type;
typedef unsigned int size_t;
typedef int difference_type;
typedef Value& reference;
typedef Value* pointer;
typedef ValueIterator SelfType;
ValueIterator();
explicit ValueIterator(const ValueConstIterator& other);
ValueIterator(const ValueIterator& other);
private:
/*! \internal Use by Value to create an iterator.
*/
explicit ValueIterator(const Value::ObjectValues::iterator& current);
public:
SelfType& operator=(const SelfType& other);
SelfType operator++(int) {
SelfType temp(*this);
++*this;
return temp;
}
SelfType operator--(int) {
SelfType temp(*this);
--*this;
return temp;
}
SelfType& operator--() {
decrement();
return *this;
}
SelfType& operator++() {
increment();
return *this;
}
reference operator*() const { return deref(); }
pointer operator->() const { return &deref(); }
};
} // namespace Json
namespace std {
/// Specialize std::swap() for Json::Value.
template<>
inline void swap(Json::Value& a, Json::Value& b) { a.swap(b); }
}
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#pragma warning(pop)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#endif // CPPTL_JSON_H_INCLUDED
// //////////////////////////////////////////////////////////////////////
// End of content of file: include/json/value.h
// //////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: include/json/reader.h
// //////////////////////////////////////////////////////////////////////
// Copyright 2007-2010 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef CPPTL_JSON_READER_H_INCLUDED
#define CPPTL_JSON_READER_H_INCLUDED
#if !defined(JSON_IS_AMALGAMATION)
#include "features.h"
#include "value.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
#include <deque>
#include <iosfwd>
#include <stack>
#include <string>
#include <istream>
// Disable warning C4251: <data member>: <type> needs to have dll-interface to
// be used by...
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#pragma warning(push)
#pragma warning(disable : 4251)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
namespace Json {
/** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a
*Value.
*
* \deprecated Use CharReader and CharReaderBuilder.
*/
class JSON_API Reader {
public:
typedef char Char;
typedef const Char* Location;
/** \brief An error tagged with where in the JSON text it was encountered.
*
* The offsets give the [start, limit) range of bytes within the text. Note
* that this is bytes, not codepoints.
*
*/
struct StructuredError {
ptrdiff_t offset_start;
ptrdiff_t offset_limit;
JSONCPP_STRING message;
};
/** \brief Constructs a Reader allowing all features
* for parsing.
*/
Reader();
/** \brief Constructs a Reader allowing the specified feature set
* for parsing.
*/
Reader(const Features& features);
/** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
* document.
* \param document UTF-8 encoded string containing the document to read.
* \param root [out] Contains the root value of the document if it was
* successfully parsed.
* \param collectComments \c true to collect comment and allow writing them
* back during
* serialization, \c false to discard comments.
* This parameter is ignored if
* Features::allowComments_
* is \c false.
* \return \c true if the document was successfully parsed, \c false if an
* error occurred.
*/
bool
parse(const std::string& document, Value& root, bool collectComments = true);
/** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
document.
* \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
document to read.
* \param endDoc Pointer on the end of the UTF-8 encoded string of the
document to read.
* Must be >= beginDoc.
* \param root [out] Contains the root value of the document if it was
* successfully parsed.
* \param collectComments \c true to collect comment and allow writing them
back during
* serialization, \c false to discard comments.
* This parameter is ignored if
Features::allowComments_
* is \c false.
* \return \c true if the document was successfully parsed, \c false if an
error occurred.
*/
bool parse(const char* beginDoc,
const char* endDoc,
Value& root,
bool collectComments = true);
/// \brief Parse from input stream.
/// \see Json::operator>>(std::istream&, Json::Value&).
bool parse(JSONCPP_ISTREAM& is, Value& root, bool collectComments = true);
/** \brief Returns a user friendly string that list errors in the parsed
* document.
* \return Formatted error message with the list of errors with their location
* in
* the parsed document. An empty string is returned if no error
* occurred
* during parsing.
* \deprecated Use getFormattedErrorMessages() instead (typo fix).
*/
JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.")
JSONCPP_STRING getFormatedErrorMessages() const;
/** \brief Returns a user friendly string that list errors in the parsed
* document.
* \return Formatted error message with the list of errors with their location
* in
* the parsed document. An empty string is returned if no error
* occurred
* during parsing.
*/
JSONCPP_STRING getFormattedErrorMessages() const;
/** \brief Returns a vector of structured erros encounted while parsing.
* \return A (possibly empty) vector of StructuredError objects. Currently
* only one error can be returned, but the caller should tolerate
* multiple
* errors. This can occur if the parser recovers from a non-fatal
* parse error and then encounters additional errors.
*/
std::vector<StructuredError> getStructuredErrors() const;
/** \brief Add a semantic error message.
* \param value JSON Value location associated with the error
* \param message The error message.
* \return \c true if the error was successfully added, \c false if the
* Value offset exceeds the document size.
*/
bool pushError(const Value& value, const JSONCPP_STRING& message);
/** \brief Add a semantic error message with extra context.
* \param value JSON Value location associated with the error
* \param message The error message.
* \param extra Additional JSON Value location to contextualize the error
* \return \c true if the error was successfully added, \c false if either
* Value offset exceeds the document size.
*/
bool pushError(const Value& value, const JSONCPP_STRING& message, const Value& extra);
/** \brief Return whether there are any errors.
* \return \c true if there are no errors to report \c false if
* errors have occurred.
*/
bool good() const;
private:
enum TokenType {
tokenEndOfStream = 0,
tokenObjectBegin,
tokenObjectEnd,
tokenArrayBegin,
tokenArrayEnd,
tokenString,
tokenNumber,
tokenTrue,
tokenFalse,
tokenNull,
tokenArraySeparator,
tokenMemberSeparator,
tokenComment,
tokenError
};
class Token {
public:
TokenType type_;
Location start_;
Location end_;
};
class ErrorInfo {
public:
Token token_;
JSONCPP_STRING message_;
Location extra_;
};
typedef std::deque<ErrorInfo> Errors;
bool readToken(Token& token);
void skipSpaces();
bool match(Location pattern, int patternLength);
bool readComment();
bool readCStyleComment();
bool readCppStyleComment();
bool readString();
void readNumber();
bool readValue();
bool readObject(Token& token);
bool readArray(Token& token);
bool decodeNumber(Token& token);
bool decodeNumber(Token& token, Value& decoded);
bool decodeString(Token& token);
bool decodeString(Token& token, JSONCPP_STRING& decoded);
bool decodeDouble(Token& token);
bool decodeDouble(Token& token, Value& decoded);
bool decodeUnicodeCodePoint(Token& token,
Location& current,
Location end,
unsigned int& unicode);
bool decodeUnicodeEscapeSequence(Token& token,
Location& current,
Location end,
unsigned int& unicode);
bool addError(const JSONCPP_STRING& message, Token& token, Location extra = 0);
bool recoverFromError(TokenType skipUntilToken);
bool addErrorAndRecover(const JSONCPP_STRING& message,
Token& token,
TokenType skipUntilToken);
void skipUntilSpace();
Value& currentValue();
Char getNextChar();
void
getLocationLineAndColumn(Location location, int& line, int& column) const;
JSONCPP_STRING getLocationLineAndColumn(Location location) const;
void addComment(Location begin, Location end, CommentPlacement placement);
void skipCommentTokens(Token& token);
typedef std::stack<Value*> Nodes;
Nodes nodes_;
Errors errors_;
JSONCPP_STRING document_;
Location begin_;
Location end_;
Location current_;
Location lastValueEnd_;
Value* lastValue_;
JSONCPP_STRING commentsBefore_;
Features features_;
bool collectComments_;
}; // Reader
/** Interface for reading JSON from a char array.
*/
class JSON_API CharReader {
public:
virtual ~CharReader() {}
/** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
document.
* The document must be a UTF-8 encoded string containing the document to read.
*
* \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
document to read.
* \param endDoc Pointer on the end of the UTF-8 encoded string of the
document to read.
* Must be >= beginDoc.
* \param root [out] Contains the root value of the document if it was
* successfully parsed.
* \param errs [out] Formatted error messages (if not NULL)
* a user friendly string that lists errors in the parsed
* document.
* \return \c true if the document was successfully parsed, \c false if an
error occurred.
*/
virtual bool parse(
char const* beginDoc, char const* endDoc,
Value* root, JSONCPP_STRING* errs) = 0;
class JSON_API Factory {
public:
virtual ~Factory() {}
/** \brief Allocate a CharReader via operator new().
* \throw std::exception if something goes wrong (e.g. invalid settings)
*/
virtual CharReader* newCharReader() const = 0;
}; // Factory
}; // CharReader
/** \brief Build a CharReader implementation.
Usage:
\code
using namespace Json;
CharReaderBuilder builder;
builder["collectComments"] = false;
Value value;
JSONCPP_STRING errs;
bool ok = parseFromStream(builder, std::cin, &value, &errs);
\endcode
*/
class JSON_API CharReaderBuilder : public CharReader::Factory {
public:
// Note: We use a Json::Value so that we can add data-members to this class
// without a major version bump.
/** Configuration of this builder.
These are case-sensitive.
Available settings (case-sensitive):
- `"collectComments": false or true`
- true to collect comment and allow writing them
back during serialization, false to discard comments.
This parameter is ignored if allowComments is false.
- `"allowComments": false or true`
- true if comments are allowed.
- `"strictRoot": false or true`
- true if root must be either an array or an object value
- `"allowDroppedNullPlaceholders": false or true`
- true if dropped null placeholders are allowed. (See StreamWriterBuilder.)
- `"allowNumericKeys": false or true`
- true if numeric object keys are allowed.
- `"allowSingleQuotes": false or true`
- true if '' are allowed for strings (both keys and values)
- `"stackLimit": integer`
- Exceeding stackLimit (recursive depth of `readValue()`) will
cause an exception.
- This is a security issue (seg-faults caused by deeply nested JSON),
so the default is low.
- `"failIfExtra": false or true`
- If true, `parse()` returns false when extra non-whitespace trails
the JSON value in the input string.
- `"rejectDupKeys": false or true`
- If true, `parse()` returns false when a key is duplicated within an object.
- `"allowSpecialFloats": false or true`
- If true, special float values (NaNs and infinities) are allowed
and their values are lossfree restorable.
You can examine 'settings_` yourself
to see the defaults. You can also write and read them just like any
JSON Value.
\sa setDefaults()
*/
Json::Value settings_;
CharReaderBuilder();
~CharReaderBuilder() JSONCPP_OVERRIDE;
CharReader* newCharReader() const JSONCPP_OVERRIDE;
/** \return true if 'settings' are legal and consistent;
* otherwise, indicate bad settings via 'invalid'.
*/
bool validate(Json::Value* invalid) const;
/** A simple way to update a specific setting.
*/
Value& operator[](JSONCPP_STRING key);
/** Called by ctor, but you can use this to reset settings_.
* \pre 'settings' != NULL (but Json::null is fine)
* \remark Defaults:
* \snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults
*/
static void setDefaults(Json::Value* settings);
/** Same as old Features::strictMode().
* \pre 'settings' != NULL (but Json::null is fine)
* \remark Defaults:
* \snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode
*/
static void strictMode(Json::Value* settings);
};
/** Consume entire stream and use its begin/end.
* Someday we might have a real StreamReader, but for now this
* is convenient.
*/
bool JSON_API parseFromStream(
CharReader::Factory const&,
JSONCPP_ISTREAM&,
Value* root, std::string* errs);
/** \brief Read from 'sin' into 'root'.
Always keep comments from the input JSON.
This can be used to read a file into a particular sub-object.
For example:
\code
Json::Value root;
cin >> root["dir"]["file"];
cout << root;
\endcode
Result:
\verbatim
{
"dir": {
"file": {
// The input stream JSON would be nested here.
}
}
}
\endverbatim
\throw std::exception on parse error.
\see Json::operator<<()
*/
JSON_API JSONCPP_ISTREAM& operator>>(JSONCPP_ISTREAM&, Value&);
} // namespace Json
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#pragma warning(pop)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#endif // CPPTL_JSON_READER_H_INCLUDED
// //////////////////////////////////////////////////////////////////////
// End of content of file: include/json/reader.h
// //////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: include/json/writer.h
// //////////////////////////////////////////////////////////////////////
// Copyright 2007-2010 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef JSON_WRITER_H_INCLUDED
#define JSON_WRITER_H_INCLUDED
#if !defined(JSON_IS_AMALGAMATION)
#include "value.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
#include <vector>
#include <string>
#include <ostream>
// Disable warning C4251: <data member>: <type> needs to have dll-interface to
// be used by...
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#pragma warning(push)
#pragma warning(disable : 4251)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
namespace Json {
class Value;
/**
Usage:
\code
using namespace Json;
void writeToStdout(StreamWriter::Factory const& factory, Value const& value) {
std::unique_ptr<StreamWriter> const writer(
factory.newStreamWriter());
writer->write(value, &std::cout);
std::cout << std::endl; // add lf and flush
}
\endcode
*/
class JSON_API StreamWriter {
protected:
JSONCPP_OSTREAM* sout_; // not owned; will not delete
public:
StreamWriter();
virtual ~StreamWriter();
/** Write Value into document as configured in sub-class.
Do not take ownership of sout, but maintain a reference during function.
\pre sout != NULL
\return zero on success (For now, we always return zero, so check the stream instead.)
\throw std::exception possibly, depending on configuration
*/
virtual int write(Value const& root, JSONCPP_OSTREAM* sout) = 0;
/** \brief A simple abstract factory.
*/
class JSON_API Factory {
public:
virtual ~Factory();
/** \brief Allocate a CharReader via operator new().
* \throw std::exception if something goes wrong (e.g. invalid settings)
*/
virtual StreamWriter* newStreamWriter() const = 0;
}; // Factory
}; // StreamWriter
/** \brief Write into stringstream, then return string, for convenience.
* A StreamWriter will be created from the factory, used, and then deleted.
*/
JSONCPP_STRING JSON_API writeString(StreamWriter::Factory const& factory, Value const& root);
/** \brief Build a StreamWriter implementation.
Usage:
\code
using namespace Json;
Value value = ...;
StreamWriterBuilder builder;
builder["commentStyle"] = "None";
builder["indentation"] = " "; // or whatever you like
std::unique_ptr<Json::StreamWriter> writer(
builder.newStreamWriter());
writer->write(value, &std::cout);
std::cout << std::endl; // add lf and flush
\endcode
*/
class JSON_API StreamWriterBuilder : public StreamWriter::Factory {
public:
// Note: We use a Json::Value so that we can add data-members to this class
// without a major version bump.
/** Configuration of this builder.
Available settings (case-sensitive):
- "commentStyle": "None" or "All"
- "indentation": "<anything>"
- "enableYAMLCompatibility": false or true
- slightly change the whitespace around colons
- "dropNullPlaceholders": false or true
- Drop the "null" string from the writer's output for nullValues.
Strictly speaking, this is not valid JSON. But when the output is being
fed to a browser's Javascript, it makes for smaller output and the
browser can handle the output just fine.
- "useSpecialFloats": false or true
- If true, outputs non-finite floating point values in the following way:
NaN values as "NaN", positive infinity as "Infinity", and negative infinity
as "-Infinity".
You can examine 'settings_` yourself
to see the defaults. You can also write and read them just like any
JSON Value.
\sa setDefaults()
*/
Json::Value settings_;
StreamWriterBuilder();
~StreamWriterBuilder() JSONCPP_OVERRIDE;
/**
* \throw std::exception if something goes wrong (e.g. invalid settings)
*/
StreamWriter* newStreamWriter() const JSONCPP_OVERRIDE;
/** \return true if 'settings' are legal and consistent;
* otherwise, indicate bad settings via 'invalid'.
*/
bool validate(Json::Value* invalid) const;
/** A simple way to update a specific setting.
*/
Value& operator[](JSONCPP_STRING key);
/** Called by ctor, but you can use this to reset settings_.
* \pre 'settings' != NULL (but Json::null is fine)
* \remark Defaults:
* \snippet src/lib_json/json_writer.cpp StreamWriterBuilderDefaults
*/
static void setDefaults(Json::Value* settings);
};
/** \brief Abstract class for writers.
* \deprecated Use StreamWriter. (And really, this is an implementation detail.)
*/
class JSON_API Writer {
public:
virtual ~Writer();
virtual JSONCPP_STRING write(const Value& root) = 0;
};
/** \brief Outputs a Value in <a HREF="http://www.json.org">JSON</a> format
*without formatting (not human friendly).
*
* The JSON document is written in a single line. It is not intended for 'human'
*consumption,
* but may be usefull to support feature such as RPC where bandwith is limited.
* \sa Reader, Value
* \deprecated Use StreamWriterBuilder.
*/
class JSON_API FastWriter : public Writer {
public:
FastWriter();
~FastWriter() JSONCPP_OVERRIDE {}
void enableYAMLCompatibility();
/** \brief Drop the "null" string from the writer's output for nullValues.
* Strictly speaking, this is not valid JSON. But when the output is being
* fed to a browser's Javascript, it makes for smaller output and the
* browser can handle the output just fine.
*/
void dropNullPlaceholders();
void omitEndingLineFeed();
public: // overridden from Writer
JSONCPP_STRING write(const Value& root) JSONCPP_OVERRIDE;
private:
void writeValue(const Value& value);
JSONCPP_STRING document_;
bool yamlCompatiblityEnabled_;
bool dropNullPlaceholders_;
bool omitEndingLineFeed_;
};
/** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
*human friendly way.
*
* The rules for line break and indent are as follow:
* - Object value:
* - if empty then print {} without indent and line break
* - if not empty the print '{', line break & indent, print one value per
*line
* and then unindent and line break and print '}'.
* - Array value:
* - if empty then print [] without indent and line break
* - if the array contains no object value, empty array or some other value
*types,
* and all the values fit on one lines, then print the array on a single
*line.
* - otherwise, it the values do not fit on one line, or the array contains
* object or non empty array, then print one value per line.
*
* If the Value have comments then they are outputed according to their
*#CommentPlacement.
*
* \sa Reader, Value, Value::setComment()
* \deprecated Use StreamWriterBuilder.
*/
class JSON_API StyledWriter : public Writer {
public:
StyledWriter();
~StyledWriter() JSONCPP_OVERRIDE {}
public: // overridden from Writer
/** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
* \param root Value to serialize.
* \return String containing the JSON document that represents the root value.
*/
JSONCPP_STRING write(const Value& root) JSONCPP_OVERRIDE;
private:
void writeValue(const Value& value);
void writeArrayValue(const Value& value);
bool isMultineArray(const Value& value);
void pushValue(const JSONCPP_STRING& value);
void writeIndent();
void writeWithIndent(const JSONCPP_STRING& value);
void indent();
void unindent();
void writeCommentBeforeValue(const Value& root);
void writeCommentAfterValueOnSameLine(const Value& root);
bool hasCommentForValue(const Value& value);
static JSONCPP_STRING normalizeEOL(const JSONCPP_STRING& text);
typedef std::vector<JSONCPP_STRING> ChildValues;
ChildValues childValues_;
JSONCPP_STRING document_;
JSONCPP_STRING indentString_;
unsigned int rightMargin_;
unsigned int indentSize_;
bool addChildValues_;
};
/** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
human friendly way,
to a stream rather than to a string.
*
* The rules for line break and indent are as follow:
* - Object value:
* - if empty then print {} without indent and line break
* - if not empty the print '{', line break & indent, print one value per
line
* and then unindent and line break and print '}'.
* - Array value:
* - if empty then print [] without indent and line break
* - if the array contains no object value, empty array or some other value
types,
* and all the values fit on one lines, then print the array on a single
line.
* - otherwise, it the values do not fit on one line, or the array contains
* object or non empty array, then print one value per line.
*
* If the Value have comments then they are outputed according to their
#CommentPlacement.
*
* \param indentation Each level will be indented by this amount extra.
* \sa Reader, Value, Value::setComment()
* \deprecated Use StreamWriterBuilder.
*/
class JSON_API StyledStreamWriter {
public:
StyledStreamWriter(JSONCPP_STRING indentation = "\t");
~StyledStreamWriter() {}
public:
/** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
* \param out Stream to write to. (Can be ostringstream, e.g.)
* \param root Value to serialize.
* \note There is no point in deriving from Writer, since write() should not
* return a value.
*/
void write(JSONCPP_OSTREAM& out, const Value& root);
private:
void writeValue(const Value& value);
void writeArrayValue(const Value& value);
bool isMultineArray(const Value& value);
void pushValue(const JSONCPP_STRING& value);
void writeIndent();
void writeWithIndent(const JSONCPP_STRING& value);
void indent();
void unindent();
void writeCommentBeforeValue(const Value& root);
void writeCommentAfterValueOnSameLine(const Value& root);
bool hasCommentForValue(const Value& value);
static JSONCPP_STRING normalizeEOL(const JSONCPP_STRING& text);
typedef std::vector<JSONCPP_STRING> ChildValues;
ChildValues childValues_;
JSONCPP_OSTREAM* document_;
JSONCPP_STRING indentString_;
unsigned int rightMargin_;
JSONCPP_STRING indentation_;
bool addChildValues_ : 1;
bool indented_ : 1;
};
#if defined(JSON_HAS_INT64)
JSONCPP_STRING JSON_API valueToString(Int value);
JSONCPP_STRING JSON_API valueToString(UInt value);
#endif // if defined(JSON_HAS_INT64)
JSONCPP_STRING JSON_API valueToString(LargestInt value);
JSONCPP_STRING JSON_API valueToString(LargestUInt value);
JSONCPP_STRING JSON_API valueToString(double value);
JSONCPP_STRING JSON_API valueToString(bool value);
JSONCPP_STRING JSON_API valueToQuotedString(const char* value);
/// \brief Output using the StyledStreamWriter.
/// \see Json::operator>>()
JSON_API JSONCPP_OSTREAM& operator<<(JSONCPP_OSTREAM&, const Value& root);
} // namespace Json
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#pragma warning(pop)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#endif // JSON_WRITER_H_INCLUDED
// //////////////////////////////////////////////////////////////////////
// End of content of file: include/json/writer.h
// //////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: include/json/assertions.h
// //////////////////////////////////////////////////////////////////////
// Copyright 2007-2010 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef CPPTL_JSON_ASSERTIONS_H_INCLUDED
#define CPPTL_JSON_ASSERTIONS_H_INCLUDED
#include <stdlib.h>
#include <sstream>
#if !defined(JSON_IS_AMALGAMATION)
#include "config.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
/** It should not be possible for a maliciously designed file to
* cause an abort() or seg-fault, so these macros are used only
* for pre-condition violations and internal logic errors.
*/
#if JSON_USE_EXCEPTION
// @todo <= add detail about condition in exception
# define JSON_ASSERT(condition) \
{if (!(condition)) {Json::throwLogicError( "assert json failed" );}}
# define JSON_FAIL_MESSAGE(message) \
{ \
JSONCPP_OSTRINGSTREAM oss; oss << message; \
Json::throwLogicError(oss.str()); \
abort(); \
}
#else // JSON_USE_EXCEPTION
# define JSON_ASSERT(condition) assert(condition)
// The call to assert() will show the failure message in debug builds. In
// release builds we abort, for a core-dump or debugger.
# define JSON_FAIL_MESSAGE(message) \
{ \
JSONCPP_OSTRINGSTREAM oss; oss << message; \
assert(false && oss.str().c_str()); \
abort(); \
}
#endif
#define JSON_ASSERT_MESSAGE(condition, message) \
if (!(condition)) { \
JSON_FAIL_MESSAGE(message); \
}
#endif // CPPTL_JSON_ASSERTIONS_H_INCLUDED
// //////////////////////////////////////////////////////////////////////
// End of content of file: include/json/assertions.h
// //////////////////////////////////////////////////////////////////////
#endif //ifndef JSON_AMALGATED_H_INCLUDED
This source diff could not be displayed because it is too large. You can view the blob instead.
FILE(GLOB INCLUDE_FILES "json/*.h") FILE(GLOB INCLUDE_FILES "json/*.h")
INSTALL(FILES ${INCLUDE_FILES} DESTINATION ${INCLUDE_INSTALL_DIR}/json) INSTALL(FILES ${INCLUDE_FILES} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/json)
...@@ -9,6 +9,8 @@ ...@@ -9,6 +9,8 @@
#include <cstring> #include <cstring>
#include <memory> #include <memory>
#pragma pack(push, 8)
namespace Json { namespace Json {
template<typename T> template<typename T>
class SecureAllocator { class SecureAllocator {
...@@ -91,4 +93,6 @@ bool operator!=(const SecureAllocator<T>&, const SecureAllocator<U>&) { ...@@ -91,4 +93,6 @@ bool operator!=(const SecureAllocator<T>&, const SecureAllocator<U>&) {
} //namespace Json } //namespace Json
#pragma pack(pop)
#endif // CPPTL_JSON_ALLOCATOR_H_INCLUDED #endif // CPPTL_JSON_ALLOCATOR_H_INCLUDED
...@@ -83,10 +83,16 @@ ...@@ -83,10 +83,16 @@
// managable and fixes a set of common hard-to-find bugs. // managable and fixes a set of common hard-to-find bugs.
#if __cplusplus >= 201103L #if __cplusplus >= 201103L
# define JSONCPP_OVERRIDE override # define JSONCPP_OVERRIDE override
#elif defined(_MSC_VER) && _MSC_VER > 1600 # define JSONCPP_NOEXCEPT noexcept
#elif defined(_MSC_VER) && _MSC_VER > 1600 && _MSC_VER < 1900
# define JSONCPP_OVERRIDE override # define JSONCPP_OVERRIDE override
# define JSONCPP_NOEXCEPT throw()
#elif defined(_MSC_VER) && _MSC_VER >= 1900
# define JSONCPP_OVERRIDE override
# define JSONCPP_NOEXCEPT noexcept
#else #else
# define JSONCPP_OVERRIDE # define JSONCPP_OVERRIDE
# define JSONCPP_NOEXCEPT throw()
#endif #endif
#ifndef JSON_HAS_RVALUE_REFERENCES #ifndef JSON_HAS_RVALUE_REFERENCES
......
...@@ -10,6 +10,8 @@ ...@@ -10,6 +10,8 @@
#include "forwards.h" #include "forwards.h"
#endif // if !defined(JSON_IS_AMALGAMATION) #endif // if !defined(JSON_IS_AMALGAMATION)
#pragma pack(push, 8)
namespace Json { namespace Json {
/** \brief Configuration passed to reader and writer. /** \brief Configuration passed to reader and writer.
...@@ -54,4 +56,6 @@ public: ...@@ -54,4 +56,6 @@ public:
} // namespace Json } // namespace Json
#pragma pack(pop)
#endif // CPPTL_JSON_FEATURES_H_INCLUDED #endif // CPPTL_JSON_FEATURES_H_INCLUDED
...@@ -23,6 +23,8 @@ ...@@ -23,6 +23,8 @@
#pragma warning(disable : 4251) #pragma warning(disable : 4251)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#pragma pack(push, 8)
namespace Json { namespace Json {
/** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a /** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a
...@@ -397,6 +399,8 @@ JSON_API JSONCPP_ISTREAM& operator>>(JSONCPP_ISTREAM&, Value&); ...@@ -397,6 +399,8 @@ JSON_API JSONCPP_ISTREAM& operator>>(JSONCPP_ISTREAM&, Value&);
} // namespace Json } // namespace Json
#pragma pack(pop)
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#pragma warning(pop) #pragma warning(pop)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
......
...@@ -42,6 +42,8 @@ ...@@ -42,6 +42,8 @@
#pragma warning(disable : 4251) #pragma warning(disable : 4251)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#pragma pack(push, 8)
/** \brief JSON (JavaScript Object Notation). /** \brief JSON (JavaScript Object Notation).
*/ */
namespace Json { namespace Json {
...@@ -53,8 +55,8 @@ namespace Json { ...@@ -53,8 +55,8 @@ namespace Json {
class JSON_API Exception : public std::exception { class JSON_API Exception : public std::exception {
public: public:
Exception(JSONCPP_STRING const& msg); Exception(JSONCPP_STRING const& msg);
~Exception() throw() JSONCPP_OVERRIDE; ~Exception() JSONCPP_NOEXCEPT JSONCPP_OVERRIDE;
char const* what() const throw() JSONCPP_OVERRIDE; char const* what() const JSONCPP_NOEXCEPT JSONCPP_OVERRIDE;
protected: protected:
JSONCPP_STRING msg_; JSONCPP_STRING msg_;
}; };
...@@ -859,6 +861,7 @@ template<> ...@@ -859,6 +861,7 @@ template<>
inline void swap(Json::Value& a, Json::Value& b) { a.swap(b); } inline void swap(Json::Value& a, Json::Value& b) { a.swap(b); }
} }
#pragma pack(pop)
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#pragma warning(pop) #pragma warning(pop)
......
...@@ -3,10 +3,10 @@ ...@@ -3,10 +3,10 @@
#ifndef JSON_VERSION_H_INCLUDED #ifndef JSON_VERSION_H_INCLUDED
# define JSON_VERSION_H_INCLUDED # define JSON_VERSION_H_INCLUDED
# define JSONCPP_VERSION_STRING "1.7.7" # define JSONCPP_VERSION_STRING "1.8.0"
# define JSONCPP_VERSION_MAJOR 1 # define JSONCPP_VERSION_MAJOR 1
# define JSONCPP_VERSION_MINOR 7 # define JSONCPP_VERSION_MINOR 8
# define JSONCPP_VERSION_PATCH 7 # define JSONCPP_VERSION_PATCH 0
# define JSONCPP_VERSION_QUALIFIER # define JSONCPP_VERSION_QUALIFIER
# define JSONCPP_VERSION_HEXA ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | (JSONCPP_VERSION_PATCH << 8)) # define JSONCPP_VERSION_HEXA ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | (JSONCPP_VERSION_PATCH << 8))
......
...@@ -20,6 +20,8 @@ ...@@ -20,6 +20,8 @@
#pragma warning(disable : 4251) #pragma warning(disable : 4251)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#pragma pack(push, 8)
namespace Json { namespace Json {
class Value; class Value;
...@@ -324,6 +326,8 @@ JSON_API JSONCPP_OSTREAM& operator<<(JSONCPP_OSTREAM&, const Value& root); ...@@ -324,6 +326,8 @@ JSON_API JSONCPP_OSTREAM& operator<<(JSONCPP_OSTREAM&, const Value& root);
} // namespace Json } // namespace Json
#pragma pack(pop)
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#pragma warning(pop) #pragma warning(pop)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
......
prefix=@CMAKE_INSTALL_PREFIX@ prefix=@CMAKE_INSTALL_PREFIX@
exec_prefix=${prefix} exec_prefix=${prefix}
libdir=${exec_prefix}/@LIBRARY_INSTALL_DIR@ libdir=${exec_prefix}/@CMAKE_INSTALL_LIBDIR@
includedir=${prefix}/@INCLUDE_INSTALL_DIR@ includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@
Name: jsoncpp Name: jsoncpp
Description: A C++ library for interacting with JSON Description: A C++ library for interacting with JSON
......
if( CMAKE_COMPILER_IS_GNUCXX ) IF( CMAKE_COMPILER_IS_GNUCXX )
#Get compiler version. #Get compiler version.
execute_process( COMMAND ${CMAKE_CXX_COMPILER} -dumpversion EXECUTE_PROCESS( COMMAND ${CMAKE_CXX_COMPILER} -dumpversion
OUTPUT_VARIABLE GNUCXX_VERSION ) OUTPUT_VARIABLE GNUCXX_VERSION )
#-Werror=* was introduced -after- GCC 4.1.2 #-Werror=* was introduced -after- GCC 4.1.2
if( GNUCXX_VERSION VERSION_GREATER 4.1.2 ) IF( GNUCXX_VERSION VERSION_GREATER 4.1.2 )
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror=strict-aliasing") SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror=strict-aliasing")
endif() ENDIF()
endif( CMAKE_COMPILER_IS_GNUCXX ) ENDIF( CMAKE_COMPILER_IS_GNUCXX )
INCLUDE(CheckIncludeFileCXX)
INCLUDE(CheckTypeSize)
INCLUDE(CheckStructHasMember)
INCLUDE(CheckCXXSymbolExists)
check_include_file_cxx(clocale HAVE_CLOCALE)
check_cxx_symbol_exists(localeconv clocale HAVE_LOCALECONV)
IF(CMAKE_VERSION VERSION_LESS 3.0.0)
# The "LANGUAGE CXX" parameter is not supported in CMake versions below 3,
# so the C compiler and header has to be used.
check_include_file(locale.h HAVE_LOCALE_H)
SET(CMAKE_EXTRA_INCLUDE_FILES locale.h)
check_type_size("struct lconv" LCONV_SIZE)
UNSET(CMAKE_EXTRA_INCLUDE_FILES)
check_struct_has_member("struct lconv" decimal_point locale.h HAVE_DECIMAL_POINT)
ELSE()
SET(CMAKE_EXTRA_INCLUDE_FILES clocale)
check_type_size(lconv LCONV_SIZE LANGUAGE CXX)
UNSET(CMAKE_EXTRA_INCLUDE_FILES)
check_struct_has_member(lconv decimal_point clocale HAVE_DECIMAL_POINT LANGUAGE CXX)
ENDIF()
IF(NOT (HAVE_CLOCALE AND HAVE_LCONV_SIZE AND HAVE_DECIMAL_POINT AND HAVE_LOCALECONV))
MESSAGE(WARNING "Locale functionality is not supported")
ADD_DEFINITIONS(-DJSONCPP_NO_LOCALE_SUPPORT)
ENDIF()
SET( JSONCPP_INCLUDE_DIR ../../include ) SET( JSONCPP_INCLUDE_DIR ../../include )
...@@ -52,13 +80,13 @@ IF(BUILD_SHARED_LIBS) ...@@ -52,13 +80,13 @@ IF(BUILD_SHARED_LIBS)
ENDIF() ENDIF()
INSTALL( TARGETS jsoncpp_lib ${INSTALL_EXPORT} INSTALL( TARGETS jsoncpp_lib ${INSTALL_EXPORT}
RUNTIME DESTINATION ${RUNTIME_INSTALL_DIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
LIBRARY DESTINATION ${LIBRARY_INSTALL_DIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
ARCHIVE DESTINATION ${ARCHIVE_INSTALL_DIR}) ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR})
IF(NOT CMAKE_VERSION VERSION_LESS 2.8.11) IF(NOT CMAKE_VERSION VERSION_LESS 2.8.11)
TARGET_INCLUDE_DIRECTORIES( jsoncpp_lib PUBLIC TARGET_INCLUDE_DIRECTORIES( jsoncpp_lib PUBLIC
$<INSTALL_INTERFACE:${INCLUDE_INSTALL_DIR}> $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
$<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/${JSONCPP_INCLUDE_DIR}>) $<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/${JSONCPP_INCLUDE_DIR}>)
ENDIF() ENDIF()
...@@ -71,15 +99,15 @@ IF(BUILD_STATIC_LIBS) ...@@ -71,15 +99,15 @@ IF(BUILD_STATIC_LIBS)
DEBUG_OUTPUT_NAME jsoncpp${DEBUG_LIBNAME_SUFFIX} ) DEBUG_OUTPUT_NAME jsoncpp${DEBUG_LIBNAME_SUFFIX} )
INSTALL( TARGETS jsoncpp_lib_static ${INSTALL_EXPORT} INSTALL( TARGETS jsoncpp_lib_static ${INSTALL_EXPORT}
RUNTIME DESTINATION ${RUNTIME_INSTALL_DIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
LIBRARY DESTINATION ${LIBRARY_INSTALL_DIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
ARCHIVE DESTINATION ${ARCHIVE_INSTALL_DIR}) ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR})
IF(NOT CMAKE_VERSION VERSION_LESS 2.8.11) IF(NOT CMAKE_VERSION VERSION_LESS 2.8.11)
TARGET_INCLUDE_DIRECTORIES( jsoncpp_lib_static PUBLIC TARGET_INCLUDE_DIRECTORIES( jsoncpp_lib_static PUBLIC
$<INSTALL_INTERFACE:${INCLUDE_INSTALL_DIR}> $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
$<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/${JSONCPP_INCLUDE_DIR}> $<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/${JSONCPP_INCLUDE_DIR}>
) )
ENDIF() ENDIF()
ENDIF() ENDIF()
// Copyright 2007-2011 Baptiste Lepilleur // Copyright 2007-2011 Baptiste Lepilleur
// Copyright (C) 2016 InfoTeCS JSC. All rights reserved.
// Distributed under MIT license, or public domain if desired and // Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction. // recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
...@@ -44,8 +45,12 @@ ...@@ -44,8 +45,12 @@
#pragma warning(disable : 4996) #pragma warning(disable : 4996)
#endif #endif
static int const stackLimit_g = 1000; // Define JSONCPP_DEPRECATED_STACK_LIMIT as an appropriate integer at compile time to change the stack limit
static int stackDepth_g = 0; // see readValue() #if !defined(JSONCPP_DEPRECATED_STACK_LIMIT)
#define JSONCPP_DEPRECATED_STACK_LIMIT 1000
#endif
static size_t const stackLimit_g = JSONCPP_DEPRECATED_STACK_LIMIT; // see readValue()
namespace Json { namespace Json {
...@@ -138,7 +143,6 @@ bool Reader::parse(const char* beginDoc, ...@@ -138,7 +143,6 @@ bool Reader::parse(const char* beginDoc,
nodes_.pop(); nodes_.pop();
nodes_.push(&root); nodes_.push(&root);
stackDepth_g = 0; // Yes, this is bad coding, but options are limited.
bool successful = readValue(); bool successful = readValue();
Token token; Token token;
skipCommentTokens(token); skipCommentTokens(token);
...@@ -161,12 +165,10 @@ bool Reader::parse(const char* beginDoc, ...@@ -161,12 +165,10 @@ bool Reader::parse(const char* beginDoc,
} }
bool Reader::readValue() { bool Reader::readValue() {
// This is a non-reentrant way to support a stackLimit. Terrible! // readValue() may call itself only if it calls readObject() or ReadArray().
// But this deprecated class has a security problem: Bad input can // These methods execute nodes_.push() just before and nodes_.pop)() just after calling readValue().
// cause a seg-fault. This seems like a fair, binary-compatible way // parse() executes one nodes_.push(), so > instead of >=.
// to prevent the problem. if (nodes_.size() > stackLimit_g) throwRuntimeError("Exceeded stackLimit in readValue().");
if (stackDepth_g >= stackLimit_g) throwRuntimeError("Exceeded stackLimit in readValue().");
++stackDepth_g;
Token token; Token token;
skipCommentTokens(token); skipCommentTokens(token);
...@@ -240,7 +242,6 @@ bool Reader::readValue() { ...@@ -240,7 +242,6 @@ bool Reader::readValue() {
lastValue_ = &currentValue(); lastValue_ = &currentValue();
} }
--stackDepth_g;
return successful; return successful;
} }
...@@ -1028,7 +1029,6 @@ private: ...@@ -1028,7 +1029,6 @@ private:
Location lastValueEnd_; Location lastValueEnd_;
Value* lastValue_; Value* lastValue_;
JSONCPP_STRING commentsBefore_; JSONCPP_STRING commentsBefore_;
int stackDepth_;
OurFeatures const features_; OurFeatures const features_;
bool collectComments_; bool collectComments_;
...@@ -1039,7 +1039,6 @@ private: ...@@ -1039,7 +1039,6 @@ private:
OurReader::OurReader(OurFeatures const& features) OurReader::OurReader(OurFeatures const& features)
: errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(), : errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(),
lastValue_(), commentsBefore_(), lastValue_(), commentsBefore_(),
stackDepth_(0),
features_(features), collectComments_() { features_(features), collectComments_() {
} }
...@@ -1063,7 +1062,6 @@ bool OurReader::parse(const char* beginDoc, ...@@ -1063,7 +1062,6 @@ bool OurReader::parse(const char* beginDoc,
nodes_.pop(); nodes_.pop();
nodes_.push(&root); nodes_.push(&root);
stackDepth_ = 0;
bool successful = readValue(); bool successful = readValue();
Token token; Token token;
skipCommentTokens(token); skipCommentTokens(token);
...@@ -1092,8 +1090,8 @@ bool OurReader::parse(const char* beginDoc, ...@@ -1092,8 +1090,8 @@ bool OurReader::parse(const char* beginDoc,
} }
bool OurReader::readValue() { bool OurReader::readValue() {
if (stackDepth_ >= features_.stackLimit_) throwRuntimeError("Exceeded stackLimit in readValue()."); // To preserve the old behaviour we cast size_t to int.
++stackDepth_; if (static_cast<int>(nodes_.size()) > features_.stackLimit_) throwRuntimeError("Exceeded stackLimit in readValue().");
Token token; Token token;
skipCommentTokens(token); skipCommentTokens(token);
bool successful = true; bool successful = true;
...@@ -1190,7 +1188,6 @@ bool OurReader::readValue() { ...@@ -1190,7 +1188,6 @@ bool OurReader::readValue() {
lastValue_ = &currentValue(); lastValue_ = &currentValue();
} }
--stackDepth_;
return successful; return successful;
} }
......
...@@ -6,7 +6,13 @@ ...@@ -6,7 +6,13 @@
#ifndef LIB_JSONCPP_JSON_TOOL_H_INCLUDED #ifndef LIB_JSONCPP_JSON_TOOL_H_INCLUDED
#define LIB_JSONCPP_JSON_TOOL_H_INCLUDED #define LIB_JSONCPP_JSON_TOOL_H_INCLUDED
#ifndef NO_LOCALE_SUPPORT
// Also support old flag NO_LOCALE_SUPPORT
#ifdef NO_LOCALE_SUPPORT
#define JSONCPP_NO_LOCALE_SUPPORT
#endif
#ifndef JSONCPP_NO_LOCALE_SUPPORT
#include <clocale> #include <clocale>
#endif #endif
...@@ -18,7 +24,7 @@ ...@@ -18,7 +24,7 @@
namespace Json { namespace Json {
static char getDecimalPoint() { static char getDecimalPoint() {
#ifdef NO_LOCALE_SUPPORT #ifdef JSONCPP_NO_LOCALE_SUPPORT
return '\0'; return '\0';
#else #else
struct lconv* lc = localeconv(); struct lconv* lc = localeconv();
......
...@@ -193,9 +193,9 @@ namespace Json { ...@@ -193,9 +193,9 @@ namespace Json {
Exception::Exception(JSONCPP_STRING const& msg) Exception::Exception(JSONCPP_STRING const& msg)
: msg_(msg) : msg_(msg)
{} {}
Exception::~Exception() throw() Exception::~Exception() JSONCPP_NOEXCEPT
{} {}
char const* Exception::what() const throw() char const* Exception::what() const JSONCPP_NOEXCEPT
{ {
return msg_.c_str(); return msg_.c_str();
} }
...@@ -343,7 +343,7 @@ bool Value::CZString::isStaticString() const { return storage_.policy_ == noDupl ...@@ -343,7 +343,7 @@ bool Value::CZString::isStaticString() const { return storage_.policy_ == noDupl
* This optimization is used in ValueInternalMap fast allocator. * This optimization is used in ValueInternalMap fast allocator.
*/ */
Value::Value(ValueType vtype) { Value::Value(ValueType vtype) {
static char const empty[] = ""; static char const emptyString[] = "";
initBasic(vtype); initBasic(vtype);
switch (vtype) { switch (vtype) {
case nullValue: case nullValue:
...@@ -357,7 +357,7 @@ Value::Value(ValueType vtype) { ...@@ -357,7 +357,7 @@ Value::Value(ValueType vtype) {
break; break;
case stringValue: case stringValue:
// allocated_ == false, so this is safe. // allocated_ == false, so this is safe.
value_.string_ = const_cast<char*>(static_cast<char const*>(empty)); value_.string_ = const_cast<char*>(static_cast<char const*>(emptyString));
break; break;
case arrayValue: case arrayValue:
case objectValue: case objectValue:
...@@ -1279,7 +1279,11 @@ bool Value::isBool() const { return type_ == booleanValue; } ...@@ -1279,7 +1279,11 @@ bool Value::isBool() const { return type_ == booleanValue; }
bool Value::isInt() const { bool Value::isInt() const {
switch (type_) { switch (type_) {
case intValue: case intValue:
#if defined(JSON_HAS_INT64)
return value_.int_ >= minInt && value_.int_ <= maxInt; return value_.int_ >= minInt && value_.int_ <= maxInt;
#else
return true;
#endif
case uintValue: case uintValue:
return value_.uint_ <= UInt(maxInt); return value_.uint_ <= UInt(maxInt);
case realValue: case realValue:
...@@ -1294,9 +1298,17 @@ bool Value::isInt() const { ...@@ -1294,9 +1298,17 @@ bool Value::isInt() const {
bool Value::isUInt() const { bool Value::isUInt() const {
switch (type_) { switch (type_) {
case intValue: case intValue:
#if defined(JSON_HAS_INT64)
return value_.int_ >= 0 && LargestUInt(value_.int_) <= LargestUInt(maxUInt); return value_.int_ >= 0 && LargestUInt(value_.int_) <= LargestUInt(maxUInt);
#else
return value_.int_ >= 0;
#endif
case uintValue: case uintValue:
#if defined(JSON_HAS_INT64)
return value_.uint_ <= maxUInt; return value_.uint_ <= maxUInt;
#else
return true;
#endif
case realValue: case realValue:
return value_.real_ >= 0 && value_.real_ <= maxUInt && return value_.real_ >= 0 && value_.real_ <= maxUInt &&
IsIntegral(value_.real_); IsIntegral(value_.real_);
...@@ -1354,9 +1366,9 @@ bool Value::isIntegral() const { ...@@ -1354,9 +1366,9 @@ bool Value::isIntegral() const {
#endif #endif
} }
bool Value::isDouble() const { return type_ == realValue || isIntegral(); } bool Value::isDouble() const { return type_ == intValue || type_ == uintValue || type_ == realValue; }
bool Value::isNumeric() const { return isIntegral() || isDouble(); } bool Value::isNumeric() const { return isDouble(); }
bool Value::isString() const { return type_ == stringValue; } bool Value::isString() const { return type_ == stringValue; }
......
...@@ -139,7 +139,7 @@ namespace { ...@@ -139,7 +139,7 @@ namespace {
JSONCPP_STRING valueToString(double value, bool useSpecialFloats, unsigned int precision) { JSONCPP_STRING valueToString(double value, bool useSpecialFloats, unsigned int precision) {
// Allocate a buffer that is more than large enough to store the 16 digits of // Allocate a buffer that is more than large enough to store the 16 digits of
// precision requested below. // precision requested below.
char buffer[32]; char buffer[36];
int len = -1; int len = -1;
char formatString[6]; char formatString[6];
...@@ -150,6 +150,12 @@ JSONCPP_STRING valueToString(double value, bool useSpecialFloats, unsigned int p ...@@ -150,6 +150,12 @@ JSONCPP_STRING valueToString(double value, bool useSpecialFloats, unsigned int p
// concepts of reals and integers. // concepts of reals and integers.
if (isfinite(value)) { if (isfinite(value)) {
len = snprintf(buffer, sizeof(buffer), formatString, value); len = snprintf(buffer, sizeof(buffer), formatString, value);
// try to ensure we preserve the fact that this was given to us as a double on input
if (!strstr(buffer, ".") && !strstr(buffer, "e")) {
strcat(buffer, ".0");
}
} else { } else {
// IEEE standard states that NaN values will not compare to themselves // IEEE standard states that NaN values will not compare to themselves
if (value != value) { if (value != value) {
......
...@@ -479,7 +479,7 @@ JSONTEST_FIXTURE(ValueTest, integers) { ...@@ -479,7 +479,7 @@ JSONTEST_FIXTURE(ValueTest, integers) {
JSONTEST_ASSERT_EQUAL(0.0, val.asDouble()); JSONTEST_ASSERT_EQUAL(0.0, val.asDouble());
JSONTEST_ASSERT_EQUAL(0.0, val.asFloat()); JSONTEST_ASSERT_EQUAL(0.0, val.asFloat());
JSONTEST_ASSERT_EQUAL(false, val.asBool()); JSONTEST_ASSERT_EQUAL(false, val.asBool());
JSONTEST_ASSERT_STRING_EQUAL("0", val.asString()); JSONTEST_ASSERT_STRING_EQUAL("0.0", val.asString());
// Zero (signed constructor arg) // Zero (signed constructor arg)
val = Json::Value(0); val = Json::Value(0);
...@@ -563,7 +563,7 @@ JSONTEST_FIXTURE(ValueTest, integers) { ...@@ -563,7 +563,7 @@ JSONTEST_FIXTURE(ValueTest, integers) {
JSONTEST_ASSERT_EQUAL(0.0, val.asDouble()); JSONTEST_ASSERT_EQUAL(0.0, val.asDouble());
JSONTEST_ASSERT_EQUAL(0.0, val.asFloat()); JSONTEST_ASSERT_EQUAL(0.0, val.asFloat());
JSONTEST_ASSERT_EQUAL(false, val.asBool()); JSONTEST_ASSERT_EQUAL(false, val.asBool());
JSONTEST_ASSERT_STRING_EQUAL("0", val.asString()); JSONTEST_ASSERT_STRING_EQUAL("0.0", val.asString());
// 2^20 (signed constructor arg) // 2^20 (signed constructor arg)
val = Json::Value(1 << 20); val = Json::Value(1 << 20);
...@@ -646,7 +646,7 @@ JSONTEST_FIXTURE(ValueTest, integers) { ...@@ -646,7 +646,7 @@ JSONTEST_FIXTURE(ValueTest, integers) {
JSONTEST_ASSERT_EQUAL((1 << 20), val.asDouble()); JSONTEST_ASSERT_EQUAL((1 << 20), val.asDouble());
JSONTEST_ASSERT_EQUAL((1 << 20), val.asFloat()); JSONTEST_ASSERT_EQUAL((1 << 20), val.asFloat());
JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_EQUAL(true, val.asBool());
JSONTEST_ASSERT_STRING_EQUAL("1048576", JSONTEST_ASSERT_STRING_EQUAL("1048576.0",
normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString())));
// -2^20 // -2^20
...@@ -887,7 +887,7 @@ JSONTEST_FIXTURE(ValueTest, integers) { ...@@ -887,7 +887,7 @@ JSONTEST_FIXTURE(ValueTest, integers) {
JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asDouble()); JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asDouble());
JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asFloat()); JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asFloat());
JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_EQUAL(true, val.asBool());
JSONTEST_ASSERT_STRING_EQUAL("1099511627776", JSONTEST_ASSERT_STRING_EQUAL("1099511627776.0",
normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString())));
// -2^40 // -2^40
...@@ -1259,7 +1259,7 @@ JSONTEST_FIXTURE(ValueTest, nonIntegers) { ...@@ -1259,7 +1259,7 @@ JSONTEST_FIXTURE(ValueTest, nonIntegers) {
// A 16-digit floating point number. // A 16-digit floating point number.
val = Json::Value(2199023255552000.0f); val = Json::Value(2199023255552000.0f);
JSONTEST_ASSERT_EQUAL(float(2199023255552000.0f), val.asFloat()); JSONTEST_ASSERT_EQUAL(float(2199023255552000.0f), val.asFloat());
JSONTEST_ASSERT_STRING_EQUAL("2199023255552000", JSONTEST_ASSERT_STRING_EQUAL("2199023255552000.0",
normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString())));
// A very large floating point number. // A very large floating point number.
......
[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论