BDE 4.39.x Production Release
Loading...
Searching...
No Matches
bslfmt_mockformatcontext

Detailed Description

Provide mock context to test formatter specializations.

Outline

Purpose

Provide mock context to test formatter specializations

Classes

Description

This component provides a class that holds the state of the format operation and is used for formatter testing.

Usage

This section illustrates intended usage of this component.

Example: Testing a formatter

Suppose we want to test format function of some formatter that meets BasicFormatter requirements. For example a formatter that formats integer values:

template <class t_VALUE>
class IntegerFormatter {
public:
// CREATORS
/// Create a formatter object.
IntegerFormatter();
// MANIPULATORS
/// Parse the specified `parseContext` and return an iterator, pointing
/// to the end of the format string.
template <class t_PARSE_CONTEXT>
typename t_PARSE_CONTEXT::iterator parse(
t_PARSE_CONTEXT& parseContext);
// ACCESSORS
/// Create string representation of the specified `value`, customized
/// in accordance with the requested format and the specified
/// `formatContext`, and copy it to the output that the output iterator
/// of the `formatContext` points to.
template <class t_FORMAT_CONTEXT>
typename t_FORMAT_CONTEXT::iterator format(
t_VALUE value,
t_FORMAT_CONTEXT& formatContext) const;
};

First, we create an object of our formatter:

IntegerFormatter<int> formatter;

Next, we specify a value to format and define expected result of formatting. In this example we will skip the spec parsing step, but let's say we want to format the number 42 with the following spec: "*<5x".

const int value = 42;
const char *expectedResult = "2a***";
const size_t expectedResultLength = std::strlen(expectedResult);

Now create a MockFormatContext and format the value using our formatter:

typedef bslfmt::MockFormatContext<char> FormatContext;
FormatContext mfc(value);
FormatContext::iterator begin = mfc.out();
mfc.advance_to(bsl::as_const(formatter).format(value, mfc));
FormatContext::iterator end = mfc.out();
Definition bslfmt_mockformatcontext.h:206
BSLS_KEYWORD_CONSTEXPR bsl::add_const< TYPE >::type & as_const(TYPE &t) BSLS_KEYWORD_NOEXCEPT
Return a reference offering non-modifiable access to the specified t.
Definition bslstl_utility.h:129

Finally, verify that format function returns the correct past-the-end iterator and produces the expected result string:

const size_t actualResultLength = static_cast<size_t>(end.rawPointer() -
begin.rawPointer());
ASSERT(expectedResultLength == actualResultLength);
assert(expectedResult == mfc.finalString());