KiCad PCB EDA Suite
Loading...
Searching...
No Matches
test_text_eval_parser_vcs.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright The KiCad Developers, see AUTHORS.TXT for contributors.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
27
32#include <pgm_base.h>
34
35#include <chrono>
36#include <fstream>
37#include <regex>
38
39#include <wx/dir.h>
40#include <wx/filename.h>
41#include <wx/utils.h>
42
43
44static const char* TEST_AUTHOR_NAME = "Test Author";
46static const char* TEST_COMMIT_MSG = "Initial test commit";
47
48
54{
56 {
59 KI_TEST::WriteGitFile( TempPath(), "test.txt", "test content\n" );
60 KI_TEST::CommitGitFile( repo.get(), "test.txt", TEST_COMMIT_MSG );
61 BOOST_REQUIRE( wxSetWorkingDirectory( TempPath() ) );
62 }
63
64 const wxString& tempDir() const { return TempPath(); }
65
66private:
67 // These tests exercise cwd-based discovery independently of projects loaded by other tests.
69};
70
71
72BOOST_FIXTURE_TEST_SUITE( TextEvalParserVcs, VCS_TEST_FIXTURE )
73
74
77BOOST_AUTO_TEST_CASE( VcsIdentifierFormatting )
78{
79 EXPRESSION_EVALUATOR evaluator;
80
81 struct TestCase
82 {
83 std::string expression;
84 int expectedLength;
85 };
86
87 const std::vector<TestCase> cases = {
88 { "@{vcsidentifier()}", 40 },
89 { "@{vcsidentifier(40)}", 40 },
90 { "@{vcsidentifier(7)}", 7 },
91 { "@{vcsidentifier(8)}", 8 },
92 { "@{vcsidentifier(12)}", 12 },
93 { "@{vcsidentifier(4)}", 4 },
94
95 { "@{vcsfileidentifier(\".\")}", 40 },
96 { "@{vcsfileidentifier(\".\", 8)}", 8 },
97 };
98
99 std::regex hexPattern( "^[0-9a-f]+$" );
100
101 for( const auto& testCase : cases )
102 {
103 auto result = evaluator.Evaluate( wxString::FromUTF8( testCase.expression ) );
104
105 BOOST_CHECK_MESSAGE( !evaluator.HasErrors(),
106 "Error in expression: " + testCase.expression + " Errors: "
107 + evaluator.GetErrorSummary().ToStdString() );
108
109 BOOST_CHECK_EQUAL( result.Length(), testCase.expectedLength );
110 BOOST_CHECK( std::regex_match( result.ToStdString(), hexPattern ) );
111 }
112}
113
117BOOST_AUTO_TEST_CASE( VcsBranchAndAuthorInfo )
118{
119 EXPRESSION_EVALUATOR evaluator;
120
121 auto branch = evaluator.Evaluate( "@{vcsbranch()}" );
122 BOOST_CHECK( !evaluator.HasErrors() );
123 BOOST_CHECK( !branch.IsEmpty() );
124
125 auto authorEmail = evaluator.Evaluate( "@{vcsauthoremail()}" );
126 BOOST_CHECK( !evaluator.HasErrors() );
127 BOOST_CHECK_EQUAL( authorEmail, TEST_AUTHOR_EMAIL );
128
129 auto committerEmail = evaluator.Evaluate( "@{vcscommitteremail()}" );
130 BOOST_CHECK( !evaluator.HasErrors() );
131 BOOST_CHECK_EQUAL( committerEmail, TEST_AUTHOR_EMAIL );
132
133 auto author = evaluator.Evaluate( "@{vcsauthor()}" );
134 BOOST_CHECK( !evaluator.HasErrors() );
136
137 auto committer = evaluator.Evaluate( "@{vcscommitter()}" );
138 BOOST_CHECK( !evaluator.HasErrors() );
140
141 // File variants should return the same values since there's only one commit
142 auto fileAuthorEmail = evaluator.Evaluate( "@{vcsfileauthoremail(\".\")}" );
143 BOOST_CHECK( !evaluator.HasErrors() );
144 BOOST_CHECK_EQUAL( fileAuthorEmail, TEST_AUTHOR_EMAIL );
145
146 auto fileCommitterEmail = evaluator.Evaluate( "@{vcsfilecommitteremail(\".\")}" );
147 BOOST_CHECK( !evaluator.HasErrors() );
148 BOOST_CHECK_EQUAL( fileCommitterEmail, TEST_AUTHOR_EMAIL );
149}
150
154BOOST_AUTO_TEST_CASE( VcsDirtyStatus )
155{
156 EXPRESSION_EVALUATOR evaluator;
157
158 struct TestCase
159 {
160 std::string expression;
161 };
162
163 const std::vector<TestCase> cases = {
164 { "@{vcsdirty()}" },
165 { "@{vcsdirty(0)}" },
166 { "@{vcsdirty(1)}" },
167 };
168
169 for( const auto& testCase : cases )
170 {
171 auto result = evaluator.Evaluate( wxString::FromUTF8( testCase.expression ) );
172
173 BOOST_CHECK( !evaluator.HasErrors() );
174 BOOST_CHECK( result == "0" || result == "1" );
175 }
176}
177
181BOOST_AUTO_TEST_CASE( VcsDirtySuffix )
182{
183 EXPRESSION_EVALUATOR evaluator;
184
185 const std::vector<std::string> cases = {
186 "@{vcsdirtysuffix()}",
187 "@{vcsdirtysuffix(\"-modified\")}",
188 "@{vcsdirtysuffix(\"+\", 1)}",
189 };
190
191 for( const auto& expr : cases )
192 {
193 evaluator.Evaluate( wxString::FromUTF8( expr ) );
194 BOOST_CHECK( !evaluator.HasErrors() );
195 }
196}
197
201BOOST_AUTO_TEST_CASE( VcsLabelsAndDistance )
202{
203 EXPRESSION_EVALUATOR evaluator;
204
205 const std::vector<std::string> cases = {
206 "@{vcsnearestlabel()}",
207 "@{vcsnearestlabel(\"\")}",
208 "@{vcsnearestlabel(\"v*\")}",
209 "@{vcsnearestlabel(\"\", 0)}",
210 "@{vcsnearestlabel(\"\", 1)}",
211
212 "@{vcslabeldistance()}",
213 "@{vcslabeldistance(\"v*\")}",
214 "@{vcslabeldistance(\"\", 1)}",
215 };
216
217 std::regex numberPattern( "^[0-9]+$" );
218
219 for( const auto& expr : cases )
220 {
221 auto result = evaluator.Evaluate( wxString::FromUTF8( expr ) );
222 BOOST_CHECK( !evaluator.HasErrors() );
223
224 if( !result.IsEmpty() && expr.find( "distance" ) != std::string::npos )
225 {
226 BOOST_CHECK( std::regex_match( result.ToStdString(), numberPattern ) );
227 }
228 }
229}
230
234BOOST_AUTO_TEST_CASE( VcsCommitDate )
235{
236 EXPRESSION_EVALUATOR evaluator;
237
238 struct TestCase
239 {
240 std::string expression;
241 std::regex pattern;
242 };
243
244 const std::vector<TestCase> cases = {
245 { "@{vcscommitdate()}", std::regex( "^[0-9]{4}-[0-9]{2}-[0-9]{2}$" ) },
246 { "@{vcscommitdate(\"ISO\")}", std::regex( "^[0-9]{4}-[0-9]{2}-[0-9]{2}$" ) },
247 { "@{vcscommitdate(\"US\")}", std::regex( "^[0-9]{2}/[0-9]{2}/[0-9]{4}$" ) },
248 { "@{vcscommitdate(\"EU\")}", std::regex( "^[0-9]{2}/[0-9]{2}/[0-9]{4}$" ) },
249
250 { "@{vcsfilecommitdate(\".\")}", std::regex( "^[0-9]{4}-[0-9]{2}-[0-9]{2}$" ) },
251 };
252
253 for( const auto& testCase : cases )
254 {
255 auto result = evaluator.Evaluate( wxString::FromUTF8( testCase.expression ) );
256
257 BOOST_CHECK_MESSAGE( !evaluator.HasErrors(),
258 "Error in expression: " + testCase.expression + " Errors: "
259 + evaluator.GetErrorSummary().ToStdString() );
260
261 BOOST_CHECK_MESSAGE( std::regex_match( result.ToStdString(), testCase.pattern ),
262 "Bad date format for " + testCase.expression + ": "
263 + result.ToStdString() );
264 }
265}
266
270BOOST_AUTO_TEST_CASE( VcsPerformance )
271{
272 EXPRESSION_EVALUATOR evaluator;
273
274 auto start = std::chrono::high_resolution_clock::now();
275
276 for( int i = 0; i < 100; ++i )
277 {
278 auto result = evaluator.Evaluate( "@{vcsidentifier(7)}" );
279 BOOST_CHECK( !evaluator.HasErrors() );
280 }
281
282 auto end = std::chrono::high_resolution_clock::now();
283 auto duration = std::chrono::duration_cast<std::chrono::milliseconds>( end - start );
284
285 // Sanitizer instrumentation changes execution cost, not the evaluation contract
286#if defined( KICAD_SANITIZE_THREADS ) || defined( KICAD_SANITIZE_ADDRESS )
287 BOOST_TEST_MESSAGE( "Instrumented VCS evaluation: " << duration.count() << " ms" );
288#else
289 BOOST_CHECK_LT( duration.count(), 2000 );
290#endif
291}
292
296BOOST_AUTO_TEST_CASE( VcsMixedExpressions )
297{
298 EXPRESSION_EVALUATOR evaluator;
299 evaluator.SetVariable( wxString( "PROJECT" ), wxString( "MyProject" ) );
300
301 const std::vector<std::string> cases = {
302 "Version: @{vcsbranch()}",
303 "Commit: @{vcsidentifier(7)}",
304 "Author: @{vcsauthor()} <@{vcsauthoremail()}>",
305
306 "${PROJECT} @{vcsbranch()}",
307 "Built from @{vcsnearestlabel()}@{vcsdirtysuffix()}",
308
309 "Distance: @{vcslabeldistance() + 0}",
310 };
311
312 for( const auto& expr : cases )
313 {
314 auto result = evaluator.Evaluate( wxString::FromUTF8( expr ) );
315
316 BOOST_CHECK( !evaluator.HasErrors() );
317 BOOST_CHECK( !result.IsEmpty() );
318 }
319}
320
328BOOST_AUTO_TEST_CASE( VcsContextPathOverride )
329{
330 // Move the process cwd somewhere that is definitely not a git repo, mirroring the
331 // kicad-cli situation where the user runs the binary from an arbitrary directory.
332 wxString scratchDir = wxFileName::GetTempDir() + wxFileName::GetPathSeparator()
333 + wxString::Format( "kicad_vcs_cli_%ld", wxGetProcessId() );
334
335 wxFileName::Mkdir( scratchDir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL );
336 wxSetWorkingDirectory( scratchDir );
337
338 auto cleanupCwd = [&]()
339 {
340 wxSetWorkingDirectory( tempDir() );
341
342 if( wxFileName::DirExists( scratchDir ) )
343 wxFileName::Rmdir( scratchDir, wxPATH_RMDIR_RECURSIVE );
344 };
345
346 try
347 {
348 // Without the context path override, vcsidentifier() falls back to cwd and reports
349 // the "not in a repository" sentinel.
350 EXPRESSION_EVALUATOR evaluator;
351 auto noContext = evaluator.Evaluate( "@{vcsidentifier(7)}" );
352 BOOST_CHECK_EQUAL( noContext.ToStdString(), std::string( "<unknown>" ) );
353
354 // With the override in place, the same expression resolves from the repo anchored
355 // at the temporary repository regardless of cwd.
356 {
357 TEXT_EVAL_VCS::CONTEXT_PATH_SCOPE scope( tempDir() );
358
359 auto hash = evaluator.Evaluate( "@{vcsidentifier(7)}" );
360 BOOST_CHECK( !evaluator.HasErrors() );
361 BOOST_CHECK_EQUAL( hash.Length(), 7 );
362
363 std::regex hexPattern( "^[0-9a-f]+$" );
364 BOOST_CHECK( std::regex_match( hash.ToStdString(), hexPattern ) );
365
366 auto branch = evaluator.Evaluate( "@{vcsbranch()}" );
367 BOOST_CHECK( !evaluator.HasErrors() );
368 BOOST_CHECK( !branch.IsEmpty() );
369 BOOST_CHECK( branch != wxS( "<unknown>" ) );
370
371 auto author = evaluator.Evaluate( "@{vcsauthor()}" );
373 }
374
375 // After the scope ends the override must be cleared and behavior returns to the
376 // cwd-based fallback.
377 auto afterScope = evaluator.Evaluate( "@{vcsidentifier(7)}" );
378 BOOST_CHECK_EQUAL( afterScope.ToStdString(), std::string( "<unknown>" ) );
379 }
380 catch( ... )
381 {
382 cleanupCwd();
383 throw;
384 }
385
386 cleanupCwd();
387}
388
395BOOST_AUTO_TEST_CASE( VcsContextPathSetByLoadProject )
396{
397 wxString scratchDir = wxFileName::GetTempDir() + wxFileName::GetPathSeparator()
398 + wxString::Format( "kicad_vcs_loadproject_%ld", wxGetProcessId() );
399
400 wxFileName::Mkdir( scratchDir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL );
401 wxSetWorkingDirectory( scratchDir );
402
403 // Drop a minimal .kicad_pro inside the git fixture so SETTINGS_MANAGER has something
404 // real to load. The content does not matter for VCS resolution.
405 wxString projectFile = tempDir() + wxFileName::GetPathSeparator()
406 + wxT( "issue23959.kicad_pro" );
407
408 {
409 std::ofstream f( projectFile.ToStdString() );
410 f << "{ \"meta\": { \"filename\": \"issue23959.kicad_pro\", \"version\": 3 } }";
411 }
412
413 auto cleanup = [&]()
414 {
415 wxRemoveFile( projectFile );
416 wxSetWorkingDirectory( tempDir() );
417
418 if( wxFileName::DirExists( scratchDir ) )
419 wxFileName::Rmdir( scratchDir, wxPATH_RMDIR_RECURSIVE );
420 };
421
422 try
423 {
424 // Baseline: with cwd outside the repo and no project loaded, lookups fail.
425 EXPRESSION_EVALUATOR evaluator;
426 auto baseline = evaluator.Evaluate( "@{vcsidentifier(7)}" );
427 BOOST_CHECK_EQUAL( baseline.ToStdString(), std::string( "<unknown>" ) );
428
429 BOOST_REQUIRE( Pgm().GetSettingsManager().LoadProject( projectFile, true ) );
430
431 // LoadProject must anchor VCS lookups to the project dir even though cwd is elsewhere.
432 auto loaded = evaluator.Evaluate( "@{vcsidentifier(7)}" );
433 BOOST_CHECK( !evaluator.HasErrors() );
434 BOOST_CHECK_EQUAL( loaded.Length(), 7 );
435
436 std::regex hexPattern( "^[0-9a-f]+$" );
437 BOOST_CHECK( std::regex_match( loaded.ToStdString(), hexPattern ) );
438
439 Pgm().GetSettingsManager().UnloadProject( &Pgm().GetSettingsManager().Prj(), false );
440 BOOST_REQUIRE( wxSetWorkingDirectory( scratchDir ) );
441
442 // UnloadProject must clear the context so lookups fall back to cwd, which is
443 // outside the repo, reproducing the sentinel state.
444 auto afterUnload = evaluator.Evaluate( "@{vcsidentifier(7)}" );
445 BOOST_CHECK_EQUAL( afterUnload.ToStdString(), std::string( "<unknown>" ) );
446 }
447 catch( ... )
448 {
449 cleanup();
450 throw;
451 }
452
453 cleanup();
454}
455
456
457// The context is process-wide, so a manager that dies with a project loaded leaves it stale.
458BOOST_AUTO_TEST_CASE( VcsContextClearedWhenSettingsManagerDies )
459{
460 wxString projectPath = tempDir() + wxFileName::GetPathSeparator() + wxT( "ctx.kicad_pro" );
461
462 {
463 std::ofstream f( projectPath.ToStdString() );
464 f << "{\"meta\": {\"filename\": \"ctx.kicad_pro\", \"version\": 3}}";
465 }
466
467 {
469 BOOST_TEST_REQUIRE( mgr.LoadProject( projectPath ) );
471 }
472
474}
475
High-level wrapper for evaluating mathematical and string expressions in wxString format.
wxString Evaluate(const wxString &aInput)
Main evaluation function - processes input string and evaluates all '@{}' expressions.
bool HasErrors() const
Check if the last evaluation had errors.
wxString GetErrorSummary() const
Get detailed error information from the last evaluation.
void SetVariable(const wxString &aName, double aValue)
Set a numeric variable for use in expressions.
Give each test a backend and a temporary directory.
const wxString & TempPath() const
virtual SETTINGS_MANAGER & GetSettingsManager() const
Definition pgm_base.h:124
bool UnloadProject(PROJECT *aProject, bool aSave=true)
Save, unload and unregister the given PROJECT.
bool LoadProject(const wxString &aFullPath, bool aSetActive=true, bool aOverrideLock=false)
Load a project or sets up a new project with a specified path.
RAII helper that sets the VCS context path on construction and restores the previous value on destruc...
static std::string ToStdString(const wxString &aStr)
PROJECT & Prj()
Definition kicad.cpp:730
std::unique_ptr< git_repository, decltype([](git_repository *aRepo) { git_repository_free(aRepo); })> GitRepositoryPtr
A unique pointer for git_repository objects with automatic cleanup.
KIGIT::GitRepositoryPtr InitGitRepository(const wxString &aPath, const char *aBranch="main", const char *aAuthorName="QA Test", const char *aAuthorEmail="[email protected]")
Pin the branch and author so repository setup does not depend on the user's Git config.
void WriteGitFile(const wxString &aRepoPath, const wxString &aRelativePath, const std::string &aContents)
Write test data without staging it. Create parent directories when needed.
git_oid CommitGitFile(git_repository *aRepo, const wxString &aPath, const wxString &aMessage)
Stage one file and commit the index. Other staged changes are kept.
wxString GetContextPath()
Return the current context path for repo-scoped VCS queries.
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
Fixture that creates a temporary git repo with one committed file.
TEXT_EVAL_VCS::CONTEXT_PATH_SCOPE m_context
const wxString & tempDir() const
BOOST_AUTO_TEST_CASE(HorizontalAlignment)
BOOST_CHECK(res.column_datatype(0)==SQL_NUMERIC||res.column_datatype(0)==SQL_DECIMAL)
BOOST_CHECK_EQUAL(std::any_cast< std::string >(rows[0].at("val")), "12345678901234567.89")
BOOST_REQUIRE(res.columns()==1)
static const char * TEST_AUTHOR_NAME
static const char * TEST_AUTHOR_EMAIL
BOOST_AUTO_TEST_SUITE_END()
VECTOR2I end
BOOST_TEST_MESSAGE("Polyline has "<< chain.PointCount()<< " points")
wxString result
Test unit parsing edge cases and error handling.
static const char * TEST_AUTHOR_NAME
static const char * TEST_AUTHOR_EMAIL
BOOST_AUTO_TEST_CASE(VcsIdentifierFormatting)
Test VCS identifier functions with various lengths.
static const char * TEST_COMMIT_MSG