diff options
40 files changed, 1199 insertions, 1198 deletions
| diff --git a/Jamroot.jam b/Jamroot.jam index 7c80214..da57267 100644 --- a/Jamroot.jam +++ b/Jamroot.jam @@ -22,10 +22,17 @@ project  			<toolset>tidy:<checkxx>bugprone-*  			<toolset>tidy:<checkxx>clang-*  			<toolset>tidy:<checkxx>misc-* +			<toolset>tidy:<xcheckxx>misc-non-private-member-variables-in-classes  			<toolset>tidy:<checkxx>modernize-*  			<toolset>tidy:<xcheckxx>modernize-use-trailing-return-type  			<toolset>tidy:<checkxx>hicpp-*  			<toolset>tidy:<checkxx>performance-* +			<toolset>tidy:<exclude>common/bin/http.h +			<toolset>tidy:<exclude>common/bin/session.h +			<toolset>tidy:<exclude>compile/bin/tidy/debug/cxxstd-17-iso/routes.h +			<toolset>tidy:<exclude>core/bin/routeOptions.h +			<toolset>tidy:<exclude>unittests/bin/test-api.h +			<toolset>tidy:<exclude>unittests/bin/test-fcgi.h  	;  build-project icespider ; diff --git a/icespider/common/formatters.h b/icespider/common/formatters.h index e42717e..2b36b08 100644 --- a/icespider/common/formatters.h +++ b/icespider/common/formatters.h @@ -10,4 +10,3 @@ namespace IceSpider {  }  #endif - diff --git a/icespider/common/pathparts.cpp b/icespider/common/pathparts.cpp index aabdd13..905e4d5 100644 --- a/icespider/common/pathparts.cpp +++ b/icespider/common/pathparts.cpp @@ -6,8 +6,7 @@ namespace ba = boost::algorithm;  namespace IceSpider {  	const auto slash = ba::first_finder("/", ba::is_equal()); -	Path::Path(const std::string_view & p) : -		path(p) +	Path::Path(const std::string_view & p) : path(p)  	{  		auto relp = p.substr(1);  		if (relp.empty()) { @@ -30,10 +29,7 @@ namespace IceSpider {  		return parts.size();  	} -	PathLiteral::PathLiteral(const std::string_view & p) : -		value(p) -	{ -	} +	PathLiteral::PathLiteral(const std::string_view & p) : value(p) { }  	bool  	PathLiteral::matches(const std::string_view & v) const @@ -41,10 +37,7 @@ namespace IceSpider {  		return value == v;  	} -	PathParameter::PathParameter(const std::string_view & s) : -		name(s.substr(1, s.length() - 2)) -	{ -	} +	PathParameter::PathParameter(const std::string_view & s) : name(s.substr(1, s.length() - 2)) { }  	bool  	PathParameter::matches(const std::string_view &) const @@ -52,4 +45,3 @@ namespace IceSpider {  		return true;  	}  } - diff --git a/icespider/common/pathparts.h b/icespider/common/pathparts.h index 7626873..4aaf926 100644 --- a/icespider/common/pathparts.h +++ b/icespider/common/pathparts.h @@ -1,51 +1,53 @@  #ifndef ICESPIDER_CORE_PATHS_H  #define ICESPIDER_CORE_PATHS_H -#include <vector> -#include <string_view> +#include <c++11Helpers.h>  #include <memory> +#include <string_view> +#include <vector>  #include <visibility.h>  namespace IceSpider {  	class DLL_PUBLIC PathPart { -		public: -			virtual ~PathPart() = default; +	public: +		PathPart() = default; +		virtual ~PathPart() = default; +		SPECIAL_MEMBERS_DEFAULT(PathPart); -			virtual bool matches(const std::string_view &) const = 0; +		[[nodiscard]] virtual bool matches(const std::string_view &) const = 0;  	}; -	typedef std::unique_ptr<PathPart> PathPartPtr; +	using PathPartPtr = std::unique_ptr<PathPart>;  	class DLL_PUBLIC PathLiteral : public PathPart { -		public: -			PathLiteral(const std::string_view & v); +	public: +		explicit PathLiteral(const std::string_view & v); -			bool matches(const std::string_view &) const; +		[[nodiscard]] bool matches(const std::string_view &) const override; -			const std::string_view value; +		const std::string_view value;  	};  	class DLL_PUBLIC PathParameter : public PathPart { -		public: -			PathParameter(const std::string_view &); +	public: +		explicit PathParameter(const std::string_view &); -			bool matches(const std::string_view &) const; +		[[nodiscard]] bool matches(const std::string_view &) const override; -			const std::string_view name; +		const std::string_view name;  	};  	class DLL_PUBLIC Path { -		public: -			typedef std::vector<PathPartPtr> PathParts; +	public: +		using PathParts = std::vector<PathPartPtr>; -			Path(const std::string_view &); +		explicit Path(const std::string_view &); -			const std::string_view path; +		std::string_view path; -			unsigned int pathElementCount() const; +		[[nodiscard]] unsigned int pathElementCount() const; -			PathParts parts; +		PathParts parts;  	};  }  #endif - diff --git a/icespider/compile/main.cpp b/icespider/compile/main.cpp index a6bc226..804141b 100644 --- a/icespider/compile/main.cpp +++ b/icespider/compile/main.cpp @@ -1,5 +1,5 @@ -#include <boost/program_options.hpp>  #include "routeCompiler.h" +#include <boost/program_options.hpp>  namespace po = boost::program_options; @@ -10,12 +10,9 @@ main(int c, char ** v)  	IceSpider::Compile::RouteCompiler rc;  	std::filesystem::path input, output;  	po::options_description opts("IceSpider compile options"); -	opts.add_options() -		("input", po::value(&input), "Input .json file") -		("output", po::value(&output), "Output .cpp file") -		("include,I", po::value(&rc.searchPath)->composing(), "Search path") -		("help,h", po::value(&showHelp)->default_value(false)->zero_tokens(), "Help") -		; +	opts.add_options()("input", po::value(&input), "Input .json file")("output", po::value(&output), +			"Output .cpp file")("include,I", po::value(&rc.searchPath)->composing(), "Search path")( +			"help,h", po::value(&showHelp)->default_value(false)->zero_tokens(), "Help");  	po::positional_options_description pod;  	pod.add("input", 1).add("output", 2);  	po::variables_map vm; @@ -34,4 +31,3 @@ main(int c, char ** v)  	return 0;  } - diff --git a/icespider/compile/routeCompiler.cpp b/icespider/compile/routeCompiler.cpp index b94606c..8b357ba 100644 --- a/icespider/compile/routeCompiler.cpp +++ b/icespider/compile/routeCompiler.cpp @@ -1,16 +1,15 @@  #include "routeCompiler.h" -#include <pathparts.h> -#include <slicer/slicer.h> -#include <slicer/modelPartsTypes.h> +#include <Slice/CPlusPlusUtil.h>  #include <Slice/Preprocessor.h> -#include <scopeExit.h> -#include <fprintbf.h> -#include <filesystem> -#include <boost/algorithm/string/replace.hpp>  #include <boost/algorithm/string/join.hpp> -#include <Slice/CPlusPlusUtil.h> +#include <boost/algorithm/string/replace.hpp>  #include <compileTimeFormatter.h> - +#include <filesystem> +#include <fprintbf.h> +#include <pathparts.h> +#include <scopeExit.h> +#include <slicer/modelPartsTypes.h> +#include <slicer/slicer.h>  namespace IceSpider {  	using namespace AdHoc::literals; @@ -23,11 +22,13 @@ namespace IceSpider {  		RouteConfigurationPtr  		RouteCompiler::loadConfiguration(const std::filesystem::path & input) const  		{ -			auto deserializer = Slicer::DeserializerPtr(Slicer::FileDeserializerFactory::createNew(input.extension().string(), input)); +			auto deserializer = Slicer::DeserializerPtr( +					Slicer::FileDeserializerFactory::createNew(input.extension().string(), input));  			return Slicer::DeserializeAnyWith<RouteConfigurationPtr>(deserializer);  		} -		Ice::StringSeq operator+(Ice::StringSeq ss, const std::string & s) +		Ice::StringSeq +		operator+(Ice::StringSeq ss, const std::string & s)  		{  			ss.push_back(s);  			return ss; @@ -66,45 +67,39 @@ namespace IceSpider {  			throw std::runtime_error("Find operation " + on + " failed.");  		} -		RouteCompiler::Type +		std::optional<RouteCompiler::Type>  		RouteCompiler::findType(const std::string & tn, const Slice::ContainerPtr & c, const Ice::StringSeq & ns)  		{  			for (const auto & strct : c->structs()) {  				auto fqon = boost::algorithm::join(ns + strct->name(), ".");  				if (fqon == tn) { -					return { strct, nullptr };	 +					return {{Slice::typeToString(strct), {}, strct->dataMembers()}};  				}  				auto t = findType(tn, strct, ns + strct->name());  			}  			for (const auto & cls : c->classes()) {  				auto fqon = boost::algorithm::join(ns + cls->name(), ".");  				if (fqon == tn) { -					return { nullptr, cls->declaration() }; +					return {{Slice::typeToString(cls->declaration()), cls->scoped(), cls->dataMembers()}};  				} -				auto t = findType(tn, cls, ns + cls->name()); -				// NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDelete) -				if (t.first || t.second) { +				if (auto t = findType(tn, cls, ns + cls->name())) {  					return t;  				}  			}  			for (const auto & m : c->modules()) { -				auto t = findType(tn, m, ns + m->name()); -				// NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDelete) -				if (t.first || t.second) { +				if (auto t = findType(tn, m, ns + m->name())) {  					return t;  				}  			} -			return { nullptr, nullptr }; +			return {};  		}  		RouteCompiler::Type  		RouteCompiler::findType(const std::string & tn, const Units & us)  		{  			for (const auto & u : us) { -				// NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDelete) -				auto t = findType(tn, u.second); -				if (t.first || t.second) { -					return t; +				if (auto t = findType(tn, u.second)) { +					return *t;  				}  			}  			throw std::runtime_error("Find type " + tn + " failed."); @@ -137,7 +132,8 @@ namespace IceSpider {  		{  			for (const auto & r : c->routes) {  				if (r.second->operation) { -					r.second->operations[std::string()] = std::make_shared<Operation>(*r.second->operation, StringMap()); +					r.second->operations[std::string()] +							= std::make_shared<Operation>(*r.second->operation, StringMap());  				}  				auto ps = findParameters(r.second, u);  				for (const auto & p : ps) { @@ -148,7 +144,12 @@ namespace IceSpider {  						}  					}  					else { -						defined = r.second->params.insert({ p.first, std::make_shared<Parameter>(ParameterSource::URL, p.first, false, Ice::optional<std::string>(), Ice::optional<std::string>(), false) }).first; +						defined = r.second->params +										  .insert({p.first, +												  std::make_shared<Parameter>(ParameterSource::URL, p.first, false, +														  Ice::optional<std::string>(), Ice::optional<std::string>(), +														  false)}) +										  .first;  					}  					auto d = defined->second;  					if (d->source == ParameterSource::URL) { @@ -184,15 +185,15 @@ namespace IceSpider {  				throw std::runtime_error("Failed to open output files");  			}  			AdHoc::ScopeExit outClose( -				[out,outh]() { -					fclose(out); -					fclose(outh); -				}, -				nullptr, -				[&output,&outputh]() { -					std::filesystem::remove(output); -					std::filesystem::remove(outputh); -				}); +					[out, outh]() { +						fclose(out); +						fclose(outh); +					}, +					nullptr, +					[&output, &outputh]() { +						std::filesystem::remove(output); +						std::filesystem::remove(outputh); +					});  			processConfiguration(out, outh, output.stem().string(), configuration, units);  		} @@ -225,7 +226,9 @@ namespace IceSpider {  				}  				Slice::UnitPtr u = Slice::Unit::createUnit(false, false, false, false); -				uDestroy.onFailure.emplace_back([u]() { u->destroy(); }); +				uDestroy.onFailure.emplace_back([u]() { +					u->destroy(); +				});  				int parseStatus = u->parse(realSlice.string(), cppHandle, false); @@ -242,9 +245,9 @@ namespace IceSpider {  			return units;  		} -		template<typename ... X> +		template<typename... X>  		void -		fprintbf(unsigned int indent, FILE * output, const X & ... x) +		fprintbf(unsigned int indent, FILE * output, const X &... x)  		{  			for (; indent > 0; --indent) {  				fputc('\t', output); @@ -254,36 +257,32 @@ namespace IceSpider {  		}  		template<typename Enum> -		std::string getEnumString(Enum & e) +		std::string +		getEnumString(Enum & e)  		{  			return Slicer::ModelPartForEnum<Enum>::lookup(e);  		} -		static -		std::string +		static std::string  		outputSerializerClass(const IceSpider::OutputSerializers::value_type & os)  		{  			return boost::algorithm::replace_all_copy(os.second->serializer, ".", "::");  		}  		AdHocFormatter(MimePair, R"C({ "%?", "%?" })C"); -		static -		std::string +		static std::string  		outputSerializerMime(const IceSpider::OutputSerializers::value_type & os)  		{  			auto slash = os.first.find('/'); -			return MimePair::get( -					os.first.substr(0, slash), os.first.substr(slash + 1)); +			return MimePair::get(os.first.substr(0, slash), os.first.substr(slash + 1));  		}  		void  		RouteCompiler::registerOutputSerializers(FILE * output, const RoutePtr & r) const  		{  			for (const auto & os : r->outputSerializers) { -				fprintbf(4, output, "addRouteSerializer(%s,\n", -						outputSerializerMime(os)); -				fprintbf(6, output, "std::make_shared<%s::IceSpiderFactory>(", -						outputSerializerClass(os)); +				fprintbf(4, output, "addRouteSerializer(%s,\n", outputSerializerMime(os)); +				fprintbf(6, output, "std::make_shared<%s::IceSpiderFactory>(", outputSerializerClass(os));  				for (auto p = os.second->params.begin(); p != os.second->params.end(); ++p) {  					if (p != os.second->params.begin()) {  						fputs(", ", output); @@ -295,7 +294,8 @@ namespace IceSpider {  		}  		void -		RouteCompiler::processConfiguration(FILE * output, FILE * outputh, const std::string & name, const RouteConfigurationPtr & c, const Units & units) const +		RouteCompiler::processConfiguration(FILE * output, FILE * outputh, const std::string & name, +				const RouteConfigurationPtr & c, const Units & units) const  		{  			fputs("// This source files was generated by IceSpider.\n", output);  			fprintbf(output, "// Configuration name: %s\n\n", c->name); @@ -332,7 +332,8 @@ namespace IceSpider {  		}  		void -		RouteCompiler::processBases(FILE * output, FILE * outputh, const RouteConfigurationPtr & c, const Units & u) const +		RouteCompiler::processBases( +				FILE * output, FILE * outputh, const RouteConfigurationPtr & c, const Units & u) const  		{  			fputs("\n", outputh);  			fprintbf(outputh, "namespace %s {\n", c->name); @@ -353,7 +354,7 @@ namespace IceSpider {  			fprintbf(1, outputh, "class %s {\n", b.first);  			fprintbf(2, outputh, "protected:\n");  			fprintbf(3, outputh, "explicit %s(const IceSpider::Core * core);\n\n", b.first); -			for (const auto & f: b.second->functions) { +			for (const auto & f : b.second->functions) {  				fprintbf(3, outputh, "%s;\n", f);  			}  			fprintbf(1, output, "%s::%s(const IceSpider::Core * core)", b.first, b.first); @@ -363,10 +364,9 @@ namespace IceSpider {  			fputs("\n", output);  			unsigned int pn = 0;  			for (const auto & p : b.second->proxies) { -				fprintbf(3, outputh, "const %sPrxPtr prx%u;\n", -						boost::algorithm::replace_all_copy(p, ".", "::"), pn); -				fprintbf(3, output, "prx%u(core->getProxy<%s>())", -						pn, boost::algorithm::replace_all_copy(p, ".", "::")); +				fprintbf(3, outputh, "const %sPrxPtr prx%u;\n", boost::algorithm::replace_all_copy(p, ".", "::"), pn); +				fprintbf( +						3, output, "prx%u(core->getProxy<%s>())", pn, boost::algorithm::replace_all_copy(p, ".", "::"));  				if (++pn < b.second->proxies.size()) {  					fputs(",", output);  				} @@ -407,7 +407,8 @@ namespace IceSpider {  			fputs(" {\n", output);  			fprintbf(2, output, "public:\n");  			fprintbf(3, output, "explicit %s(const IceSpider::Core * core) :\n", r.first); -			fprintbf(4, output, "IceSpider::IRouteHandler(IceSpider::HttpMethod::%s, \"%s\")", methodName, r.second->path); +			fprintbf(4, output, "IceSpider::IRouteHandler(IceSpider::HttpMethod::%s, \"%s\")", methodName, +					r.second->path);  			for (const auto & b : r.second->bases) {  				fputs(",\n", output);  				fprintbf(4, output, "%s(core)", b); @@ -437,8 +438,7 @@ namespace IceSpider {  				}  				if (p.second->defaultExpr) {  					fputs(",\n", output); -					fprintbf(4, output, "_pd_%s(%s)", -							p.first, *p.second->defaultExpr); +					fprintbf(4, output, "_pd_%s(%s)", p.first, *p.second->defaultExpr);  				}  			}  			fputs("\n", output); @@ -453,24 +453,23 @@ namespace IceSpider {  				if (p.second->hasUserSource) {  					auto ip = ps.find(p.first)->second;  					const auto paramType = "std::remove_cvref<%?>::type"_fmt( -						Slice::inputTypeToString(ip->type(), false, "", ip->getMetaData())); +							Slice::inputTypeToString(ip->type(), false, "", ip->getMetaData()));  					// This shouldn't be needed... the warning is ignored elsewhere to no effect -					fprintbf(4, output, "// NOLINTNEXTLINE(clang-analyzer-optin.cplusplus.VirtualCall)\n");  					if (p.second->source == ParameterSource::Body) {  						if (p.second->key) {  							if (!doneBody) {  								if (p.second->type) { -									fprintbf(4, output, "const auto _pbody(request->getBody<%s>());\n", -											*p.second->type); +									fprintbf( +											4, output, "const auto _pbody(request->getBody<%s>());\n", *p.second->type);  								}  								else { -									fprintbf(4, output, "const auto _pbody(request->getBody<IceSpider::StringMap>());\n"); +									fprintbf(4, output, +											"const auto _pbody(request->getBody<IceSpider::StringMap>());\n");  								}  								doneBody = true;  							}  							if (p.second->type) { -								fprintbf(4, output, "const auto _p_%s(_pbody->%s", -										p.first, p.first); +								fprintbf(4, output, "const auto _p_%s(_pbody->%s", p.first, p.first);  							}  							else {  								fprintbf(4, output, "const auto _p_%s(request->getBodyParam<%s>(_pbody, _pn_%s)", @@ -478,25 +477,25 @@ namespace IceSpider {  							}  						}  						else { -							fprintbf(4, output, "const auto _p_%s(request->getBody<%s>()", -									p.first, paramType); +							fprintbf(4, output, "const auto _p_%s(request->getBody<%s>()", p.first, paramType);  						}  					}  					else { -						fprintbf(4, output, "const auto _p_%s(request->get%sParam<%s>(_p%c_%s)", -								p.first, getEnumString(p.second->source), paramType, -								p.second->source == ParameterSource::URL ? 'i' : 'n', -								p.first); +						fprintbf(4, output, "const auto _p_%s(request->get%sParam<%s>(_p%c_%s)", p.first, +								getEnumString(p.second->source), paramType, +								p.second->source == ParameterSource::URL ? 'i' : 'n', p.first);  					}  					if (!p.second->isOptional && p.second->source != ParameterSource::URL) {  						fprintbf(0, output, " /\n");  						if (p.second->defaultExpr) { -							fprintbf(5, output, " [this]() { return _pd_%s; }", -									p.first); +							fprintbf(5, output, " [this]() { return _pd_%s; }", p.first);  						}  						else { -							fprintbf(5, output, " [this]() { return requiredParameterNotFound<std::remove_reference<%s>::type>(\"%s\", _pn_%s); }", -									Slice::inputTypeToString(ip->type(), false, "", ip->getMetaData()), getEnumString(p.second->source), p.first); +							fprintbf(5, output, +									" [this]() { return " +									"requiredParameterNotFound<std::remove_reference<%s>::type>(\"%s\", _pn_%s); }", +									Slice::inputTypeToString(ip->type(), false, "", ip->getMetaData()), +									getEnumString(p.second->source), p.first);  						}  					}  					fprintbf(0, output, ");\n"); @@ -522,9 +521,7 @@ namespace IceSpider {  				}  				if (p.second->defaultExpr) {  					auto ip = ps.find(p.first)->second; -					fprintbf(3, output, "const %s _pd_%s;\n", -							Slice::typeToString(ip->type()), p.first); - +					fprintbf(3, output, "const %s _pd_%s;\n", Slice::typeToString(ip->type()), p.first);  				}  			}  			fprintbf(1, output, "};\n\n"); @@ -540,7 +537,8 @@ namespace IceSpider {  				if (proxies.find(proxyName) == proxies.end()) {  					proxies[proxyName] = n;  					fputs(",\n", output); -					fprintbf(4, output, "prx%d(core->getProxy<%s>())", n, boost::algorithm::replace_all_copy(proxyName, ".", "::")); +					fprintbf(4, output, "prx%d(core->getProxy<%s>())", n, +							boost::algorithm::replace_all_copy(proxyName, ".", "::"));  					n += 1;  				}  			} @@ -551,7 +549,8 @@ namespace IceSpider {  		RouteCompiler::declareProxies(FILE * output, const Proxies & proxies) const  		{  			for (const auto & p : proxies) { -				fprintbf(3, output, "const %sPrxPtr prx%d;\n", boost::algorithm::replace_all_copy(p.first, ".", "::"), p.second); +				fprintbf(3, output, "const %sPrxPtr prx%d;\n", boost::algorithm::replace_all_copy(p.first, ".", "::"), +						p.second);  			}  		} @@ -575,7 +574,7 @@ namespace IceSpider {  				}  			}  			fprintbf(output, "request->getContext());\n"); -			for(const auto & mutator : r->mutators) { +			for (const auto & mutator : r->mutators) {  				fprintbf(4, output, "%s(request, _responseModel);\n", mutator);  			}  			if (o->returnType()) { @@ -587,12 +586,14 @@ namespace IceSpider {  		}  		void -		RouteCompiler::addMashupOperations(FILE * output, const RoutePtr & r, const Proxies & proxies, const Units & us) const +		RouteCompiler::addMashupOperations( +				FILE * output, const RoutePtr & r, const Proxies & proxies, const Units & us) const  		{  			for (const auto & o : r->operations) {  				auto proxyName = o.second->operation.substr(0, o.second->operation.find_last_of('.'));  				auto operation = o.second->operation.substr(o.second->operation.find_last_of('.') + 1); -				fprintbf(4, output, "auto _ar_%s = prx%s->%sAsync(", o.first, proxies.find(proxyName)->second, operation); +				fprintbf(4, output, "auto _ar_%s = prx%s->%sAsync(", o.first, proxies.find(proxyName)->second, +						operation);  				auto so = findOperation(o.second->operation, us);  				for (const auto & p : so->parameters()) {  					auto po = o.second->paramOverrides.find(p->name()); @@ -607,23 +608,14 @@ namespace IceSpider {  				fprintbf(output, "request->getContext());\n");  			}  			auto t = findType(r->type, us); -			Slice::DataMemberList members; -			if (t.second) { -				fprintbf(4, output, "%s _responseModel = std::make_shared<%s>();\n", -						Slice::typeToString(t.second), -						t.second->scoped()); -				members = t.second->definition()->dataMembers(); +			fprintbf(4, output, "%s _responseModel", t.type); +			if (t.scoped) { +				fprintbf(4, output, " = std::make_shared<%s>()", *t.scoped);  			} -			else { -				fprintbf(4, output, "%s _responseModel;\n", -						Slice::typeToString(t.first)); -				members = t.first->dataMembers(); -			} -			for (const auto & mi : members) { +			fprintbf(4, output, ";\n"); +			for (const auto & mi : t.members) {  				bool isOp = false; -				fprintbf(4, output, "_responseModel%s%s = ", -						t.second ? "->" : ".", -						mi->name()); +				fprintbf(4, output, "_responseModel%s%s = ", t.scoped ? "->" : ".", mi->name());  				for (const auto & o : r->operations) {  					auto proxyName = o.second->operation.substr(0, o.second->operation.find_last_of('.'));  					auto operation = o.second->operation.substr(o.second->operation.find_last_of('.') + 1); @@ -645,4 +637,3 @@ namespace IceSpider {  		}  	}  } - diff --git a/icespider/compile/routeCompiler.h b/icespider/compile/routeCompiler.h index fef7648..7549d2b 100644 --- a/icespider/compile/routeCompiler.h +++ b/icespider/compile/routeCompiler.h @@ -1,54 +1,61 @@  #ifndef ICESPIDER_COMPILE_ROURTECOMPILER_H  #define ICESPIDER_COMPILE_ROURTECOMPILER_H +#include <Ice/BuiltinSequences.h> +#include <Slice/Parser.h>  #include <filesystem> -#include <visibility.h> -#include <vector>  #include <routes.h> -#include <Slice/Parser.h> -#include <Ice/BuiltinSequences.h> +#include <vector> +#include <visibility.h>  namespace IceSpider {  	namespace Compile {  		class DLL_PUBLIC RouteCompiler { -			public: -				typedef std::map<std::string, Slice::UnitPtr> Units; +		public: +			using Units = std::map<std::string, Slice::UnitPtr>; -				RouteCompiler(); +			RouteCompiler(); -				RouteConfigurationPtr loadConfiguration(const std::filesystem::path &) const; -				Units loadUnits(const RouteConfigurationPtr &) const; +			[[nodiscard]] RouteConfigurationPtr loadConfiguration(const std::filesystem::path &) const; +			[[nodiscard]] Units loadUnits(const RouteConfigurationPtr &) const; -				void applyDefaults(const RouteConfigurationPtr &, const Units & u) const; -				void compile(const std::filesystem::path & input, const std::filesystem::path & output) const; +			void applyDefaults(const RouteConfigurationPtr &, const Units & u) const; +			void compile(const std::filesystem::path & input, const std::filesystem::path & output) const; -				std::vector<std::filesystem::path> searchPath; +			std::vector<std::filesystem::path> searchPath; -			private: -				typedef std::map<std::string, int> Proxies; +		private: +			using Proxies = std::map<std::string, int>;  #pragma GCC visibility push(hidden) -				void processConfiguration(FILE * output, FILE * outputh, const std::string & name, const RouteConfigurationPtr &, const Units &) const; -				void processBases(FILE * output, FILE * outputh, const RouteConfigurationPtr &, const Units &) const; -				void processBase(FILE * output, FILE * outputh, const RouteBases::value_type &, const Units &) const; -				void processRoutes(FILE * output, const RouteConfigurationPtr &, const Units &) const; -				void processRoute(FILE * output, const Routes::value_type &, const Units &) const; -				void registerOutputSerializers(FILE * output, const RoutePtr &) const; -				Proxies initializeProxies(FILE * output, const RoutePtr &) const; -				void declareProxies(FILE * output, const Proxies &) const; -				void addSingleOperation(FILE * output, const RoutePtr &, const Slice::OperationPtr &) const; -				void addMashupOperations(FILE * output, const RoutePtr &, const Proxies &, const Units &) const; -				using ParameterMap = std::map<std::string, Slice::ParamDeclPtr>; -				static ParameterMap findParameters(const RoutePtr &, const Units &); -				static Slice::OperationPtr findOperation(const std::string &, const Units &); -				static Slice::OperationPtr findOperation(const std::string &, const Slice::ContainerPtr &, const Ice::StringSeq & = Ice::StringSeq()); -				using Type = std::pair<Slice::StructPtr, Slice::ClassDeclPtr>; -				static Type findType(const std::string &, const Units &); -				static Type findType(const std::string &, const Slice::ContainerPtr &, const Ice::StringSeq & = Ice::StringSeq()); +			void processConfiguration(FILE * output, FILE * outputh, const std::string & name, +					const RouteConfigurationPtr &, const Units &) const; +			void processBases(FILE * output, FILE * outputh, const RouteConfigurationPtr &, const Units &) const; +			void processBase(FILE * output, FILE * outputh, const RouteBases::value_type &, const Units &) const; +			void processRoutes(FILE * output, const RouteConfigurationPtr &, const Units &) const; +			void processRoute(FILE * output, const Routes::value_type &, const Units &) const; +			void registerOutputSerializers(FILE * output, const RoutePtr &) const; +			[[nodiscard]] Proxies initializeProxies(FILE * output, const RoutePtr &) const; +			void declareProxies(FILE * output, const Proxies &) const; +			void addSingleOperation(FILE * output, const RoutePtr &, const Slice::OperationPtr &) const; +			void addMashupOperations(FILE * output, const RoutePtr &, const Proxies &, const Units &) const; +			using ParameterMap = std::map<std::string, Slice::ParamDeclPtr>; +			static ParameterMap findParameters(const RoutePtr &, const Units &); +			static Slice::OperationPtr findOperation(const std::string &, const Units &); +			static Slice::OperationPtr findOperation( +					const std::string &, const Slice::ContainerPtr &, const Ice::StringSeq & = Ice::StringSeq()); +			// using Type = std::pair<Slice::StructPtr, Slice::ClassDeclPtr>; +			struct Type { +				std::string type; +				std::optional<std::string> scoped; +				Slice::DataMemberList members; +			}; +			static Type findType(const std::string &, const Units &); +			static std::optional<Type> findType( +					const std::string &, const Slice::ContainerPtr &, const Ice::StringSeq & = Ice::StringSeq());  #pragma GCC visibility pop  		};  	}  }  #endif - diff --git a/icespider/core/core.cpp b/icespider/core/core.cpp index 98ad99c..6bf8ad3 100644 --- a/icespider/core/core.cpp +++ b/icespider/core/core.cpp @@ -2,10 +2,10 @@  #include "exceptions.h"  #include <Ice/Initialize.h>  #include <Ice/ObjectAdapter.h> -#include <filesystem> +#include <compileTimeFormatter.h>  #include <cxxabi.h>  #include <factory.impl.h> -#include <compileTimeFormatter.h> +#include <filesystem>  INSTANTIATEFACTORY(IceSpider::Plugin, Ice::CommunicatorPtr, Ice::PropertiesPtr);  INSTANTIATEPLUGINOF(IceSpider::ErrorHandler); @@ -105,7 +105,8 @@ namespace IceSpider {  		defaultErrorReport(request, exception);  	} -	auto demangle(const char * const name) +	auto +	demangle(const char * const name)  	{  		return std::unique_ptr<char, decltype(&std::free)>(  				__cxxabiv1::__cxa_demangle(name, nullptr, nullptr, nullptr), std::free); @@ -143,8 +144,7 @@ namespace IceSpider {  		return i;  	} -	static -	bool +	static bool  	operator/=(const PathElements & pathparts, const IRouteHandler * r)  	{  		auto rpi = r->parts.begin(); @@ -156,8 +156,7 @@ namespace IceSpider {  		return true;  	} -	CoreWithDefaultRouter::CoreWithDefaultRouter(const Ice::StringSeq & opts) : -		Core(opts) +	CoreWithDefaultRouter::CoreWithDefaultRouter(const Ice::StringSeq & opts) : Core(opts)  	{  		for (const auto & r : allRoutes) {  			if (routes.size() <= r->pathElementCount()) { @@ -193,4 +192,3 @@ namespace IceSpider {  	}  } - diff --git a/icespider/core/core.h b/icespider/core/core.h index 08b649e..d60b20f 100644 --- a/icespider/core/core.h +++ b/icespider/core/core.h @@ -1,58 +1,61 @@  #ifndef ICESPIDER_CORE_CORE_H  #define ICESPIDER_CORE_CORE_H -#include <visibility.h> -#include <vector>  #include "irouteHandler.h"  #include <Ice/Communicator.h> +#include <c++11Helpers.h>  #include <filesystem>  #include <plugins.h> +#include <vector> +#include <visibility.h>  namespace IceSpider {  	class DLL_PUBLIC Core { -		public: -			typedef std::vector<IRouteHandlerCPtr> AllRoutes; +	public: +		using AllRoutes = std::vector<IRouteHandlerCPtr>; -			Core(const Ice::StringSeq & = {}); -			virtual ~Core(); +		explicit Core(const Ice::StringSeq & = {}); +		SPECIAL_MEMBERS_MOVE_RO(Core); +		virtual ~Core(); -			virtual const IRouteHandler * findRoute(const IHttpRequest *) const = 0; -			void process(IHttpRequest *, const IRouteHandler * = nullptr) const; -			void handleError(IHttpRequest *, const std::exception &) const; +		virtual const IRouteHandler * findRoute(const IHttpRequest *) const = 0; +		void process(IHttpRequest *, const IRouteHandler * = nullptr) const; +		void handleError(IHttpRequest *, const std::exception &) const; -			Ice::ObjectPrxPtr getProxy(const char * type) const; +		[[nodiscard]] Ice::ObjectPrxPtr getProxy(const char * type) const; -			template<typename Interface> -			auto getProxy() const -			{ -				return Ice::uncheckedCast<typename Interface::ProxyType>(getProxy(typeid(Interface).name())); -			} +		template<typename Interface> +		[[nodiscard]] auto +		getProxy() const +		{ +			return Ice::uncheckedCast<typename Interface::ProxyType>(getProxy(typeid(Interface).name())); +		} -			AllRoutes allRoutes; -			Ice::CommunicatorPtr communicator; -			Ice::ObjectAdapterPtr pluginAdapter; +		AllRoutes allRoutes; +		Ice::CommunicatorPtr communicator; +		Ice::ObjectAdapterPtr pluginAdapter; -			static const std::filesystem::path defaultConfig; +		static const std::filesystem::path defaultConfig; -		private: -			void defaultErrorReport(IHttpRequest * request, const std::exception & ex) const; +	private: +		void defaultErrorReport(IHttpRequest * request, const std::exception & ex) const;  	};  	class DLL_PUBLIC CoreWithDefaultRouter : public Core { -		public: -			typedef std::vector<IRouteHandlerCPtr> LengthRoutes; -			typedef std::vector<LengthRoutes> Routes; +	public: +		using LengthRoutes = std::vector<IRouteHandlerCPtr>; +		using Routes = std::vector<LengthRoutes>; -			CoreWithDefaultRouter(const Ice::StringSeq & = {}); +		explicit CoreWithDefaultRouter(const Ice::StringSeq & = {}); -			const IRouteHandler * findRoute(const IHttpRequest *) const override; +		const IRouteHandler * findRoute(const IHttpRequest *) const override; -			Routes routes; +		Routes routes;  	};  	class DLL_PUBLIC Plugin : public virtual Ice::Object {  	}; -	typedef AdHoc::Factory<Plugin, Ice::CommunicatorPtr, Ice::PropertiesPtr> PluginFactory; +	using PluginFactory = AdHoc::Factory<Plugin, Ice::CommunicatorPtr, Ice::PropertiesPtr>;  	enum ErrorHandlerResult {  		ErrorHandlerResult_Unhandled, @@ -60,11 +63,10 @@ namespace IceSpider {  		ErrorHandlerResult_Modified,  	};  	class DLL_PUBLIC ErrorHandler : public AdHoc::AbstractPluginImplementation { -		public: -			virtual ErrorHandlerResult handleError(IHttpRequest * IHttpRequest, const std::exception &) const = 0; +	public: +		virtual ErrorHandlerResult handleError(IHttpRequest * IHttpRequest, const std::exception &) const = 0;  	}; -	typedef AdHoc::PluginOf<ErrorHandler> ErrorHandlerPlugin; +	using ErrorHandlerPlugin = AdHoc::PluginOf<ErrorHandler>;  }  #endif - diff --git a/icespider/core/exceptions.cpp b/icespider/core/exceptions.cpp index d249fcc..83ab13a 100644 --- a/icespider/core/exceptions.cpp +++ b/icespider/core/exceptions.cpp @@ -7,4 +7,3 @@ namespace IceSpider {  	DefineHttpEx(Http406_NotAcceptable, 406, "Not Acceptable");  	DefineHttpEx(Http415_UnsupportedMediaType, 415, "Unsupported Media Type");  } - diff --git a/icespider/core/exceptions.h b/icespider/core/exceptions.h index a11ea45..8e3466d 100644 --- a/icespider/core/exceptions.h +++ b/icespider/core/exceptions.h @@ -6,10 +6,10 @@  #define DeclareHttpEx(Name) \  	class DLL_PUBLIC Name : public ::IceSpider::HttpException { \ -		public: \ -			Name(); \ -			static const short code; \ -			static const std::string message; \ +	public: \ +		Name(); \ +		static const short code; \ +		static const std::string message; \  	}  #define DefineHttpEx(Name, Code, Message) \  	Name::Name() : ::IceSpider::HttpException(__FILE__, __LINE__, code, message) { } \ @@ -25,4 +25,3 @@ namespace IceSpider {  }  #endif - diff --git a/icespider/core/ihttpRequest.cpp b/icespider/core/ihttpRequest.cpp index bb0b7af..75b050a 100644 --- a/icespider/core/ihttpRequest.cpp +++ b/icespider/core/ihttpRequest.cpp @@ -1,20 +1,17 @@  #include "ihttpRequest.h" +#include "exceptions.h"  #include "irouteHandler.h"  #include "util.h" -#include "exceptions.h"  #include "xwwwFormUrlEncoded.h"  #include <boost/lexical_cast.hpp> -#include <ctime>  #include <cstdio> +#include <ctime>  #include <formatters.h>  namespace IceSpider {  	using namespace AdHoc::literals; -	IHttpRequest::IHttpRequest(const Core * c) : -		core(c) -	{ -	} +	IHttpRequest::IHttpRequest(const Core * c) : core(c) { }  	Ice::Context  	IHttpRequest::getContext() const @@ -27,9 +24,10 @@ namespace IceSpider {  	{  		try {  			return Slicer::StreamDeserializerFactory::createNew( -				getEnv(E::CONTENT_TYPE) / []() -> std::string_view { -					throw Http400_BadRequest(); -				}, getInputStream()); +					getEnv(E::CONTENT_TYPE) / []() -> std::string_view { +						throw Http400_BadRequest(); +					}, +					getInputStream());  		}  		catch (const AdHoc::NoSuchPluginException &) {  			throw Http415_UnsupportedMediaType(); @@ -82,7 +80,9 @@ namespace IceSpider {  		if (accepts.empty()) {  			throw Http400_BadRequest();  		} -		std::stable_sort(accepts.begin(), accepts.end(), [](const auto & a, const auto & b) { return a->q > b->q; }); +		std::stable_sort(accepts.begin(), accepts.end(), [](const auto & a, const auto & b) { +			return a->q > b->q; +		});  		return accepts;  	} @@ -93,7 +93,7 @@ namespace IceSpider {  		if (acceptHdr) {  			auto accepts = parseAccept(*acceptHdr);  			auto & strm = getOutputStream(); -			for(auto & a : accepts) { +			for (auto & a : accepts) {  				ContentTypeSerializer serializer = handler->getSerializer(a, strm);  				if (serializer.second) {  					return serializer; @@ -116,8 +116,9 @@ namespace IceSpider {  		return url[idx];  	} -	template <typename T, typename Y> -	inline T wrapLexicalCast(const Y & y) +	template<typename T, typename Y> +	inline T +	wrapLexicalCast(const Y & y)  	{  		try {  			return boost::lexical_cast<T>(y); @@ -129,9 +130,9 @@ namespace IceSpider {  	// Set-Cookie: value[; expires=date][; domain=domain][; path=path][; secure]  	// Sat, 02 May 2009 23:38:25 GMT -	void IHttpRequest::setCookie(const std::string_view & name, const std::string_view & value, -			const OptionalString & d, const OptionalString & p, bool s, -			std::optional<time_t> e) +	void +	IHttpRequest::setCookie(const std::string_view & name, const std::string_view & value, const OptionalString & d, +			const OptionalString & p, bool s, std::optional<time_t> e)  	{  		std::stringstream o;  		XWwwFormUrlEncoded::urlencodeto(o, name.begin(), name.end()); @@ -139,7 +140,8 @@ namespace IceSpider {  		XWwwFormUrlEncoded::urlencodeto(o, value.begin(), value.end());  		if (e) {  			std::string buf(45, 0); -			struct tm tm { }; +			struct tm tm { +			};  			gmtime_r(&*e, &tm);  			buf.resize(strftime(buf.data(), buf.length(), "; expires=%a, %d %b %Y %T %Z", &tm));  			o << buf; @@ -150,15 +152,16 @@ namespace IceSpider {  		if (p) {  			"; path=%?"_fmt(o, *p);  		} -		if (s){ +		if (s) {  			"; secure"_fmt(o);  		}  		"; samesite=strict"_fmt(o);  		setHeader(H::SET_COOKIE, o.str());  	} -	template <typename T> -	inline std::optional<T> optionalLexicalCast(const OptionalString & p) +	template<typename T> +	inline std::optional<T> +	optionalLexicalCast(const OptionalString & p)  	{  		if (p) {  			return wrapLexicalCast<T>(*p); @@ -166,7 +169,8 @@ namespace IceSpider {  		return {};  	} -	void IHttpRequest::responseRedirect(const std::string_view & url, const OptionalString & statusMsg) const +	void +	IHttpRequest::responseRedirect(const std::string_view & url, const OptionalString & statusMsg) const  	{  		setHeader(H::LOCATION, url);  		response(303, (statusMsg ? *statusMsg : S::MOVED)); @@ -185,5 +189,3 @@ namespace IceSpider {  	static_assert(!std::is_convertible<OptionalString::value_type, std::string>::value);  	static_assert(std::is_constructible<OptionalString::value_type, std::string>::value);  } - - diff --git a/icespider/core/ihttpRequest.h b/icespider/core/ihttpRequest.h index a8eee28..b4bab30 100644 --- a/icespider/core/ihttpRequest.h +++ b/icespider/core/ihttpRequest.h @@ -1,143 +1,147 @@  #ifndef ICESPIDER_IHTTPREQUEST_H  #define ICESPIDER_IHTTPREQUEST_H +#include "exceptions.h" +#include <Ice/Current.h> +#include <Ice/Optional.h>  #include <IceUtil/Exception.h>  #include <IceUtil/Optional.h> -#include <Ice/Current.h> -#include <visibility.h> +#include <boost/lexical_cast.hpp>  #include <http.h>  #include <slicer/slicer.h> -#include <Ice/Optional.h> -#include <boost/lexical_cast.hpp> -#include "exceptions.h" +#include <visibility.h>  namespace IceSpider {  	class Core;  	class IRouteHandler; -	typedef std::vector<std::string> PathElements; -	typedef std::optional<std::string_view> OptionalString; -	typedef std::pair<MimeType, Slicer::SerializerPtr> ContentTypeSerializer; +	using PathElements = std::vector<std::string>; +	using OptionalString = std::optional<std::string_view>; +	using ContentTypeSerializer = std::pair<MimeType, Slicer::SerializerPtr>;  	class DLL_PUBLIC IHttpRequest { -		public: -			IHttpRequest(const Core *); +	public: +		explicit IHttpRequest(const Core *); -			Ice::Context getContext() const; -			virtual const PathElements & getRequestPath() const = 0; -			virtual PathElements & getRequestPath() = 0; -			virtual HttpMethod getRequestMethod() const = 0; +		[[nodiscard]] Ice::Context getContext() const; +		[[nodiscard]] virtual const PathElements & getRequestPath() const = 0; +		[[nodiscard]] virtual PathElements & getRequestPath() = 0; +		[[nodiscard]] virtual HttpMethod getRequestMethod() const = 0; -			OptionalString getURLParam(const unsigned int &) const; -			virtual OptionalString getQueryStringParam(const std::string_view &) const = 0; -			virtual OptionalString getHeaderParam(const std::string_view &) const = 0; -			virtual OptionalString getCookieParam(const std::string_view &) const = 0; -			virtual OptionalString getEnv(const std::string_view &) const = 0; -			virtual bool isSecure() const = 0; -			static Accepted parseAccept(const std::string_view &); -			virtual Slicer::DeserializerPtr getDeserializer() const; -			virtual ContentTypeSerializer getSerializer(const IRouteHandler *) const; -			virtual std::istream & getInputStream() const = 0; -			virtual std::ostream & getOutputStream() const = 0; -			virtual void setHeader(const std::string_view &, const std::string_view &) const = 0; +		[[nodiscard]] OptionalString getURLParam(const unsigned int &) const; +		[[nodiscard]] virtual OptionalString getQueryStringParam(const std::string_view &) const = 0; +		[[nodiscard]] virtual OptionalString getHeaderParam(const std::string_view &) const = 0; +		[[nodiscard]] virtual OptionalString getCookieParam(const std::string_view &) const = 0; +		[[nodiscard]] virtual OptionalString getEnv(const std::string_view &) const = 0; +		[[nodiscard]] virtual bool isSecure() const = 0; +		[[nodiscard]] static Accepted parseAccept(const std::string_view &); +		[[nodiscard]] virtual Slicer::DeserializerPtr getDeserializer() const; +		[[nodiscard]] virtual ContentTypeSerializer getSerializer(const IRouteHandler *) const; +		[[nodiscard]] virtual std::istream & getInputStream() const = 0; +		[[nodiscard]] virtual std::ostream & getOutputStream() const = 0; +		virtual void setHeader(const std::string_view &, const std::string_view &) const = 0; -			virtual std::ostream & dump(std::ostream & s) const = 0; +		virtual std::ostream & dump(std::ostream & s) const = 0; -			template<typename T, typename K> -			inline -			std::optional<T> getFrom(const K & key, OptionalString (IHttpRequest::*src)(const K &) const) const -			{ -				if (auto v = (this->*src)(key)) { -					if constexpr (std::is_convertible<std::string_view, T>::value) { -						return *v; -					} -					else if constexpr (std::is_constructible<std::string_view, T>::value) { -						return T(*v); -					} -					else if constexpr (std::is_same<std::string, T>::value) { -						return std::to_string(*v); -					} -					else { -						try { -							// NOLINTNEXTLINE(clang-analyzer-optin.cplusplus.VirtualCall) -							return boost::lexical_cast<T>(*v); -						} -						catch (const boost::bad_lexical_cast & e) { -							throw Http400_BadRequest(); -						} -					} +		template<typename T, typename K> +		[[nodiscard]] inline std::optional<T> +		getFrom(const K & key, OptionalString (IHttpRequest::*src)(const K &) const) const +		{ +			if (auto v = (this->*src)(key)) { +				if constexpr (std::is_convertible<std::string_view, T>::value) { +					return *v;  				} -				else { -					return std::nullopt; +				else if constexpr (std::is_constructible<std::string_view, T>::value) { +					return T(*v);  				} -			} -			template<typename T> -			T getURLParam(unsigned int n) const -			{ -				// NOLINTNEXTLINE(clang-analyzer-optin.cplusplus.VirtualCall) -				return *getFrom<T, unsigned int>(n, &IHttpRequest::getURLParam); -			} -			template<typename T> -			std::optional<T> getBody() const -			{ -				return Slicer::DeserializeAnyWith<T>(getDeserializer()); -			} -			template<typename T> -			std::optional<T> getBodyParam(const std::optional<IceSpider::StringMap> & map, const std::string_view & key) const -			{ -				if (!map) { -					return {}; -				} -				auto i = map->find(key); -				if (i == map->end()) { -					return {}; +				else if constexpr (std::is_same<std::string, T>::value) { +					return std::to_string(*v);  				}  				else { -					return boost::lexical_cast<T>(i->second); +					try { +						return boost::lexical_cast<T>(*v); +					} +					catch (const boost::bad_lexical_cast & e) { +						throw Http400_BadRequest(); +					}  				}  			} -			void responseRedirect(const std::string_view & url, const OptionalString & = {}) const; -			void setCookie(const std::string_view &, const std::string_view &, -					const OptionalString & = {}, const OptionalString & = {}, -					bool = false, std::optional<time_t> = {}); -			template<typename T> -			void setCookie(const std::string_view & n, const T & v, -					const OptionalString & d, const OptionalString & p, -					bool s, std::optional<time_t> e) { -				if constexpr (std::is_constructible<std::string_view, T>::value) { -					setCookie(n, std::string_view(v), d, p, s, e); -				} -				else { -					auto vs = boost::lexical_cast<std::string>(v); -					setCookie(n, std::string_view(vs), d, p, s, e); -				} +			else { +				return std::nullopt; +			} +		} +		template<typename T> +		[[nodiscard]] T +		getURLParam(unsigned int n) const +		{ +			return *getFrom<T, unsigned int>(n, &IHttpRequest::getURLParam); +		} +		template<typename T> +		[[nodiscard]] std::optional<T> +		getBody() const +		{ +			return Slicer::DeserializeAnyWith<T>(getDeserializer()); +		} +		template<typename T> +		[[nodiscard]] std::optional<T> +		getBodyParam(const std::optional<IceSpider::StringMap> & map, const std::string_view & key) const +		{ +			if (!map) { +				return {};  			} -			template<typename T> -			std::optional<T> getQueryStringParam(const std::string_view & key) const -			{ -				return getFrom<T, std::string_view>(key, &IHttpRequest::getQueryStringParam); +			auto i = map->find(key); +			if (i == map->end()) { +				return {};  			} -			template<typename T> -			std::optional<T> getHeaderParam(const std::string_view & key) const -			{ -				return getFrom<T, std::string_view>(key, &IHttpRequest::getHeaderParam); +			else { +				return boost::lexical_cast<T>(i->second);  			} -			template<typename T> -			std::optional<T> getCookieParam(const std::string_view & key) const -			{ -				return getFrom<T, std::string_view>(key, &IHttpRequest::getCookieParam); +		} +		void responseRedirect(const std::string_view & url, const OptionalString & = {}) const; +		void setCookie(const std::string_view &, const std::string_view &, const OptionalString & = {}, +				const OptionalString & = {}, bool = false, std::optional<time_t> = {}); +		template<typename T> +		void +		setCookie(const std::string_view & n, const T & v, const OptionalString & d, const OptionalString & p, bool s, +				std::optional<time_t> e) +		{ +			if constexpr (std::is_constructible<std::string_view, T>::value) { +				setCookie(n, std::string_view(v), d, p, s, e);  			} -			virtual void response(short, const std::string_view &) const = 0; -			template<typename T> -			void response(const IRouteHandler * route, const T & t) const -			{ -				modelPartResponse(route, Slicer::ModelPart::CreateRootFor(t)); +			else { +				auto vs = boost::lexical_cast<std::string>(v); +				setCookie(n, std::string_view(vs), d, p, s, e);  			} -			void modelPartResponse(const IRouteHandler * route, const Slicer::ModelPartForRootPtr &) const; +		} +		template<typename T> +		[[nodiscard]] std::optional<T> +		getQueryStringParam(const std::string_view & key) const +		{ +			return getFrom<T, std::string_view>(key, &IHttpRequest::getQueryStringParam); +		} +		template<typename T> +		[[nodiscard]] std::optional<T> +		getHeaderParam(const std::string_view & key) const +		{ +			return getFrom<T, std::string_view>(key, &IHttpRequest::getHeaderParam); +		} +		template<typename T> +		[[nodiscard]] std::optional<T> +		getCookieParam(const std::string_view & key) const +		{ +			return getFrom<T, std::string_view>(key, &IHttpRequest::getCookieParam); +		} +		virtual void response(short, const std::string_view &) const = 0; +		template<typename T> +		void +		response(const IRouteHandler * route, const T & t) const +		{ +			modelPartResponse(route, Slicer::ModelPart::CreateRootFor(t)); +		} +		void modelPartResponse(const IRouteHandler * route, const Slicer::ModelPartForRootPtr &) const; -			const Core * core; +		const Core * core;  	};  }  #endif - diff --git a/icespider/core/irouteHandler.cpp b/icespider/core/irouteHandler.cpp index 244f660..b968397 100644 --- a/icespider/core/irouteHandler.cpp +++ b/icespider/core/irouteHandler.cpp @@ -10,22 +10,18 @@ namespace IceSpider {  	static const std::string JSON = "json";  	static const std::string APPLICATION_JSON = MimeTypeFmt::get(APPLICATION, JSON); -	const RouteOptions IRouteHandler::defaultRouteOptions { -	}; +	const RouteOptions IRouteHandler::defaultRouteOptions {};  	IRouteHandler::IRouteHandler(HttpMethod m, const std::string_view & p) : -		IRouteHandler(m, p, defaultRouteOptions) -	{ -	} +		IRouteHandler(m, p, defaultRouteOptions) { } -	IRouteHandler::IRouteHandler(HttpMethod m, const std::string_view & p, const RouteOptions & ro) : -		Path(p), -		method(m) +	IRouteHandler::IRouteHandler(HttpMethod m, const std::string_view & p, const RouteOptions & ro) : Path(p), method(m)  	{  		if (ro.addDefaultSerializers) {  			auto globalSerializers = AdHoc::PluginManager::getDefault()->getAll<Slicer::StreamSerializerFactory>();  			for (const auto & gs : globalSerializers) {  				auto slash = gs->name.find('/'); -				routeSerializers.insert({ { gs->name.substr(0, slash), gs->name.substr(slash + 1) }, gs->implementation() }); +				routeSerializers.insert( +						{{gs->name.substr(0, slash), gs->name.substr(slash + 1)}, gs->implementation()});  			}  		}  	} @@ -35,7 +31,7 @@ namespace IceSpider {  	{  		for (const auto & rs : routeSerializers) {  			if ((!a->group || rs.first.group == a->group) && (!a->type || rs.first.type == a->type)) { -				return { rs.first, rs.second->create(strm) }; +				return {rs.first, rs.second->create(strm)};  			}  		}  		return ContentTypeSerializer(); @@ -44,10 +40,7 @@ namespace IceSpider {  	ContentTypeSerializer  	IRouteHandler::defaultSerializer(std::ostream & strm) const  	{ -		return { -			{ APPLICATION, JSON }, -			Slicer::StreamSerializerFactory::createNew(APPLICATION_JSON, strm) -		}; +		return {{APPLICATION, JSON}, Slicer::StreamSerializerFactory::createNew(APPLICATION_JSON, strm)};  	}  	void @@ -60,7 +53,6 @@ namespace IceSpider {  	IRouteHandler::addRouteSerializer(const MimeType & ct, const StreamSerializerFactoryPtr & ssfp)  	{  		routeSerializers.erase(ct); -		routeSerializers.insert({ ct, ssfp }); +		routeSerializers.insert({ct, ssfp});  	}  } - diff --git a/icespider/core/irouteHandler.h b/icespider/core/irouteHandler.h index 168008e..7889031 100644 --- a/icespider/core/irouteHandler.h +++ b/icespider/core/irouteHandler.h @@ -1,60 +1,61 @@  #ifndef ICESPIDER_IROUTEHANDLER_H  #define ICESPIDER_IROUTEHANDLER_H +#include "exceptions.h"  #include "ihttpRequest.h" +#include "routeOptions.h"  #include "util.h" -#include "exceptions.h" -#include <pathparts.h> +#include <c++11Helpers.h>  #include <factory.h> +#include <pathparts.h>  #include <visibility.h> -#include "routeOptions.h"  namespace IceSpider {  	class Core;  	class DLL_PUBLIC IRouteHandler : public Path { -		public: -			const static RouteOptions defaultRouteOptions; - -			IRouteHandler(HttpMethod, const std::string_view & path); -			IRouteHandler(HttpMethod, const std::string_view & path, const RouteOptions &); -			virtual ~IRouteHandler() = default; - -			virtual void execute(IHttpRequest * request) const = 0; -			virtual ContentTypeSerializer getSerializer(const AcceptPtr &, std::ostream &) const; -			virtual ContentTypeSerializer defaultSerializer(std::ostream &) const; - -			const HttpMethod method; - -		protected: -			typedef std::shared_ptr<Slicer::StreamSerializerFactory> StreamSerializerFactoryPtr; -			typedef std::map<MimeType, StreamSerializerFactoryPtr> RouteSerializers; -			RouteSerializers routeSerializers; - -			void requiredParameterNotFound(const char *, const std::string_view & key) const; - -			template <typename T, typename K> -			inline T requiredParameterNotFound(const char * s, const K & key) const -			{ -				requiredParameterNotFound(s, key); -				// LCOV_EXCL_START unreachable, requiredParameterNotFound always throws -				return T(); -				// LCOV_EXCL_STOP -			} - -			void addRouteSerializer(const MimeType &, const StreamSerializerFactoryPtr &); +	public: +		const static RouteOptions defaultRouteOptions; + +		IRouteHandler(HttpMethod, const std::string_view & path); +		IRouteHandler(HttpMethod, const std::string_view & path, const RouteOptions &); +		SPECIAL_MEMBERS_MOVE_RO(IRouteHandler); +		virtual ~IRouteHandler() = default; + +		virtual void execute(IHttpRequest * request) const = 0; +		virtual ContentTypeSerializer getSerializer(const AcceptPtr &, std::ostream &) const; +		virtual ContentTypeSerializer defaultSerializer(std::ostream &) const; + +		const HttpMethod method; + +	protected: +		using StreamSerializerFactoryPtr = std::shared_ptr<Slicer::StreamSerializerFactory>; +		using RouteSerializers = std::map<MimeType, StreamSerializerFactoryPtr>; +		RouteSerializers routeSerializers; + +		void requiredParameterNotFound(const char *, const std::string_view & key) const; + +		template<typename T, typename K> +		inline T +		requiredParameterNotFound(const char * s, const K & key) const +		{ +			requiredParameterNotFound(s, key); +			// LCOV_EXCL_START unreachable, requiredParameterNotFound always throws +			return T(); +			// LCOV_EXCL_STOP +		} + +		void addRouteSerializer(const MimeType &, const StreamSerializerFactoryPtr &);  	}; -	typedef std::shared_ptr<IRouteHandler> IRouteHandlerPtr; -	typedef std::shared_ptr<const IRouteHandler> IRouteHandlerCPtr; -	typedef AdHoc::Factory<IRouteHandler, const Core *> RouteHandlerFactory; +	using IRouteHandlerPtr = std::shared_ptr<IRouteHandler>; +	using IRouteHandlerCPtr = std::shared_ptr<const IRouteHandler>; +	using RouteHandlerFactory = AdHoc::Factory<IRouteHandler, const Core *>;  }  #if __cplusplus < 201709  namespace std { -	template <typename T> using remove_cvref = typename std::remove_cv<typename std::remove_reference<T>::type>; +	template<typename T> using remove_cvref = typename std::remove_cv<typename std::remove_reference<T>::type>;  }  #endif  #endif - - diff --git a/icespider/core/util.h b/icespider/core/util.h index 0edc3d2..e320523 100644 --- a/icespider/core/util.h +++ b/icespider/core/util.h @@ -5,30 +5,37 @@  #include <IceUtil/Optional.h>  namespace std::experimental::Ice { -	template <typename T, typename TF> -	auto operator/(const Ice::optional<T> & o, const TF & tf) -> decltype(tf()) +	template<typename T, typename TF> +	auto +	operator/(const Ice::optional<T> & o, const TF & tf) -> decltype(tf())  	{ -		if (o) return *o; +		if (o) { +			return *o; +		}  		return tf();  	}  }  namespace std { -	template <typename T, typename TF> -	auto operator/(const std::optional<T> & o, const TF & tf) -> decltype(tf()) +	template<typename T, typename TF> +	auto +	operator/(const std::optional<T> & o, const TF & tf) -> decltype(tf())  	{ -		if (o) return *o; +		if (o) { +			return *o; +		}  		return tf();  	}  } -template <typename T> -T orelse(const T & a, const T & b) +template<typename T> +T +orelse(const T & a, const T & b)  { -	if (a) return a; +	if (a) { +		return a; +	}  	return b;  } -  #endif - diff --git a/icespider/core/xwwwFormUrlEncoded.cpp b/icespider/core/xwwwFormUrlEncoded.cpp index 3de39c3..6137d97 100644 --- a/icespider/core/xwwwFormUrlEncoded.cpp +++ b/icespider/core/xwwwFormUrlEncoded.cpp @@ -1,25 +1,24 @@ -#include "xwwwFormUrlEncoded.h"  #include "exceptions.h" -#include <boost/lexical_cast.hpp> +#include "xwwwFormUrlEncoded.h"  #include <Ice/BuiltinSequences.h>  #include <array> +#include <boost/lexical_cast.hpp>  namespace ba = boost::algorithm;  using namespace std::literals; -constexpr std::array<char, 255> hextable = []() -{ -    std::array<char, 255> hextable{}; -    for (int n = 0; n < 255; n++) { -        hextable[n] = -1; -    } -    for (int n = '0'; n <= '9'; n++) { -        hextable[n] = n - '0'; -    } -    for (int n = 'a'; n <= 'f'; n++) { -        hextable[n] = hextable[n - 32] = n - 'a' + 10; -    } -    return hextable; +constexpr std::array<char, 255> hextable = []() { +	std::array<char, 255> hextable {}; +	for (int n = 0; n < 255; n++) { +		hextable[n] = -1; +	} +	for (int n = '0'; n <= '9'; n++) { +		hextable[n] = n - '0'; +	} +	for (int n = 'a'; n <= 'f'; n++) { +		hextable[n] = hextable[n - 32] = n - 'a' + 10; +	} +	return hextable;  }();  static_assert(hextable['~'] == -1); @@ -69,46 +68,45 @@ namespace IceSpider {  	}  	class SetFromString : public Slicer::ValueSource { -		public: -			explicit SetFromString(const std::string & v) : s(v) -			{ +	public: +		explicit SetFromString(const std::string & v) : s(v) { } + +		void +		set(bool & t) const override +		{ +			if (s == TRUE) { +				t = true;  			} - -			void set(bool & t) const override -			{ -				if (s == TRUE) { -					t = true; -				} -				else if (s == FALSE) { -					t = false; -				} -				else { -					throw Http400_BadRequest(); -				} +			else if (s == FALSE) { +				t = false;  			} - -			void set(std::string & t) const override -			{ -				t = s; +			else { +				throw Http400_BadRequest();  			} +		} + +		void +		set(std::string & t) const override +		{ +			t = s; +		}  #define SET(T) \ -			/* NOLINTNEXTLINE(bugprone-macro-parentheses) */ \ -			void set(T & t) const override \ -			{ \ -				t = boost::lexical_cast<T>(s); \ -			} +	/* NOLINTNEXTLINE(bugprone-macro-parentheses) */ \ +	void set(T & t) const override \ +	{ \ +		t = boost::lexical_cast<T>(s); \ +	} -			SET(Ice::Byte); -			SET(Ice::Short); -			SET(Ice::Int); -			SET(Ice::Long); -			SET(Ice::Float); -			// NOLINTNEXTLINE(clang-analyzer-optin.cplusplus.VirtualCall) -			SET(Ice::Double); +		SET(Ice::Byte); +		SET(Ice::Short); +		SET(Ice::Int); +		SET(Ice::Long); +		SET(Ice::Float); +		SET(Ice::Double); -		private: -			const std::string & s; +	private: +		const std::string & s;  	};  	std::string @@ -117,9 +115,17 @@ namespace IceSpider {  		return urlencode(s.begin(), s.end());  	} -	inline auto hexchar(int c) { return c < 10 ? '0' + c : 'a' - 10 + c; } +	inline auto +	hexchar(int c) +	{ +		return c < 10 ? '0' + c : 'a' - 10 + c; +	}  	template<typename T> -	inline char hexlookup(const T & i) { return hextable[(int)*i]; } +	inline char +	hexlookup(const T & i) +	{ +		return hextable[(int)*i]; +	}  	std::string  	XWwwFormUrlEncoded::urlencode(std::string_view::const_iterator i, std::string_view::const_iterator e) @@ -130,7 +136,8 @@ namespace IceSpider {  	}  	void -	XWwwFormUrlEncoded::urlencodeto(std::ostream & o, std::string_view::const_iterator i, std::string_view::const_iterator e) +	XWwwFormUrlEncoded::urlencodeto( +			std::ostream & o, std::string_view::const_iterator i, std::string_view::const_iterator e)  	{  		while (i != e) {  			if (*i == ' ') { @@ -231,4 +238,3 @@ namespace IceSpider {  }  NAMEDFACTORY("application/x-www-form-urlencoded", IceSpider::XWwwFormUrlEncoded, Slicer::StreamDeserializerFactory); - diff --git a/icespider/core/xwwwFormUrlEncoded.h b/icespider/core/xwwwFormUrlEncoded.h index d09b0c4..e0f8053 100644 --- a/icespider/core/xwwwFormUrlEncoded.h +++ b/icespider/core/xwwwFormUrlEncoded.h @@ -1,38 +1,40 @@  #ifndef ICESPIDER_CGI_XWWWFORMURLENCODED_H  #define ICESPIDER_CGI_XWWWFORMURLENCODED_H -#include <visibility.h> -#include <slicer/serializer.h>  #include <boost/algorithm/string/split.hpp> +#include <slicer/serializer.h> +#include <visibility.h>  namespace IceSpider {  	class XWwwFormUrlEncoded : public Slicer::Deserializer { -		public: -			typedef std::function<void(std::string &&, std::string &&)> KVh; +	public: +		using KVh = std::function<void(std::string &&, std::string &&)>; -			XWwwFormUrlEncoded(std::istream & in); +		explicit XWwwFormUrlEncoded(std::istream & in); -			void Deserialize(Slicer::ModelPartForRootPtr mp) override; -			DLL_PUBLIC static void iterateVars(const std::string_view & input, const KVh & h, const std::string_view & split); +		void Deserialize(Slicer::ModelPartForRootPtr mp) override; +		DLL_PUBLIC static void iterateVars( +				const std::string_view & input, const KVh & h, const std::string_view & split); -			DLL_PUBLIC static std::string urldecode(std::string_view::const_iterator s, std::string_view::const_iterator); -			DLL_PUBLIC static std::string urlencode(std::string_view::const_iterator s, std::string_view::const_iterator); -			DLL_PUBLIC static void urlencodeto(std::ostream &, std::string_view::const_iterator s, std::string_view::const_iterator); -			DLL_PUBLIC static std::string urlencode(const std::string_view & s); +		DLL_PUBLIC static std::string urldecode(std::string_view::const_iterator s, std::string_view::const_iterator); +		DLL_PUBLIC static std::string urlencode(std::string_view::const_iterator s, std::string_view::const_iterator); +		DLL_PUBLIC static void urlencodeto( +				std::ostream &, std::string_view::const_iterator s, std::string_view::const_iterator); +		DLL_PUBLIC static std::string urlencode(const std::string_view & s); -		private: -			static inline void iterateVars(const KVh & h, boost::algorithm::split_iterator<std::string_view::const_iterator> pi); +	private: +		static inline void iterateVars( +				const KVh & h, boost::algorithm::split_iterator<std::string_view::const_iterator> pi); -			void iterateVars(const KVh & h); +		void iterateVars(const KVh & h); -			void DeserializeSimple(const Slicer::ModelPartPtr & mp); -			void DeserializeComplex(const Slicer::ModelPartPtr & mp); -			void DeserializeDictionary(const Slicer::ModelPartPtr & mp); +		void DeserializeSimple(const Slicer::ModelPartPtr & mp); +		void DeserializeComplex(const Slicer::ModelPartPtr & mp); +		void DeserializeDictionary(const Slicer::ModelPartPtr & mp); -			const std::string input; +		const std::string input;  	};  };  #endif - diff --git a/icespider/fcgi/cgiRequest.cpp b/icespider/fcgi/cgiRequest.cpp index d0c4c83..2158956 100644 --- a/icespider/fcgi/cgiRequest.cpp +++ b/icespider/fcgi/cgiRequest.cpp @@ -1,8 +1,7 @@  #include "cgiRequest.h"  namespace IceSpider { -	CgiRequest::CgiRequest(Core * c, int argc, char ** argv, char ** env) : -		CgiRequestBase(c, env) +	CgiRequest::CgiRequest(Core * c, int argc, char ** argv, char ** env) : CgiRequestBase(c, env)  	{  		for (; argc > 0;) {  			addenv(argv[--argc]); @@ -22,4 +21,3 @@ namespace IceSpider {  		return std::cout;  	}  } - diff --git a/icespider/fcgi/cgiRequest.h b/icespider/fcgi/cgiRequest.h index 1e48e98..c78f76e 100644 --- a/icespider/fcgi/cgiRequest.h +++ b/icespider/fcgi/cgiRequest.h @@ -5,13 +5,12 @@  namespace IceSpider {  	class CgiRequest : public CgiRequestBase { -		public: -			CgiRequest(Core * c, int argc, char ** argv, char ** env); +	public: +		CgiRequest(Core * c, int argc, char ** argv, char ** env); -			std::istream & getInputStream() const override; -			std::ostream & getOutputStream() const override; +		std::istream & getInputStream() const override; +		std::ostream & getOutputStream() const override;  	};  }  #endif - diff --git a/icespider/fcgi/cgiRequestBase.cpp b/icespider/fcgi/cgiRequestBase.cpp index 8e04c07..2b95abd 100644 --- a/icespider/fcgi/cgiRequestBase.cpp +++ b/icespider/fcgi/cgiRequestBase.cpp @@ -1,13 +1,13 @@  #include "cgiRequestBase.h"  #include "xwwwFormUrlEncoded.h"  #include <boost/algorithm/string/case_conv.hpp> -#include <boost/algorithm/string/split.hpp>  #include <boost/algorithm/string/classification.hpp>  #include <boost/algorithm/string/predicate.hpp> -#include <util.h> -#include <slicer/modelPartsTypes.h> -#include <slicer/common.h> +#include <boost/algorithm/string/split.hpp>  #include <formatters.h> +#include <slicer/common.h> +#include <slicer/modelPartsTypes.h> +#include <util.h>  namespace ba = boost::algorithm;  using namespace std::literals; @@ -26,10 +26,9 @@ namespace IceSpider {  	CGI_CONST(HTTP_COOKIE);  	CGI_CONST(REQUEST_METHOD); -	CgiRequestBase::CgiRequestBase(Core * c, const char * const * const env) : -		IHttpRequest(c) +	CgiRequestBase::CgiRequestBase(Core * c, const char * const * const env) : IHttpRequest(c)  	{ -		for(const char * const * e = env; *e; ++e) { +		for (const char * const * e = env; *e; ++e) {  			addenv(*e);  		}  	} @@ -38,25 +37,28 @@ namespace IceSpider {  	CgiRequestBase::addenv(const char * const e)  	{  		if (auto eq = strchr(e, '=')) { -			envmap.insert({ std::string_view(e, eq - e), eq + 1 }); +			envmap.insert({std::string_view(e, eq - e), eq + 1});  		}  	}  	template<typename in, typename out> -	inline -	void -	mapVars(const std::string_view & vn, const in & envmap, out & map, const std::string_view & sp) { +	inline void +	mapVars(const std::string_view & vn, const in & envmap, out & map, const std::string_view & sp) +	{  		auto qs = envmap.find(vn);  		if (qs != envmap.end()) { -			XWwwFormUrlEncoded::iterateVars(qs->second, [&map](auto && k, auto && v) { -				map.emplace(std::move(k), std::move(v)); -			}, sp); +			XWwwFormUrlEncoded::iterateVars( +					qs->second, +					[&map](auto && k, auto && v) { +						map.emplace(std::forward<decltype(k)>(k), std::forward<decltype(v)>(v)); +					}, +					sp);  		}  	} -	template<typename Ex, typename Map, typename ... Ks> +	template<typename Ex, typename Map, typename... Ks>  	const std::string_view & -	findFirstOrElse(const Map & map, const std::string_view & k, const Ks & ... ks) +	findFirstOrElse(const Map & map, const std::string_view & k, const Ks &... ks)  	{  		if (const auto i = map.find(k); i != map.end()) {  			return i->second; @@ -79,9 +81,8 @@ namespace IceSpider {  		mapVars(QUERY_STRING, envmap, qsmap, amp);  		mapVars(HTTP_COOKIE, envmap, cookiemap, semi);  		for (auto header = envmap.lower_bound(HEADER_PREFIX); -				header != envmap.end() && ba::starts_with(header->first, HEADER_PREFIX); -				header++) { -			hdrmap.insert({ header->first.substr(HEADER_PREFIX.length()), header->second }); +				header != envmap.end() && ba::starts_with(header->first, HEADER_PREFIX); header++) { +			hdrmap.insert({header->first.substr(HEADER_PREFIX.length()), header->second});  		}  	} @@ -178,7 +179,8 @@ namespace IceSpider {  		return optionalLookup(key, hdrmap);  	} -	void CgiRequestBase::response(short statusCode, const std::string_view & statusMsg) const +	void +	CgiRequestBase::response(short statusCode, const std::string_view & statusMsg) const  	{  		StatusFmt::write(getOutputStream(), statusCode, statusMsg);  	} @@ -189,4 +191,3 @@ namespace IceSpider {  		HdrFmt::write(getOutputStream(), header, value);  	}  } - diff --git a/icespider/fcgi/cgiRequestBase.h b/icespider/fcgi/cgiRequestBase.h index f235acf..c0d6d81 100644 --- a/icespider/fcgi/cgiRequestBase.h +++ b/icespider/fcgi/cgiRequestBase.h @@ -8,40 +8,38 @@  namespace IceSpider {  	class CgiRequestBase : public IHttpRequest { -		protected: -			CgiRequestBase(Core * c, const char * const * const env); -			void addenv(const char * const); -			void initialize(); - -		public: -			typedef std::map<std::string_view, const std::string_view> VarMap; -			typedef std::map<std::string_view, const std::string_view, Slicer::case_less> HdrMap; - -			const PathElements & getRequestPath() const override; -			PathElements & getRequestPath() override; -			HttpMethod getRequestMethod() const override; -			OptionalString getQueryStringParam(const std::string_view & key) const override; -			OptionalString getHeaderParam(const std::string_view & key) const override; -			OptionalString getCookieParam(const std::string_view & key) const override; -			OptionalString getEnv(const std::string_view & key) const override; -			bool isSecure() const override; - -			void response(short, const std::string_view &) const override; -			void setHeader(const std::string_view &, const std::string_view &) const override; - -			std::ostream & dump(std::ostream & s) const override; - -		private: -			template<typename MapType> -			static OptionalString optionalLookup(const std::string_view & key, const MapType &); - -			VarMap envmap; -			StringMap qsmap; -			StringMap cookiemap; -			HdrMap hdrmap; -			PathElements pathElements; +	protected: +		CgiRequestBase(Core * c, const char * const * const env); +		void addenv(const char * const); +		void initialize(); + +	public: +		using VarMap = std::map<std::string_view, const std::string_view>; +		using HdrMap = std::map<std::string_view, const std::string_view, Slicer::case_less>; + +		[[nodiscard]] const PathElements & getRequestPath() const override; +		[[nodiscard]] PathElements & getRequestPath() override; +		[[nodiscard]] HttpMethod getRequestMethod() const override; +		[[nodiscard]] OptionalString getQueryStringParam(const std::string_view & key) const override; +		[[nodiscard]] OptionalString getHeaderParam(const std::string_view & key) const override; +		[[nodiscard]] OptionalString getCookieParam(const std::string_view & key) const override; +		[[nodiscard]] OptionalString getEnv(const std::string_view & key) const override; +		[[nodiscard]] bool isSecure() const override; + +		void response(short, const std::string_view &) const override; +		void setHeader(const std::string_view &, const std::string_view &) const override; + +		std::ostream & dump(std::ostream & s) const override; + +	private: +		template<typename MapType> static OptionalString optionalLookup(const std::string_view & key, const MapType &); + +		VarMap envmap; +		StringMap qsmap; +		StringMap cookiemap; +		HdrMap hdrmap; +		PathElements pathElements;  	};  }  #endif - diff --git a/icespider/fcgi/fcgiRequest.cpp b/icespider/fcgi/fcgiRequest.cpp index 0d2ff75..5692c65 100644 --- a/icespider/fcgi/fcgiRequest.cpp +++ b/icespider/fcgi/fcgiRequest.cpp @@ -2,11 +2,7 @@  namespace IceSpider {  	FcgiRequest::FcgiRequest(Core * c, FCGX_Request * r) : -		CgiRequestBase(c, r->envp), -		inputbuf(r->in), -		input(&inputbuf), -		outputbuf(r->out), -		output(&outputbuf) +		CgiRequestBase(c, r->envp), inputbuf(r->in), input(&inputbuf), outputbuf(r->out), output(&outputbuf)  	{  		initialize();  	} @@ -23,4 +19,3 @@ namespace IceSpider {  		return output;  	}  } - diff --git a/icespider/fcgi/fcgiRequest.h b/icespider/fcgi/fcgiRequest.h index 0bc2e41..58ffc0a 100644 --- a/icespider/fcgi/fcgiRequest.h +++ b/icespider/fcgi/fcgiRequest.h @@ -6,18 +6,17 @@  namespace IceSpider {  	class FcgiRequest : public CgiRequestBase { -		public: -			FcgiRequest(Core * c, FCGX_Request * r); +	public: +		FcgiRequest(Core * c, FCGX_Request * r); -			std::istream & getInputStream() const override; -			std::ostream & getOutputStream() const override; +		std::istream & getInputStream() const override; +		std::ostream & getOutputStream() const override; -			fcgi_streambuf inputbuf; -			mutable std::istream input; -			fcgi_streambuf outputbuf; -			mutable std::ostream output; +		fcgi_streambuf inputbuf; +		mutable std::istream input; +		fcgi_streambuf outputbuf; +		mutable std::ostream output;  	};  }  #endif - diff --git a/icespider/fcgi/main.cpp b/icespider/fcgi/main.cpp index 7191310..8402501 100644 --- a/icespider/fcgi/main.cpp +++ b/icespider/fcgi/main.cpp @@ -1,7 +1,7 @@ -#include <visibility.h> -#include "fcgiRequest.h"  #include "cgiRequest.h"  #include "core.h" +#include "fcgiRequest.h" +#include <visibility.h>  using namespace IceSpider; @@ -28,4 +28,3 @@ main(int argc, char ** argv, char ** env)  	}  	return 0;  } - diff --git a/icespider/fileSessions/fileSessions.cpp b/icespider/fileSessions/fileSessions.cpp index bee3f7c..2b1acbe 100644 --- a/icespider/fileSessions/fileSessions.cpp +++ b/icespider/fileSessions/fileSessions.cpp @@ -1,155 +1,162 @@ +#include "Ice/Initialize.h" +#include <Ice/InputStream.h> +#include <Ice/OutputStream.h> +#include <boost/uuid/uuid_generators.hpp> +#include <boost/uuid/uuid_io.hpp>  #include <core.h> -#include <session.h> +#include <factory.impl.h>  #include <fcntl.h>  #include <fileUtils.h> +#include <filesystem> +#include <session.h>  #include <sys.h>  #include <sys/file.h> -#include <sys/stat.h>  #include <sys/mman.h> -#include <factory.impl.h> -#include <filesystem> -#include <boost/uuid/uuid_generators.hpp> -#include <boost/uuid/uuid_io.hpp> -#include <Ice/OutputStream.h> -#include <Ice/InputStream.h> -#include "Ice/Initialize.h" +#include <sys/stat.h>  namespace IceSpider {  	class FileSessions : public Plugin, public SessionManager { -		public: -			FileSessions(Ice::CommunicatorPtr c, const Ice::PropertiesPtr & p) : -				ic(std::move(c)), -				root(p->getProperty("IceSpider.FileSessions.Path")), -				duration(p->getPropertyAsIntWithDefault("IceSpider.FileSessions.Duration", 3600)) -			{ -				if (!root.empty() && !std::filesystem::exists(root)) { -					std::filesystem::create_directories(root); -				} +	public: +		FileSessions(Ice::CommunicatorPtr c, const Ice::PropertiesPtr & p) : +			ic(std::move(c)), root(p->getProperty("IceSpider.FileSessions.Path")), +			duration(p->getPropertyAsIntWithDefault("IceSpider.FileSessions.Duration", 3600)) +		{ +			if (!root.empty() && !std::filesystem::exists(root)) { +				std::filesystem::create_directories(root);  			} +		} -			FileSessions(const FileSessions &) = delete; -			FileSessions(FileSessions &&) = delete; +		FileSessions(const FileSessions &) = delete; +		FileSessions(FileSessions &&) = delete; -			~FileSessions() override -			{ -				try { -					removeExpired(); -				} -				catch (...) { -					// Meh :) -				} +		~FileSessions() override +		{ +			try { +				removeExpired(); +			} +			catch (...) { +				// Meh :)  			} +		} -			void operator=(const FileSessions &) = delete; -			void operator=(FileSessions &&) = delete; +		void operator=(const FileSessions &) = delete; +		void operator=(FileSessions &&) = delete; -			SessionPtr createSession(const ::Ice::Current &) override -			{ -				auto s = std::make_shared<Session>(); -				// NOLINTNEXTLINE(clang-analyzer-optin.cplusplus.VirtualCall) -				s->id = boost::lexical_cast<std::string>(boost::uuids::random_generator()()); -				s->duration = duration; -				save(s); -				return s; -			} +		SessionPtr +		createSession(const ::Ice::Current &) override +		{ +			auto s = std::make_shared<Session>(); +			// NOLINTNEXTLINE(clang-analyzer-optin.cplusplus.VirtualCall) +			s->id = boost::lexical_cast<std::string>(boost::uuids::random_generator()()); +			s->duration = duration; +			save(s); +			return s; +		} -			SessionPtr getSession(const ::std::string id, const ::Ice::Current & current) override -			{ -				auto s = load(id); -				if (s && isExpired(s)) { -					destroySession(id, current); -					return nullptr; -				} -				return s; +		SessionPtr +		getSession(const ::std::string id, const ::Ice::Current & current) override +		{ +			auto s = load(id); +			if (s && isExpired(s)) { +				destroySession(id, current); +				return nullptr;  			} +			return s; +		} -			void updateSession(const SessionPtr s, const ::Ice::Current &) override -			{ -				save(s); -			} +		void +		updateSession(const SessionPtr s, const ::Ice::Current &) override +		{ +			save(s); +		} -			void destroySession(const ::std::string id, const ::Ice::Current &) override -			{ -				try { -					std::filesystem::remove(root / id); -				} -				catch (const std::exception & e) { -					throw SessionError(e.what()); -				} +		void +		destroySession(const ::std::string id, const ::Ice::Current &) override +		{ +			try { +				std::filesystem::remove(root / id);  			} +			catch (const std::exception & e) { +				throw SessionError(e.what()); +			} +		} + +	private: +		void +		save(const SessionPtr & s) +		{ +			s->lastUsed = time(nullptr); +			Ice::OutputStream buf(ic); +			buf.write(s); +			auto range = buf.finished(); +			// NOLINTNEXTLINE(hicpp-signed-bitwise) +			AdHoc::FileUtils::FileHandle f(root / s->id, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); +			sysassert(flock(f.fh, LOCK_EX), -1); +			sysassert(pwrite(f.fh, range.first, range.second - range.first, 0), -1); +			sysassert(ftruncate(f.fh, range.second - range.first), -1); +			sysassert(flock(f.fh, LOCK_UN), -1); +		} -		private: -			void save(const SessionPtr & s) -			{ -				s->lastUsed = time(nullptr); -				Ice::OutputStream buf(ic); -				buf.write(s); -				auto range = buf.finished(); -				// NOLINTNEXTLINE(hicpp-signed-bitwise) -				AdHoc::FileUtils::FileHandle f(root / s->id, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); -				sysassert(flock(f.fh, LOCK_EX), -1); -				sysassert(pwrite(f.fh, range.first, range.second - range.first, 0), -1); -				sysassert(ftruncate(f.fh, range.second - range.first), -1); +		SessionPtr +		load(const std::string & id) +		{ +			auto path = root / id; +			if (!std::filesystem::exists(path)) { +				return nullptr; +			} +			try { +				AdHoc::FileUtils::MemMap f(path); +				sysassert(flock(f.fh, LOCK_SH), -1); +				auto fbuf = (Ice::Byte *)f.data; +				Ice::InputStream buf(ic, std::make_pair(fbuf, fbuf + f.getStat().st_size)); +				SessionPtr s; +				buf.read(s);  				sysassert(flock(f.fh, LOCK_UN), -1); +				return s;  			} - -			SessionPtr load(const std::string & id) -			{ -				auto path = root / id; -				if (!std::filesystem::exists(path)) { +			catch (const AdHoc::SystemException & e) { +				if (e.errNo == ENOENT) {  					return nullptr;  				} -				try { -					AdHoc::FileUtils::MemMap f(path); -					sysassert(flock(f.fh, LOCK_SH), -1); -					auto fbuf = (Ice::Byte *)f.data; -					Ice::InputStream buf(ic, std::make_pair(fbuf, fbuf + f.getStat().st_size)); -					SessionPtr s; -					buf.read(s); -					sysassert(flock(f.fh, LOCK_UN), -1); -					return s; -				} -				catch (const AdHoc::SystemException & e) { -					if (e.errNo == ENOENT) { -						return nullptr; -					} -					throw; -				} +				throw;  			} +		} -			void removeExpired() -			{ -				if (root.empty() || !std::filesystem::exists(root)) { -					return; -				} -				std::filesystem::directory_iterator di(root); -				while (di != std::filesystem::directory_iterator()) { -					auto s = load(di->path()); -					if (s && isExpired(s)) { -						FileSessions::destroySession(s->id, Ice::Current()); -					} -					di++; +		void +		removeExpired() +		{ +			if (root.empty() || !std::filesystem::exists(root)) { +				return; +			} +			std::filesystem::directory_iterator di(root); +			while (di != std::filesystem::directory_iterator()) { +				auto s = load(di->path()); +				if (s && isExpired(s)) { +					FileSessions::destroySession(s->id, Ice::Current());  				} +				di++;  			} +		} -			bool isExpired(const SessionPtr & s) -			{ -				return (s->lastUsed + s->duration < time(nullptr)); -			} +		bool +		isExpired(const SessionPtr & s) +		{ +			return (s->lastUsed + s->duration < time(nullptr)); +		} -			template<typename R, typename ER> -			R sysassert(R rtn, ER ertn) -			{ -				if (rtn == ertn) { -					throw SessionError(strerror(errno)); -				} -				return rtn; +		template<typename R, typename ER> +		R +		sysassert(R rtn, ER ertn) +		{ +			if (rtn == ertn) { +				throw SessionError(strerror(errno));  			} +			return rtn; +		} -			Ice::CommunicatorPtr ic; - 			const std::filesystem::path root; -			const Ice::Int duration; +		Ice::CommunicatorPtr ic; +		const std::filesystem::path root; +		const Ice::Int duration;  	};  }  NAMEDFACTORY("IceSpider-FileSessions", IceSpider::FileSessions, IceSpider::PluginFactory); - diff --git a/icespider/testing/testRequest.cpp b/icespider/testing/testRequest.cpp index fea77f2..c384b31 100644 --- a/icespider/testing/testRequest.cpp +++ b/icespider/testing/testRequest.cpp @@ -1,13 +1,11 @@  #include "testRequest.h" -#include <boost/algorithm/string/split.hpp>  #include <boost/algorithm/string/classification.hpp> +#include <boost/algorithm/string/split.hpp>  #include <formatters.h>  namespace IceSpider {  	constexpr std::string_view slash("/"); -	TestRequest::TestRequest(const Core * c, HttpMethod m, const std::string_view & p) : -		IHttpRequest(c), -		method(m) +	TestRequest::TestRequest(const Core * c, HttpMethod m, const std::string_view & p) : IHttpRequest(c), method(m)  	{  		namespace ba = boost::algorithm;  		auto path = p.substr(1); @@ -158,4 +156,3 @@ namespace IceSpider {  		return responseHeaders;  	}  } - diff --git a/icespider/testing/testRequest.h b/icespider/testing/testRequest.h index 31d3e4b..4d93197 100644 --- a/icespider/testing/testRequest.h +++ b/icespider/testing/testRequest.h @@ -6,48 +6,47 @@  namespace IceSpider {  	class DLL_PUBLIC TestRequest : public IHttpRequest { -		public: -			typedef std::map<std::string, std::string, std::less<>> MapVars; - -			TestRequest(const Core * c, HttpMethod m, const std::string_view & p); - -			const PathElements & getRequestPath() const override; -			PathElements & getRequestPath() override; -			HttpMethod getRequestMethod() const override; -			OptionalString getEnv(const std::string_view & key) const override; -			OptionalString getQueryStringParam(const std::string_view & key) const override; -			OptionalString getCookieParam(const std::string_view & key) const override; -			OptionalString getHeaderParam(const std::string_view & key) const override; -			bool isSecure() const override; -			void setQueryStringParam(const std::string_view &, const OptionalString &); -			void setHeaderParam(const std::string_view &, const OptionalString &); -			void setCookieParam(const std::string_view &, const OptionalString &); -			void setEnv(const std::string_view &, const OptionalString &); -			std::istream & getInputStream() const override; -			std::ostream & getOutputStream() const override; -			void response(short statusCode, const std::string_view & statusMsg) const override; -			void setHeader(const std::string_view & header, const std::string_view & value) const override; -			std::ostream & dump(std::ostream & s) const override; - -			const MapVars & getResponseHeaders(); - -			PathElements url; -			MapVars qs; -			MapVars cookies; -			MapVars hdr; -			MapVars env; -			mutable std::stringstream input; -			mutable std::stringstream output; -			const HttpMethod method; - -		protected: -			OptionalString get(const std::string_view &, const MapVars &) const; -			void set(const std::string_view &, const OptionalString &, MapVars &); - -		private: -			MapVars responseHeaders; +	public: +		using MapVars = std::map<std::string, std::string, std::less<>>; + +		TestRequest(const Core * c, HttpMethod m, const std::string_view & p); + +		const PathElements & getRequestPath() const override; +		PathElements & getRequestPath() override; +		HttpMethod getRequestMethod() const override; +		OptionalString getEnv(const std::string_view & key) const override; +		OptionalString getQueryStringParam(const std::string_view & key) const override; +		OptionalString getCookieParam(const std::string_view & key) const override; +		OptionalString getHeaderParam(const std::string_view & key) const override; +		bool isSecure() const override; +		void setQueryStringParam(const std::string_view &, const OptionalString &); +		void setHeaderParam(const std::string_view &, const OptionalString &); +		void setCookieParam(const std::string_view &, const OptionalString &); +		void setEnv(const std::string_view &, const OptionalString &); +		std::istream & getInputStream() const override; +		std::ostream & getOutputStream() const override; +		void response(short statusCode, const std::string_view & statusMsg) const override; +		void setHeader(const std::string_view & header, const std::string_view & value) const override; +		std::ostream & dump(std::ostream & s) const override; + +		const MapVars & getResponseHeaders(); + +		PathElements url; +		MapVars qs; +		MapVars cookies; +		MapVars hdr; +		MapVars env; +		mutable std::stringstream input; +		mutable std::stringstream output; +		const HttpMethod method; + +	protected: +		OptionalString get(const std::string_view &, const MapVars &) const; +		void set(const std::string_view &, const OptionalString &, MapVars &); + +	private: +		MapVars responseHeaders;  	};  }  #endif - diff --git a/icespider/unittests/base2.cpp b/icespider/unittests/base2.cpp index 4f6d8ef..a64d46b 100644 --- a/icespider/unittests/base2.cpp +++ b/icespider/unittests/base2.cpp @@ -1,13 +1,10 @@  #include "base2.h"  namespace common { -	base2::base2(const IceSpider::Core *) -	{ -	} +	base2::base2(const IceSpider::Core *) { }  	void  	base2::testMutate(const IceSpider::IHttpRequest *, ::TestIceSpider::SomeModelPtr &) const  	{  	}  } - diff --git a/icespider/unittests/base2.h b/icespider/unittests/base2.h index d89cf85..d0ad75c 100644 --- a/icespider/unittests/base2.h +++ b/icespider/unittests/base2.h @@ -2,8 +2,8 @@  #define ICESPIDER_TEST_BASE2_H  // Standard headers. -#include <irouteHandler.h>  #include <core.h> +#include <irouteHandler.h>  // Interface headers.  #include <test-api.h> @@ -12,12 +12,11 @@ namespace common {  	// Base classes.  	class DLL_PUBLIC base2 { -		protected: -			base2(const IceSpider::Core * core); +	protected: +		explicit base2(const IceSpider::Core * core); -			void testMutate(const IceSpider::IHttpRequest *, TestIceSpider::SomeModelPtr &) const; +		void testMutate(const IceSpider::IHttpRequest *, TestIceSpider::SomeModelPtr &) const;  	}; // base2  } // namespace common  #endif - diff --git a/icespider/unittests/string_view_support.h b/icespider/unittests/string_view_support.h index ef9fb94..12d8077 100644 --- a/icespider/unittests/string_view_support.h +++ b/icespider/unittests/string_view_support.h @@ -1,32 +1,30 @@  #ifndef ICETRAY_STRING_VIEW_SUPPORT_H  #define ICETRAY_STRING_VIEW_SUPPORT_H -#include <string_view>  #include <Ice/OutputStream.h>  #include <Ice/StreamHelpers.h> +#include <string_view> -namespace Ice -{ -	template<> -	struct StreamableTraits<std::string_view> -	{ +namespace Ice { +	template<> struct StreamableTraits<std::string_view> {  		static const StreamHelperCategory helper = StreamHelperCategoryBuiltin;  		static const int minWireSize = 1;  		static const bool fixedLength = false;  	}; -	template<> -	struct StreamHelper<std::string_view, StreamHelperCategoryBuiltin> { -		template<class S> static inline void -		write(S * stream, const std::string_view& v) +	template<> struct StreamHelper<std::string_view, StreamHelperCategoryBuiltin> { +		template<class S> +		static inline void +		write(S * stream, const std::string_view & v)  		{  			stream->write(v.data(), v.size());  		} -		template<class S> static inline void -		read(S * stream, std::string_view& v) +		template<class S> +		static inline void +		read(S * stream, std::string_view & v)  		{ -			const char* vdata = 0; +			const char * vdata = nullptr;  			size_t vsize = 0;  			stream->read(vdata, vsize); @@ -42,4 +40,3 @@ namespace Ice  }  #endif - diff --git a/icespider/unittests/test-api-impl.cpp b/icespider/unittests/test-api-impl.cpp index 7d5b556..bcf32ed 100644 --- a/icespider/unittests/test-api-impl.cpp +++ b/icespider/unittests/test-api-impl.cpp @@ -5,4 +5,3 @@ TestIceSpider::Ex::ice_print(std::ostream & s) const  {  	s << message;  } - diff --git a/icespider/unittests/testAccept.cpp b/icespider/unittests/testAccept.cpp index 2cabe5e..cc08f0a 100644 --- a/icespider/unittests/testAccept.cpp +++ b/icespider/unittests/testAccept.cpp @@ -1,46 +1,48 @@  #define BOOST_TEST_MODULE TestAccept -#include <boost/test/included/unit_test.hpp>  #include <boost/test/data/test_case.hpp> +#include <boost/test/included/unit_test.hpp> -#include <ihttpRequest.h>  #include <exceptions.h> +#include <ihttpRequest.h>  auto parse = IceSpider::IHttpRequest::parseAccept;  using namespace boost::unit_test::data;  namespace std { -	ostream & operator<<(ostream & s, const IceSpider::Accept & a) +	ostream & +	operator<<(ostream & s, const IceSpider::Accept & a)  	{ -		s << (a.group ? *a.group : "*") -			<< "/" -			<< (a.type ? *a.type : "*") -			<< ";q=" << a.q; +		s << (a.group ? *a.group : "*") << "/" << (a.type ? *a.type : "*") << ";q=" << a.q;  		return s;  	}  } -BOOST_TEST_DECORATOR(* boost::unit_test::timeout(1)) -BOOST_DATA_TEST_CASE(bad_requests, make({ -	"", // Can't specify nothing -	"  ", // This is still nothing -	" group ", -	" ; ", -	" / ", -	" ^ ", -	" * / plain ", -	" text / plain ; q = 0.0 ", -	" text / plain ; q = 1.1 ", -}), a) +BOOST_TEST_DECORATOR(*boost::unit_test::timeout(1)) +BOOST_DATA_TEST_CASE(bad_requests, +		make({ +				"", // Can't specify nothing +				"  ", // This is still nothing +				" group ", +				" ; ", +				" / ", +				" ^ ", +				" * / plain ", +				" text / plain ; q = 0.0 ", +				" text / plain ; q = 1.1 ", +		}), +		a)  {  	BOOST_CHECK_THROW(parse(a), IceSpider::Http400_BadRequest);  } -BOOST_DATA_TEST_CASE(texthtml, make({ -	"text/html", -	"image/png;q=0.1, text/html", -	"image/png;q=0.9, text/html;q=1.0", -	"image/png;q=0.9, text/html;q=1.0, something/else;q=1.0", -}), a) +BOOST_DATA_TEST_CASE(texthtml, +		make({ +				"text/html", +				"image/png;q=0.1, text/html", +				"image/png;q=0.9, text/html;q=1.0", +				"image/png;q=0.9, text/html;q=1.0, something/else;q=1.0", +		}), +		a)  {  	auto front = parse(a).front();  	BOOST_REQUIRE(front->group); @@ -49,12 +51,14 @@ BOOST_DATA_TEST_CASE(texthtml, make({  	BOOST_REQUIRE_EQUAL(*front->type, "html");  } -BOOST_DATA_TEST_CASE(textany, make({ -	"text/*", -	"image/png;q=0.1, text/*", -	"image/png;q=0.9, text/*;q=1.0", -	"image/png;q=0.9, text/*;q=1.0, something/else;q=1.0", -}), a) +BOOST_DATA_TEST_CASE(textany, +		make({ +				"text/*", +				"image/png;q=0.1, text/*", +				"image/png;q=0.9, text/*;q=1.0", +				"image/png;q=0.9, text/*;q=1.0, something/else;q=1.0", +		}), +		a)  {  	auto front = parse(a).front();  	BOOST_REQUIRE(front->group); @@ -62,13 +66,15 @@ BOOST_DATA_TEST_CASE(textany, make({  	BOOST_REQUIRE(!front->type);  } -BOOST_DATA_TEST_CASE(anyhtml, make({ -	"any/html", -	"image/png;q=0.1, any/html", -	"image/png;q=0.9, any/html;q=1.0", -	"image/png;q=0.9, any/html;q=1.0, something/else;q=1.0", -	" image / png ; q = 0.9 , any / html ; q = 1.0 , something / else ; q = 1.0", -}), a) +BOOST_DATA_TEST_CASE(anyhtml, +		make({ +				"any/html", +				"image/png;q=0.1, any/html", +				"image/png;q=0.9, any/html;q=1.0", +				"image/png;q=0.9, any/html;q=1.0, something/else;q=1.0", +				" image / png ; q = 0.9 , any / html ; q = 1.0 , something / else ; q = 1.0", +		}), +		a)  {  	auto front = parse(a).front();  	BOOST_REQUIRE(front->group); @@ -76,29 +82,32 @@ BOOST_DATA_TEST_CASE(anyhtml, make({  	BOOST_REQUIRE_EQUAL(*front->type, "html");  } -BOOST_DATA_TEST_CASE(anyany, make({ -	"*/*", -	"image/png;q=0.1, */*", -	"image/png;q=0.9, */*;q=1.0", -	"image/png;q=0.9, */*;q=1.0, something/else;q=1.0", -}), a) +BOOST_DATA_TEST_CASE(anyany, +		make({ +				"*/*", +				"image/png;q=0.1, */*", +				"image/png;q=0.9, */*;q=1.0", +				"image/png;q=0.9, */*;q=1.0, something/else;q=1.0", +		}), +		a)  {  	auto front = parse(a).front();  	BOOST_REQUIRE(!front->group);  	BOOST_REQUIRE(!front->type);  } -BOOST_DATA_TEST_CASE(q1, make({ -	"*/*", -	"image/png, */*", -	"image/png;q=1.0, */*", -}), a) +BOOST_DATA_TEST_CASE(q1, +		make({ +				"*/*", +				"image/png, */*", +				"image/png;q=1.0, */*", +		}), +		a)  {  	auto all = parse(a); -	for(const auto & accept : all) { +	for (const auto & accept : all) {  		BOOST_TEST_CONTEXT(*accept) {  			BOOST_CHECK_CLOSE(accept->q, 1.0, 0.1);  		}  	}  } - diff --git a/icespider/unittests/testApp.cpp b/icespider/unittests/testApp.cpp index cabcd0c..46fda40 100644 --- a/icespider/unittests/testApp.cpp +++ b/icespider/unittests/testApp.cpp @@ -1,88 +1,75 @@  #define BOOST_TEST_MODULE TestApp  #include <boost/test/unit_test.hpp> -#include <safeMapFind.h> -#include <irouteHandler.h> -#include <core.h> -#include <exceptions.h> -#include <test-api.h> -#include <Ice/ObjectAdapter.h>  #include <Ice/Initialize.h> -#include <boost/algorithm/string/split.hpp> +#include <Ice/ObjectAdapter.h>  #include <boost/algorithm/string/classification.hpp>  #include <boost/algorithm/string/predicate.hpp> -#include <filesystem> +#include <boost/algorithm/string/split.hpp> +#include <core.h>  #include <definedDirs.h> -#include <slicer/slicer.h> -#include <xml/serializer.h> +#include <exceptions.h> +#include <factory.impl.h> +#include <filesystem> +#include <irouteHandler.h>  #include <json/serializer.h>  #include <libxml++/parsers/domparser.h> -#include <factory.impl.h> +#include <safeMapFind.h> +#include <slicer/slicer.h> +#include <test-api.h>  #include <testRequest.h> +#include <xml/serializer.h>  using namespace IceSpider;  static void forceEarlyChangeDir() __attribute__((constructor(101))); -void forceEarlyChangeDir() +void +forceEarlyChangeDir()  {  	std::filesystem::current_path(XSTR(ROOT));  } -BOOST_AUTO_TEST_CASE( testLoadConfiguration ) +BOOST_AUTO_TEST_CASE(testLoadConfiguration)  {  	BOOST_REQUIRE_EQUAL(13, AdHoc::PluginManager::getDefault()->getAll<IceSpider::RouteHandlerFactory>().size());  }  class CoreWithProps : public CoreWithDefaultRouter { -	public: -		CoreWithProps() : -			CoreWithDefaultRouter({ -				"--Custom.Prop=value" -			}) -		{ -		} +public: +	CoreWithProps() : CoreWithDefaultRouter({"--Custom.Prop=value"}) { }  };  BOOST_FIXTURE_TEST_SUITE(props, CoreWithProps); -BOOST_AUTO_TEST_CASE( properties ) +BOOST_AUTO_TEST_CASE(properties)  { -	BOOST_REQUIRE_EQUAL("Test", -			this->communicator->getProperties()->getProperty("TestIceSpider.TestApi")); -	BOOST_REQUIRE_EQUAL("value", -			this->communicator->getProperties()->getProperty("Custom.Prop")); +	BOOST_REQUIRE_EQUAL("Test", this->communicator->getProperties()->getProperty("TestIceSpider.TestApi")); +	BOOST_REQUIRE_EQUAL("value", this->communicator->getProperties()->getProperty("Custom.Prop"));  }  BOOST_AUTO_TEST_SUITE_END();  class CoreWithFileProps : public CoreWithDefaultRouter { -	public: -		CoreWithFileProps() : -			CoreWithDefaultRouter({ -				"--IceSpider.Config=config/custom.properties", -				"--Custom.Prop=value" -			}) -		{ -		} +public: +	CoreWithFileProps() : CoreWithDefaultRouter({"--IceSpider.Config=config/custom.properties", "--Custom.Prop=value"}) +	{ +	}  };  BOOST_FIXTURE_TEST_SUITE(fileProps, CoreWithFileProps); -BOOST_AUTO_TEST_CASE( properties ) +BOOST_AUTO_TEST_CASE(properties)  { -	BOOST_REQUIRE_EQUAL("", -			this->communicator->getProperties()->getProperty("TestIceSpider.TestApi")); -	BOOST_REQUIRE_EQUAL("something", -			this->communicator->getProperties()->getProperty("InFile")); -	BOOST_REQUIRE_EQUAL("value", -			this->communicator->getProperties()->getProperty("Custom.Prop")); +	BOOST_REQUIRE_EQUAL("", this->communicator->getProperties()->getProperty("TestIceSpider.TestApi")); +	BOOST_REQUIRE_EQUAL("something", this->communicator->getProperties()->getProperty("InFile")); +	BOOST_REQUIRE_EQUAL("value", this->communicator->getProperties()->getProperty("Custom.Prop"));  }  BOOST_AUTO_TEST_SUITE_END();  BOOST_FIXTURE_TEST_SUITE(defaultProps, CoreWithDefaultRouter); -BOOST_AUTO_TEST_CASE( testCoreSettings ) +BOOST_AUTO_TEST_CASE(testCoreSettings)  {  	BOOST_REQUIRE_EQUAL(5, routes.size());  	BOOST_REQUIRE_EQUAL(1, routes[0].size()); @@ -92,7 +79,7 @@ BOOST_AUTO_TEST_CASE( testCoreSettings )  	BOOST_REQUIRE_EQUAL(2, routes[4].size());  } -BOOST_AUTO_TEST_CASE( testFindRoutes ) +BOOST_AUTO_TEST_CASE(testFindRoutes)  {  	TestRequest requestGetIndex(this, HttpMethod::GET, "/");  	BOOST_REQUIRE(findRoute(&requestGetIndex)); @@ -115,7 +102,8 @@ BOOST_AUTO_TEST_CASE( testFindRoutes )  	TestRequest requestGetItemDefault(this, HttpMethod::GET, "/item/something");  	BOOST_REQUIRE(findRoute(&requestGetItemDefault)); -	TestRequest requestGetItemLong(this, HttpMethod::GET, "/view/something/something/extra/many/things/longer/than/longest/route"); +	TestRequest requestGetItemLong( +			this, HttpMethod::GET, "/view/something/something/extra/many/things/longer/than/longest/route");  	BOOST_REQUIRE_THROW(findRoute(&requestGetItemLong), IceSpider::Http404_NotFound);  	TestRequest requestGetItemShort(this, HttpMethod::GET, "/view/missingSomething"); @@ -137,96 +125,102 @@ BOOST_AUTO_TEST_CASE( testFindRoutes )  BOOST_AUTO_TEST_SUITE_END();  class TestSerice : public TestIceSpider::TestApi { -	public: -		TestIceSpider::SomeModelPtr index(const Ice::Current &) override -		{ -			return std::make_shared<TestIceSpider::SomeModel>("index"); +public: +	TestIceSpider::SomeModelPtr +	index(const Ice::Current &) override +	{ +		return std::make_shared<TestIceSpider::SomeModel>("index"); +	} + +	TestIceSpider::SomeModelPtr +	withParams(const std::string s, Ice::Int i, const Ice::Current &) override +	{ +		BOOST_REQUIRE_EQUAL(s, "something"); +		BOOST_REQUIRE_EQUAL(i, 1234); +		return std::make_shared<TestIceSpider::SomeModel>("withParams"); +	} + +	void +	returnNothing(const std::string_view s, const Ice::Current &) override +	{ +		if (s == "error") { +			throw TestIceSpider::Ex("test error");  		} - -		TestIceSpider::SomeModelPtr withParams(const std::string s, Ice::Int i, const Ice::Current &) override -		{ -			BOOST_REQUIRE_EQUAL(s, "something"); -			BOOST_REQUIRE_EQUAL(i, 1234); -			return std::make_shared<TestIceSpider::SomeModel>("withParams"); -		} - -		void returnNothing(const std::string_view s, const Ice::Current &) override -		{ -			if (s == "error") { -				throw TestIceSpider::Ex("test error"); -			} -			else if (s.length() == 3) { -				throw TestIceSpider::Ex(std::string(s)); -			} -			BOOST_REQUIRE_EQUAL(s, "some value"); -		} - -		void complexParam(const Ice::optional<std::string> s, const TestIceSpider::SomeModelPtr m, const Ice::Current &) override -		{ -			BOOST_REQUIRE(s); -			BOOST_REQUIRE_EQUAL("1234", *s); -			BOOST_REQUIRE(m); -			BOOST_REQUIRE_EQUAL("some value", m->value); -		} - -		Ice::Int simple(const Ice::Current &) override -		{ -			return 1; -		} - -		std::string simplei(Ice::Int n, const Ice::Current &) override -		{ -			return std::to_string(n); +		else if (s.length() == 3) { +			throw TestIceSpider::Ex(std::string(s));  		} +		BOOST_REQUIRE_EQUAL(s, "some value"); +	} + +	void +	complexParam(const Ice::optional<std::string> s, const TestIceSpider::SomeModelPtr m, const Ice::Current &) override +	{ +		BOOST_REQUIRE(s); +		BOOST_REQUIRE_EQUAL("1234", *s); +		BOOST_REQUIRE(m); +		BOOST_REQUIRE_EQUAL("some value", m->value); +	} + +	Ice::Int +	simple(const Ice::Current &) override +	{ +		return 1; +	} + +	std::string +	simplei(Ice::Int n, const Ice::Current &) override +	{ +		return std::to_string(n); +	}  };  // NOLINTNEXTLINE(hicpp-special-member-functions)  class TestApp : public CoreWithDefaultRouter { -	public: -		TestApp() : -			adp(communicator->createObjectAdapterWithEndpoints("test", "default")) -		{ -			adp->activate(); -			adp->add(std::make_shared<TestSerice>(), Ice::stringToIdentity("Test")); -		} - -		~TestApp() override -		{ -			adp->deactivate(); -			adp->destroy(); -		} - -	private: -		Ice::ObjectAdapterPtr adp; +public: +	TestApp() : adp(communicator->createObjectAdapterWithEndpoints("test", "default")) +	{ +		adp->activate(); +		adp->add(std::make_shared<TestSerice>(), Ice::stringToIdentity("Test")); +	} + +	~TestApp() override +	{ +		adp->deactivate(); +		adp->destroy(); +	} + +private: +	Ice::ObjectAdapterPtr adp;  };  class Dummy : public IceSpider::Plugin, TestIceSpider::DummyPlugin { -	public: -		Dummy(const Ice::CommunicatorPtr &, const Ice::PropertiesPtr &) { } +public: +	Dummy(const Ice::CommunicatorPtr &, const Ice::PropertiesPtr &) { }  };  NAMEDFACTORY("DummyPlugin", Dummy, IceSpider::PluginFactory);  BOOST_FIXTURE_TEST_SUITE(ta, TestApp); -BOOST_AUTO_TEST_CASE( plugins ) +BOOST_AUTO_TEST_CASE(plugins)  {  	auto prx = this->getProxy<TestIceSpider::DummyPlugin>();  	BOOST_REQUIRE(prx);  	prx->ice_ping();  } -BOOST_AUTO_TEST_CASE( testCallIndex ) +BOOST_AUTO_TEST_CASE(testCallIndex)  {  	TestRequest requestGetIndex(this, HttpMethod::GET, "/");  	process(&requestGetIndex);  	auto h = requestGetIndex.getResponseHeaders();  	BOOST_REQUIRE_EQUAL(h["Status"], "200 OK");  	BOOST_REQUIRE_EQUAL(h["Content-Type"], "application/json"); -	auto v = Slicer::DeserializeAny<Slicer::JsonStreamDeserializer, TestIceSpider::SomeModelPtr>(requestGetIndex.output); +	auto v = Slicer::DeserializeAny<Slicer::JsonStreamDeserializer, TestIceSpider::SomeModelPtr>( +			requestGetIndex.output);  	BOOST_REQUIRE_EQUAL(v->value, "index");  } -BOOST_AUTO_TEST_CASE( testCallMashS ) +BOOST_AUTO_TEST_CASE(testCallMashS)  {  	TestRequest requestGetMashS(this, HttpMethod::GET, "/mashS/something/something/1234");  	process(&requestGetMashS); @@ -238,7 +232,7 @@ BOOST_AUTO_TEST_CASE( testCallMashS )  	BOOST_REQUIRE_EQUAL(v.b->value, "withParams");  } -BOOST_AUTO_TEST_CASE( testCallMashC ) +BOOST_AUTO_TEST_CASE(testCallMashC)  {  	TestRequest requestGetMashC(this, HttpMethod::GET, "/mashC/something/something/1234");  	process(&requestGetMashC); @@ -250,7 +244,7 @@ BOOST_AUTO_TEST_CASE( testCallMashC )  	BOOST_REQUIRE_EQUAL(v->b->value, "withParams");  } -BOOST_AUTO_TEST_CASE( testCallViewSomething1234 ) +BOOST_AUTO_TEST_CASE(testCallViewSomething1234)  {  	TestRequest requestGetItem(this, HttpMethod::GET, "/view/something/1234");  	process(&requestGetItem); @@ -261,29 +255,31 @@ BOOST_AUTO_TEST_CASE( testCallViewSomething1234 )  	BOOST_REQUIRE_EQUAL(v->value, "withParams");  } -BOOST_AUTO_TEST_CASE( testCallViewSomething1234_ ) +BOOST_AUTO_TEST_CASE(testCallViewSomething1234_)  {  	TestRequest requestGetItemGiven(this, HttpMethod::GET, "/item/something/1234");  	process(&requestGetItemGiven);  	auto h = requestGetItemGiven.getResponseHeaders();  	BOOST_REQUIRE_EQUAL(h["Status"], "200 OK");  	BOOST_REQUIRE_EQUAL(h["Content-Type"], "application/json"); -	auto v = Slicer::DeserializeAny<Slicer::JsonStreamDeserializer, TestIceSpider::SomeModelPtr>(requestGetItemGiven.output); +	auto v = Slicer::DeserializeAny<Slicer::JsonStreamDeserializer, TestIceSpider::SomeModelPtr>( +			requestGetItemGiven.output);  	BOOST_REQUIRE_EQUAL(v->value, "withParams");  } -BOOST_AUTO_TEST_CASE( testCallViewSomething ) +BOOST_AUTO_TEST_CASE(testCallViewSomething)  {  	TestRequest requestGetItemDefault(this, HttpMethod::GET, "/item/something");  	process(&requestGetItemDefault);  	auto h = requestGetItemDefault.getResponseHeaders();  	BOOST_REQUIRE_EQUAL(h["Status"], "200 OK");  	BOOST_REQUIRE_EQUAL(h["Content-Type"], "application/json"); -	auto v = Slicer::DeserializeAny<Slicer::JsonStreamDeserializer, TestIceSpider::SomeModelPtr>(requestGetItemDefault.output); +	auto v = Slicer::DeserializeAny<Slicer::JsonStreamDeserializer, TestIceSpider::SomeModelPtr>( +			requestGetItemDefault.output);  	BOOST_REQUIRE_EQUAL(v->value, "withParams");  } -BOOST_AUTO_TEST_CASE( testCallDeleteSomeValue ) +BOOST_AUTO_TEST_CASE(testCallDeleteSomeValue)  {  	TestRequest requestDeleteItem(this, HttpMethod::DELETE, "/some value");  	process(&requestDeleteItem); @@ -293,7 +289,7 @@ BOOST_AUTO_TEST_CASE( testCallDeleteSomeValue )  	BOOST_REQUIRE(requestDeleteItem.output.eof());  } -BOOST_AUTO_TEST_CASE( testCallPost1234 ) +BOOST_AUTO_TEST_CASE(testCallPost1234)  {  	TestRequest requestUpdateItem(this, HttpMethod::POST, "/1234");  	requestUpdateItem.env["CONTENT_TYPE"] = "application/json"; @@ -305,7 +301,7 @@ BOOST_AUTO_TEST_CASE( testCallPost1234 )  	BOOST_REQUIRE(requestUpdateItem.output.eof());  } -BOOST_AUTO_TEST_CASE( testCallPost1234NoContentType ) +BOOST_AUTO_TEST_CASE(testCallPost1234NoContentType)  {  	TestRequest requestUpdateItem(this, HttpMethod::POST, "/1234");  	requestUpdateItem.input << R"({"value": "some value"})"; @@ -316,7 +312,7 @@ BOOST_AUTO_TEST_CASE( testCallPost1234NoContentType )  	BOOST_REQUIRE(requestUpdateItem.output.eof());  } -BOOST_AUTO_TEST_CASE( testCallPost1234UnsupportedMediaType ) +BOOST_AUTO_TEST_CASE(testCallPost1234UnsupportedMediaType)  {  	TestRequest requestUpdateItem(this, HttpMethod::POST, "/1234");  	requestUpdateItem.env["CONTENT_TYPE"] = "application/notathing"; @@ -328,7 +324,7 @@ BOOST_AUTO_TEST_CASE( testCallPost1234UnsupportedMediaType )  	BOOST_REQUIRE(requestUpdateItem.output.eof());  } -BOOST_AUTO_TEST_CASE( testCallIndexAcceptJson ) +BOOST_AUTO_TEST_CASE(testCallIndexAcceptJson)  {  	TestRequest requestJson(this, HttpMethod::GET, "/");  	requestJson.hdr["Accept"] = "application/json"; @@ -340,7 +336,7 @@ BOOST_AUTO_TEST_CASE( testCallIndexAcceptJson )  	BOOST_REQUIRE_EQUAL(v->value, "index");  } -BOOST_AUTO_TEST_CASE( testCallIndexAcceptAny ) +BOOST_AUTO_TEST_CASE(testCallIndexAcceptAny)  {  	TestRequest requestAnyAny(this, HttpMethod::GET, "/");  	requestAnyAny.hdr["Accept"] = "*/*"; @@ -351,7 +347,7 @@ BOOST_AUTO_TEST_CASE( testCallIndexAcceptAny )  	BOOST_REQUIRE_EQUAL(v->value, "index");  } -BOOST_AUTO_TEST_CASE( testCallIndexAcceptApplicationAny ) +BOOST_AUTO_TEST_CASE(testCallIndexAcceptApplicationAny)  {  	TestRequest requestApplicationAny(this, HttpMethod::GET, "/");  	requestApplicationAny.hdr["Accept"] = "application/*"; @@ -359,11 +355,12 @@ BOOST_AUTO_TEST_CASE( testCallIndexAcceptApplicationAny )  	auto h = requestApplicationAny.getResponseHeaders();  	BOOST_REQUIRE_EQUAL(h["Status"], "200 OK");  	BOOST_REQUIRE(boost::algorithm::starts_with(h["Content-Type"], "application/")); -	auto v = Slicer::DeserializeAny<Slicer::JsonStreamDeserializer, TestIceSpider::SomeModelPtr>(requestApplicationAny.output); +	auto v = Slicer::DeserializeAny<Slicer::JsonStreamDeserializer, TestIceSpider::SomeModelPtr>( +			requestApplicationAny.output);  	BOOST_REQUIRE_EQUAL(v->value, "index");  } -BOOST_AUTO_TEST_CASE( testCallIndexAcceptXml ) +BOOST_AUTO_TEST_CASE(testCallIndexAcceptXml)  {  	TestRequest requestXml(this, HttpMethod::GET, "/");  	requestXml.hdr["Accept"] = "application/xml"; @@ -375,7 +372,7 @@ BOOST_AUTO_TEST_CASE( testCallIndexAcceptXml )  	BOOST_REQUIRE_EQUAL(v->value, "index");  } -BOOST_AUTO_TEST_CASE( testCallIndexAcceptTextHtml ) +BOOST_AUTO_TEST_CASE(testCallIndexAcceptTextHtml)  {  	TestRequest requestHtml(this, HttpMethod::GET, "/");  	requestHtml.hdr["Accept"] = "text/html"; @@ -388,7 +385,7 @@ BOOST_AUTO_TEST_CASE( testCallIndexAcceptTextHtml )  	BOOST_REQUIRE_EQUAL(d.get_document()->get_root_node()->get_name(), "html");  } -BOOST_AUTO_TEST_CASE( testCallViewSomethingAcceptHtml ) +BOOST_AUTO_TEST_CASE(testCallViewSomethingAcceptHtml)  {  	TestRequest requestHtml(this, HttpMethod::GET, "/view/something/1234");  	requestHtml.hdr["Accept"] = "text/html"; @@ -399,7 +396,7 @@ BOOST_AUTO_TEST_CASE( testCallViewSomethingAcceptHtml )  	BOOST_REQUIRE(requestHtml.output.eof());  } -BOOST_AUTO_TEST_CASE( testCallIndexAcceptNotSupported ) +BOOST_AUTO_TEST_CASE(testCallIndexAcceptNotSupported)  {  	TestRequest requestBadAccept(this, HttpMethod::GET, "/");  	requestBadAccept.hdr["Accept"] = "not/supported"; @@ -410,7 +407,7 @@ BOOST_AUTO_TEST_CASE( testCallIndexAcceptNotSupported )  	BOOST_REQUIRE(requestBadAccept.output.eof());  } -BOOST_AUTO_TEST_CASE( testCallIndexComplexAccept ) +BOOST_AUTO_TEST_CASE(testCallIndexComplexAccept)  {  	TestRequest requestChoice(this, HttpMethod::GET, "/");  	requestChoice.hdr["Accept"] = "something/special ; q = 0.9, application/json ; q = 0.8, application/xml;q=1.0"; @@ -422,7 +419,7 @@ BOOST_AUTO_TEST_CASE( testCallIndexComplexAccept )  	BOOST_REQUIRE_EQUAL(v->value, "index");  } -BOOST_AUTO_TEST_CASE( testCall404 ) +BOOST_AUTO_TEST_CASE(testCall404)  {  	TestRequest requestGetIndex(this, HttpMethod::GET, "/this/404");  	process(&requestGetIndex); @@ -432,7 +429,7 @@ BOOST_AUTO_TEST_CASE( testCall404 )  	BOOST_REQUIRE(requestGetIndex.output.eof());  } -BOOST_AUTO_TEST_CASE( testCall405 ) +BOOST_AUTO_TEST_CASE(testCall405)  {  	TestRequest requestGetIndex(this, HttpMethod::GET, "/405");  	process(&requestGetIndex); @@ -442,7 +439,7 @@ BOOST_AUTO_TEST_CASE( testCall405 )  	BOOST_REQUIRE(requestGetIndex.output.eof());  } -BOOST_AUTO_TEST_CASE( testCallSearch ) +BOOST_AUTO_TEST_CASE(testCallSearch)  {  	TestRequest request(this, HttpMethod::GET, "/search");  	request.qs["s"] = "something"; @@ -453,7 +450,7 @@ BOOST_AUTO_TEST_CASE( testCallSearch )  	Slicer::DeserializeAny<Slicer::JsonStreamDeserializer, TestIceSpider::SomeModelPtr>(request.output);  } -BOOST_AUTO_TEST_CASE( testCallSearchBadLexicalCast ) +BOOST_AUTO_TEST_CASE(testCallSearchBadLexicalCast)  {  	TestRequest request(this, HttpMethod::GET, "/search");  	request.qs["s"] = "something"; @@ -465,7 +462,7 @@ BOOST_AUTO_TEST_CASE( testCallSearchBadLexicalCast )  	BOOST_REQUIRE(request.output.eof());  } -BOOST_AUTO_TEST_CASE( testCallSearchMissingS ) +BOOST_AUTO_TEST_CASE(testCallSearchMissingS)  {  	TestRequest request(this, HttpMethod::GET, "/search");  	request.qs["i"] = "1234"; @@ -476,7 +473,7 @@ BOOST_AUTO_TEST_CASE( testCallSearchMissingS )  	BOOST_REQUIRE(request.output.eof());  } -BOOST_AUTO_TEST_CASE( testCallSearchMissingI ) +BOOST_AUTO_TEST_CASE(testCallSearchMissingI)  {  	TestRequest request(this, HttpMethod::GET, "/search");  	request.qs["s"] = "something"; @@ -487,7 +484,7 @@ BOOST_AUTO_TEST_CASE( testCallSearchMissingI )  	BOOST_REQUIRE(request.output.eof());  } -BOOST_AUTO_TEST_CASE( testCookies ) +BOOST_AUTO_TEST_CASE(testCookies)  {  	TestRequest request(this, HttpMethod::GET, "/cookies");  	request.cookies["mycookievar"] = "something"; @@ -498,30 +495,30 @@ BOOST_AUTO_TEST_CASE( testCookies )  }  class DummyErrorHandler : public IceSpider::ErrorHandler { -	public: -		IceSpider::ErrorHandlerResult -		handleError(IceSpider::IHttpRequest * request, const std::exception & ex) const override -		{ -			if (const auto * tex = dynamic_cast<const TestIceSpider::Ex *>(&ex)) { -				if (tex->message == "404") { -					throw IceSpider::Http404_NotFound(); -				} -				if (tex->message == "304") { -					request->getRequestPath().front() = "some value"; -					return IceSpider::ErrorHandlerResult_Modified; -				} -				if (tex->message == "400") { -					request->response(400, "Handled"); -					return IceSpider::ErrorHandlerResult_Handled; -				} +public: +	IceSpider::ErrorHandlerResult +	handleError(IceSpider::IHttpRequest * request, const std::exception & ex) const override +	{ +		if (const auto * tex = dynamic_cast<const TestIceSpider::Ex *>(&ex)) { +			if (tex->message == "404") { +				throw IceSpider::Http404_NotFound(); +			} +			if (tex->message == "304") { +				request->getRequestPath().front() = "some value"; +				return IceSpider::ErrorHandlerResult_Modified; +			} +			if (tex->message == "400") { +				request->response(400, "Handled"); +				return IceSpider::ErrorHandlerResult_Handled;  			} -			return IceSpider::ErrorHandlerResult_Unhandled;  		} +		return IceSpider::ErrorHandlerResult_Unhandled; +	}  };  PLUGIN(DummyErrorHandler, IceSpider::ErrorHandler); -BOOST_AUTO_TEST_CASE( testErrorHandler_Unhandled ) +BOOST_AUTO_TEST_CASE(testErrorHandler_Unhandled)  {  	TestRequest requestDeleteItem(this, HttpMethod::DELETE, "/error");  	process(&requestDeleteItem); @@ -533,7 +530,7 @@ BOOST_AUTO_TEST_CASE( testErrorHandler_Unhandled )  	BOOST_REQUIRE_EQUAL(b, "Exception type: TestIceSpider::Ex\nDetail: test error\n");  } -BOOST_AUTO_TEST_CASE( testErrorHandler_Handled1 ) +BOOST_AUTO_TEST_CASE(testErrorHandler_Handled1)  {  	TestRequest requestDeleteItem(this, HttpMethod::DELETE, "/404");  	process(&requestDeleteItem); @@ -543,7 +540,7 @@ BOOST_AUTO_TEST_CASE( testErrorHandler_Handled1 )  	BOOST_REQUIRE(requestDeleteItem.output.eof());  } -BOOST_AUTO_TEST_CASE( testErrorHandler_Handled2 ) +BOOST_AUTO_TEST_CASE(testErrorHandler_Handled2)  {  	TestRequest requestDeleteItem(this, HttpMethod::DELETE, "/400");  	process(&requestDeleteItem); @@ -553,7 +550,7 @@ BOOST_AUTO_TEST_CASE( testErrorHandler_Handled2 )  	BOOST_REQUIRE(requestDeleteItem.output.eof());  } -BOOST_AUTO_TEST_CASE( testErrorHandler_Handled3 ) +BOOST_AUTO_TEST_CASE(testErrorHandler_Handled3)  {  	TestRequest requestDeleteItem(this, HttpMethod::DELETE, "/304");  	process(&requestDeleteItem); @@ -564,4 +561,3 @@ BOOST_AUTO_TEST_CASE( testErrorHandler_Handled3 )  }  BOOST_AUTO_TEST_SUITE_END(); - diff --git a/icespider/unittests/testCompile.cpp b/icespider/unittests/testCompile.cpp index 0135303..811de52 100644 --- a/icespider/unittests/testCompile.cpp +++ b/icespider/unittests/testCompile.cpp @@ -1,34 +1,34 @@  #define BOOST_TEST_MODULE TestCompile  #include <boost/test/unit_test.hpp> -#include <definedDirs.h> -#include <plugins.h> -#include <dlfcn.h>  #include "../compile/routeCompiler.h"  #include "../core/irouteHandler.h"  #include <boost/algorithm/string/join.hpp> +#include <definedDirs.h> +#include <dlfcn.h> +#include <plugins.h>  #include <slicer/modelPartsTypes.h>  using namespace IceSpider;  static void forceEarlyChangeDir() __attribute__((constructor(101))); -void forceEarlyChangeDir() +void +forceEarlyChangeDir()  {  	std::filesystem::current_path(XSTR(ROOT));  }  class CoreFixture { -	protected: -		CoreFixture() : -			modeDir(binDir.lexically_relative(rootDir / "bin" / "testCompile.test")) -		{ -		} -		// NOLINTNEXTLINE(misc-non-private-member-variables-in-classes) -		const std::filesystem::path modeDir; +protected: +	CoreFixture() : modeDir(binDir.lexically_relative(rootDir / "bin" / "testCompile.test")) { } +	// NOLINTNEXTLINE(misc-non-private-member-variables-in-classes) +	const std::filesystem::path modeDir;  };  namespace std { -	ostream & operator<<(ostream & s, const IceSpider::HttpMethod & m) { +	ostream & +	operator<<(ostream & s, const IceSpider::HttpMethod & m) +	{  		s << Slicer::ModelPartForEnum<IceSpider::HttpMethod>::lookup(m);  		return s;  	} @@ -36,7 +36,7 @@ namespace std {  BOOST_FIXTURE_TEST_SUITE(cf, CoreFixture) -BOOST_AUTO_TEST_CASE( testLoadConfiguration ) +BOOST_AUTO_TEST_CASE(testLoadConfiguration)  {  	Compile::RouteCompiler rc;  	rc.searchPath.push_back(rootDir); @@ -71,7 +71,7 @@ BOOST_AUTO_TEST_CASE( testLoadConfiguration )  	BOOST_REQUIRE_EQUAL("test-api.ice", cfg->slices[0]);  } -BOOST_AUTO_TEST_CASE( testRouteCompile ) +BOOST_AUTO_TEST_CASE(testRouteCompile)  {  	auto input = rootDir / "testRoutes.json";  	auto outputc = binDir / "testRoutes.cpp"; @@ -82,4 +82,3 @@ BOOST_AUTO_TEST_CASE( testRouteCompile )  }  BOOST_AUTO_TEST_SUITE_END(); - diff --git a/icespider/unittests/testFcgi.cpp b/icespider/unittests/testFcgi.cpp index d8c1b0f..789e6fa 100644 --- a/icespider/unittests/testFcgi.cpp +++ b/icespider/unittests/testFcgi.cpp @@ -1,16 +1,18 @@  #define BOOST_TEST_MODULE TestApp  #include <boost/test/unit_test.hpp> +#include <cgiRequestBase.h>  #include <core.h>  #include <definedDirs.h> -#include <cgiRequestBase.h> -#include <test-fcgi.h>  #include <slicer/modelPartsTypes.h> +#include <test-fcgi.h>  using namespace std::literals;  namespace std {  	template<typename T> -	ostream & operator<<(ostream & s, const std::optional<T> & o) { +	ostream & +	operator<<(ostream & s, const std::optional<T> & o) +	{  		if (o) {  			s << *o;  		} @@ -19,89 +21,90 @@ namespace std {  }  namespace std { -	ostream & operator<<(ostream & s, const IceSpider::HttpMethod & m) { +	ostream & +	operator<<(ostream & s, const IceSpider::HttpMethod & m) +	{  		s << Slicer::ModelPartForEnum<IceSpider::HttpMethod>::lookup(m);  		return s;  	}  } -  class TestRequest : public IceSpider::CgiRequestBase { -	public: -		TestRequest(IceSpider::Core * c, char ** env) : IceSpider::CgiRequestBase(c, env) -		{ -			initialize(); -		} +public: +	TestRequest(IceSpider::Core * c, char ** env) : IceSpider::CgiRequestBase(c, env) +	{ +		initialize(); +	} -		std::ostream & getOutputStream() const override -		{ -			return out; -		} +	std::ostream & +	getOutputStream() const override +	{ +		return out; +	} -		// LCOV_EXCL_START we never actually read or write anything here -		std::istream & getInputStream() const override -		{ -			return std::cin; -		} -		// LCOV_EXCL_STOP +	// LCOV_EXCL_START we never actually read or write anything here +	std::istream & +	getInputStream() const override +	{ +		return std::cin; +	} +	// LCOV_EXCL_STOP -		// NOLINTNEXTLINE(misc-non-private-member-variables-in-classes) -		mutable std::stringstream out; +	// NOLINTNEXTLINE(misc-non-private-member-variables-in-classes) +	mutable std::stringstream out;  };  class TestPayloadRequest : public TestRequest { -	public: -		TestPayloadRequest(IceSpider::Core * c, char ** env, std::istream & s) : -			TestRequest(c, env), -			in(s) -		{ -			initialize(); -		} +public: +	TestPayloadRequest(IceSpider::Core * c, char ** env, std::istream & s) : TestRequest(c, env), in(s) +	{ +		initialize(); +	} -		std::istream & getInputStream() const override -		{ -			return in; -		} +	std::istream & +	getInputStream() const override +	{ +		return in; +	} -	private: -		std::istream & in; +private: +	std::istream & in;  };  // NOLINTNEXTLINE(hicpp-special-member-functions)  class CharPtrPtrArray : public std::vector<char *> { -	public: -		CharPtrPtrArray() -		{ -			push_back(nullptr); -		} +public: +	CharPtrPtrArray() +	{ +		push_back(nullptr); +	} -		explicit CharPtrPtrArray(const std::vector<std::string> & a) -		{ -			for (const auto & e : a) { -				push_back(strdup(e.c_str())); -			} -			push_back(nullptr); +	explicit CharPtrPtrArray(const std::vector<std::string> & a) +	{ +		for (const auto & e : a) { +			push_back(strdup(e.c_str()));  		} +		push_back(nullptr); +	} -		~CharPtrPtrArray() -		{ -			for (const auto & e : *this) { -				// NOLINTNEXTLINE(hicpp-no-malloc) -				free(e); -			} +	~CharPtrPtrArray() +	{ +		for (const auto & e : *this) { +			// NOLINTNEXTLINE(hicpp-no-malloc) +			free(e);  		} +	} -		// NOLINTNEXTLINE(hicpp-explicit-conversions) -		operator char **() -		{ -			return &front(); -		} +	// NOLINTNEXTLINE(hicpp-explicit-conversions) +	operator char * *() +	{ +		return &front(); +	}  };  namespace std {  	// LCOV_EXCL_START assert failure helper only -	static -	std::ostream & +	static std::ostream &  	operator<<(std::ostream & s, const IceSpider::PathElements & pe)  	{  		for (const auto & e : pe) { @@ -112,73 +115,75 @@ namespace std {  	// LCOV_EXCL_STOP  } -BOOST_FIXTURE_TEST_SUITE( CgiRequestBase, IceSpider::CoreWithDefaultRouter ); +BOOST_FIXTURE_TEST_SUITE(CgiRequestBase, IceSpider::CoreWithDefaultRouter); -BOOST_AUTO_TEST_CASE( NoEnvironment ) +BOOST_AUTO_TEST_CASE(NoEnvironment)  { -	BOOST_REQUIRE_THROW({ -		CharPtrPtrArray env; -		TestRequest r(this, env); -	}, IceSpider::Http400_BadRequest); +	BOOST_REQUIRE_THROW( +			{ +				CharPtrPtrArray env; +				TestRequest r(this, env); +			}, +			IceSpider::Http400_BadRequest);  } -BOOST_AUTO_TEST_CASE( script_name_root ) +BOOST_AUTO_TEST_CASE(script_name_root)  { -	CharPtrPtrArray env ({ "SCRIPT_NAME=/" }); +	CharPtrPtrArray env({"SCRIPT_NAME=/"});  	TestRequest r(this, env);  	BOOST_REQUIRE(r.getRequestPath().empty());  	BOOST_CHECK(!r.isSecure());  } -BOOST_AUTO_TEST_CASE( script_name_root_https ) +BOOST_AUTO_TEST_CASE(script_name_root_https)  { -	CharPtrPtrArray env ({ "SCRIPT_NAME=/", "HTTPS=on" }); +	CharPtrPtrArray env({"SCRIPT_NAME=/", "HTTPS=on"});  	TestRequest r(this, env);  	BOOST_REQUIRE(r.getRequestPath().empty());  	BOOST_CHECK(r.isSecure());  } -BOOST_AUTO_TEST_CASE( redirect_uri_root ) +BOOST_AUTO_TEST_CASE(redirect_uri_root)  { -	CharPtrPtrArray env ({ "REDIRECT_URL=/" }); +	CharPtrPtrArray env({"REDIRECT_URL=/"});  	TestRequest r(this, env);  	BOOST_REQUIRE(r.getRequestPath().empty());  } -BOOST_AUTO_TEST_CASE( script_name_foobar ) +BOOST_AUTO_TEST_CASE(script_name_foobar)  { -	CharPtrPtrArray env ({ "SCRIPT_NAME=/foo/bar" }); +	CharPtrPtrArray env({"SCRIPT_NAME=/foo/bar"});  	TestRequest r(this, env);  	BOOST_REQUIRE_EQUAL(IceSpider::PathElements({"foo", "bar"}), r.getRequestPath());  } -BOOST_AUTO_TEST_CASE( query_string_empty ) +BOOST_AUTO_TEST_CASE(query_string_empty)  { -	CharPtrPtrArray env ({ "SCRIPT_NAME=/foo/bar", "QUERY_STRING=" }); +	CharPtrPtrArray env({"SCRIPT_NAME=/foo/bar", "QUERY_STRING="});  	TestRequest r(this, env);  	BOOST_REQUIRE(!r.getQueryStringParam(""));  } -BOOST_AUTO_TEST_CASE( query_string_one ) +BOOST_AUTO_TEST_CASE(query_string_one)  { -	CharPtrPtrArray env ({ "SCRIPT_NAME=/foo/bar", "QUERY_STRING=one=1" }); +	CharPtrPtrArray env({"SCRIPT_NAME=/foo/bar", "QUERY_STRING=one=1"});  	TestRequest r(this, env);  	BOOST_REQUIRE(!r.getQueryStringParam(""));  	BOOST_REQUIRE_EQUAL("1", *r.getQueryStringParam("one"));  } -BOOST_AUTO_TEST_CASE( query_string_two ) +BOOST_AUTO_TEST_CASE(query_string_two)  { -	CharPtrPtrArray env ({ "SCRIPT_NAME=/foo/bar", "QUERY_STRING=one=1&two=2" }); +	CharPtrPtrArray env({"SCRIPT_NAME=/foo/bar", "QUERY_STRING=one=1&two=2"});  	TestRequest r(this, env);  	BOOST_REQUIRE(!r.getQueryStringParam(""));  	BOOST_REQUIRE_EQUAL("1", *r.getQueryStringParam("one"));  	BOOST_REQUIRE_EQUAL("2", *r.getQueryStringParam("two"));  } -BOOST_AUTO_TEST_CASE( query_string_three ) +BOOST_AUTO_TEST_CASE(query_string_three)  { -	CharPtrPtrArray env ({ "SCRIPT_NAME=/foo/bar", "QUERY_STRING=one=1&two=2&three=3" }); +	CharPtrPtrArray env({"SCRIPT_NAME=/foo/bar", "QUERY_STRING=one=1&two=2&three=3"});  	TestRequest r(this, env);  	BOOST_REQUIRE(!r.getQueryStringParam(""));  	BOOST_REQUIRE_EQUAL("1", *r.getQueryStringParam("one")); @@ -186,18 +191,18 @@ BOOST_AUTO_TEST_CASE( query_string_three )  	BOOST_REQUIRE_EQUAL("3", *r.getQueryStringParam("three"));  } -BOOST_AUTO_TEST_CASE( query_string_urlencoding ) +BOOST_AUTO_TEST_CASE(query_string_urlencoding)  { -	CharPtrPtrArray env ({ "SCRIPT_NAME=/foo/bar", "QUERY_STRING=url+%65ncoded=%53tring%2e" }); +	CharPtrPtrArray env({"SCRIPT_NAME=/foo/bar", "QUERY_STRING=url+%65ncoded=%53tring%2e"});  	TestRequest r(this, env);  	BOOST_REQUIRE(!r.getQueryStringParam(""));  	BOOST_REQUIRE(r.getQueryStringParam("url encoded"));  	BOOST_REQUIRE_EQUAL("String.", *r.getQueryStringParam("url encoded"));  } -BOOST_AUTO_TEST_CASE( query_string_three_emptyVal ) +BOOST_AUTO_TEST_CASE(query_string_three_emptyVal)  { -	CharPtrPtrArray env ({ "SCRIPT_NAME=/foo/bar", "QUERY_STRING=one=1&two=&three=3" }); +	CharPtrPtrArray env({"SCRIPT_NAME=/foo/bar", "QUERY_STRING=one=1&two=&three=3"});  	TestRequest r(this, env);  	BOOST_REQUIRE(!r.getQueryStringParam(""));  	BOOST_REQUIRE_EQUAL("1", *r.getQueryStringParam("one")); @@ -205,9 +210,9 @@ BOOST_AUTO_TEST_CASE( query_string_three_emptyVal )  	BOOST_REQUIRE_EQUAL("3", *r.getQueryStringParam("three"));  } -BOOST_AUTO_TEST_CASE( query_string_three_noVal ) +BOOST_AUTO_TEST_CASE(query_string_three_noVal)  { -	CharPtrPtrArray env ({ "SCRIPT_NAME=/foo/bar", "QUERY_STRING=one=1&two&three=3" }); +	CharPtrPtrArray env({"SCRIPT_NAME=/foo/bar", "QUERY_STRING=one=1&two&three=3"});  	TestRequest r(this, env);  	BOOST_REQUIRE(!r.getQueryStringParam(""));  	BOOST_REQUIRE_EQUAL("1", *r.getQueryStringParam("one")); @@ -215,109 +220,112 @@ BOOST_AUTO_TEST_CASE( query_string_three_noVal )  	BOOST_REQUIRE_EQUAL("3", *r.getQueryStringParam("three"));  } -BOOST_AUTO_TEST_CASE( requestmethod_get ) +BOOST_AUTO_TEST_CASE(requestmethod_get)  { -	CharPtrPtrArray env ({ "SCRIPT_NAME=/", "REQUEST_METHOD=GET" }); +	CharPtrPtrArray env({"SCRIPT_NAME=/", "REQUEST_METHOD=GET"});  	TestRequest r(this, env);  	BOOST_REQUIRE_EQUAL(IceSpider::HttpMethod::GET, r.getRequestMethod());  } -BOOST_AUTO_TEST_CASE( requestmethod_post ) +BOOST_AUTO_TEST_CASE(requestmethod_post)  { -	CharPtrPtrArray env ({ "SCRIPT_NAME=/", "REQUEST_METHOD=POST" }); +	CharPtrPtrArray env({"SCRIPT_NAME=/", "REQUEST_METHOD=POST"});  	TestRequest r(this, env);  	BOOST_REQUIRE_EQUAL(IceSpider::HttpMethod::POST, r.getRequestMethod());  } -BOOST_AUTO_TEST_CASE( requestmethod_bad ) +BOOST_AUTO_TEST_CASE(requestmethod_bad)  { -	CharPtrPtrArray env ({ "SCRIPT_NAME=/", "REQUEST_METHOD=No" }); +	CharPtrPtrArray env({"SCRIPT_NAME=/", "REQUEST_METHOD=No"});  	TestRequest r(this, env); -	BOOST_REQUIRE_THROW(r.getRequestMethod(), IceSpider::Http405_MethodNotAllowed); +	BOOST_REQUIRE_THROW((void)r.getRequestMethod(), IceSpider::Http405_MethodNotAllowed);  } -BOOST_AUTO_TEST_CASE( requestmethod_missing ) +BOOST_AUTO_TEST_CASE(requestmethod_missing)  { -	CharPtrPtrArray env ({ "SCRIPT_NAME=/" }); +	CharPtrPtrArray env({"SCRIPT_NAME=/"});  	TestRequest r(this, env); -	BOOST_REQUIRE_THROW(r.getRequestMethod(), IceSpider::Http400_BadRequest); +	BOOST_REQUIRE_THROW((void)r.getRequestMethod(), IceSpider::Http400_BadRequest);  } -BOOST_AUTO_TEST_CASE( acceptheader ) +BOOST_AUTO_TEST_CASE(acceptheader)  { -	CharPtrPtrArray env ({ "SCRIPT_NAME=/", "HTTP_ACCEPT=text/html" }); +	CharPtrPtrArray env({"SCRIPT_NAME=/", "HTTP_ACCEPT=text/html"});  	TestRequest r(this, env);  	BOOST_REQUIRE_EQUAL("text/html", *r.getHeaderParam("ACCEPT"));  	BOOST_REQUIRE_EQUAL("text/html", *r.getHeaderParam(IceSpider::H::ACCEPT));  } -BOOST_AUTO_TEST_CASE( missingheader ) +BOOST_AUTO_TEST_CASE(missingheader)  { -	CharPtrPtrArray env ({ "SCRIPT_NAME=/", "HTTP_ACCEPT=text/html" }); +	CharPtrPtrArray env({"SCRIPT_NAME=/", "HTTP_ACCEPT=text/html"});  	TestRequest r(this, env);  	BOOST_REQUIRE(!r.getHeaderParam("ACCEPT_LANGUAGE"));  } -BOOST_AUTO_TEST_CASE( postxwwwformurlencoded_simple ) +BOOST_AUTO_TEST_CASE(postxwwwformurlencoded_simple)  { -	CharPtrPtrArray env ({ "SCRIPT_NAME=/", "REQUEST_METHOD=No", "CONTENT_TYPE=application/x-www-form-urlencoded" }); +	CharPtrPtrArray env({"SCRIPT_NAME=/", "REQUEST_METHOD=No", "CONTENT_TYPE=application/x-www-form-urlencoded"});  	std::stringstream f("value=314");  	TestPayloadRequest r(this, env, f);  	auto n = r.getBody<int>();  	BOOST_REQUIRE_EQUAL(314, n);  } -BOOST_AUTO_TEST_CASE( reqParsePerf ) +BOOST_AUTO_TEST_CASE(reqParsePerf)  { -	CharPtrPtrArray env ({ -		"CONTEXT_DOCUMENT_ROOT=/var/www/shared/vhosts/sys.randomdan.homeip.net", -		"CONTEXT_PREFIX=", -		"DOCUMENT_ROOT=/var/www/shared/vhosts/sys.randomdan.homeip.net", -		"GATEWAY_INTERFACE=CGI/1.1", -		"H2PUSH=on", -		"H2_PUSH=on", -		"H2_PUSHED=", -		"H2_PUSHED_ON=", -		"H2_STREAM_ID=1", -		"H2_STREAM_TAG=137-1", -		"HTTP2=on", -		"HTTPS=on", -		"HTTP_ACCEPT=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3", -		"HTTP_ACCEPT_ENCODING=gzip, deflate, br", -		"HTTP_ACCEPT_LANGUAGE=en,en-GB;q=0.9", -		"HTTP_HOST=sys.randomdan.homeip.net", -		"HTTP_SEC_FETCH_SITE=none", -		"HTTP_UPGRADE_INSECURE_REQUESTS=1", -		"HTTP_USER_AGENT=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36", -		"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", -		"PWD=/var/www/shared/files/localhost", -		"QUERY_STRING=", -		"REMOTE_ADDR=10.10.0.189", -		"REMOTE_PORT=44030", -		"REQUEST_METHOD=GET", -		"REQUEST_SCHEME=https", -		"REQUEST_URI=/env.cgi", -		"SCRIPT_FILENAME=/var/www/shared/vhosts/sys.randomdan.homeip.net/env.cgi", -		"SCRIPT_NAME=/env.cgi", -		"SERVER_ADDR=fdc7:602:e9c5:b8f0::3", -		"SERVER_ADMIN=dan.goodliffe@randomdan.homeip.net", -		"SERVER_NAME=sys.randomdan.homeip.net", -		"SERVER_PORT=443", -		"SERVER_PROTOCOL=HTTP/2.0", -		"SERVER_SIGNATURE=<address>Apache/2.4.41 (Gentoo) mod_fcgid/2.3.9 PHP/7.2.23 OpenSSL/1.1.1d mod_perl/2.0.10 Perl/v5.30.0 Server at sys.randomdan.homeip.net Port 443</address>", -		"SERVER_SOFTWARE=Apache/2.4.41 (Gentoo) mod_fcgid/2.3.9 PHP/7.2.23 OpenSSL/1.1.1d mod_perl/2.0.10 Perl/v5.30.0", -		"SHLVL=0", -		"SSL_TLS_SNI=sys.randomdan.homeip.net", +	CharPtrPtrArray env({ +			"CONTEXT_DOCUMENT_ROOT=/var/www/shared/vhosts/sys.randomdan.homeip.net", +			"CONTEXT_PREFIX=", +			"DOCUMENT_ROOT=/var/www/shared/vhosts/sys.randomdan.homeip.net", +			"GATEWAY_INTERFACE=CGI/1.1", +			"H2PUSH=on", +			"H2_PUSH=on", +			"H2_PUSHED=", +			"H2_PUSHED_ON=", +			"H2_STREAM_ID=1", +			"H2_STREAM_TAG=137-1", +			"HTTP2=on", +			"HTTPS=on", +			("HTTP_ACCEPT=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/" +			 "*;q=0.8,application/signed-exchange;v=b3"), +			"HTTP_ACCEPT_ENCODING=gzip, deflate, br", +			"HTTP_ACCEPT_LANGUAGE=en,en-GB;q=0.9", +			"HTTP_HOST=sys.randomdan.homeip.net", +			"HTTP_SEC_FETCH_SITE=none", +			"HTTP_UPGRADE_INSECURE_REQUESTS=1", +			("HTTP_USER_AGENT=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " +			 "Chrome/77.0.3865.90 Safari/537.36"), +			"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", +			"PWD=/var/www/shared/files/localhost", +			"QUERY_STRING=", +			"REMOTE_ADDR=10.10.0.189", +			"REMOTE_PORT=44030", +			"REQUEST_METHOD=GET", +			"REQUEST_SCHEME=https", +			"REQUEST_URI=/env.cgi", +			"SCRIPT_FILENAME=/var/www/shared/vhosts/sys.randomdan.homeip.net/env.cgi", +			"SCRIPT_NAME=/env.cgi", +			"SERVER_ADDR=fdc7:602:e9c5:b8f0::3", +			"SERVER_ADMIN=dan.goodliffe@randomdan.homeip.net", +			"SERVER_NAME=sys.randomdan.homeip.net", +			"SERVER_PORT=443", +			"SERVER_PROTOCOL=HTTP/2.0", +			("SERVER_SIGNATURE=<address>Apache/2.4.41 (Gentoo) mod_fcgid/2.3.9 PHP/7.2.23 OpenSSL/1.1.1d " +			 "mod_perl/2.0.10 Perl/v5.30.0 Server at sys.randomdan.homeip.net Port 443</address>"), +			("SERVER_SOFTWARE=Apache/2.4.41 (Gentoo) mod_fcgid/2.3.9 PHP/7.2.23 OpenSSL/1.1.1d mod_perl/2.0.10 " +			 "Perl/v5.30.0"), +			"SHLVL=0", +			"SSL_TLS_SNI=sys.randomdan.homeip.net",  	}); -	for (int x = 0; x < 10000; x +=1) { +	for (int x = 0; x < 10000; x += 1) {  		TestRequest req(this, env);  	}  } - -BOOST_AUTO_TEST_CASE( postxwwwformurlencoded_dictionary ) +BOOST_AUTO_TEST_CASE(postxwwwformurlencoded_dictionary)  { -	CharPtrPtrArray env ({ "SCRIPT_NAME=/", "REQUEST_METHOD=No", "CONTENT_TYPE=application/x-www-form-urlencoded" }); +	CharPtrPtrArray env({"SCRIPT_NAME=/", "REQUEST_METHOD=No", "CONTENT_TYPE=application/x-www-form-urlencoded"});  	std::stringstream f("alpha=abcde&number=3.14&boolean=true&spaces=This+is+a%20string.&empty=");  	TestPayloadRequest r(this, env, f);  	auto n = *r.getBody<IceSpider::StringMap>(); @@ -329,9 +337,9 @@ BOOST_AUTO_TEST_CASE( postxwwwformurlencoded_dictionary )  	BOOST_REQUIRE_EQUAL("", n["empty"]);  } -BOOST_AUTO_TEST_CASE( postxwwwformurlencoded_complex ) +BOOST_AUTO_TEST_CASE(postxwwwformurlencoded_complex)  { -	CharPtrPtrArray env ({ "SCRIPT_NAME=/", "REQUEST_METHOD=No", "CONTENT_TYPE=application/x-www-form-urlencoded" }); +	CharPtrPtrArray env({"SCRIPT_NAME=/", "REQUEST_METHOD=No", "CONTENT_TYPE=application/x-www-form-urlencoded"});  	std::stringstream f("alpha=abcde&number=3.14&boolean=true&empty=&spaces=This+is+a%20string.");  	TestPayloadRequest r(this, env, f);  	auto n = *r.getBody<TestFcgi::ComplexPtr>(); @@ -342,9 +350,9 @@ BOOST_AUTO_TEST_CASE( postxwwwformurlencoded_complex )  	BOOST_REQUIRE_EQUAL("", n->empty);  } -BOOST_AUTO_TEST_CASE( postjson_complex ) +BOOST_AUTO_TEST_CASE(postjson_complex)  { -	CharPtrPtrArray env ({ "SCRIPT_NAME=/", "REQUEST_METHOD=No", "CONTENT_TYPE=application/json" }); +	CharPtrPtrArray env({"SCRIPT_NAME=/", "REQUEST_METHOD=No", "CONTENT_TYPE=application/json"});  	std::stringstream f(R"J({"alpha":"abcde","number":3.14,"boolean":true,"empty":"","spaces":"This is a string."})J");  	TestPayloadRequest r(this, env, f);  	auto n = *r.getBody<TestFcgi::ComplexPtr>(); @@ -355,10 +363,11 @@ BOOST_AUTO_TEST_CASE( postjson_complex )  	BOOST_REQUIRE_EQUAL("", n->empty);  } -BOOST_AUTO_TEST_CASE( postjson_dictionary ) +BOOST_AUTO_TEST_CASE(postjson_dictionary)  { -	CharPtrPtrArray env ({ "SCRIPT_NAME=/", "REQUEST_METHOD=No", "CONTENT_TYPE=application/json" }); -	std::stringstream f(R"J({"alpha":"abcde","number":"3.14","boolean":"true","empty":"","spaces":"This is a string."})J"); +	CharPtrPtrArray env({"SCRIPT_NAME=/", "REQUEST_METHOD=No", "CONTENT_TYPE=application/json"}); +	std::stringstream f( +			R"J({"alpha":"abcde","number":"3.14","boolean":"true","empty":"","spaces":"This is a string."})J");  	TestPayloadRequest r(this, env, f);  	auto n = *r.getBody<IceSpider::StringMap>();  	BOOST_REQUIRE_EQUAL(5, n.size()); @@ -369,24 +378,26 @@ BOOST_AUTO_TEST_CASE( postjson_dictionary )  	BOOST_REQUIRE_EQUAL("", n["empty"]);  } -BOOST_AUTO_TEST_CASE( cookies ) +BOOST_AUTO_TEST_CASE(cookies)  { -	CharPtrPtrArray env ({ "SCRIPT_NAME=/", "REQUEST_METHOD=No", "CONTENT_TYPE=application/json", "HTTP_COOKIE=valueA=1234; value+B=Something+with+spaces." }); +	CharPtrPtrArray env({"SCRIPT_NAME=/", "REQUEST_METHOD=No", "CONTENT_TYPE=application/json", +			"HTTP_COOKIE=valueA=1234; value+B=Something+with+spaces."});  	TestRequest r(this, env);  	BOOST_REQUIRE_EQUAL(1234, *r.IceSpider::IHttpRequest::getCookieParam<Ice::Int>("valueA"));  	BOOST_REQUIRE_EQUAL("Something with spaces.", *r.IceSpider::IHttpRequest::getCookieParam<std::string>("value B"));  	BOOST_REQUIRE(!r.IceSpider::IHttpRequest::getCookieParam<Ice::Int>("notAThing"));  	r.setCookie("some int.", 1234, "www.com"s, "/dir"s, true, 1476142378); -	BOOST_REQUIRE_EQUAL("Set-Cookie: some+int%2e=1234; expires=Mon, 10 Oct 2016 23:32:58 GMT; domain=www.com; path=/dir; secure; samesite=strict\r\n", r.out.str()); +	BOOST_REQUIRE_EQUAL("Set-Cookie: some+int%2e=1234; expires=Mon, 10 Oct 2016 23:32:58 GMT; domain=www.com; " +						"path=/dir; secure; samesite=strict\r\n", +			r.out.str());  } -BOOST_AUTO_TEST_CASE( response ) +BOOST_AUTO_TEST_CASE(response)  { -	CharPtrPtrArray env ({ "SCRIPT_NAME=/" }); +	CharPtrPtrArray env({"SCRIPT_NAME=/"});  	TestRequest r(this, env);  	r.response(200, "OK");  	BOOST_REQUIRE_EQUAL("Status: 200 OK\r\n\r\n", r.out.str());  }  BOOST_AUTO_TEST_SUITE_END(); - diff --git a/icespider/unittests/testFileSessions.cpp b/icespider/unittests/testFileSessions.cpp index 1ab75f7..3712d03 100644 --- a/icespider/unittests/testFileSessions.cpp +++ b/icespider/unittests/testFileSessions.cpp @@ -3,28 +3,26 @@  #include <Ice/Initialize.h>  #include <Ice/Properties.h> -#include <session.h>  #include <core.h>  #include <definedDirs.h> +#include <session.h>  BOOST_TEST_DONT_PRINT_LOG_VALUE(IceSpider::Variables);  class TestCore : public IceSpider::CoreWithDefaultRouter { -	public: -		TestCore() : -			IceSpider::CoreWithDefaultRouter({ -				"--IceSpider.SessionManager=IceSpider-FileSessions", +public: +	TestCore() : +		IceSpider::CoreWithDefaultRouter({"--IceSpider.SessionManager=IceSpider-FileSessions",  				"--IceSpider.FileSessions.Path=" + (binDir / "test-sessions").string(), -				"--IceSpider.FileSessions.Duration=0" -			}), -			root(communicator->getProperties()->getProperty("IceSpider.FileSessions.Path")) -		{ -		} -		// NOLINTNEXTLINE(misc-non-private-member-variables-in-classes) -		const std::filesystem::path root; +				"--IceSpider.FileSessions.Duration=0"}), +		root(communicator->getProperties()->getProperty("IceSpider.FileSessions.Path")) +	{ +	} +	// NOLINTNEXTLINE(misc-non-private-member-variables-in-classes) +	const std::filesystem::path root;  }; -BOOST_AUTO_TEST_CASE( clear ) +BOOST_AUTO_TEST_CASE(clear)  {  	TestCore tc;  	if (std::filesystem::exists(tc.root)) { @@ -34,14 +32,14 @@ BOOST_AUTO_TEST_CASE( clear )  BOOST_FIXTURE_TEST_SUITE(Core, TestCore); -BOOST_AUTO_TEST_CASE( ping ) +BOOST_AUTO_TEST_CASE(ping)  {  	auto prx = this->getProxy<IceSpider::SessionManager>();  	BOOST_REQUIRE(prx);  	prx->ice_ping();  } -BOOST_AUTO_TEST_CASE( createAndDestroy ) +BOOST_AUTO_TEST_CASE(createAndDestroy)  {  	auto prx = this->getProxy<IceSpider::SessionManager>();  	auto s = prx->createSession(); @@ -52,7 +50,7 @@ BOOST_AUTO_TEST_CASE( createAndDestroy )  	BOOST_REQUIRE(!std::filesystem::exists(root / s->id));  } -BOOST_AUTO_TEST_CASE( createAndChangeRestore ) +BOOST_AUTO_TEST_CASE(createAndChangeRestore)  {  	auto prx = this->getProxy<IceSpider::SessionManager>();  	auto s = prx->createSession(); @@ -66,7 +64,7 @@ BOOST_AUTO_TEST_CASE( createAndChangeRestore )  	prx->destroySession(s->id);  } -BOOST_AUTO_TEST_CASE( createAndExpire ) +BOOST_AUTO_TEST_CASE(createAndExpire)  {  	auto prx = this->getProxy<IceSpider::SessionManager>();  	auto s = prx->createSession(); @@ -79,35 +77,34 @@ BOOST_AUTO_TEST_CASE( createAndExpire )  	BOOST_REQUIRE(!std::filesystem::exists(root / s->id));  } -BOOST_AUTO_TEST_CASE( missing ) +BOOST_AUTO_TEST_CASE(missing)  {  	auto prx = this->getProxy<IceSpider::SessionManager>();  	BOOST_REQUIRE(!prx->getSession("missing"));  	BOOST_REQUIRE(!std::filesystem::exists(root / "missing"));  } -BOOST_AUTO_TEST_CASE( createAndLeave ) +BOOST_AUTO_TEST_CASE(createAndLeave)  {  	auto prx = this->getProxy<IceSpider::SessionManager>();  	auto s = prx->createSession();  	BOOST_REQUIRE(std::filesystem::exists(root / s->id));  } -BOOST_AUTO_TEST_CASE( left ) +BOOST_AUTO_TEST_CASE(left)  {  	BOOST_REQUIRE(!std::filesystem::is_empty(root));  } -BOOST_AUTO_TEST_CASE( expire ) +BOOST_AUTO_TEST_CASE(expire)  {  	usleep(1001000);  }  BOOST_AUTO_TEST_SUITE_END(); -BOOST_AUTO_TEST_CASE( empty ) +BOOST_AUTO_TEST_CASE(empty)  {  	TestCore tc;  	BOOST_REQUIRE(std::filesystem::is_empty(tc.root));  } - diff --git a/icespider/xslt/exslt.cpp b/icespider/xslt/exslt.cpp index 772ef5e..186c77a 100644 --- a/icespider/xslt/exslt.cpp +++ b/icespider/xslt/exslt.cpp @@ -2,7 +2,8 @@  #include <libxslt/transform.h>  static void initLibXml() __attribute__((constructor(102))); -void initLibXml() +void +initLibXml()  {  	xmlInitParser();  	exsltRegisterAll(); @@ -10,10 +11,10 @@ void initLibXml()  // LCOV_EXCL_START lcov actually misses destructor functions  static void cleanupLibXml() __attribute__((destructor(102))); -void cleanupLibXml() +void +cleanupLibXml()  {  	xsltCleanupGlobals();  	xmlCleanupParser();  }  // LCOV_EXCL_STOP - diff --git a/icespider/xslt/xsltStreamSerializer.cpp b/icespider/xslt/xsltStreamSerializer.cpp index d798835..b6dc44c 100644 --- a/icespider/xslt/xsltStreamSerializer.cpp +++ b/icespider/xslt/xsltStreamSerializer.cpp @@ -1,26 +1,26 @@  #include "xsltStreamSerializer.h" -#include <libxslt/xsltInternals.h> -#include <libxml/HTMLtree.h>  #include <factory.impl.h>  #include <filesystem> +#include <libxml/HTMLtree.h> +#include <libxslt/xsltInternals.h>  namespace IceSpider { -	static int xmlstrmclosecallback(void * context) +	static int +	xmlstrmclosecallback(void * context)  	{ -		((std::ostream*)context)->flush(); +		((std::ostream *)context)->flush();  		return 0;  	} -	static int xmlstrmwritecallback(void * context, const char * buffer, int len) +	static int +	xmlstrmwritecallback(void * context, const char * buffer, int len)  	{ -		((std::ostream*)context)->write(buffer, len); +		((std::ostream *)context)->write(buffer, len);  		return len;  	}  	XsltStreamSerializer::IceSpiderFactory::IceSpiderFactory(const char * path) : -		stylesheetPath(path), -		stylesheetWriteTime(std::filesystem::file_time_type::min()), -		stylesheet(nullptr) +		stylesheetPath(path), stylesheetWriteTime(std::filesystem::file_time_type::min()), stylesheet(nullptr)  	{  	} @@ -47,10 +47,7 @@ namespace IceSpider {  	}  	XsltStreamSerializer::XsltStreamSerializer(std::ostream & os, xsltStylesheet * ss) : -		Slicer::XmlDocumentSerializer(doc), -		strm(os), -		doc(nullptr), -		stylesheet(ss) +		Slicer::XmlDocumentSerializer(doc), strm(os), doc(nullptr), stylesheet(ss)  	{  	} @@ -69,13 +66,12 @@ namespace IceSpider {  		}  		xmlOutputBufferPtr buf = xmlOutputBufferCreateIO(xmlstrmwritecallback, xmlstrmclosecallback, &strm, nullptr);  		if (xmlStrcmp(stylesheet->method, BAD_CAST "html") == 0) { -			htmlDocContentDumpFormatOutput(buf, result, (const char *) stylesheet->encoding, 0); +			htmlDocContentDumpFormatOutput(buf, result, (const char *)stylesheet->encoding, 0);  		}  		else { -			xmlNodeDumpOutput(buf, result, result->children, 0, 0, (const char *) stylesheet->encoding); +			xmlNodeDumpOutput(buf, result, result->children, 0, 0, (const char *)stylesheet->encoding);  		}  		xmlOutputBufferClose(buf);  		xmlFreeDoc(result);  	}  } - diff --git a/icespider/xslt/xsltStreamSerializer.h b/icespider/xslt/xsltStreamSerializer.h index dae6ac3..a21f424 100644 --- a/icespider/xslt/xsltStreamSerializer.h +++ b/icespider/xslt/xsltStreamSerializer.h @@ -1,38 +1,40 @@  #ifndef ICESPIDER_CORE_XSLTSTREAMSERIALIZER_H  #define ICESPIDER_CORE_XSLTSTREAMSERIALIZER_H +#include <c++11Helpers.h> +#include <filesystem> +#include <libxslt/transform.h>  #include <slicer/xml/serializer.h>  #include <visibility.h> -#include <libxslt/transform.h> -#include <filesystem>  namespace IceSpider {  	class DLL_PUBLIC XsltStreamSerializer : public Slicer::XmlDocumentSerializer { +	public: +		class IceSpiderFactory : public Slicer::StreamSerializerFactory {  		public: -			class IceSpiderFactory : public Slicer::StreamSerializerFactory { -				public: -					IceSpiderFactory(const char *); -					~IceSpiderFactory(); +			explicit IceSpiderFactory(const char *); +			SPECIAL_MEMBERS_MOVE_RO(IceSpiderFactory); +			~IceSpiderFactory() override; -					Slicer::SerializerPtr create(std::ostream &) const override; +			Slicer::SerializerPtr create(std::ostream &) const override; -				private: -					const std::filesystem::path stylesheetPath; -					mutable std::filesystem::file_time_type stylesheetWriteTime; -					mutable xsltStylesheet * stylesheet; -			}; +		private: +			const std::filesystem::path stylesheetPath; +			mutable std::filesystem::file_time_type stylesheetWriteTime; +			mutable xsltStylesheet * stylesheet; +		}; -			XsltStreamSerializer(std::ostream &, xsltStylesheet *); -			~XsltStreamSerializer(); +		XsltStreamSerializer(std::ostream &, xsltStylesheet *); +		SPECIAL_MEMBERS_DELETE(XsltStreamSerializer); +		~XsltStreamSerializer() override; -			void Serialize(Slicer::ModelPartForRootPtr mp) override; +		void Serialize(Slicer::ModelPartForRootPtr mp) override; -		protected: -			std::ostream & strm; -			xmlpp::Document * doc; -			xsltStylesheet * stylesheet; +	protected: +		std::ostream & strm; +		xmlpp::Document * doc; +		xsltStylesheet * stylesheet;  	};  }  #endif - | 
