2016-07-01 35 views
2

問題:證明函數沒有適當的輸入驗證

我有該人工示例功能:

def test_function(target, words): 
    pattern = re.compile(r"|".join(words)) 

    return bool(pattern.search(target)) 

這需要一個單詞列表和動態地構造正則表達式模式沒有適當的轉義列表中的單詞

使用示例:

text = "hello world!" 

print(test_function(text, ["test"])) # prints False 
print(test_function(text, ["hello"])) # prints True 
print(test_function(text, ["test", "world"])) # prints True 

問題:

如何測試這個功能證明,沒有適當的正則表達式逃逸或輸入清理

換句話說,我應該提供一個words列表中的哪些項目用於「中斷」此功能?


我試過幾個「邪惡」的正則表達式來模擬災難性的回溯和強制功能,掛像(x+x+)+y(a+)+,但功能只是返回False立即並沒有出現問題的信息。

+1

一個空字符串,總是返回「真」 *(無論換句話說)*。 –

回答

2

有很多方法可以做到這一點。例如,一個詞,不是一個有效的正則表達式:

>>> test_function('a', ['*']) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<string>", line 2, in test_function 
    File "/usr/lib64/python2.6/re.py", line 190, in compile 
    return _compile(pattern, flags) 
    File "/usr/lib64/python2.6/re.py", line 245, in _compile 
    raise error, v # invalid expression 
sre_constants.error: nothing to repeat 

或匹配的一切,正則表達式的一句話:

>>> test_function('a', ['.*']) 
True 

或詞不匹配它應該作爲正則表達式:

>>> test_function('$^', ['$^']) 
False 

,或者在一個反斜槓結尾和逸出|一個字:

>>> test_function('a', ['\\', 'a']) 
False 

災難性回溯工作過:

>>> test_function('a'*100, ['(a+)+b']) 
# Hangs. 
+0

哦,是的,「沒有重複」是一個很好的。謝謝!我們可以模擬一個災難性的回溯並看到該功能行爲非常緩慢嗎? – alecxe

+1

@alecxe:是的,那也可以。我添加了一個帶有災難性回溯的例子。 – user2357112

+0

真棒,很好的例子,感謝您的幫助。 – alecxe