2017-03-22 3 views
1

Ich möchte das Verhalten der os.path.exists-Methode überspionieren, damit ich überprüfen kann, ob mein Skript korrekt funktioniert, wenn os.path.exists meldet, dass die Datei/der Ordner nicht existiert .Wie man in einer BDD-Steps-Datei mockt

@when("Service starts with input file that does not exist") 
def step_impl(context): 
    """ 
    :type context: behave.runner.Context 
    """ 
    json_file_path = "fake_file_path" 
    mock_os_path = mock.Mock() 
    mock_os_path.exists.return_value = False 

    context.returncode = dicom_send_service.launch(json_file_path) 

    mock_os_path.exists.assert_called_once_with(json_file_abspath) 

Wie kann ich den Schein in mein Skript injizieren? Ich versuchte, die

@mock.patch("mymodule.os.path") 
@when("Service starts with input file that does not exist") 
def step_impl(context, mock_os_path): 

jedoch zu verwenden, wenn ich die Methode Python zurückkehrt laufen:

Traceback (most recent call last): 
    File "/usr/local/lib/python2.7/dist-packages/behave/model.py", line 1456, in run 
    match.run(runner.context) 
    File "/usr/local/lib/python2.7/dist-packages/behave/model.py", line 1903, in run 
    self.func(context, *args, **kwargs) 
TypeError: step_impl() takes exactly 2 arguments (1 given) 

Wie Sie die step_impl Methode erwartet zwei Argumente auf der Grundlage der Erklärung sehen kann, aber BDD nannte es mit nur 1 (der Kontextwert) und die Scheinannotation wurde nicht aufgenommen.

Hier ist der Code, den ich testen bin:

import os 

def validate(json_file_path): 
    """Method which validates the JSON file, an error message is returned if the file fails verification. 

     json_file_path -- the path to the file with the message configuration details""" 
    if not os.path.exists(json_file_path): 
     return "Could not find file at path {0}".format(json_file_path) 
    ... 
    return "" 

def launch(json_file_path): 
    error_message = valid(json_file_path) 
    if error_message: 
     print(error_message) 
     return 1 

Antwort

3

Also meine eigene Frage zu beantworten, müssen Sie die with mock.patch Syntax:

with mock.patch('name of thing to mock') as name_of_mock: 

So über mein Beispiel werden würde:

@when("Service starts with input file that does not exist") 
def step_impl(context): 
    """ 
    :type context: behave.runner.Context 
    """ 
    json_file_path = "fake_file_path" 

    # This is where the magic happens 
    with mock.patch ('os.path') as mock_os_path: 

     mock_os_path.exists.return_value = False 

     context.returncode = dicom_send_service.launch(json_file_path) 

     mock_os_path.exists.assert_called_once_with(json_file_abspath) 

Ich habe es getestet und es funktioniert wie ein Charme. Viel einfacher als andere Mockito-Frameworks wie Mockito oder Powermock von Java.

Verwandte Themen