Skip to content

Modules

CLI tool for auto-generating Google Mock test code from C++ header files.

This module provides a command-line interface for automatically generating Google Mock test code from C++ headers.

GMockClassModel

Represents a Google Mock class model.

Attributes:

Name Type Description
classname str

Class name

parent_class Optional[GMockClassModel]

Parent class (if any)

namespace str

Namespace

mock_methods list[GMockMethod]

List of mock methods

Source code in src/autogtest/cli.py
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
class GMockClassModel:
    """Represents a Google Mock class model.

    Attributes:
        classname: Class name
        parent_class: Parent class (if any)
        namespace: Namespace
        mock_methods: List of mock methods
    """

    def __init__(self, classname: str, namespace: str) -> None:
        self.classname: str = classname
        self.parent_class: Optional[GMockClassModel] = None
        self.namespace: str = namespace
        self.mock_methods: list[GMockMethod] = []

    def getClassname(self) -> str:
        if self.parent_class:
            return self.parent_class.getClassname() + "::" + self.classname
        return self.classname

    def getMockClassname(self) -> str:
        mock_classname_parts: list[str] = self.getClassname().split("::")
        mock_classname_parts[-1] = mock_classname_parts[-1].removeprefix("I")
        mock_classname_parts[-1] = mock_classname_parts[-1].removesuffix("Interface")
        mock_classname: str = "::".join(mock_classname_parts)
        mock_classname += "Mock"
        return mock_classname

    def tryAddGMockMethod(self, method_scope: Method) -> bool:
        if not method_scope.pure_virtual:
            return False
        mock_method = GMockMethod(method_scope.name.format())
        for param in method_scope.parameters:
            mock_method.params.append(param.format())
        if method_scope.return_type is None:
            mock_method.ret = "void"
        else:
            mock_method.ret = method_scope.return_type.format()
        if method_scope.const:
            mock_method.qualifier.append("const")
        if method_scope.constexpr:
            mock_method.qualifier.append("constexpr")
        if method_scope.noexcept:
            mock_method.qualifier.append("noexcept")
        if method_scope.ref_qualifier:
            mock_method.qualifier.append("&&")
        self.mock_methods.append(mock_method)
        return True

    def json(self) -> dict:
        return {
            "namespace": self.namespace,
            "name": self.getMockClassname(),
            "interface": self.getClassname(),
            "methods": [method.format() for method in self.mock_methods],
        }

    def format(self) -> str:
        methods_section = "\n    ".join([method.format() for method in self.mock_methods])
        return f"""namespace {self.namespace} {{

class {self.getMockClassname()}Mock: public {self.getClassname()} {{
public:
    {methods_section}
}};

}} // namespace {self.namespace}
"""

GMockMethod

Represents a Google Mock method model.

Attributes:

Name Type Description
name

Method name

qualifier list[str]

Method qualifiers (e.g. override, const)

params list[str]

Method parameters

ret str

Return type

Source code in src/autogtest/cli.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class GMockMethod:
    """Represents a Google Mock method model.

    Attributes:
        name: Method name
        qualifier: Method qualifiers (e.g. override, const)
        params: Method parameters
        ret: Return type
    """

    def __init__(self, name: str) -> None:
        self.name = name
        self.qualifier: list[str] = ["override"]
        self.params: list[str] = []
        self.ret: str = ""

    def format(self) -> str:
        params_str = ", ".join(self.params)
        qualifier_str = " ".join(self.qualifier)
        return f"MOCK_METHOD({self.ret}, {self.name}, ({params_str}), ({qualifier_str}));"

MockGenerator

Generates Google Mock class models from parsed C++ header data.

Attributes:

Name Type Description
data ParsedData

Parsed C++ header data

namespace list[str]

Current namespace stack

classes list[GMockClassModel]

Generated mock classes

Source code in src/autogtest/cli.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
class MockGenerator:
    """Generates Google Mock class models from parsed C++ header data.

    Attributes:
        data: Parsed C++ header data
        namespace: Current namespace stack
        classes: Generated mock classes
    """

    def __init__(self, data: ParsedData) -> None:
        self.data: ParsedData = data
        self.namespace: list[str] = []
        self.classes: list[GMockClassModel] = []

    def parse(self) -> None:
        self.visitNamespaceScope(self.data.namespace)

    def visitNamespaceScope(self, namespace_scope: NamespaceScope) -> None:
        self.namespace.append(namespace_scope.name)
        for class_scope in namespace_scope.classes:
            self.visitClassScope(class_scope=class_scope, parent_class=None)

        for _child_namespace_name, child_namespace_scope in namespace_scope.namespaces.items():
            self.visitNamespaceScope(namespace_scope=child_namespace_scope)
        self.namespace.pop()

    def visitClassScope(self, class_scope: ClassScope, parent_class: Optional[GMockClassModel]) -> None:
        mock_class = self.tryAddMockClassModel(class_scope=class_scope, parent_class=parent_class)
        for child_class_scope in class_scope.classes:
            self.visitClassScope(class_scope=child_class_scope, parent_class=mock_class)

    def isTargetClass(self, class_scope: ClassScope) -> bool:
        return any(method.pure_virtual for method in class_scope.methods)

    def tryAddMockClassModel(
        self, class_scope: ClassScope, parent_class: Optional[GMockClassModel] = None
    ) -> GMockClassModel:
        mock_class = GMockClassModel(
            classname=self.classname(class_scope=class_scope), namespace=self.currentNamespace()
        )
        mock_class.parent_class = parent_class
        [mock_class.tryAddGMockMethod(method) for method in class_scope.methods]
        if self.isTargetClass(class_scope=class_scope):
            self.classes.append(mock_class)
        return mock_class

    def classname(self, class_scope: ClassScope) -> str:
        return class_scope.class_decl.typename.format().replace("class ", "").replace("struct ", "")

    def currentNamespace(self) -> str:
        return "::".join(self.namespace).removeprefix("::")

