Exemple #1
0
def main(url, pathname, tmpdir):
    if tmpdir and os.path.exists(tmpdir):
        logging.error('TMP dir %s exists, but may not', tmpdir)
        raise Exception('TMP dir %s exists, but may not', tmpdir)

    dir = Dir()
    files = dir.scan(pathname)
    if len(files) < 1:
        logging.warn("No file into " + pathname)
        sys.exit(0)

    if tmpdir:
        for file in files:
            File.split(file, tmpdir)
        files = dir.scan(tmpdir)

    uploader = Uploader(url)
    for file in files:
        logging.info('File: %s', file)
        response = uploader.upload(file)
        time.sleep(15)
        if 299 < response.status_code:
            logging.error('Request Error: %s', response.text)
        else:
            logging.info(response.text)
    uploader.upload_dashboard()
    if tmpdir:
        logging.info('Remove %s and contents', tmpdir)
        shutil.rmtree(tmpdir)
    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)
Exemple #5
0
    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
 def test_load7(self):
     assert File.load().filename == "这是一个function作用域的mock"
 def test_load6(self):
     assert File.load().filename == "这是一个class作用域的mock"
def test_load5():
    assert File.load().filename == "这是一个module作用域的mock"
def test_load4():
    assert File.load().filename == "使用别名装饰器,把前缀连起来"
def test_load4():
    assert File.load().filename == "还能给工厂传参"
def test_load1():
    assert File.load().filename == "直接mock返回值"
######为了发现在当前目录下创建的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")
Exemple #13
0
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
Exemple #15
0
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")