id
int64
0
25.6k
text
stringlengths
0
4.59k
19,200
pytest testing framework setting up pytest you will probably need to set up pytest so that you can use it from within your environment if you are using the pycharm editorthen you will need to add the pytest module to the current pycharm project and tell pycharm that you want to use pytest to run all tests for you simpl...
19,201
simple pytest example the exact import statement will depend on where you placed the calculator file relative to the test class in this case the two files are both in the same directory and so we can writefrom calculator import calculator we will now define testthe test should be pre-fixed with test_ for pytest to find...
19,202
pytest testing framework editor this can be seen in the following picture where green arrow has been added at line this is the 'run testbuttonthe developer can click on the green arrow to run the test they will then be presented with the run menu that is preconfigured to use pytest for youif the developer now selects t...
19,203
working with pytest working with pytest testing functions we can test standalone functions as well as classes using pytest for examplegiven the function increment below (which merely adds one to any number passed into it)def increment( )return we can write pytest test for this as followsdef test_increment_integer_ ()as...
19,204
pytest testing framework pytest will recursively search down into sub directoriesunless they match norecursedirs environment variable in those directoriesit will search for files that match the naming conventions test_py or *_test py files tests can also be arranged within test files into test classes using test classe...
19,205
working with pytest we now have four tests to run (we could go further but this is enough for nowone of the issues with this set of tests is that we have repeated the creation of the calculator object at the start of each test while this is not problem in itself it does result in duplicated code and the possibility of ...
19,206
pytest testing framework in the above codeeach of the test functions accepts the calculator fixture that is used to instantiate the calculator object we have therefore de-duplicated our codethere is now only one piece of code that defines how calculator object should be created for our tests note each test is supplied ...
19,207
working with pytest def test_initial_value(calculator)assert calculator total = def test_add_one(calculator)calculator set( calculator add(assert calculator total = def test_subtract_one(calculator)calculator set( calculator sub(assert calculator total =- def test_add_one_and_one(calculator)calculator set( calculator a...
19,208
pytest testing framework @pytest mark parametrize decorator @pytest mark parametrize('input ,input ,expected'( )( )]def test_calculator_add_operation(calculatorinput input ,expected)calculator set(input calculator add(calculator set(input calculator add(assert calculator total =expected this illustrates setting up para...
19,209
parameterised tests one way to address this problem is to decorate test with the @pytest mark skip decorator@pytest mark skip(reason='not implemented yet'def test_calculator_multiply(calculator)calculator multiply( assert calculator total = this indicates that pytest should record the presence of the test but should no...
19,210
pytest testing framework this will be purely command driven application that will allow the user to specify the operation to perform and the two numbers to use with that operation the calculator object will then return result the same object can be used to repeat this sequence of steps this general behaviour of the cal...
19,211
mocking for testing introduction testing software systems is not an easy thing to dothe functionsobjectsmethods etc that are involved in any program can be complex things in their own right in many cases they depend on and interact with other functionsmethods and objectsvery few functions and methods operate in isolati...
19,212
mocking for testing it may now be necessary to verify data updates made to the databaseor information sent to remote service etc to confirm that the operation of class' object is correct this makes not only the software being tested more complex but it also makes the tests themselves more complex this means that there ...
19,213
why mock testing in isolation is easier as mentioned in the introductiontesting unit (whether that is classa functiona module etc is easier in isolation then when dependent on external classesfunctionsmodules etc the real thing is not available in many cases it is necessary to mock out part of system or an interface to...
19,214
mocking for testing happen if the data provided by systems that test depends on do not supply repeatable data this can happen for several different reason but common cause is because they return real data such real data may be subject to changefor example consider system that uses data feed for the current exchange rat...
19,215
what is mocking the are different types of mock includingtest stubs test stub is typically hand coded functionmethod or object used for testing purposes the behaviour implemented by test stub may represent limited sub set of the functionality of the real thing fakes fakes typically provide addition functionality compar...
19,216
mocking for testing assertions can then be used to verify the results returned by the unit under test while mock specific methods are typically used to verify (spy onthe methods defined on the mock mocking frameworks for python due to python' dynamic nature it is well suited to the construction of mock functionsmethods...
19,217
the unittest mock library mock and magic mock classes the unittest mock library provides the mock class and the magicmock class the mock class is the base class for mock objects the magicmock class is subclass of the mock class it is called the magicmock class as it provides default implementations for several magic me...
19,218
mocking for testing in this case note that the class being tested is instantiated first the magicmock is then instantiated and assigned to the name of the method to be mocked this in effect replaces that method for the test_object the magicmock the magicmock object is given name as this helps with treating any issues i...
19,219
the unittest mock library class test_someclass_public_interface(testcase)@patch object(someclass'_hidden_method'def test_public_method(selfmock_method)set up canned response mock_method return_value create object to be tested test_object someclass(result test_object public_method( self assertequal( result'return value ...
19,220
mocking for testing import external_module from unittest mock import from unittest import testcase from unittest import main import json def some_func()calls out to external api which we want to mock response external_module api_call(return responseclass test_some_func_calling_api(testcase)class test_some_func_calling_...
19,221
the unittest mock library the following version of the test_some_func_with_params(test method verifies that the mock api_call(function was called with the correct parameter @patch('external_module api_call_with_param'def test_some_func_with_param(selfmock_api_call)sets up mock version of api_call mock_api_call return_v...
19,222
mocking for testing import people from unittest mock import from unittest import testcase from unittest import main class mytest(testcase)@patch('people person'def test_one(selfmockperson)self assertis(people personmockpersoninstance mockperson return_value instance calculate_pay return_value payroll people payroll(res...
19,223
mock and magicmock usage if the attribute itself needs to be mock object then all that is required is to assign magicmock (or mockobject to that attributeinstance address magicmock(name='address'mocking constants it is very easy to mock out constantthis can be done using the @patch(decorator and proving the name of the...
19,224
mocking for testing applying patch to every test method if you want to mock out something for every test in test class then you can decorate the whole class rather than each individual method the effect of decorating the class is that the patch will be automatically applied to all test methods in the class ( to all met...
19,225
mock and magicmock usage import people from unittest mock import from unittest import testcase from unittest import main class mytest(testcase)def test_one(self)with patch('people person'as mockpersonself assertis(people personmockpersoninstance mockperson return_value instance calculate_pay return_value payroll people...
19,226
mocking for testing notice that the last patch' mock is passed into the second parameter passed to the test_something(method (self is the first parameter to all methodsin turn the first patch' mock is passed into the last parameter thus the mocks are passed into the test method in the reverse order to that which they a...
19,227
mocking considerations decide what to mocktypical examples of what to mock include those elements that are not yet availablethose elements that are not by default repeatable (such as live data feedsor those elements of the system that are time consuming or complex decide where to mock such as the interfaces for the uni...
19,228
mocking for testing import random def create_suite(suite)return (isuitefor in range( )def pick_a_card(deck)print('you picked'position random randint( print(deck[position][ ]"of"deck[position][ ]return (deck[position]set up the data hearts create_suite('hearts'spades create_suite('spades'diamonds create_suite('diamonds'...
19,229
file input/output
19,230
introduction to filespaths and io introduction the operating system is critical part of any computer systems it is comprised of elements that manage the processes that run on the cpuhow memory is utilised and managedhow peripheral devices are used (such as printers and scanners)it allows the computer system to communic...
19,231
introduction to filespaths and io each file is contained within directory (also known as folder on some operating systems such as windowsa directory can hold zero or more files and zero or more directories for any give directory there are relationships with other directories as shown below for the directory jhuntthe ro...
19,232
file attributes file attributes file will have set of attributes associated with it such as the date that it was createdthe date it was last updated/modifiedhow large the file is etc it will also typically have an attribute indicating who the owner of the file is this may be the creator of the filehowever the ownership...
19,233
introduction to filespaths and io the first group of three characters this indicates that the user can read ' 'write 'wand execute 'xthe file however the next six characters are all dashes indicating that the group and all other users cannot access the file at all the group that file belongs to is group that can have a...
19,234
file attributes directories have similar attributes and access rights to files for examplethe following symbolic notation indicates that directory (indicated by the ' 'has read and execute permissions for the directory owner and for the group other users cannot access this directorythe permissions associated with file ...
19,235
introduction to filespaths and io for examplein the following diagramthe relative path pycharmprojectsfurtherpythonis only meaningful relative to the directory workspacesnote that an absolute path starts from the root directory (represented by '/'where as relative path starts from particular subdirectory (such as pycha...
19,236
file input/output (continueddecimal code character meaning lowercase lowercase lowercase lowercase ascii is very useful format to use for text files as they can be read by wide range of editors and browsers these editors and browsers make it very easy to create human readable files howeverprogramming languages such as ...
19,237
introduction to filespaths and io also known as direct access as the computer program needs to know where the data is stored within the file and thus goes directly to that location for the data in some cases the location of the data is recorded in an index and thus is also known as indexed access sequential file access...
19,238
reading and writing files introduction reading data from and writing data to file is very common within many programs python provides large amount of support for working with files of various types this introduces you to the core file io functionality in python obtaining references to files reading fromand writing tote...
19,239
reading and writing files buffering if the buffering value is set to no buffering takes place if the buffering value is line buffering is performed while accessing file the access_mode values are given in the following table mode description opens file for reading only the file pointer is placed at the beginning of the...
19,240
obtaining references to files may all be used up resulting in future errors being thrown as files can no longer be opened the following short code snippet illustrates the above ideasfile open('myfile txt'' +'print('file name:'file nameprint('file closed:'file closedprint('file mode:'file modefile close(print('file clos...
19,241
reading and writing files notice that within the for loop we have indicated to the print function that we want the end character to be rather than newlinethis is because the line string already possesses the newline character read from the file file contents iteration as suggested by the previous exampleit is very comm...
19,242
writing data to files this creates new file called my-new-file txt it then writes three strings to the file each with newline character on the endit then closes the file the effect of this is to create new file called myfile txt with three lines in it using files and with statements like several other types where it is...
19,243
reading and writing files features provided by the fileinput module include return the name of the file currently being read return the integer "file descriptorfor the current file return the cumulative line number of the line that has just been read return the line number in the current file before the first line has ...
19,244
random access files random access files all the examples presented so far suggest that files are accessed sequentiallywith the first line read before the second and so on although this is (probablythe most common approach it is not the only approach supported by pythonit is also possible to use random-access approach t...
19,245
reading and writing files indicates that the offset is relative to start of file (the default means that the offset is relative to the current pointer position indicates the offset is relative to end of file thuswe can move the pointer to position relative to the start of the fileto the end of the fileor to the current...
19,246
directories simple example illustrates the use of some of these functions is given belowimport os print('os getcwd(:'os getcwd()print('list contents of directory'print(os listdir()print('create mydir'os mkdir('mydir'print('list the updated contents of directory'print(os listdir()print('change into mydir directory'os ch...
19,247
reading and writing files temporary files during the execution of many applications it may be necessary to create temporary file that will be created at one point and deleted before the application finishes it is of course possible to manage such temporary files yourself howeverthe tempfile module provides range of fac...
19,248
temporary files temporary files it then creates temporaryfile object and prints its name and mode (the default mode is binary but for this example we have overwritten this so that plain text is usedwe have then written line to the file using seek we are repositioning ourselves at the start of the file and then reading ...
19,249
reading and writing files the path(constructor takes the path to create for example ' :/mydir(on windowsor '/users/user /mydiron mac or '/var/tempon linux etc you can then use several different methods on the path object to obtain information about the path such asexists(returns true of false depending on whether the p...
19,250
working with paths rename(targetrename this file or directory to the given target unlink(removes the file referenced by the path object joinpath(*otherappends elements to the path object path joinpath('temp'with_name(new_namereturn new path object with the name changed the '/operator can also be used to create new path...
19,251
reading and writing files note that '**/pywould indicate the current directory and any sub directory for examplethe following code will return all files where the file name ends with txtfor given pathprint('- for file in path glob('txt')print('file:'fileprint('- an example of the output generated by this code isfilemy-...
19,252
working with paths these are used below dir path(/test'print('create new file'newfile dir 'text txtprint('write some text to file'newfile write_text('hello python world!'print('read the text back again'print(newfile read_text()print('remove the file'newfile unlink(which generates the following outputcreate new file wri...
19,253
reading and writing files function to obtain the current date and time you can use the str(function to convert this date time object into string so that it can be written out to file create second program to reload the date from the file and convert the string into date object you can use the datetime strptime(function...
19,254
stream io introduction in this we will explore the stream / model that under pins the way in which data is read from and written to data sources and sinks one example of data source or sink is file but another might be byte array this model is actually what sits underneath the file access mechanisms discussed in the pr...
19,255
stream io in the above figure the initial fileio stream reads raw data from the actual data source (in this case filethe bufferedreader then buffers the data reading process for efficiency finally the textiowrapper handles string encodingthat is it converts strings from the typical ascii representation used in file int...
19,256
python streams the abstract iobase class is at the root of the stream io class hierarchy below this class are stream classes for unbuffered and buffered io and for text oriented io iobase this is the abstract base class for all / stream classes the class provides many abstract methods that subclasses will need to imple...
19,257
stream io seekable(does the stream support seek(tell(return the current stream position/pointer writeable(returns true if data can be written to the stream writelines(lineswrite list of lines to the stream raw io/unbuffered io classes raw io or unbuffered io is provided by the rawiobase and fileio classes rawiobase thi...
19,258
binary io/buffered io classes bufferedwriter when writing to this objectdata is normally placed into an internal buffer the buffer will be written out to the underlying rawiobase object under various conditionsincludingwhen the buffer gets too small for all pending datawhen flush(is calledwhen the bufferedwriter object...
19,259
stream io the operations supported by buffered writers includewrite(byteswrites the bytes-like data and returns the number of bytes written flush(this method forces the bytes held in the buffer into the raw stream text stream classes the text stream classes are the textiobase class and its two subclasses textiowrapper ...
19,260
text stream classes where buffer is the buffered binary stream encoding represents the text encoding used such as utf- errors defines the error handling policy such as strict or ignore newline controls how line endings are handled for example should they be ignored (noneor represented as linefeedcarriage return or newl...
19,261
stream io io fileio('myfile txt'br io bufferedreader(ftext_stream io textiowrapper(brencoding='utf- 'print('text_stream'text_streamprint('text_stream readable():'text_stream readable()print('text_stream seekable()'text_stream seekable()print('text_stream writeable()'text_stream writable()text_stream close(the output fr...
19,262
returning to the open(function import io text stream open('myfile txt'mode=' 'encoding='utf- 'print( binary io aka buffered io open('myfile dat'mode='rb'print( open('myfile dat'mode='wb'print( raw io aka unbufferedf io open('starship png'mode='rb'buffering= print( when this short example is run the output isas you can ...
19,263
stream io note that not all mode combinations make sense and thus some combinations will generate an error in general you don' therefore need to worry about which stream you are using or what that stream doesnot least because all the streams extend the iobase class and thus have common set of methods and attributes how...
19,264
working with csv files introduction this introduces module that supports the generation of csv (or comma separated valuesfiles csv files the csv (comma separated valuesformat is the most common import and export format for spreadsheets and databases howevercsv is not precise standard with multiple different application...
19,265
working with csv files csv writer (csvfiledialect='excel'**fmtparamsreturns writer object responsible for converting the user' data into delimited strings on the given csvfile an optional dialect parameter provided the fmtparams keyword arguments can be given to override individual formatting parameters in the current ...
19,266
csv files howeveras it is csv filewe can also open it in excelthe csv reader class csv reader object is obtained from the csv reader(function it implements the iteration protocol if csv reader object is used with for loop then each time round the loop it supplies the next row from the csv file as listparsed according t...
19,267
working with csv files the output from this programbased on the sample csv file created earlier isstarting to read csv file she loves yousept want to hold your handdec cant buy me loveapr hard days nightjuly done reading the csv dictwriter class in many cases the first row of csv file contains set of names (or keysthat...
19,268
csv files the csv dictreader class as well as the csv dictwriter there is csv dictreader the file to be used with the dictreader is provided when the class is instantiated as with the dictreader the dictwriter class takes list of keys used to define the columns in the csv file if the headings to be used for the first r...
19,269
working with csv files this generates the following outputstarting to read dict csv example first_name last_name result john smith jane lewis chris davies done online resources see the following online resources for information on the topics in this on csv files reading csv files exercises in this exercise you will cre...
19,270
exercises the history could be implemented as list containing an ordered sequence to transactions transaction itself could be defined by class with an action (deposit or withdrawaland an amount each time withdrawal or deposit is made new transaction record should be added to transaction history list next provide functi...
19,271
working with excel files introduction this introduces the openpyxl module that can be used when working with excel files excel is software application developed by microsoft that allows users to work with spreadsheets it is very widely used tool and files using the excel file format are commonly encountered within many...
19,272
working with excel files the openpyxl workbook class the key element in the openpyxl library is the workbook class this can be imported from the modulefrom openpyxl import workbook new instance of the (in memoryworkbook can be created using the workbook class (note at this point it is purely structure within the python...
19,273
working with cells or cell ws[' 'this returns cell objectyou can obtain the value of the cell using the value propertyfor example print(cell valuethere is also the worksheet cell(method this provides access to cells using row and column notationd ws cell(row= column= value= row of values can also be added at the curren...
19,274
working with excel files from openpyxl import workbook def main()print('starting write excel example with openpyxl'workbook workbook(get the current active worksheet ws workbook active ws title 'my worksheetws sheet_properties tabcolor ' baws[' ' ws[' ' ws[' ''=sum( )ws workbook create_sheet(title='my other sheet'ws ['...
19,275
loading workbook from an excel file loading workbook from an excel file of coursein many cases it is necessary not just to create excel files for data export but also to import data from an existing excel file this can be done using the openpyxl load_workbook(function this function opens the specified excel file (in re...
19,276
working with excel files print('finished reading excel file using openpyxl'if __name__ ='__main__'main(the output from this application is illustrated belowstarting reading excel file using openpyxl ['my worksheet''my other sheet'[ =sum( my worksheet my other sheet =sum( finished reading excel file using openpyxl onlin...
19,277
exercises the following sample application illustrates how this function might be usedprint('starting'acc accounts currentaccount(' ''john' acc deposit( acc withdraw( print('writing account transactions'write_account_transaction_to_excel('accounts xlsx'accprint('done'the contents of the excel file would then be
19,278
regular expressions in python introduction regular expression are very powerful way of processing text while looking for recurring patternsthey are often used with data held in plain text files (such as log files)csv files as well as excel files this introduces regular expressionsdiscusses the syntax used to define reg...
19,279
regular expressions in python regular expression are very widely used for finding information in filesfor example finding all lines in log file associated with specific user or specific operationfor validating input such as checking that string is valid email address or postcode/zip code etc support for regular express...
19,280
regular expression patterns pattern metacharacters there are several special characters (often referred to as metacharactersthat have specific meaning within regex patternthese are listed in the following tablecharacter description example [ set of characters indicates special sequence (can also be used to escape speci...
19,281
regular expressions in python sequence description example \ returns match if the following characters are at the beginning of the string returns match where the specified characters are at the beginning or at the end of word "\athemust start with 'the\ \ \ \ \ \ \ \ \ indicates that the following characters must be pr...
19,282
the python re module the python re module the python re module is the built-in module provided by python for working with regular expressions you might also like to examine the third party regex module (see org/project/regexwhich is backwards compatible with the default re module but provides additional functionality w...
19,283
regular expressions in python simple example the following simple python program illustrates the basic use of the re module it is necessary to import the re module before you can use it import re text 'john williamspattern '[jj]ohnprint('looking in'text 'for the pattern'patternif re search(patterntext )print('match has...
19,284
working with python regular expressions import re match re search(patternstringif matchprocess(matchmatch objects support range of methods and attributes includingmatch re the regular expression object whose match(or search(method produced this match instance match string the string passed to match(or search(match star...
19,285
regular expressions in python if there is more than one matchonly the first occurrence of the match will be returnedimport re line 'the price is containsintegers '\ +if re search(containsintegersline )print('line contains an integer'elseprint('line does not contain an integer'in this case the output is line contains an...
19,286
working with python regular expressions the parameters arepattern this is the regular expression to be matched string this is the string to be searched flags modifier flags that can be used the re match(function returns match object on successnone on failure the difference between matching and searching python offers t...
19,287
regular expressions in python the output from this program is ['spain''plain'spain plain the finditer(function this function returns an iterator yielding matched objects for the regular expression pattern in the string supplied the signature for this function isre finditer(patternstringflags= the string is scanned left...
19,288
working with python regular expressions the sub(function the sub(function replaces occurrences of the regular expression pattern in the string with the repl string re sub(patternreplstringmax= this method replaces all occurrences of the regular expression pattern in string with replsubstituting all occurrences unless m...
19,289
regular expressions in python import re pattern '(england|wales|scotland)input 'england for footballwales for rugby and scotland for the highland gamesprint(re subn(pattern,'scotland'input )the output from this is('scotland for footballscotland for rugby and scotland for the highland games' the compile(function most re...
19,290
working with python regular expressions matches the pattern starting at pos if provided and ending at endpos if this is provided (otherwise process the whole stringpattern match(stringposendpos)if zero or more characters at the beginning of string match this regular expressionreturn corresponding match object return no...
19,291
regular expressions in python of course the compiler pattern object supports range of methods in addition to search(as illustrated by the spilt methodp re compile( '\ +' ' high streetprint( split( )the output from this is [' ''high''street' online resources see the python standard library documentation forhow to the re...
19,292
exercises spacefollowed by one or two numbers and finally two letters an example of postcode is sy zz another postcode might be bb po and finally we might have aa nn (note this is simplification of the uk postcode system but is suitable for our purposesusing the output from this function you should be able to run the f...
19,293
database access
19,294
introduction to databases introduction there are several different types of database system in common use today including object databasesnosql databases and (probably the most commonrelational databases this focusses on relational databases as typified by database systems such as oraclemicrosoft sql server and mysql t...
19,295
introduction to databases in this diagram there is table called studentsit is being used to hold information about students attending meeting the table has attributes (or columnsdefined for idnamesurnamesubject and email in this casethe id is probably what is known as primary key the primary key is property that is use...
19,296
what is database this is an example of many to one (often written as many: relationshipthat is there are many people who can live at one address (in the above adam smith also lives at address 'addr 'in relational databases there can be several different types of relationship such asone:one where only one row in one tab...
19,297
introduction to databases workbench is tool that allows you to work with mysql databases to manage and query the data held within particular database instance for references for mysql and the mysql workbench see the links at the end of this as an examplewithin the mysql workbench we can create new table using menu opti...
19,298
what is database the tool also allows us to populate data into the tablethis is done by entering data into grid and hitting apply as shown below sql and databases we can now use query languages to identify and return data held in the database often using specific criteria for examplelet us say we want to return all the...
19,299
introduction to databases this would return only the names of the students data manipulation language data can also be inserted into table or existing data in table can be updated this is done using the data manipulation language (dmlfor exampleto insert data into table we merely need to write an insert sql statement p...