KiCad PCB EDA Suite
Loading...
Searching...
No Matches
test_project_template.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
24
26#include <project_template.h>
28
29#include <wx/dir.h>
30#include <wx/filename.h>
31
32#include <algorithm>
33#include <filesystem>
34#include <fstream>
35#include <sstream>
36
37namespace fs = std::filesystem;
38
39
41{
42public:
44 {
45 m_originalDir = fs::current_path();
46 m_tempDir = fs::temp_directory_path() / "kicad_template_test";
47 fs::remove_all( m_tempDir );
48 fs::create_directories( m_tempDir );
49 }
50
52 {
53 fs::current_path( m_originalDir );
54 fs::remove_all( m_tempDir );
55 }
56
57 void CreateTemplateStructure( const std::string& templateName,
58 const std::vector<std::string>& subdirs,
59 const std::vector<std::string>& files )
60 {
61 fs::path templatePath = m_tempDir / templateName;
62 fs::create_directories( templatePath );
63
64 fs::path metaPath = templatePath / "meta";
65 fs::create_directories( metaPath );
66
67 std::ofstream infoFile( ( metaPath / "info.html" ).string() );
68 infoFile << "<html><head><title>Test Template</title></head><body></body></html>";
69 infoFile.close();
70
71 for( const auto& subdir : subdirs )
72 {
73 fs::create_directories( templatePath / subdir );
74 }
75
76 for( const auto& file : files )
77 {
78 fs::path filePath = templatePath / file;
79 fs::create_directories( filePath.parent_path() );
80 std::ofstream f( filePath.string() );
81 f << "test content";
82 f.close();
83 }
84 }
85
86 fs::path m_originalDir;
87 fs::path m_tempDir;
88};
89
90
91BOOST_FIXTURE_TEST_SUITE( ProjectTemplate, PROJECT_TEMPLATE_TEST_FIXTURE )
92
93
94BOOST_AUTO_TEST_CASE( DirectoriesRenamedCorrectly )
95{
96 // Create a template with subdirectories that should be renamed
97 CreateTemplateStructure(
98 "issue22289",
99 { "issue22289-dir", "issue22289-backups", "other-dir" },
100 { "issue22289.kicad_pro", "issue22289.kicad_sch", "issue22289-dir/test.kicad_sym" } );
101
102 fs::path templatePath = m_tempDir / "issue22289";
103 fs::path destPath = m_tempDir / "myproject";
104 fs::create_directories( destPath );
105
106 PROJECT_TEMPLATE tmpl( wxString::FromUTF8( templatePath.string() ) );
107
108 // GetDestinationFiles expects a wxFileName with the project file path
109 wxFileName newProjectPath;
110 newProjectPath.SetPath( wxString::FromUTF8( destPath.string() ) );
111 newProjectPath.SetName( wxS( "myproject" ) );
112 newProjectPath.SetExt( wxS( "kicad_pro" ) );
113
114 std::vector<wxFileName> destFiles;
115 tmpl.GetDestinationFiles( newProjectPath, destFiles );
116
117 bool foundRenamedDir = false;
118 bool foundRenamedFile = false;
119 bool foundOtherDir = false;
120
121 for( const wxFileName& destFile : destFiles )
122 {
123 wxString fullPath = destFile.GetFullPath();
124
125 if( fullPath.Contains( wxS( "myproject-dir" ) ) )
126 foundRenamedDir = true;
127
128 if( fullPath.Contains( wxS( "issue22289-dir" ) ) )
129 BOOST_FAIL( "Directory should have been renamed from issue22289-dir to myproject-dir" );
130
131 if( fullPath.Contains( wxS( "other-dir" ) ) )
132 foundOtherDir = true;
133
134 if( destFile.GetName() == wxS( "myproject" ) && destFile.GetExt() == wxS( "kicad_pro" ) )
135 foundRenamedFile = true;
136 }
137
138 BOOST_CHECK_MESSAGE( foundRenamedDir, "Should find myproject-dir in destination files" );
139 BOOST_CHECK_MESSAGE( foundRenamedFile, "Should find myproject.kicad_pro in destination files" );
140 BOOST_CHECK_MESSAGE( foundOtherDir, "Should preserve other-dir (not matching template name)" );
141}
142
143
144BOOST_AUTO_TEST_CASE( CreateProjectRenamesDirectories )
145{
146 CreateTemplateStructure(
147 "testtemplate",
148 { "testtemplate-lib", "testtemplate" },
149 { "testtemplate.kicad_pro", "testtemplate-lib/component.kicad_sym",
150 "testtemplate/nested.txt" } );
151
152 fs::path templatePath = m_tempDir / "testtemplate";
153 fs::path destPath = m_tempDir / "newproject";
154 fs::create_directories( destPath );
155
156 PROJECT_TEMPLATE tmpl( wxString::FromUTF8( templatePath.string() ) );
157
158 // CreateProject expects a wxFileName with the project file path (including extension)
159 wxFileName newProjectPath;
160 newProjectPath.SetPath( wxString::FromUTF8( destPath.string() ) );
161 newProjectPath.SetName( wxS( "newproject" ) );
162 newProjectPath.SetExt( wxS( "kicad_pro" ) );
163
164 wxString errorMsg;
165 bool result = tmpl.CreateProject( newProjectPath, &errorMsg );
166
167 BOOST_CHECK_MESSAGE( result, "CreateProject should succeed: " + errorMsg.ToStdString() );
168
169 BOOST_CHECK( fs::exists( destPath / "newproject.kicad_pro" ) );
170 BOOST_CHECK( fs::exists( destPath / "newproject-lib" ) );
171 BOOST_CHECK( fs::exists( destPath / "newproject-lib" / "component.kicad_sym" ) );
172
173 BOOST_CHECK_MESSAGE( !fs::exists( destPath / "testtemplate-lib" ),
174 "Old directory name should not exist" );
175}
176
177
178BOOST_AUTO_TEST_CASE( ExactMatchDirectoryRenamed )
179{
180 // Test that a directory exactly matching the template name is renamed
181 CreateTemplateStructure( "mytemplate", { "mytemplate" },
182 { "mytemplate.kicad_pro", "mytemplate/subfile.txt" } );
183
184 fs::path templatePath = m_tempDir / "mytemplate";
185 fs::path destPath = m_tempDir / "finalproject";
186 fs::create_directories( destPath );
187
188 PROJECT_TEMPLATE tmpl( wxString::FromUTF8( templatePath.string() ) );
189
190 // GetDestinationFiles expects a wxFileName with the project file path
191 wxFileName newProjectPath;
192 newProjectPath.SetPath( wxString::FromUTF8( destPath.string() ) );
193 newProjectPath.SetName( wxS( "finalproject" ) );
194 newProjectPath.SetExt( wxS( "kicad_pro" ) );
195
196 std::vector<wxFileName> destFiles;
197 tmpl.GetDestinationFiles( newProjectPath, destFiles );
198
199 bool foundExactRenamedDir = false;
200
201 for( const wxFileName& destFile : destFiles )
202 {
203 wxString fullPath = destFile.GetFullPath();
204
205 if( fullPath.Contains( wxS( "/finalproject/finalproject/" ) )
206 || fullPath.Contains( wxS( "\\finalproject\\finalproject\\" ) ) )
207 {
208 foundExactRenamedDir = true;
209 }
210
211 if( fullPath.Contains( wxS( "/finalproject/mytemplate/" ) )
212 || fullPath.Contains( wxS( "\\finalproject\\mytemplate\\" ) ) )
213 {
214 BOOST_FAIL( "Exact match directory should be renamed from mytemplate to finalproject" );
215 }
216 }
217
218 BOOST_CHECK_MESSAGE( foundExactRenamedDir, "Should find renamed subdirectory finalproject" );
219}
220
221
222BOOST_AUTO_TEST_CASE( TemplateWithoutMetaDirSetsErrorTitle )
223{
224 // Issue #23623: user template directories that are just regular KiCad projects
225 // (no meta/info.html) should not crash. The constructor should set an error
226 // title and GetTitle() should return that error without trying to open a
227 // nonexistent file.
228 fs::path noMetaPath = m_tempDir / "no_meta_template";
229 fs::create_directories( noMetaPath );
230
231 std::ofstream f( ( noMetaPath / "no_meta_template.kicad_pro" ).string() );
232 f << "{}";
233 f.close();
234
235 PROJECT_TEMPLATE tmpl( wxString::FromUTF8( noMetaPath.string() ) );
236
237 wxString* title = tmpl.GetTitle();
238 BOOST_REQUIRE( title != nullptr );
239 BOOST_CHECK_MESSAGE( !title->IsEmpty(), "Template without meta dir should have an error title" );
240
241 // Calling GetTitle() again should return the same cached result without
242 // attempting to open meta/info.html
243 wxString* title2 = tmpl.GetTitle();
244 BOOST_CHECK( *title == *title2 );
245}
246
247
248BOOST_AUTO_TEST_CASE( TemplateWithMetaDirButNoInfoHtml )
249{
250 // meta directory exists but info.html is missing
251 fs::path tmplPath = m_tempDir / "meta_no_html";
252 fs::create_directories( tmplPath / "meta" );
253
254 std::ofstream f( ( tmplPath / "meta_no_html.kicad_pro" ).string() );
255 f << "{}";
256 f.close();
257
258 PROJECT_TEMPLATE tmpl( wxString::FromUTF8( tmplPath.string() ) );
259
260 wxString* title = tmpl.GetTitle();
261 BOOST_REQUIRE( title != nullptr );
262 BOOST_CHECK_MESSAGE( !title->IsEmpty(),
263 "Template with meta dir but no info.html should have an error title" );
264}
265
266
267// Regression test for https://gitlab.com/kicad/code/kicad/-/issues/24343
268// EnsureDefaultProjectTemplate must seed the built-in "default" template under the given base
269// directory and yield a directory that PROJECT_TEMPLATE can load as a valid template.
270BOOST_AUTO_TEST_CASE( EnsureDefaultTemplateSeedsBaseDir )
271{
272 wxString baseDir = wxString::FromUTF8( ( m_tempDir / "default_seed" ).string() );
273 wxFileName seeded = EnsureDefaultProjectTemplate( baseDir );
274
275 BOOST_REQUIRE_MESSAGE( seeded.IsOk(), "Seeding the default template should succeed" );
276
277 // The default template must live directly under the requested base directory, not somewhere
278 // derived from an environment variable.
279 fs::path expected = m_tempDir / "default_seed" / "default";
280 BOOST_CHECK( fs::exists( expected ) );
281 BOOST_CHECK( fs::exists( expected / "meta" / "info.html" ) );
282 BOOST_CHECK( fs::exists( expected / "default.kicad_pro" ) );
283
284 // PROJECT_TEMPLATE must recognize the seeded directory as a valid template (meta dir and
285 // info.html present, so no error is reported).
286 PROJECT_TEMPLATE tmpl( seeded.GetPath() );
287
288 BOOST_CHECK_MESSAGE( tmpl.GetError().IsEmpty(),
289 "Seeded default template should load without error: " + tmpl.GetError() );
290
291 wxString* title = tmpl.GetTitle();
292
293 BOOST_REQUIRE( title != nullptr );
294 BOOST_CHECK( !title->IsEmpty() );
295}
296
297
298BOOST_AUTO_TEST_CASE( ProjectCreatedFromDefaultTemplateLoads )
299{
300 wxString baseDir = wxString::FromUTF8( ( m_tempDir / "default_load" ).string() );
301 wxFileName seeded = EnsureDefaultProjectTemplate( baseDir );
302
303 BOOST_REQUIRE( seeded.IsOk() );
304
305 fs::path destPath = m_tempDir / "fromdefault";
306 fs::create_directories( destPath );
307
308 PROJECT_TEMPLATE tmpl( seeded.GetPath() );
309
310 wxFileName newProjectPath;
311 newProjectPath.SetPath( wxString::FromUTF8( destPath.string() ) );
312 newProjectPath.SetName( wxS( "fromdefault" ) );
313 newProjectPath.SetExt( wxS( "kicad_pro" ) );
314
315 wxString errorMsg;
316
317 BOOST_REQUIRE_MESSAGE( tmpl.CreateProject( newProjectPath, &errorMsg ),
318 "CreateProject should succeed: " + errorMsg.ToStdString() );
319
321
322 BOOST_CHECK_MESSAGE( mgr.LoadProject( newProjectPath.GetFullPath() ),
323 "A project made from the default template must load" );
324}
325
326
327// An empty base directory must not create anything and must report failure.
328BOOST_AUTO_TEST_CASE( EnsureDefaultTemplateRejectsEmptyBaseDir )
329{
330 wxFileName seeded = EnsureDefaultProjectTemplate( wxEmptyString );
331
332 BOOST_CHECK( !seeded.IsOk() );
333}
334
335
336// Calling EnsureDefaultProjectTemplate twice must be idempotent and not clobber existing content.
337BOOST_AUTO_TEST_CASE( EnsureDefaultTemplateIsIdempotent )
338{
339 wxString baseDir = wxString::FromUTF8( ( m_tempDir / "default_idempotent" ).string() );
340
341 wxFileName first = EnsureDefaultProjectTemplate( baseDir );
342 BOOST_REQUIRE( first.IsOk() );
343
344 // Overwrite the project file with custom content to verify it survives a second call.
345 fs::path proFile = m_tempDir / "default_idempotent" / "default" / "default.kicad_pro";
346 {
347 std::ofstream f( proFile.string() );
348 f << "{\"custom\":true}";
349 }
350
351 wxFileName second = EnsureDefaultProjectTemplate( baseDir );
352 BOOST_REQUIRE( second.IsOk() );
353 BOOST_CHECK_EQUAL( first.GetPath(), second.GetPath() );
354
355 std::ifstream in( proFile.string() );
356 std::stringstream buffer;
357 buffer << in.rdbuf();
358
359 BOOST_CHECK_EQUAL( buffer.str(), std::string( "{\"custom\":true}" ) );
360}
361
362
363BOOST_AUTO_TEST_CASE( ReadOnlyTemplateProducesWritableProject )
364{
365 CreateTemplateStructure( "rotemplate", { "rotemplate-lib" },
366 { "rotemplate.kicad_pro", "rotemplate.kicad_sch", "rotemplate-lib/component.kicad_sym" } );
367
368 fs::path templatePath = m_tempDir / "rotemplate";
369 fs::path destPath = m_tempDir / "rwproject";
370 fs::create_directories( destPath );
371
372 const std::vector<fs::path> templateFiles = { templatePath / "rotemplate.kicad_pro",
373 templatePath / "rotemplate.kicad_sch",
374 templatePath / "rotemplate-lib" / "component.kicad_sym" };
375
376 for( const fs::path& file : templateFiles )
377 {
378 fs::permissions( file, fs::perms::owner_write | fs::perms::group_write | fs::perms::others_write,
379 fs::perm_options::remove );
380 }
381
382 PROJECT_TEMPLATE tmpl( wxString::FromUTF8( templatePath.string() ) );
383
384 wxFileName newProjectPath;
385 newProjectPath.SetPath( wxString::FromUTF8( destPath.string() ) );
386 newProjectPath.SetName( wxS( "rwproject" ) );
387 newProjectPath.SetExt( wxS( "kicad_pro" ) );
388
389 wxString errorMsg;
390 bool created = tmpl.CreateProject( newProjectPath, &errorMsg );
391
392 // Restore write permission before asserting, so that a failed assertion still leaves the
393 // fixture able to remove the temporary directory.
394 for( const fs::path& file : templateFiles )
395 fs::permissions( file, fs::perms::owner_write, fs::perm_options::add );
396
397 BOOST_REQUIRE_MESSAGE( created, "CreateProject failed: " + errorMsg.ToStdString() );
398
399 const std::vector<fs::path> projectFiles = { destPath / "rwproject.kicad_pro", destPath / "rwproject.kicad_sch",
400 destPath / "rwproject-lib" / "component.kicad_sym" };
401
402 for( const fs::path& file : projectFiles )
403 {
404 wxFileName fn( wxString::FromUTF8( file.string() ) );
405
406 BOOST_REQUIRE_MESSAGE( fn.FileExists(), file.string() + " was not created" );
407 BOOST_CHECK_MESSAGE( fn.IsFileWritable(), file.string() + " is read only" );
408 }
409}
410
411
412BOOST_AUTO_TEST_CASE( PinnedTemplatesSortFirst )
413{
414 struct ENTRY
415 {
416 wxString title;
417 bool pinned;
418 };
419
420 std::vector<ENTRY> entries = { { wxS( "STM32F407" ), false },
421 { wxS( "Default" ), false },
422 { wxS( "Motor_Driver" ), true },
423 { wxS( "Arduino_Mega" ), false },
424 { wxS( "amplifier" ), true } };
425
426 std::sort( entries.begin(), entries.end(),
427 []( const ENTRY& a, const ENTRY& b )
428 {
429 return TemplateListLess( a.title, a.pinned, b.title, b.pinned );
430 } );
431
432 std::vector<wxString> titles;
433
434 for( const ENTRY& entry : entries )
435 titles.push_back( entry.title );
436
437 const std::vector<wxString> expected = { wxS( "amplifier" ), wxS( "Motor_Driver" ), wxS( "Default" ),
438 wxS( "Arduino_Mega" ), wxS( "STM32F407" ) };
439
440 BOOST_CHECK( titles == expected );
441}
442
443
void CreateTemplateStructure(const std::string &templateName, const std::vector< std::string > &subdirs, const std::vector< std::string > &files)
A class which provides project template functionality.
size_t GetDestinationFiles(const wxFileName &aNewProjectPath, std::vector< wxFileName > &aDestFiles)
Fetch the list of destination files to be copied when the new project is created.
wxString * GetTitle()
Get the title of the project (extracted from the html title tag)
bool CreateProject(wxFileName &aNewProjectPath, wxString *aErrorMsg=nullptr)
Copies and renames all template files to create a new project.
const wxString & GetError() const
bool LoadProject(const wxString &aFullPath, bool aSetActive=true, bool aOverrideLock=false)
Load a project or sets up a new project with a specified path.
wxFileName EnsureDefaultProjectTemplate(const wxString &aBaseDir)
Seed the built-in "default" project template under aBaseDir, creating the directory tree and minimal ...
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_MESSAGE(dc.CacheTableInfo(table, { "part_id", "val" }), dc.GetLastError())
BOOST_REQUIRE(res.columns()==1)
BOOST_AUTO_TEST_SUITE_END()
VECTOR3I expected(15, 30, 45)
BOOST_AUTO_TEST_CASE(DirectoriesRenamedCorrectly)
wxString result
Test unit parsing edge cases and error handling.