21
Strings and Testing string methods, formatting testing approaches CS 112 @ GMU

5.Strings and Testing - George Mason University · 2019-12-03 · Two Testing Styles Black box testing–"outsider's expectations". given a piece of code, think about what it is supposed

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: 5.Strings and Testing - George Mason University · 2019-12-03 · Two Testing Styles Black box testing–"outsider's expectations". given a piece of code, think about what it is supposed

Strings and Testingstring methods, formatting

testing approaches

CS 112 @ GMU

Page 2: 5.Strings and Testing - George Mason University · 2019-12-03 · Two Testing Styles Black box testing–"outsider's expectations". given a piece of code, think about what it is supposed

• string methods• string formatting• testing, unit testing

2

Topics

Page 3: 5.Strings and Testing - George Mason University · 2019-12-03 · Two Testing Styles Black box testing–"outsider's expectations". given a piece of code, think about what it is supposed

Some String Methods (See LIB 4.7.1)

usage: stringExpr . methodName ( args )

3

method purpose returned values.upper()s.lower()

converts letters to upper or lower case

modified copy of s

s.startswith(svar[,start[,stop]])s.endswith(svar[,start[,stop]])

is svar a prefix/suffix of s? bool

s.join(iterable) concatenates items from iterable, with copies of string s inbetweenthem.

string result of all those joined things

s.split(sep) get list of strings obtained by splitting s into parts at each occurrence of sep.

list of strings from between occurrences of sep

s.replace(old, new[,count]) replace all (or count) occurrencesof old str with new str.

string with replacements performed

Page 4: 5.Strings and Testing - George Mason University · 2019-12-03 · Two Testing Styles Black box testing–"outsider's expectations". given a piece of code, think about what it is supposed

Useful Tip: printing without a newline

print() specializations

• end=… : choose what print() adds at the end; default: "\n"• sep= … " choose what's printed between arguments; default: " "→ you have a lot of control over printing!

print("a",end='')print('b c', end='')print("d")

print(1,2,3,sep='.', end='!')print(4,5,6,sep='-->')

ab cd1.2.3!4-->5-->6

Page 5: 5.Strings and Testing - George Mason University · 2019-12-03 · Two Testing Styles Black box testing–"outsider's expectations". given a piece of code, think about what it is supposed

Formatting Strings

Brief introductions here, but also read the documentation.

Three approaches:• percent operator, % LIB 4.7.2 ZY 3.7

• format method LIB 6.1.3 ZY 7.5

• f-strings new as of Python 3.6

Page 6: 5.Strings and Testing - George Mason University · 2019-12-03 · Two Testing Styles Black box testing–"outsider's expectations". given a piece of code, think about what it is supposed

String Formatting: % operator

6

• describe pattern of string with placeholders, then supply all substitutions at once.

• Syntax: pattern_string % tuple

• Semantics:→ simplify lefthand string to value→ left to right, match placeholders in string with values from tuple→ substitutions obey special formatting directives

Page 7: 5.Strings and Testing - George Mason University · 2019-12-03 · Two Testing Styles Black box testing–"outsider's expectations". given a piece of code, think about what it is supposed

String Formatting: % operator

7

"there are %d days until %s." % (75, "holiday")

"%s ran %f miles today"% ("Zeke", 3.5)

"change is %d dollars and %d cents." % (4,39)

"you got %f%% of them, %s." % (0.95*100, "George")

"%s's number is %g/mol." % ("Avogadro",6.02214e23)

placeholder style of output accepted input

%d integer integers, floats

%f float integers, floats

%g float(scientific notation)

integers, floats – but it prefers scientific notation representation

%s string anything (calls str() )

%% the '%' character none – just represents the % symbol

<more> … don't memorize these: %i, %o, %u, %x, %X, %e, %E, %c, %r…

Page 8: 5.Strings and Testing - George Mason University · 2019-12-03 · Two Testing Styles Black box testing–"outsider's expectations". given a piece of code, think about what it is supposed

More Options

purpose examples resultsstate exact # columns after decimal point (%f)

"%.2f" % (2/3)"%.0f" % 15.5

'0.67''16'

state min. # columns for entire thing

"%4d" % 30"%3d" % 1234"%5f" % 2.5

' 30''1234'' 2.5'

use leading sign (+/-) "%+f" % 5 '+5.000000'

Page 9: 5.Strings and Testing - George Mason University · 2019-12-03 · Two Testing Styles Black box testing–"outsider's expectations". given a piece of code, think about what it is supposed

POLL – 5A

String formatting

Page 10: 5.Strings and Testing - George Mason University · 2019-12-03 · Two Testing Styles Black box testing–"outsider's expectations". given a piece of code, think about what it is supposed

The format( ) method

A powerful option to craft a string is the format method.• use { }'s as placeholders, put style rules inside

– examples: "{}" "{:4.2f}" "{:^5}"

• provide substitutions as arguments to .format() method

See more examples: LIB 6.1.3.2

Page 11: 5.Strings and Testing - George Mason University · 2019-12-03 · Two Testing Styles Black box testing–"outsider's expectations". given a piece of code, think about what it is supposed

More options…Again, indicate min # cols and exact # cols after the decimal.

• Show as percent:

• Align left/center/right:

"{:10.2}".format(0.123)