create_gmock_file(header, output, include, template)

Generate mock file from a single header.

Parameters:

Name Type Description Default
header str

Input header path

required
output str

Output mock file path

required
include str

Include base directory

required
template Template

Jinja2 template to use

required

Returns:

Name Type Description
bool bool

True if mock file was generated successfully

Source code in src/autogtest/cli.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
def create_gmock_file(header: str, output: str, include: str, template: Template) -> bool:
    """Generate mock file from a single header.

    Args:
        header: Input header path
        output: Output mock file path
        include: Include base directory
        template: Jinja2 template to use

    Returns:
        bool: True if mock file was generated successfully
    """
    if not header.endswith(".h") and not header.endswith(".hpp"):
        return False
    generator = MockGenerator(data=parse_file(filename=header))
    generator.parse()
    if len(generator.classes) == 0:
        return False
    json_mock_classes = [mock_class.json() for mock_class in generator.classes]

    context = template.render({"gmock_data": json_mock_classes, "header": os.path.relpath(header, include)})
    write_file_if_not_exist(filepath=output, content=context)
    return True

create_gmock_files_batch(header_dir, mock_dir, include, template)

Batch generate mock files from directory headers.

Parameters:

Name Type Description Default
header_dir str

Input header directory

required
mock_dir str

Output mock directory

required
include str

Include base directory

required
template Template

Jinja2 template

required
Source code in src/autogtest/cli.py
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
def create_gmock_files_batch(header_dir: str, mock_dir: str, include: str, template: Template) -> None:
    """Batch generate mock files from directory headers.

    Args:
        header_dir: Input header directory
        mock_dir: Output mock directory
        include: Include base directory
        template: Jinja2 template
    """
    for root, _, files in os.walk(header_dir):
        for file in files:
            if file.endswith(".h") or file.endswith(".hpp"):
                header = os.path.join(root, file)
                header_relative_path = os.path.relpath(header, header_dir)
                mock_relative_path = header_relative_path.replace(".h", "_mock.h").replace(".hpp", "_mock.hpp")
                mock = os.path.join(mock_dir, mock_relative_path)
                create_gmock_file(header=header, output=mock, include=include, template=template)

gmock(header, mock, include, template=None)

Generate Google Mock code from C++ headers.

Parameters:

Name Type Description Default
header Annotated[str, Argument(help='Directory or C++ header file containing the header files')]

Input header/directory

required
mock Annotated[str, Option(help='Output path for mock files')]

Output mock file/directory

required
include Annotated[str, Option(help='Base include directory')]

Base include directory

required
template Annotated[Optional[str], Option(help='Path to custom Jinja2 template')]

Optional custom template path

None
Source code in src/autogtest/cli.py
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
@app.command()
def gmock(
    header: Annotated[str, typer.Argument(help="Directory or C++ header file containing the header files")],
    mock: Annotated[str, typer.Option(help="Output path for mock files")],
    include: Annotated[str, typer.Option(help="Base include directory")],
    template: Annotated[Optional[str], typer.Option(help="Path to custom Jinja2 template")] = None,
) -> None:
    """Generate Google Mock code from C++ headers.

    Args:
        header: Input header/directory
        mock: Output mock file/directory
        include: Base include directory
        template: Optional custom template path
    """
    header = os.path.abspath(header)
    mock = os.path.abspath(mock)
    include = os.path.abspath(include)

    print(
        f"auto gmock, header: {header}, mock: {mock}, template: {template if template else 'None'}, include: {include}"
    )
    if template:
        template = os.path.abspath(template)
        env = Environment(loader=FileSystemLoader(os.path.dirname(template)), autoescape=True)
        jinja2_template: Template = env.get_template(os.path.basename(template))
    else:
        env = Environment(loader=BaseLoader(), autoescape=True)
        jinja2_template = env.from_string(jinja2_default_template)

    if os.path.isdir(header):
        create_gmock_files_batch(header_dir=header, mock_dir=mock, include=include, template=jinja2_template)
    else:
        create_gmock_file(header=header, output=mock, include=include, template=jinja2_template)

write_file_if_not_exist(filepath, content)

Write content to file if it doesn't exist.

Parameters:

Name Type Description Default
filepath str

Path to file

required
content str

Content to write

required
Source code in src/autogtest/cli.py
183
184
185
186
187
188
189
190
191
192
193
194
195
def write_file_if_not_exist(filepath: str, content: str) -> None:
    """Write content to file if it doesn't exist.

    Args:
        filepath: Path to file
        content: Content to write
    """
    directory = os.path.dirname(filepath)
    if not os.path.exists(directory):
        os.makedirs(directory)
    if not os.path.exists(filepath):
        with open(filepath, "w") as file:
            file.write(content)