测试两个类型列表中的所有组合

Test all the combinations out of two type lists

本文关键字:组合 列表 类型 两个 测试      更新时间:2023-10-16

我正在使用Google测试框架,并且有两个类型列表,我需要运行相同的测试套件。我使用的是宏TYPED_TEST_CASE但这里的问题是它被迫只与一个类型列表一起使用,而不是两个或更多。

我需要使用这两个类型列表之间的所有组合运行此测试套件。有可能做到吗?如果TYPED_TEST_CASE宏只接受一个类型列表,是否可以生成包含之前所有组合的列表,将它们插入到列表中,然后使用仅一个列表的宏?

你去吧。它一如既往地需要一些元魔法。为了使它顺利适应GTest,我使用了::testing::Types,现在您只需将cartesian_product作为类型参数传递即可进行测试。 编辑:由于::testing::Types不是真正的可变参数,我不得不做一些帮助和转换:

template<class... Args>
struct Types { };
template<class First, class Second>
struct type_pair {
using first = First;
using second = Second;
};
template<class TypeList, template <class> class Mapper>
struct meta_map {
using type = void;
};
template<template <class> class Mapper, class... Args>
struct meta_map<Types<Args...>, Mapper> {
using type = Types<Mapper<Args>...>;
};
template<class Arg, class TypeList>
struct create_pairs {
template<class T>
using make_pair = type_pair<T, Arg>;
using type = typename meta_map<TypeList, make_pair>::type;
};
template<class List, class... Lists>
struct sum {
using type = void;
};
template<class... Ts>
struct sum<Types<Ts...>> {
using type = Types<Ts...>;
};
template<class... T1, class... T2>
struct sum<Types<T1...>, Types<T2...>> {
using type = typename sum<Types<T1..., T2...>>::type;
};
template<class... T1, class... T2>
struct sum<Types<T1...>, T2...> {
using type = typename sum<Types<T1...>, typename sum<T2...>::type>::type;
};

template<class List, template <class...> class Reducer>
struct meta_reduce {
using type = void;
};
template<class... Args, template <class...> class Reducer>
struct meta_reduce<Types<Args...>, Reducer> {
using type = typename Reducer<Args...>::type;
};
template<class TypeList1, class TypeList2>
struct cartesian_product_helper {
using type = void;
};
template<class TypeList1, class... Args>
struct cartesian_product_helper<TypeList1, Types<Args...>> {
using type = typename meta_reduce<Types<typename create_pairs<Args, TypeList1>::type...>, sum>::type;
};
template<class List1, class List2>
using cartesian_product = typename cartesian_product_helper<List1, List2>::type;
template<class TypeList>
struct to_test_types {
using type = void;
};
template<class... Ts>
struct to_test_types<Types<Ts...>> {
using type = ::testing::Types<Ts...>;
};
template<class TypeList>
using to_test_types_t = typename to_test_types<TypeList>::type;

用法如下所示:

to_test_types_t<cartesian_product<
Types<char, bool, unsigned>,
Types<char, bool>
>>;

现场示例: https://godbolt.org/z/XmyHDT

编辑:在Godbolt上添加了gtest,它似乎可以与此代码正常工作