forked from qgis/QGIS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CODING
1407 lines (952 loc) · 46.9 KB
/
CODING
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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
128
129
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Quantum GIS (QGIS)
Developers guide for QGIS
------------------------------------------------------------------------
1. QGIS Coding Standards
1.1. Classes
1.1.1. Names
1.1.2. Members
1.1.3. Accessor Functions
1.1.4. Functions
1.2. Qt Designer
1.2.1. Generated Classes
1.2.2. Dialogs
1.3. C++ Files
1.3.1. Names
1.3.2. Standard Header and License
1.3.3. SVN Keyword
1.4. Variable Names
1.5. Enumerated Types
1.6. Global Constants
1.7. Editing
1.7.1. Tabs
1.7.2. Indentation
1.7.3. Braces
1.8. API Compatibility
1.9. Coding Style
1.9.1. Where-ever Possible Generalize Code
1.9.2. Prefer Having Constants First in Predicates
1.9.3. Whitespace Can Be Your Friend
1.9.4. Add Trailing Identifying Comments
1.9.5. Use Braces Even for Single Line Statements
1.9.6. Book recommendations
2. SVN Access
2.1. Accessing the Repository
2.2. Anonymous Access
2.3. QGIS documentation sources
2.4. SVN Documentation
2.5. Development in branches
2.5.1. Purpose
2.5.2. Procedure
2.5.3. Creating a branch
2.5.4. Merge regularly from trunk to branch
2.6. Submitting Patches
2.6.1. Patch file naming
2.6.2. Create your patch in the top level QGIS source dir
2.6.3. Including non version controlled files in your patch
2.6.4. Getting your patch noticed
2.6.5. Due Diligence
2.7. Obtaining SVN Write Access
2.7.1. Procedure once you have access
3. Unit Testing
3.1. The QGIS testing framework - an overview
3.2. Creating a unit test
3.3. Adding your unit test to CMakeLists.txt
3.4. The ADD_QGIS_TEST macro explained
3.5. Building your unit test
3.6. Run your tests
4. HIG (Human Interface Guidelines)
5. Authors
------------------------------------------------------------------------
1. QGIS Coding Standards
========================
These standards should be followed by all QGIS developers.
1.1. Classes
============
1.1.1. Names
============
Class in QGIS begin with Qgs and are formed using mixed case.
Examples:
QgsPoint
QgsMapCanvas
QgsRasterLayer
1.1.2. Members
==============
Class member names begin with a lower case m and are formed using mixed
case.
mMapCanvas
mCurrentExtent
All class members should be private.
Public class members are STRONGLY discouraged
1.1.3. Accessor Functions
=========================
Class member values should be obtained through accesssor functions. The
function should be named without a get prefix. Accessor functions for the
two private members above would be:
mapCanvas()
currentExtent()
1.1.4. Functions
================
Function names begin with a lowercase letter and are formed using mixed case.
The function name should convey something about the purpose of the function.
updateMapExtent()
setUserOptions()
1.2. Qt Designer
================
1.2.1. Generated Classes
========================
QGIS classes that are generated from Qt Designer (ui) files should have a
Base suffix. This identifies the class as a generated base class.
Examples:
QgsPluginMangerBase
QgsUserOptionsBase
1.2.2. Dialogs
==============
All dialogs should implement the following:
* Tooltip help for all toolbar icons and other relevant widgets
* WhatsThis help for all widgets on the dialog
* An optional (though highly recommended) context sensitive Help button
that directs the user to the appropriate help page by launching their web
browser
1.3. C++ Files
==============
1.3.1. Names
============
C++ implementation and header files should be have a .cpp and .h extension
respectively. Filename should be all lowercase and, in the case of classes,
match the class name.
Example:
Class QgsFeatureAttribute source files are
qgsfeatureattribute.cpp and qgsfeatureattribute.h
/!\ Note: in case it is not clear from the statement above, for a filename
to match a class name it implicitly means that each class should be declared
and implemented in its own file. This makes it much easier for newcomers to
identify where the code is relating to specific class.
1.3.2. Standard Header and License
==================================
Each source file should contain a header section patterned after the following
example:
/***************************************************************************
qgsfield.cpp - Describes a field in a layer or table
--------------------------------------
Date : 01-Jan-2004
Copyright : (C) 2004 by Gary E.Sherman
Email : sherman at mrcc.com
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
1.3.3. SVN Keyword
==================
Each source file should contain the $Id$ keyword. This will be expanded by CVS
to contain useful information about the file, revision, last committer, and
date/time of last checkin.
Place the keyword right after the standard header/license that is found at the
top of each source file:
/* $Id$ */
1.4. Variable Names
===================
Variable names begin with a lower case letter and are formed using mixed case.
Examples:
mapCanvas
currentExtent
1.5. Enumerated Types
=====================
Enumerated types should be named in CamelCase with a leading capital e.g.:
enum UnitType
{
Meters,
Feet,
Degrees,
UnknownUnit
} ;
Do not use generic type names that will conflict with other types. e.g. use
"UnkownUnit" rather than "Unknown"
1.6. Global Constants
=====================
Global constants should be written in upper case underscore separated e.g.:
const long GEOCRS_ID = 3344;
1.7. Editing
============
Any text editor/IDE can be used to edit QGIS code, providing the following
requirements are met.
1.7.1. Tabs
===========
Set your editor to emulate tabs with spaces. Tab spacing should be set to 2
spaces.
1.7.2. Indentation
==================
Source code should be indented to improve readability. There is a .indent.pro
file in the QGIS src directory that contains the switches to be used when
indenting code using the GNU indent program. If you don't use GNU indent, you
should emulate these settings.
1.7.3. Braces
=============
Braces should start on the line following the expression:
if(foo == 1)
{
// do stuff
...
}else
{
// do something else
...
}
1.8. API Compatibility
======================
From QGIS 1.0 we will provide a stable, backwards compatible API. This will
provide a stable basis for people to develop against, knowing their code will
work against any of the 1.x QGIS releases (although recompiling may be
required).Cleanups to the API should be done in a manner similar to the
Trolltech developers e.g.
class Foo
{
public:
/** This method will be deprecated, you are encouraged to use
doSomethingBetter() rather.
@see doSomethingBetter()
*/
bool doSomething();
/** Does something a better way.
@note This method was introduced in QGIS version 1.1
*/
bool doSomethingBetter();
}
1.9. Coding Style
=================
Here are described some programming hints and tips that will hopefully reduce
errors, development time, and maintenance.
1.9.1. Where-ever Possible Generalize Code
==========================================
If you are cut-n-pasting code, or otherwise writing the same thing more than
once, consider consolidating the code into a single function.
This will:
* allow changes to be made in one location instead of in multiple places
* help prevent code bloat
* make it more difficult for multiple copies to evolve differences over time,
thus making it harder to understand and maintain for others
1.9.2. Prefer Having Constants First in Predicates
==================================================
Prefer to put constants first in predicates.
"0 == value" instead of "value == 0"
This will help prevent programmers from accidentally using "=" when they meant
to use "==", which can introduce very subtle logic bugs. The compiler will
generate an error if you accidentally use "=" instead of "==" for comparisons
since constants inherently cannot be assigned values.
1.9.3. Whitespace Can Be Your Friend
====================================
Adding spaces between operators, statements, and functions makes it easier for
humans to parse code.
Which is easier to read, this:
if (!a&&b)
or this:
if ( ! a && b )
1.9.4. Add Trailing Identifying Comments
========================================
Adding comments at the end of function, struct and class implementations makes
it easier to find them later.
Consider that you're at the bottom of a source file and need to find a very
long function -- without these kinds of trailing comments you will have to page
up past the body of the function to find its name. Of course this is ok if you
wanted to find the beginning of the function; but what if you were interested
at code near its end? You'd have to page up and then back down again to the
desired part.
e.g.,
void foo::bar()
{
// ... imagine a lot of code here
} // foo::bar()
1.9.5. Use Braces Even for Single Line Statements
=================================================
Using braces for code in if/then blocks or similar code structures even for
single line statements means that adding another statement is less likely to
generate broken code.
Consider:
if (foo)
bar();
else
baz();
Adding code after bar() or baz() without adding enclosing braces would create
broken code. Though most programmers would naturally do that, some may forget
to do so in haste.
So, prefer this:
if (foo)
{
bar();
}
else
{
baz();
}
1.9.6. Book recommendations
===========================
- Effective C++ (http://www.awprofessional.com/title/0321334876), Scott Meyers
- More Effective C++ (http://www.awprofessional.com/bookstore/product.asp?isbn=020163371X&rl=1), Scott Meyers
- Effective STL (http://www.awprofessional.com/title/0201749629), Scott Meyers
- Design Patterns (http://www.awprofessional.com/title/0201634988), GoF
You should also really read this article from Qt Quarterly on
http://doc.trolltech.com/qq/qq13-apis.html designing Qt style (APIs)
2. SVN Access
=============
This page describes how to get started using the QGIS Subversion repository
2.1. Accessing the Repository
=============================
To check out QGIS HEAD:
svn --username [your user name] co https://svn.osgeo.org/qgis/trunk/qgis
2.2. Anonymous Access
=====================
You can use the following commands to perform an anonymous checkout from the
QGIS Subversion repository. Note we recommend checking out the trunk (unless
you are a developer or really HAVE to have the latest changes and don't mind
lots of crashing!).
You must have a subversion client installed prior to checking out the code. See
the Subversion website for more information. The Links page contains a good
selection of SVN clients for various platforms.
To check out a branch
svn co https://svn.osgeo.org/qgis/branches/<branch name>
To check out SVN stable trunk:
svn co https://svn.osgeo.org/qgis/trunk/qgis qgis_trunk
/!\ Note: If you are behind a proxy server, edit your ~/subversion/servers
file to specify your proxy settings first!
/!\ Note: In QGIS we keep our most stable code in the version 1_0 branch.
Trunk contains code for the so called 'unstable' release series. Periodically
we will tag a release off trunk, and then continue stabilisation and selective
incorporation of new features into trunk.
See the INSTALL file in the source tree for specific instructions on building
development versions.
2.3. QGIS documentation sources
===============================
If you're interested in checking out Quantum GIS documentation sources:
svn co https://svn.osgeo.org/qgis/docs/trunk qgis_docs
You can also take a look at DocumentationWritersCorner for more information.
2.4. SVN Documentation
======================
The repository is organized as follows:
http://wiki.qgis.org/images/repo.png
See the Subversion book http://svnbook.red-bean.com for information on becoming
a SVN master.
2.5. Development in branches
============================
2.5.1. Purpose
==============
The complexity of the QGIS source code has increased considerably during the
last years. Therefore it is hard to anticipate the side effects that the
addition of a feature will have. In the past, the QGIS project had very long
release cycles because it was a lot of work to reetablish the stability of the
software system after new features were added. To overcome these problems, QGIS
switched to a development model where new features are coded in svn branches
first and merged to trunk (the main branch) when they are finished and stable.
This section describes the procedure for branching and merging in the QGIS
project.
2.5.2. Procedure
================
- Initial announcement on mailing list:
Before starting, make an announcement on the developer mailing list to see if
another developer is already working on the same feature. Also contact the
technical advisor of the project steering committee (PSC). If the new feature
requires any changes to the QGIS architecture, a request for comment (RFC) is
needed.
- Create a branch:
Create a new svn branch for the development of the new feature (see
UsingSubversion for the svn syntax). Now you can start developing.
- Merge from trunk regularly:
It is recommended to merge the changes in trunk to the branch on a regular
basis. This makes it easier to merge the branch back to trunk later.
- Documentation on wiki:
It is also recommended to document the intended changes and the current status
of the work on a wiki page.
- Testing before merging back to trunk:
When you are finished with the new feature and happy with the stability, make
an announcement on the developer list. Before merging back, the changes will
be tested by developers and users. Binary packages (especially for OsX and
Windows) will be generated to also involve non-developers. In trac, a new
Component will be opened to file tickets against. Once there are no remaining
issues left, the technical advisor of the PSC merges the changes into trunk.
2.5.3. Creating a branch
========================
We prefer that new feature developments happen out of trunk so that trunk
remains in a stable state. To create a branch use the following command:
svn copy https://svn.osgeo.org/qgis/trunk/qgis https://svn.osgeo.org/qgis/branches/qgis_newfeature
svn commit -m "New feature branch"
2.5.4. Merge regularly from trunk to branch
===========================================
When working in a branch you should regularly merge trunk into it so that your
branch does not diverge more than necessary. In the top level dir of your
branch, first type `svn info` to determine the revision numbers of your
branch which will produce output something like this:
timlinux@timlinux-desktop:~/dev/cpp/qgis_raster_transparency_branch$ svn info
Caminho: .
URL: https://svn.osgeo.org/qgis/branches/raster_transparency_branch
Raiz do Repositório: https://svn.osgeo.org/qgis
UUID do repositório: c8812cc2-4d05-0410-92ff-de0c093fc19c
Revisão: 6546
Tipo de Nó: diretório
Agendado: normal
Autor da Última Mudança: timlinux
Revisão da Última Mudança: 6495
Data da Última Mudança: 2007-02-02 09:29:47 -0200 (Sex, 02 Fev 2007)
Propriedades da Última Mudança: 2007-01-09 11:32:55 -0200 (Ter, 09 Jan 2007)
The second revision number shows the revision number of the start revision of
your branch and the first the current revision. You can do a dry run of the
merge like this:
svn merge --dry-run -r 6495:6546 https://svn.osgeo.org/qgis/trunk/qgis
After you are happy with the changes that will be made do the merge for real
like this:
svn merge -r 6495:6546 https://svn.osgeo.org/qgis/trunk/qgis
svn commit -m "Merged upstream changes from trunk to my branch"
2.6. Submitting Patches
=======================
There are a few guidelines that will help you to get your patches into QGIS
easily, and help us deal with the patches that are sent to use easily.
2.6.1. Patch file naming
========================
If the patch is a fix for a specific bug, please name the file with the bug
number in it e.g. bug777fix.diff, and attach it to the original bug report
in trac (https://trac.osgeo.org/qgis/).
If the bug is an enhancement or new feature, its usually a good idea to create
a ticket in trac (https://trac.osgeo.org/qgis/) first and then attach you
2.6.2. Create your patch in the top level QGIS source dir
=========================================================
This makes it easier for us to apply the patches since we don't need to
navigate to a specific place in the source tree to apply the patch. Also when I
receive patches I usually evaluate them using kompare, and having the patch
from the top level dir makes this much easier. Below is an example of you you
can include multiple changed files into your patch from the top level
directory:
cd qgis
svn diff src/ui/somefile.ui src/app/somefile2.cpp > bug872fix.diff
2.6.3. Including non version controlled files in your patch
===========================================================
If your improvements include new files that don't yet exist in the repository,
you should indicate to svn that they need to be added before generating your
patch e.g.
cd qgis
svn add src/lib/somenewfile.cpp
svn diff > bug7887fix.diff
2.6.4. Getting your patch noticed
=================================
QGIS developers are busy folk. We do scan the incoming patches on bug reports
but sometimes we miss things. Don't be offended or alarmed. Try to identify a
developer to help you - using the ["Project Organigram"] and contact them
asking them if they can look at your patch. If you don't get any response, you
can escalate your query to one of the Project Steering Committee members
(contact details also available on the ["Project Organigram"]).
2.6.5. Due Diligence
====================
QGIS is licensed under the GPL. You should make every effort to ensure you only
submit patches which are unencumbered by conflicting intellectual property
rights. Also do not submit code that you are not happy to have made available
under the GPL.
2.7. Obtaining SVN Write Access
===============================
Write access to QGIS source tree is by invitation. Typically when a person
submits several (there is no fixed number here) substantial patches that
demonstrate basic competance and understanding of C++ and QGIS coding
conventions, one of the PSC members or other existing developers can nominate
that person to the PSC for granting of write access. The nominator should give
a basic promotional paragraph of why they think that person should gain write
access. In some cases we will grant write access to non C++ developers e.g. for
translators and documentors. In these cases, the person should still have
demonstrated ability to submit patches and should ideally have submtted several
substantial patches that demonstrate their understanding of modifying the code
base without breaking things, etc.
2.7.1. Procedure once you have access
=====================================
Checkout the sources:
svn co https://svn.osgeo.org/qgis/trunk/qgis qgis
Build the sources (see INSTALL document for proper detailed instructions)
cd qgis
mkdir build
ccmake .. (set your preferred options)
make
make install (maybe you need to do with sudo / root perms)
Make your edits
cd ..
Make your changes in sources. Always check that everything compiles before
making any commits. Try to be aware of possible breakages your commits may
cause for people building on other platforms and with older / newer versions of
libraries.
Add files (if you added any new files). The svn status command can be used to
quickly see if you have added new files.
svn status src/pluguns/grass/modules
Files listed with ? in front are not in SVN and possibly need to be added by
you:
svn add src/pluguns/grass/modules/foo.xml
Commit your changes
svn commit src/pluguns/grass/modules/foo.xml
Your editor (as defined in $EDITOR environment variable) will appear and you
should make a comment at the top of the file (above the area that says 'don't
change this'. Put a descriptive comment and rather do several small commits if
the changes across a number of files are unrelated. Conversely we prefer you to
group related changes into a single commit.
Save and close in your editor. The first time you do this, you should be
prompted to put in your username and password. Just use the same ones as your
trac account.
3. Unit Testing
===============
As of November 2007 we require all new features going into trunk to be
accompanied with a unit test. Initially we have limited this requirement to
qgis_core, and we will extend this requirement to other parts of the code base
once people are familiar with the procedures for unit testing explained in the
sections that follow.
3.1. The QGIS testing framework - an overview
==============================================
Unit testing is carried out using a combination of QTestLib (the Qt testing
library) and CTest (a framework for compiling and running tests as part of the
CMake build process). Lets take an overview of the process before I delve into
the details:
- There is some code you want to test, e.g. a class or function. Extreme
programming advocates suggest that the code should not even be written yet
when you start building your tests, and then as you implement your code you can
immediately validate each new functional part you add with your test. In
practive you will probably need to write tests for pre-existing code in QGIS
since we are starting with a testing framework well after much application
logic has already been implemented.
- You create a unit test. This happens under <QGIS Source Dir>/tests/src/core
in the case of the core lib. The test is basically a client that creates an
instance of a class and calls some methods on that class. It will check the
return from each method to make sure it matches the expected value. If any
one of the calls fails, the unit will fail.
- You include QtTestLib macros in your test class. This macro is processed by
the Qt meta object compiler (moc) and expands your test class into a
runnable application.
- You add a section to the CMakeLists.txt in your tests directory that will
build your test.
- You ensure you have ENABLE_TESTING enabled in ccmake / cmakesetup. This
will ensure your tests actually get compiled when you type make.
- You optionally add test data to <QGIS Source Dir>/tests/testdata if your
test is data driven (e.g. needs to load a shapefile). These test data should
be as small as possible and wherever possible you should use the existing
datasets already there. Your tests should never modify this data in situ,
but rather may a temporary copy somewhere if needed.
- You compile your sources and install. Do this using normal make && (sudo)
make install procedure.
- You run your tests. This is normally done simply by doing make test
after the make install step, though I will explain other aproaches that offer
more fine grained control over running tests.
Right with that overview in mind, I will delve into a bit of detail. I've
already done much of the configuration for you in CMake and other places in the
source tree so all you need to do are the easy bits - writing unit tests!
3.2. Creating a unit test
=========================
Creating a unit test is easy - typically you will do this by just creating a
single .cpp file (not .h file is used) and implement all your test methods as
public methods that return void. I'll use a simple test class for
QgsRasterLayer throughout the section that follows to illustrate. By convention
we will name our test with the same name as the class they are testing but
prefixed with 'Test'. So our test implementation goes in a file called
testqgsrasterlayer.cpp and the class itself will be TestQgsRasterLayer. First
we add our standard copyright banner:
/***************************************************************************
testqgsvectorfilewriter.cpp
--------------------------------------
Date : Frida Nov 23 2007
Copyright : (C) 2007 by Tim Sutton
Email : [email protected]
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
Next we use start our includes needed for the tests we plan to run. There is
one special include all tests should have:
#include <QtTest>
Beyond that you just continue implementing your class as per normal, pulling
in whatever headers you may need:
//Qt includes...
#include <QObject>
#include <QString>
#include <QObject>
#include <QApplication>
#include <QFileInfo>
#include <QDir>
//qgis includes...
#include <qgsrasterlayer.h>
#include <qgsrasterbandstats.h>
#include <qgsapplication.h>
Since we are combining both class declaration and implementation in a single
file the class declaration comes next. We start with our doxygen documentation.
Every test case should be properly documented. We use the doxygen ingroup
directive so that all the UnitTests appear as a module in the generated Doxygen
documentation. After that comes a short description of the unit test:
/** \ingroup UnitTests
* This is a unit test for the QgsRasterLayer class.
*/
The class must inherit from QObject and include the Q_OBJECT macro.
class TestQgsRasterLayer: public QObject
{
Q_OBJECT;
All our test methods are implemented as private slots. The QtTest framework
will sequentially call each private slot method in the test class. There are
four 'special' methods which if implemented will be called at the start of the
unit test (initTestCase), at the end of the unit test
(cleanupTestCase). Before each test method is called, the init()
method will be called and after each test method is called the cleanup()
method is called. These methods are handy in that they allow you to allocate
and cleanup resources prior to running each test, and the test unit as a whole.
private slots:
// will be called before the first testfunction is executed.
void initTestCase();
// will be called after the last testfunction was executed.
void cleanupTestCase(){};
// will be called before each testfunction is executed.
void init(){};
// will be called after every testfunction.
void cleanup();
Then come your test methods, all of which should take no parameters and
should return void. The methods will be called in order of declaration. I
am implementing two methods here which illustrates to types of testing. In the
first case I want to generally test the various parts of the class are working,
I can use a functional testing approach. Once again, extreme programmers
would advocate writing these tests before implementing the class. Then as
you work your way through your class implementation you iteratively run your
unit tests. More and more test functions should complete sucessfully as your
class implementation work progresses, and when the whole unit test passes, your
new class is done and is now complete with a repeatable way to validate it.
Typically your unit tests would only cover the public API of your class,
and normally you do not need to write tests for accessors and mutators. If it
should happen that an acccessor or mutator is not working as expected you would
normally implement a regression test to check for this (see lower down).
//
// Functional Testing
//
/** Check if a raster is valid. */
void isValid();
// more functional tests here ...
Next we implement our regression tests. Regression tests should be
implemented to replicate the conditions of a particular bug. For example I
recently received a report by email that the cell count by rasters was off by
1, throwing off all the statistics for the raster bands. I opened a bug (ticket
#832) and then created a regression test that replicated the bug using a small
test dataset (a 10x10 raster). Then I ran the test and ran it, verifying that
it did indeed fail (the cell count was 99 instead of 100). Then I went to fix
the bug and reran the unit test and the regression test passed. I committed the
regression test along with the bug fix. Now if anybody breakes this in the
source code again in the future, we can immediatly identify that the code has
regressed. Better yet before committing any changes in the future, running our
tests will ensure our changes don't have unexpected side effects - like breaking
existing functionality.
There is one more benifit to regression tests - they can save you time. If you
ever fixed a bug that involved making changes to the source, and then running
the application and performing a series of convoluted steps to replicate the
issue, it will be immediately apparent that simply implementing your regression
test before fixing the bug will let you automate the testing for bug
resolution in an efficient manner.
To implement your regression test, you should follow the naming convention of
regression<TicketID> for your test functions. If no trac ticket exists for the
regression, you should create one first. Using this approach allows the person
running a failed regression test easily go and find out more information.
//
// Regression Testing
//
/** This is our second test case...to check if a raster
reports its dimensions properly. It is a regression test
for ticket #832 which was fixed with change r7650.
*/
void regression832();
// more regression tests go here ...