def test_delete_not_existing_file(self, mock_os, mock_path): mock_path.exists.return_value = False File().delete("path") self.assertFalse(mock_os.remove.called, "Failed to not remove the file if not present.")
def test_read(self): content_mock = 'Hello World!' file_path = '/fake/file/path.txt' with patch('file.file.open'.format(__name__), new=mock_open(read_data=content_mock)) as _file: actual = File().read(file_path) _file.assert_called_once_with(file_path, 'r') self.assertEqual(content_mock + '\n', actual)
def test_write(self): fake_file_path = "fake/file/path" content = "Message to write on file to be written" with patch('file.file.open', mock_open()) as f: File().write(fake_file_path, content) # assert if opened file on write mode 'w' f.assert_called_once_with(fake_file_path, 'w') # assert if the specific content was written in file f().write.assert_called_once_with(content)
def get_file(self, file_id): """ Get file by id :param file_id: id of file :return: file with id """ query = select(self.files).where(self.files.c.id == file_id) file = None for row in self.con.execute(query): file = File(row[0], row[1], row[2], row[3]) return file
######为了发现在当前目录下创建的file包手动将当前目录加入环境变量###### import os import sys sys.path.insert(0, os.path.dirname(__file__)) ######正常测试我们的项目应该已存在于pythonpath中所以不需要这么写##### import pytest from file.file import File # 如果mock掉的方法不需要逻辑判断,直接使用ret_val指定返回值即可 @pytest.mark.usefixtures("mock") @pytest.mark.prop("file.file.File.load", ret_val=File("直接mock返回值")) def test_load1(): assert File.load().filename == "直接mock返回值" # 无论被mock的方法是异步还是同步,无脑指定返回值 # 不过异步的方法测试需要pytest-asyncio这个包支持,指定一个asyncio的mark才可以 @pytest.mark.asyncio @pytest.mark.usefixtures("mock") @pytest.mark.prop("file.file.File.load_async", ret_val=File("异步方法也能mock")) async def test_load2(): assert (await File.load_async()).filename == "异步方法也能mock" # 如果我们用来替代的mock方法有一定的逻辑,我们可以指定一个ret_factory,指向替代方法的包地址 @pytest.mark.asyncio @pytest.mark.usefixtures("mock") @pytest.mark.prop("file.file.File.load_async", ret_factory="factories.mock_load")
import subprocess import atexit import os from sys import executable from file.file import File from time import sleep path_stat_file = r'{}'.format(os.getcwd()+"\\"+os.path.basename(__file__)) #Actualiza la variable de estado del código, cuando se cambia stat_storage.stat, #El archivo cambia stat_storage = File() print('Iniciando programa en sección {}'.format(stat_storage.stat)) @atexit.register def callback(): print("Salida del código sin señal, reiniciando programa en sección {}".format(stat_storage.stat)) #https://stackoverflow.com/questions/25651990/oserror-winerror-193-1-is-not-a-valid-win32-application subprocess.call([executable,repr(path_stat_file)[1:-1],'htmlfilename.htm']) #Decorator for the fase's functions, it checks if the state in the file is equal to the fase´s state, #if thats the case, the fase´s function is executed, when the function finishes, the state.txt file #is updated by the decorator, if there is an interruption the next function is the one with #the same state that is in the stat.txt, aka: each time that the program is ran, it starts from the #las fase. def check_state(*args,**kargs): def decorator(func): def wrapper(): if(stat_storage.stat==kargs['target_stat']): func() stat_storage.stat = kargs['next_stat'] return wrapper
def upload_file(algoritm, variable): if request.method == 'POST': print(request.files) # check if the post request has the file part if 'file' not in request.files: response = Response("{'msg': 'No file part'", status=403, mimetype='application/json') response.headers.add('Access-Control-Allow-Origin', '*') return response request_file = request.files['file'] # if user does not select file, browser also # submit an empty part without filename if request_file.filename == '': flash('No selected file') response = Response("{'msg': 'No selected file'", status=403, mimetype='application/json') response.headers.add('Access-Control-Allow-Origin', '*') return response file = File(request_file) #file.unzip(settings.DRASTIC_DATA_FOLDER_D_INPUT) #response = Response('{"msg":"Sucess"}', status=200, mimetype='application/json') #response.headers.add('Access-Control-Allow-Origin', '*') #return response if request_file and file.allowed_file(settings.ALLOWED_EXTENSIONS): if algoritm == 'drastic': if variable == 'd': file.save(settings.DRASTIC_DATA_D_FOLDER_INPUT, variable) elif variable == 'r': file.save(settings.DRASTIC_DATA_R_FOLDER_INPUT, variable) elif variable == 'a': file.save(settings.DRASTIC_DATA_A_FOLDER_INPUT, variable) elif variable == 's': file.save(settings.DRASTIC_DATA_S_FOLDER_INPUT, variable) elif variable == 't': file.save(settings.DRASTIC_DATA_T_FOLDER_INPUT, variable) elif variable == 'i': file.save(settings.DRASTIC_DATA_I_FOLDER_INPUT, variable) elif variable == 'c': file.save(settings.DRASTIC_DATA_C_FOLDER_INPUT, variable) elif algoritm == 'god': if variable == 'g': file.save(settings.GOD_DATA_G_FOLDER_INPUT, variable) elif variable == 'o': file.save(settings.GOD_DATA_O_FOLDER_INPUT, variable) elif variable == 'd': file.save(settings.GOD_DATA_D_FOLDER_INPUT, variable) elif algoritm == 'si': if variable == 'g': file.save(settings.SI_DATA_G_FOLDER_INPUT, variable) elif variable == 'r': file.save(settings.SI_DATA_R_FOLDER_INPUT, variable) elif variable == 'a': file.save(settings.SI_DATA_A_FOLDER_INPUT, variable) elif variable == 't': file.save(settings.SI_DATA_T_FOLDER_INPUT, variable) elif variable == 'lu': file.save(settings.SI_DATA_LU_FOLDER_INPUT, variable) response = Response('{"msg":"Sucess"}', status=200, mimetype='application/json') response.headers.add('Access-Control-Allow-Origin', '*') return response
def mock_load(filename="通过工厂mock"): return File(filename)
def test_delete_existing_file(self, mock_os, mock_path): mock_path.exists.return_value = True File().delete("path") mock_os.remove.assert_called_with("path")