CKANdocumentation,Release2.6.0a
Example:
class TestSomethingWithResourceViews(object):
@classmethod
def setup_class(cls):
if not p.plugin_loaded('image_view'):
p.load('image_view')
@classmethod
def teardown_class(cls):
p.unload('image_view')
classckan.tests.factories.Sysadmin
Afactoryclassforcreatingsysadminusers.
classckan.tests.factories.Group
AfactoryclassforcreatingCKANgroups.
classckan.tests.factories.Organization
AfactoryclassforcreatingCKANorganizations.
classckan.tests.factories.Dataset
AfactoryclassforcreatingCKANdatasets.
classckan.tests.factories.MockUser
AfactoryclassforcreatingmockCKANusersusingthemocklibrary.
FACTORY_FOR
aliasofMagicMock
classckan.tests.factories.SystemInfo
AfactoryclassforcreatingSystemInfoobjects(configobjectsstoredintheDB).
ckan.tests.factories.validator_data_dict()
Returnadatadictwithsomearbitrarydatainit,suitabletobepassedtovalidatorfunctionsfortesting.
ckan.tests.factories.validator_errors_dict()
Returnanerrorsdictwithsomearbitraryerrorsinit,suitabletobepassedtovalidatorfunctionsfortesting.
classckan.tests.factories.Vocabulary
Afactoryclassforcreatingtagvocabularies.
Testhelperfunctions:ckan.tests.helpers
Thisisacollectionofhelperfunctionsforuseintests.
Wewanttoavoidsharingtesthelperfunctionsbetweentestmodulesasmuchaspossible,andwedefinitelydon’twant
tosharetestfixturesbetweentestmodules,ortointroduceacomplexhierarchyoftestclasssubclasses,etc.
Wewanttoreducetheamountof“travel”thatareaderneedstoundertaketounderstandatestmethod–reducingthe
numberofotherfilestheyneedtogoandreadtounderstandwhatthetestcodedoes. Andwewanttoavoidtightly
couplingtestmodulestoeachotherbyhavingthemsharecode.
Butsometesthelperfunctionsjustincreasethereadabilityoftestssomuchandmakewritingtestssomucheasier,
thatit’sworthhavingthemdespitethepotentialdrawbacks.
Thismoduleisreservedfortheseveryusefulfunctions.
ckan.tests.helpers.reset_db()
ResetCKAN’sdatabase.
7.15. Testingcodingstandards
325
Pdf to ppt - C# Create PDF from PowerPoint Library to convert pptx, ppt to PDF in C#.net, ASP.NET MVC, WinForms, WPF
Online C# Tutorial for Creating PDF from Microsoft PowerPoint Presentation
how to convert pdf to ppt using; convert pdf file to powerpoint presentation
Pdf to ppt - VB.NET Create PDF from PowerPoint Library to convert pptx, ppt to PDF in vb.net, ASP.NET MVC, WinForms, WPF
VB.NET Tutorial for Export PDF file from Microsoft Office PowerPoint
convert pdf file to ppt online; how to convert pdf to powerpoint slides
CKANdocumentation,Release2.6.0a
Ifatestclassusesthedatabase,thenitshouldcallthisfunctioninitssetup()methodtomakesurethatithas
acleandatabasetostartwith(nothingleftoverfromothertestclassesorfromprevioustestruns).
Ifatestclassdoesn’tusethedatabase(andmosttestclassesshouldn’tneedto)thenitdoesn’tneedtocallthis
function.
Returns None
ckan.tests.helpers.call_action(action_name,context=None,**kwargs)
Callthenamedckan.logic.actionfunctionandreturntheresult.
Thisisjustanicerwayforusercodetocallactionfunctions,nicerthaneithercallingtheactionfunctiondirectly
orviackan.logic.get_action().
Forexample:
user_dict call_action('user_create', name='seanh',
email='seanh@seanh.com', password='pass')
Anykeywordargumentsgivenwillbewrappedinadictandpassedtotheactionfunctionasitsdata_dict
argument.
Note: thisskipsauthorization! ! Itpasses‘ignore_auth’: : Truetoactionfunctionsintheircontextdicts,so
thecorrespondingauthorizationfunctionswillnotberun. Thisisbecauseckan.tests.logic.actiontestsonlythe
actions,theauthorizationfunctionsaretestedseparatelyinckan.tests.logic.auth. Seethetestingguidelinesfor
moreinfo.
This function n should d eventually be e moved d to o ckan.logic.call_action() and d the current
ckan.logic.get_action()functionshouldbedeprecated. Thetestsmaystillneedtheirownwrapper
functionforckan.logic.call_action(),e.g.toinsert’ignore_auth’: Trueintothecontext
dict.
Parameters
• action_name(string)–thenameoftheactionfunctiontocall,e.g.’user_update’
• context(dict)–thecontextdicttopasstotheactionfunction(optional,ifnocontextis
givenadefaultonewillbesupplied)
Returns thedictorothervaluethattheactionfunctionreturns
ckan.tests.helpers.call_auth(auth_name,context,**kwargs)
Callthenamedckan.logic.authfunctionandreturntheresult.
Thisisjustaconveniencefunctionfortestsinckan.tests.logic.authtouse.
Usage:
result helpers.call_auth('user_update', context=context,
id='some_user_id',
name='updated_user_name')
Parameters
• auth_name(string)–thenameoftheauthfunctiontocall,e.g.’user_update’
• context t (dict) – – the context t dict t to pass to o the e auth h function, , must t con-
tain ’user’ ’ and d ’model’ ’ keys, , e.g.
{’user’:
’fred’, ’model’:
my_mock_model_object}
Returns thedictthattheauthfunctionreturns,e.g. . {’success’:
True}or{’success’:
False, msg:
’...’}orjust{’success’:
False}
Returntype dict
326
Chapter7. Contributingguide
Online Convert PowerPoint to PDF file. Best free online export
Creating a PDF from PPTX/PPT has never been so easy! Web Security. Your PDF and PPTX/PPT files will be deleted from our servers an hour after the conversion.
convert pdf file to powerpoint online; pdf into powerpoint
How to C#: Convert PDF, Excel, PPT to Word
How to C#: Convert PDF, Excel, PPT to Word. Online C# Tutorial for Converting PDF, MS-Excel, MS-PPT to Word. PDF, MS-Excel, MS-PPT to Word Conversion Overview.
add pdf to powerpoint presentation; how to convert pdf to ppt
CKANdocumentation,Release2.6.0a
classckan.tests.helpers.FunctionalTestBase
Abaseclassforfunctionaltestclassestoinheritfrom.
Allowsconfigurationchangesbyoverriding_apply_config_changesandresettingtheCKANconfigafteryour
testclasshasrun. Itcreatesawebtest.TestAppatself.appforyourclasstousetomakeHTTPrequeststothe
CKANwebUIorAPI.
Ifyou’reoverridingmethodsthatthisclassprovides,likesetup_class()andteardown_class(),makesuretouse
super()tocallthisclass’smethodsatthetopofyours!
setup()
Resetthedatabaseandclearthesearchindexes.
ckan.tests.helpers.submit_and_follow(app,
form,
extra_environ=None,
name=None,
value=None,**args)
Callwebtest_submitwithname/valuepassedexpectingaredirectandreturntheresponsefromfollowingthat
redirect.
ckan.tests.helpers.webtest_submit(form,name=None,index=None,value=None,**args)
backportedversionofwebtest.Form.submitthatactuallyworksforsubmittingwithdifferentsubmitbuttons.
We’restuckonanoldversionofwebtestbecausewe’restuckonanoldversionofwebobbecausewe’restuck
onanoldversionofPylons. Thisprolongsoursuffering,butonthebrightsideitletsushavefunctionaltests
thatwork.
ckan.tests.helpers.webtest_submit_fields(form,
name=None,
index=None,
sub-
mit_value=None)
backportedversionofwebtest.Form.submit_fieldsthatactuallyworksforsubmittingwithdifferentsubmitbut-
tons.
ckan.tests.helpers.webtest_maybe_follow(response,**kw)
Followallredirects.Ifthisresponseisnotaredirect,donothing.Returnsanotherresponseobject.
(backportedfromWebTest2.0.1)
ckan.tests.helpers.change_config(key,value)
DecoratortotemporarilychangesPylons’configtoanewvalue
Thisallowsyoutoeasilycreateteststhatneedspecificconfigvaluestobeset,makingsureit’llberevertedto
whatitwasoriginally,afteryourtestisrun.
Usage:
@helpers.change_config('ckan.site_title''My Test CKAN')
def test_ckan_site_title(self):
assert pylons.config['ckan.site_title'== 'My Test CKAN'
Parameters
• key(string)–theconfigkeytobechanged,e.g.’ckan.site_title’
• value(string)–thenewconfigkey’svalue,e.g.’My y Test CKAN’
ckan.tests.helpers.mock_action(action_name)
DecoratortoeasilymockaCKANactioninthecontextofatestfunction
Itaddsamockobjectfortheprovidedactionasaparametertothetestfunction.Themockisdiscardedatthe
endofthefunction,evenifthereisanexceptionraised.
Note that this mocks the action bothwhenit’s called directlyviackan.logic.get_action and via
ckan.plugins.toolkit.get_action.
Usage:
7.15. Testingcodingstandards
327
C# PDF Convert: How to Convert MS PPT to Adobe PDF Document
C# PDF Convert: How to Convert MS PPT to Adobe PDF Document. Provide Free Demo Code for PDF Conversion from Microsoft PowerPoint in C# Program.
how to change pdf to powerpoint format; copying image from pdf to powerpoint
How to C#: Convert Word, Excel and PPT to PDF
How to C#: Convert Word, Excel and PPT to PDF. Online C# Tutorial for Converting MS Office Word, Excel and PowerPoint to PDF. How to C#: Convert PPT to PDF.
how to convert pdf file to powerpoint presentation; how to convert pdf into powerpoint slides
CKANdocumentation,Release2.6.0a
@mock_action('user_list')
def test_mock_user_list(self, mock_user_list):
mock_user_list.return_value 'hi'
# user_list is mocked
eq_(helpers.call_action('user_list', {}), 'hi')
assert mock_user_list.called
Parameters action_name(string)–thenameoftheactiontobemocked,e.g.package_create
ckan.tests.helpers.set_extra_environ(key,value)
Decoratortotemporarilychangesasinglerequestenvironemntvalue
Createanewtestappandusetheasideeffectofmakingarequesttosetanextra_environvalue.Resetthevalue
to‘’afterthetest.
Usage:
@helpers.extra_environ('SCRIPT_NAME', '/myscript')
def test_ckan_thing_affected_by_script_name(self):
# ...
Parameters
• key(string)–theextra_environkeytobechanged,e.g.’SCRIPT_NAME’
• value(string)–thenewextra_environkey’svalue,e.g.’/myscript’
Mocking:themocklibrary
WeusethemocklibrarytoreplacepartsofCKANwithmockobjects. ThisallowsaCKANfunctiontobetested
independentlyofotherpartsofCKANorthird-partylibrariesthatthefunctionuses. Thisgenerallymakesthetest
simplerandfaster(especiallywhenckan.modelismockedoutsothatthetestsdon’ttouchthedatabase). With
mockobjectswecanalsomakeassertionsaboutwhatmethodsthefunctioncalledonthemockobjectandwithwhich
arguments.
Note: Overuseofmockingisdiscouragedasitcanmaketestsdifficulttounderstandandmaintain.Mockingcanbe
usefulandmaketestsbothfasterandsimplerwhenusedappropriately.Somerulesofthumb:
• Don’tmockoutmorethanoneortwoobjectsinasingletestmethod.
• Don’t t use mocking in n more functional-style e tests.
For example e the e action function n tests in
ckan.tests.logic.actionand the frontend tests s in ckan.tests.controllers are functional
tests,andprobablyshouldn’tdoanymocking.
• Do o use mocking in more unit-style tests.
For example the e authorization function n tests in
ckan.tests.logic.auth,theconverterandvalidatortestsinckan.tests.logic.auth,andmost
(all?)libtestsinckan.tests.libareunittestsandshouldusemockingwhennecessary(oftenit’spossible
tounittestamethodinisolationfromotherCKANcodewithoutdoinganymocking,whichisideal).
Inthesekindoftestswecanoftenmockoneortwoobjectsinasimpleandeasytounderstandway,andmake
thetestbothsimplerandfaster.
Amockobjectisaspecialobjectthatallowsusercodetoaccessanyattributenameorcallanymethodname(andpass
anyparameters)ontheobject,andthecodewillalwaysgetanothermockobjectback:
328
Chapter7. Contributingguide
VB.NET PowerPoint: Process & Manipulate PPT (.pptx) Slide(s)
VB.NET PowerPoint processing control add-on can do PPT creating, loading We are dedicated to provide powerful & profession imaging controls, PDF document, image
convert pdf file into ppt; how to change pdf file to powerpoint
C# TIFF: Learn to Convert MS Word, Excel, and PPT to TIFF Image
C# TIFF - Conversion from Word, Excel, PPT to TIFF. Learn How to Change Load your PPT (.pptx) document. PPTXDocument doc = new PPTXDocument
how to convert pdf into powerpoint; pdf conversion to powerpoint
CKANdocumentation,Release2.6.0a
>>> import mock
>>> my_mock mock.MagicMock()
>>> my_mock.foo
<MagicMock name='mock.foo' ' id='56032400'>
>>> my_mock.bar
<MagicMock name='mock.bar' ' id='54093968'>
>>> my_mock.foobar()
<MagicMock name='mock.foobar()' ' id='54115664'>
>>> my_mock.foobar(12'barfoo')
<MagicMock name='mock.foobar()' ' id='54115664'>
Whenatestneedsamockobjecttoactuallyhavesomebehaviorbesidesalwaysreturningothermockobjects,itcan
setthevalueofacertainattributeonthemockobject,setthereturnvalueofacertainmethod,specifythatacertain
methodshouldraiseacertainexception,etc.
Youshouldreadthemocklibrary’sdocumentationtoreallyunderstandwhat’sgoingon,buthere’sanexampleof
atestfromckan.tests.logic.auth.test_updatethatteststheuser_update()authorizationfunction
andmocksoutckan.model:
def test_user_update_user_cannot_update_another_user(self):
'''Users should not be able to o update e other users' accounts.'''
# 1. . Setup.
# Make a a mock k ckan.model.User object, , Fred.
fred factories.MockUser(name='fred')
# Make a a mock k ckan.model object.
mock_model mock.MagicMock()
# model.User.get(user_id) ) should return Fred.
mock_model.User.get.return_value fred
# Put t the mock model in n the e context.
# This is s easier than patching g import t ckan.model.
context {'model': mock_model}
# The e logged-in user is s going to o be e Bob, , not Fred.
context['user''bob'
# 2. . Call the e function n that's s being tested, , once only.
# Make Bob b try to o update Fred's s user r account.
params {
'id': fred.id,
'name''updated_user_name',
}
# 3. . Make assertions about the e return n value and/or side-effects.
nose.tools.assert_raises(logic.NotAuthorized, helpers.call_auth,
'user_update', context=context,
**
params)
# 4. . Do o nothing g else!
ThefollowingsectionswillgivespecificguidelinesandexamplesforwritingtestsforeachmoduleinCKAN.
Note: Whenwesaythatallfunctionsshouldhavetestsinthesectionsbelow,wemeanallpublicfunctionsthatthe
7.15. Testingcodingstandards
329
VB.NET PowerPoint: Convert & Render PPT into PDF Document
VB.NET PowerPoint - Render PPT to PDF in VB.NET. What VB.NET demo code can I use for fast PPT (.pptx) to PDF conversion in .NET class application?
pdf to ppt converter online; how to change pdf to powerpoint
VB.NET PowerPoint: Read & Scan Barcode Image from PPT Slide
VB.NET PPT PDF-417 barcode scanning SDK to detect PDF-417 barcode image from PowerPoint slide. VB.NET APIs to detect and decode
converter pdf to powerpoint; convert pdf pages into powerpoint slides
CKANdocumentation,Release2.6.0a
moduleorclassexportsforusebyothermodulesorclassesinCKANorbyextensionsortemplates.
Privatehelpermethods(withnamesbeginningwith_)neverhavetohavetheirowntests,althoughtheycanhavetests
ifhelpful.
Writingckan.logic.actiontests
Allactionfunctionsshouldhavetests.
Mostactionfunctiontestswillbehigh-levelteststhatbothtestthecodeintheactionfunctionitself,andalsoindirectly
testthecodeinckan.lib,ckan.model,ckan.logic.schemaetc.thattheactionfunctioncalls.Thismeans
thatmostactionfunctiontestsshouldnotusemocking.
Testsforactionfunctionsshouldusetheckan.tests.helpers.call_action()functiontocalltheaction
functions.
One thing call_action() does is toadd ignore_auth:
True intothe context dictthat’s passed to
the action function, , so that CKAN willnotcall the e actionfunction’s s authorization function. . The e tests foran
action function don’t need to cover authorization, , because e the authorization functions s have their own n tests s in
ckan.tests.logic.auth.Butactionfunctiontestsdoneedtocovervalidation,moreonthatlater.
Actionfunctiontestsshouldtestthelogicoftheactionsthemselves,andshouldtestvalidation(e.g.thatvariouskinds
ofvalidinputworkasexpected,andinvalidinputsraisetheexpectedexceptions).
Here’sanexampleofasimpleckan.logic.actiontest:
def test_user_update_name(self):
'''Test that updating g a a user's name works successfully.'''
# The e canonical form of f a a test t has s four steps:
# 1. . Setup any preconditions needed d for r the test.
# 2. . Call the e function n that's s being tested, , once only.
# 3. . Make assertions about the e return n value and/or side-effects of
#
of the e function that's being tested.
# 4. . Do o nothing g else!
# 1. . Setup.
user factories.User()
# 2. . Call the e function n that's s being tested, , once only.
# FIXME we e have to o pass the e email address s and d password to user_update
# even though we're e not t updating g those fields, , otherwise e validation
# fails.
helpers.call_action('user_update'id=user['name'],
email=user['email'],
password=factories.User.attributes()['password'],
name='updated',
)
# 3. . Make assertions about the e return n value and/or side-effects.
updated_user helpers.call_action('user_show'id=user['id'])
# Note that t we check just the e field we e were trying to o update, , not t the
# entire e dict, only assert what we're actually y testing.
assert updated_user['name'== 'updated'
# 4. . Do o nothing g else!
Todo
330
Chapter7. Contributingguide
CKANdocumentation,Release2.6.0a
Insertthenamesofalltestsforckan.logic.action.update.user_update,forexample,toshowwhatlevel
ofdetailthingsshouldbetestedin.
Writingckan.logic.authtests
Allauthfunctionsshouldhavetests.
Mostauthfunctiontestsshouldbeunitteststhattesttheauthfunctioninisolation,withoutbringinginotherparts
ofCKANortouchingthedatabase. Thisrequiresusingthemocklibrarytomockckan.model,seeMocking:the
mocklibrary.
Testsforauthfunctionsshouldusetheckan.tests.helpers.call_auth()functiontocallauthfunctions.
Here’sanexampleofasimpleckan.logic.authtest:
def test_user_update_user_cannot_update_another_user(self):
'''Users should not be able to o update e other users' accounts.'''
# 1. . Setup.
# Make a a mock k ckan.model.User object, , Fred.
fred factories.MockUser(name='fred')
# Make a a mock k ckan.model object.
mock_model mock.MagicMock()
# model.User.get(user_id) ) should return Fred.
mock_model.User.get.return_value fred
# Put t the mock model in n the e context.
# This is s easier than patching g import t ckan.model.
context {'model': mock_model}
# The e logged-in user is s going to o be e Bob, , not Fred.
context['user''bob'
# 2. . Call the e function n that's s being tested, , once only.
# Make Bob b try to o update Fred's s user r account.
params {
'id': fred.id,
'name''updated_user_name',
}
# 3. . Make assertions about the e return n value and/or side-effects.
nose.tools.assert_raises(logic.NotAuthorized, helpers.call_auth,
'user_update', context=context,
**
params)
# 4. . Do o nothing g else!
Writingconverterandvalidatortests
Allconverterandvalidatorfunctionsshouldhaveunittests.
Althoughtheseconverterandvalidatorfunctionsaretestedindirectlybytheactionfunctiontests,thismaynotcatch
alltheconvertersandvalidatorsandalltheiroptions,andconvertersandvalidatorsarenotonlyusedbytheaction
7.15. Testingcodingstandards
331
CKANdocumentation,Release2.6.0a
functionsbutarealsoavailabletoplugins. Havingunittestswillalsohelptoclarifytheintendedbehaviorofeach
converterandvalidator.
CKAN’s actionfunctions callckan.lib.navl.dictization_functions.validate()tovalidatedata
postedbytheuser. Eachactionfunctionpassesaschemafromckan.logic.schematovalidate(). . The
schemagives validate() lists ofvalidationandconversionfunctionstoapplytotheuserdata. . These e vali-
dationandconversionfunctionsaredefinedinckan.logic.validators,ckan.logic.convertersand
ckan.lib.navl.validators.
Mostvalidatorandconvertertestsshouldbeunitteststhattestthevalidatororconverterfunctioninisolation,with-
out bringinginotherparts ofCKANortouchingthe database. . This s requires using g the mocklibrarytomock
ckan.model,seeMocking:themocklibrary.
When testing validators, we often want to make e the e same e assertions s in n many tests: : assert t that the valida-
tor didn’t modify the data dict, , assert t that the e validator r didn’t modify the errors dict, , assert t that t the
validator raised d Invalid, , etc. . Decorator r functions s are defined at the e top of validator test t modules like
ckan.tests.logic.test_validatorstomakethesecommonassertseasy. Touseoneofthesedecorators
youhaveto:
1. Defineanestedfunctioninsideyourtestmethod,thatsimplycallsthevalidatorfunctionthatyou’retryingto
test.
2. Applythedecoratorsthatyouwanttothisnestedfunction.
3. Callthenestedfunction.
Here’sanexampleofasimplevalidatortestthatusesthistechnique:
def test_user_name_validator_with_non_string_value(self):
'''user_name_validator() should d raise Invalid if given a non-string
value.
'''
non_string_values [
13,
23.7,
100L,
1.0j,
None,
True,
False,
('a'2False),
[13NoneTrue],
{'foo''bar'},
lambda x: x
**
2,
]
# Mock ckan.model.
mock_model mock.MagicMock()
# model.User.get(some_user_id) needs to o return n None e for this test.
mock_model.User.get.return_value None
key ('name',)
for non_string_value in non_string_values:
data factories.validator_data_dict()
data[key] non_string_value
errors factories.validator_errors_dict()
errors[key] []
@t.does_not_modify_data_dict
332
Chapter7. Contributingguide
CKANdocumentation,Release2.6.0a
@raises_Invalid
def call_validator(
*
args,
**
kwargs):
return validators.user_name_validator(
*
args,
**
kwargs)
call_validator(key, data, errors, , context={'model': mock_model})
Notestsforckan.logic.schema.py
Wedon’twritetestsfortheschemasdefinedinckan.logic.schema. Thevalidationdonebytheschemasis
insteadtestedindirectlybytheactionfunctiontests. ThereasonforthisisthatCKANactuallydoesvalidationin
multipleplaces:somevalidationisdoneusingschemas,somevalidationisdoneintheactionfunctionsthemselves,
someisdoneindictization,andsomeinthemodel. Bytestingallthedifferentvalidandinvalidinputsattheaction
functionlevel,wecatchitallinoneplace.
Writingckan.controllerstests
Controllertestsprobablyshouldn’tusemocking.
Todo
Writethetestsforonecontroller,figuringoutthebestwaytowritecontrollertests.Thenfillinthisguidelinessection,
usingthefirstsetofcontrollertestsasanexample.
Somethingshavebeendecidedalready:
• Allcontrollermethodsshouldhavetests
• Controllertestsshouldbehigh-levelteststhatworkbypostingsimulatedHTTPrequeststoCKANURLsand
testingtheresponse.SothecontrollertestsarealsotestingCKAN’stemplatesandrendering-theseareCKAN’s
front-endtests.
Forexample,maybeweuseawebteststestappandthenusebeautifulsouptoparsetheHTML?
• Ingeneralthetestsforacontrollershouldn’tneedtobetoodetailed,becausethereshouldn’tbealotofcompli-
catedlogicandcodeincontrollerclasses. Thelogicshouldbehandledinotherplacessuchasckan.logic
andckan.lib,whereitcanbetestedeasilyandalsosharedwithothercode.
• Thetestsforacontrollershould:
– Makesurethatthetemplaterenderswithoutcrashing.
– Testthatthepagecontentsseembasicallycorrect,ortestcertainimportantelementsinthepagecontents
(butdon’tdotoomuchHTMLparsing).
– Testthatsubmittinganyformsonthepageworkswithoutcrashingandhastheexpectedside-effects.
– When n asserting side-effects after r submitting g a a form, , controller r tests s should d user the
ckan.tests.helpers.call_action() function. For r example after creating a a new w user by
submittingthenewuserform,atestcouldcalltheuser_show()actionfunctiontoverifythattheuser
wascreatedwiththecorrectvalues.
Warning: SomeCKANcontrollersdocontainalotofcomplicatedlogiccode. . Thesecontrollersshouldbe
refactoredtomovethelogicintockan.logicorckan.libwhereitcanbetestedeasily. Unfortunatelyin
caseslikethisitmaybenecessarytowritealotofcontrollerteststogetthiscode’sbehaviorintoatestharness
beforeitcanbesafelyrefactored.
7.15. Testingcodingstandards
333
CKANdocumentation,Release2.6.0a
Writingckan.modeltests
Allmodelmethodsshouldhavetests.
Todo
Writethetestsforoneckan.modelmodule,figuringoutthebestwaytowritemodeltests.Thenfillinthisguidelines
section,usingthefirstsetofmodeltestsasanexample.
Writingckan.libtests
Alllibfunctionsshouldhavetests.
Todo
Writethetestsforoneckan.libmodule,figuringoutthebestwaytowritelibtests. Thenfillinthisguidelines
section,usingthefirst
Weprobablywanttomaketheseunittestsratherthanhigh-leveltestsandmockoutckan.model,sothetestsare
reallyfastandsimple.
Notethatsomethingsinlibareparticularlyimportant,e.g.thefunctionsinckan.lib.helpersareexportedfor
templates(includingextensions)touse,soallofthesefunctionsshouldreallyhavetestsanddocstrings.It’sprobably
worthfocusingonthesemodulesfirst.
Writingckan.pluginstests
Theplugininterfacesinckan.plugins.interfacesarenotdirectlytestablebecausetheydon’tcontainany
code,but:
• Eachplugininterfaceshouldhaveanexampleplugininckan.ckanextandtheexamplepluginshouldhave
itsownfunctionaltests.
• Thetestsforthecodethatcallstheplugininterfacemethodsshouldtestthatthemethodsarecalledcorrectly.
Forexampleckan.logic.action.get.package_show()callsckan.plugins.interfaces.IDatasetForm.read(),
sothepackage_show()testsshouldincludetests thatread()iscalledattherighttimesandwiththeright
parameters.
Everythinginckan.plugins.toolkitshouldhavetests,becausethesefunctionsarepartoftheAPIforexten-
sionstouse.ButtoolkitimportsmostofthesefunctionsfromelsewhereinCKAN,sothetestsshouldbeelsewhere
also,inthetestmodulesforthemoduleswherethefunctionsaredefined.
Otherthantheplugininterfacesandpluginstoolkit,anyothercodeinckan.pluginsshouldhavetests.
Writingckan.migrationtests
Allmigrationscriptsshouldhavetests.
Todo
Writesometestsforamigrationscript,andthenusethemasanexampletofilloutthisguidelinessection.
334
Chapter7. Contributingguide
Documents you may be interested
Documents you may be interested