несколько дней назад я написал код в качестве части моего процесса собеседования. Вопросу была дана текстовая находка, если текст текста присутствует в данном тексте или нет. Я использовал хэш-таблицу, чтобы сохранить данный текст (ключи были словами, присутствующими в тексте, а значение было позицией этого слова в тексте). Итак, теперь, учитывая строку запроса, я мог найти расположение слов, присутствующих в тексте, и отобразить фрагмент текста с максимальными словами запроса в нем. Я думал, все хорошо.Unit Test Design
Но меня также попросили написать для него единичный тест. Хотя я никогда раньше не писал модульные тесты, но я знал, почему они так необходимы в процессе разработки. Поэтому я создал несколько тестовых примеров, имея в виду средний тестовый пример, а также граничный случай. Но то, что не было ясно для меня, было нам нужно знать правильный результат заранее, чтобы написать тестовый пример или нет.
Я начал с получения некоторых текстов для ввода в программу и соответствующего вывода, поместил их в класс и позже прочитал их как ввод для моей программы.
Код испытания блока показан ниже:
import unittest
import random
import generate_random_test
class c_Known_Output():
Input_Text1 = '''We ordered the traditional deep dish pizza and a Manchego salad. Were started off with a complimentary bread, that looks like a really big hamburger bun top at first glance. Even though it was free bread, it was soft and slightly sweet and delicious. I liked dipping it in the balsamic reduction and olive oil from the salad plate. The salad dish was perfectly fine, but I wish the Manchego slices on top were somehow sliced a bit thinner. The deep dish traditional pizza came out a bit later (remember the 40 min. cooking time, folks!), piping hot and smelling delicious. At first bite, I wasnt sure how much I liked it.'''
Output_Text1 = '''I liked dipping it in the balsamic reduction and olive oil from the salad plate. The salad [[HIGHLIGHT]]dish[[ENDHIGHLIGHT]] was perfectly fine, but I wish the Manchego slices on top were somehow sliced a bit thinner. The [[HIGHLIGHT]]deep dish[[ENDHIGHLIGHT]] traditional pizza came out a bit later (remember the 40 min. cooking time, folks!), piping hot and smelling delicious.'''
Input_Text2 = '''Best tacos I have ever had Lived down the road from this truck for years. Watched almost every episode of BSG eating these tacos with beer. Moved to Az and El Chato is one of the things I miss the most! ANYONE that is around them, you have to go here.'''
Output_Text2 = '''Best [[HIGHLIGHT]]tacos[[ENDHIGHLIGHT]] I have ever had Lived down the road from this truck for years. Watched almost every episode of BSG eating these [[HIGHLIGHT]]tacos[[ENDHIGHLIGHT]] with beer. Moved to Az and El Chato is one of the things I miss the most!'''
Query_Not_found = '''Query Not Found'''
class c_myTest(unittest.TestCase):
Generator = generate_random_test.TestCaseGenerator()
KnowOutput = c_Known_Output()
def testAverageCase1(self):
"""no keywords present...no highlight"""
output = highlight.m_Highlight_doc(self.KnowOutput.Input_Text1, 'deep dish')
print "\nTest Case 1"
print output
self.assertEqual(output, self.KnowOutput.Output_Text1)
def testAverageCase2(self):
output = highlight.m_Highlight_doc(self.KnowOutput.Input_Text2, 'burrito taco take out')
print "\nTest Case 2"
print output
self.assertEqual(output, self.KnowOutput.Output_Text2)
def testSnippetLength(self):
""" if the search word is present only once in the text...check if the snippet is of optimum length...optimum length is defined as one sentence before
and after the sentence in which the query word is present"""
output = highlight.m_Highlight_doc(self.KnowOutput.Input_Text3, 'tacos')
print "\nTest Case 3"
print output
self.assertEqual(output, self.KnowOutput.Output_Text3)
def testSmallText(self):
"""The text is just one sentence, with the query present in it. The same sentence should be the output"""
output = highlight.m_Highlight_doc(self.KnowOutput.Input_Text4, 'deep dish pizzas')
print "\nTest Case 4"
print output
self.assertEqual(output, self.KnowOutput.Output_Text4)
def testBadInput(self):
"""no keywords present...no highlight"""
output = highlight.m_Highlight_doc(self.KnowOutput.Input_Text4, 'tacos')
print "\nTest Case 5"
print output
self.assertEqual(output, self.KnowOutput.Query_Not_found)
#Now test with randomly generated text
def testDistantKeywords(self):
"""the search queries are very distant in the text. 6 query words are generated. First 4 of these queries are inserted in one paragraph and the last two
queries are inserted in another. The snippet should be of the first paragraph which has the maximum number of query words present in it."""
query = self.Generator.generateSentence(6, 5)
text1 = self.Generator.generateTextwithQuery(query[0:4], 10, 10, 5, 3)
text2 = self.Generator.generateTextwithQuery(query[5:], 10, 10, 5, 3)
text1.append('\n')
text1.extend(text2)
print "\nTest Case 6"
print "=========================TEXT=================="
print ' '.join(text1)
print "========================QUERY=================="
print ' '.join(query)
print " "
output_text = highlight.m_Highlight_doc(' '.join(text1), ' '.join(query))
print "=======================SNIPPET================="
print output_text
print " "
if __name__=='__main__':
unittest.main()
Очевидно, я завалил и нет оснований было дано мне, и теперь я пытаюсь выяснить, если этот код был ONE. Может ли кто-нибудь помочь мне определить проблемы в модульных тестах, что нужно делать, если вы действительно знаете вывод своего кода заранее, и должны написать для него единичные тесты. например, можно ли написать единичные тесты для генератора случайных чисел?
Заранее благодарен!
Перед следующим интервью обязательно прочитайте и изучите код, который следует руководству по стилю Python. Интервьюер, который встречает кусок кода, который выглядит как вышеприведенный код, может легко сказать, что раньше вы не имели дело с большим количеством кода на Python. В качестве упражнения вы можете попытаться исправить код выше, следуя рекомендациям здесь: http://www.python.org/dev/peps/pep-0008/ – Udi
Я понимаю, что я не соблюдал рекомендации при написании кода на Python (более того, потому что я только начал с python за неделю до этого, и это был мой первый код !!! еще одна ошибка ... должна была закодировать его на Java или C++), но мне действительно интересно узнать, можем ли мы писать модульные тесты для функций, выход которых нам неизвестен, скажем, например, для написания модульных тестов для генератора случайных чисел. –
В python очень важен стиль и лучшие практики. Если вы хотите перейти на python, вы должны принять это. – Udi