Skip to content

Commit

Permalink
String adventure tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Ignacio Avas committed May 2, 2017
1 parent 9e8a253 commit b3f52c8
Show file tree
Hide file tree
Showing 5 changed files with 132 additions and 14 deletions.
55 changes: 50 additions & 5 deletions py101/strings/README.es.rst
Original file line number Diff line number Diff line change
@@ -1,14 +1,59 @@
Boilerplate
-----------
Operations con cadenas de caracteres
------------------------------------

Insertar alguna introducción aquí.
Las cadenas de caracteres son uno de los tipos más usados en Python. Son un tipo de secuenca de caracteres. Para acceder a los substring se debe usar los paréntesis rectos para indicar qué partes de la cadena se pueden obtener. Se pueden usar índices negativos para contar desde el final.

.. sourcecode:: python

print('Some python code here')
mystring = 'Show me the code'
print(mystring[0]) # Imprime S
print(mystring[0:4]) # Imprime Show
print(mystring[-4:]) # Imprime code

La función "len" puede ser utilizada para obtener el largo de una cadena

.. sourcecode:: python

print(len('hola')) # Imprime 4

Adicionalmente hay una variedad de funciones para transformar o consultar una cadena:


* upper: Convierte unca cadena a mayúsculas
* lower: Transforma todos los caracteres a minúsculas
* startswith: Usado para saber si una cadena empieza con cierta subcadena
* endswith: Usado para saber si un cadena termina con una subcadena específica
* find: Busca una subcadena dentro de la cadena y retorna el índice de la primera ocurrencia, o -1 si la subcadena no fue encontrada.
* split: Genera una lista de cadenas a partir de una cadena, separando por cierto sentinela.
* join: Concatena una lista de cadenas usando cierta subcadena como unión.

.. sourcecode:: python

mystring = 'Big Movie'

mystring.upper() # BIG MOVIE
mystring.lower() # big movie
mystring.startswith('Big') # True
mystring.startswith('Movie') # False
mystring.endswith('Movie') # True
mystring.find('Movie') # 4
mystring.find('Big') # this is 0
mystring.find('TV') # this is -1

ingredients = [ 'Tomato', 'Ham', 'Eggs' ]
'and '.join(ingredients) # 'Tomato and Ham and Eggs'

comma_values = '1,2,3,4,5,6'
comma_values.split(',') # [ '1', '2' , '3', '4', '5']

Desafío
-------

Describir el desafío aquí.
Haz un programa usando funciones de cadena que imprima las siguientes líneas en este orden.

* 17
* THIS IS MY STRING
* this is my string
* [ 'This', 'Is', 'My', 'string' ]

Debes usar la función len para imprimir la primer línea, y la función splic para imprimir la cuarta línea.
54 changes: 49 additions & 5 deletions py101/strings/README.rst
Original file line number Diff line number Diff line change
@@ -1,14 +1,58 @@
Boilerplate
-----------
String Operations
-----------------

Insert some introduction here.
Strings are amongst the most popular types in Python. They are an special type of sequence of characters. To access substrings, use the square brackets for slicing along with the index or indices to obtain a a particular substring, negative indexes refer to the string counting from the ending.

.. sourcecode:: python

print('Some python code here')
mystring = 'Show me the code'
print(mystring[0]) # prints S
print(mystring[0:4]) # prints Show
print(mystring[-4:]) # prints code

The "len" function can be used to get the length of a particular string

.. sourcecode:: python

print(len('hello')) # prints 5

In addition, there a variety of functions to transform and query an string, such as

* upper: Converts the string to UPPERCASE
* lower: Transforms all characters to lowercase
* startswith: Used to know if a string begins with some substring
* endswith: Used to know if a string ends with some substring
* find: Used to know if a string is contained in other string. Returns the index of the first occurrence or -1 if it was not found
* split: Generates a list of substring, separated by a certain substring
* join: Concatenates a lists of string by using a particular str

.. sourcecode:: python

mystring = 'Big Movie'

mystring.upper() # BIG MOVIE
mystring.lower() # big movie
mystring.startswith('Big') # True
mystring.startswith('Movie') # False
mystring.endswith('Movie') # True
mystring.find('Movie') # 4
mystring.find('Big') # this is 0
mystring.find('TV') # this is -1

ingredients = [ 'Tomato', 'Ham', 'Eggs' ]
'and '.join(ingredients) # 'Tomato and Ham and Eggs'

comma_values = '1,2,3,4,5,6'
comma_values.split(',') # [ '1', '2' , '3', '4', '5']

Challenge
---------

Describe the challenge here
Make a program using string functions that prints the following lines in this order

* 17
* THIS IS MY STRING
* this is my string
* [ 'This', 'Is', 'MY', 'string' ]

You must use the len function to print the first line, and the split function to print the fourth line
7 changes: 6 additions & 1 deletion py101/strings/SOLUTION.rst
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
.. sourcecode:: python

print('Some solution here')
mystring = 'This Is MY string'

print(len(mystring))
print(mystring.upper())
print(mystring.lower())
print(mystring.split(' '))
20 changes: 17 additions & 3 deletions py101/strings/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@
class TestOutput(unittest.TestCase):
"""Adventure test"""

expected_output = [
"17",
"THIS IS MY STRING",
"this is my string",
"['This', 'Is', 'MY', 'string']",
""
]

def __init__(self, candidate_code, file_name='<inline>'):
"""Init the test"""
super(TestOutput, self).__init__()
Expand All @@ -31,9 +39,15 @@ def tearDown(self):
def runTest(self):
"""Makes a simple test of the output"""

# code = compile(self.candidate_code, self.file_name, 'exec', optimize=0)
# exec(code)
self.fail("Test not implemented")
code = compile(self.candidate_code, self.file_name, 'exec', optimize=0)

self.assertIn('len', code.co_names, 'Should have called the len function')
self.assertIn('split', code.co_names, 'Should have called the split function')
self.assertIn('upper', code.co_names, 'Should have called the upper function')
self.assertIn('lower', code.co_names, 'Should have called the lower function')
exec(code)
lines = self.__mockstdout.getvalue().split('\n')
self.assertEqual(self.expected_output, lines, 'Should have same output')


class Adventure(BaseAdventure):
Expand Down
10 changes: 10 additions & 0 deletions tests/test_story.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import py101.variables
import py101.operators
import py101.formatting
import py101.strings
import unittest


Expand Down Expand Up @@ -33,6 +34,15 @@ def __init__(self, test_module, good_solution):
AdventureData(
py101.formatting,
"""s = 'Talk is {}. Show me the {}.'.format('cheap', 'code'); print(s)"""
),
AdventureData(
py101.strings,
"""mystring = 'This Is MY string'
print(len(mystring))
print(mystring.upper())
print(mystring.lower())
print(mystring.split(' '))
"""
)
]

Expand Down

0 comments on commit b3f52c8

Please sign in to comment.