"{:%}".format(0.12)

"{:>6}".format("hi")"{:<6}".format("hi")"{:^6}".format("hi")"{:.^6}".format("hi")"{:o^6}".format("hi")

' hi''hi '' hi ''..hi..''oohioo'

' 0.12'

'12.000000%'

Page 12: 5.Strings and Testing - George Mason University · 2019-12-03 · Two Testing Styles Black box testing–"outsider's expectations". given a piece of code, think about what it is supposed

New! f-Strings

• special version of string literals with embedded expressions

• indicated with leading f in front of open-quote.

name = "George"age = 67print( f"Happy {age}th birthday, {name}!")

Page 13: 5.Strings and Testing - George Mason University · 2019-12-03 · Two Testing Styles Black box testing–"outsider's expectations". given a piece of code, think about what it is supposed

Some corner cases of f-strings

• you can call functions and methods:– f"{len(name)} letters long"– f"{name.upper()}!"

• watch out for clashing quote styles!(can't \escape them inside the {}'s)– f"{1+3} years"– f"{int('1')+3} years"– f"{int(\"1\")+3} years" FORBIDDEN

Page 14: 5.Strings and Testing - George Mason University · 2019-12-03 · Two Testing Styles Black box testing–"outsider's expectations". given a piece of code, think about what it is supposed

Testing Code

Page 15: 5.Strings and Testing - George Mason University · 2019-12-03 · Two Testing Styles Black box testing–"outsider's expectations". given a piece of code, think about what it is supposed

Notes on Debugging and Testing

• We basically never write 100% correct code on our first try• How can we debug our code? (identify the problem)• how can we thoroughly test it? (check for correct behavior)

Debugging code is essentially a careful analysis of all the assumptions about our code, to find the assumption that is false.Examples:→ I assume I used correct syntax.→ I assume I modified the correct variable.→ I assume the list (or some index) exists before I use it→ I assume this print statement happens each iteration→ I assume I'm editing the same file I'm running!

Page 16: 5.Strings and Testing - George Mason University · 2019-12-03 · Two Testing Styles Black box testing–"outsider's expectations". given a piece of code, think about what it is supposed

Locating the Syntax Error

Getting a syntax error on a "perfect" line of code? Look up to the previous line(s). You're likely missing a parenthesis, colon, or something else.

→ the indicated location is merely where Python got when it realized something was wrong.

line # code1 print("hello!")

2 n = int(input("please enter a number: ")

3 if n>0:

4 print("number is "+str(n))

5 else:

6 print("number was negative.")

demo$ python3 syntax_error.pyFile "syntax_error.py", line 3

if n>0:^

SyntaxError: invalid syntax

Page 17: 5.Strings and Testing - George Mason University · 2019-12-03 · Two Testing Styles Black box testing–"outsider's expectations". given a piece of code, think about what it is supposed

print-style debuggingruntime error: some value/variable can't be used that way. Did we build it wrong, or use it wrong?

print out relevant variables/expressions just before the offending operation occurs.Pros:→ access variables at the confusing portion of the code.→ Flexible, easy to include.Cons:→ need to be removed before code is ready to publish.→ Can introduce their own errors!→When overused, hard to tell what program is doing versus what debugging print statements are doing.

Page 18: 5.Strings and Testing - George Mason University · 2019-12-03 · Two Testing Styles Black box testing–"outsider's expectations". given a piece of code, think about what it is supposed

Drawing Out Memory

Run the code by hand or by using the visualizer.• preserve and identify aliases→ check with id() calls

• updates vs. re-assignments• make sure you perform the actions that are indicated, not

just what you think should happen!• seek where your expectations and actual performance

diverge. Did we forget to handle this situation, or are we handling it incorrectly?

Page 19: 5.Strings and Testing - George Mason University · 2019-12-03 · Two Testing Styles Black box testing–"outsider's expectations". given a piece of code, think about what it is supposed

Testing Approaches

Unit Testing – for the smallest parts of code you can manage, write tests that test this piece of code.• programmers often create large batches of unit

tests that can be rerun as desired – this is called "regression testing".→ all our testing files do this! J

• standardized ways of creating these exist but tend to use classes and objects – topics we haven't learned yet.

Page 20: 5.Strings and Testing - George Mason University · 2019-12-03 · Two Testing Styles Black box testing–"outsider's expectations". given a piece of code, think about what it is supposed

Two Testing Styles

Black box testing – "outsider's expectations". given a piece of code, think about what it is supposed to do, and create test cases that give specific inputs and look for the expected outputs/behavior (including tests that you expect to fail!)

White box testing – "code coverage." Looking at the actual structure of your code, think of test cases that should use/'touch' each part of the code, to make sure each part of the code works when used.

Page 21: 5.Strings and Testing - George Mason University · 2019-12-03 · Two Testing Styles Black box testing–"outsider's expectations". given a piece of code, think about what it is supposed

Practice Problem

def prime(n):is_prime = Truefor d in range(2,sqrt(n))

if d%n==0:is_prime = False

else:is_prime = True

return is_prime

This code is riddled with various kinds of errors!copy it from: http://cs.gmu.edu/~marks/112/examples/buggy.py• debug the code until it gets correct values.• choose blackbox test cases.• choose white box test cases.