Как использовать тестовые данные записываются в файл (xlwt python) - PullRequest
0 голосов
/ 07 октября 2019

Я пишу модульный тест для записи данных в файл xls. Содержимое файла не может быть проверено. Итак, как я могу проверить данные при записи в файл - данные, переданные в функцию ws.write? Как использовать макет?

def data(self, ws, station, start_date, end_date):
        display = []
        col = 0
        row = 1
        col_lable = 0
        row_lable = 0
        list_name = [gettext('Nội dung tin nhắn'), gettext('Ngày giờ')]
        for chip in station.chips.all():
            for sensor in chip.sensors.all():
                for config in sensor.configs.is_alarm():
                    max = float(config.allow_max_value or 0)
                    min = float(config.allow_min_value or 0)
                    if min >= max:
                        lable = f'{station.symbol or ""} {config.name} {config.unit or ""}'
                    else:
                        lable = f'{station.symbol or ""} {config.name} ({min} ~ {max}) {config.unit or ""}'
                    display.append({
                        'values': config.alert_history.filter(created_at__range=(start_date, end_date)).order_by('-created_at'),
                    })
                    ws.write(row_lable, col_lable, lable)
                    index = len(lable) + 15
                    ws.col(col_lable).width = 300 * index
                    ws.row(row_lable).height = 25 * 20
                    col_lable += 1
                    for name in list_name:
                        ws.write(row_lable, col_lable, name, lable_style)
                        ws.col(col_lable).width = 300 * index
                        ws.row(row_lable).height = 25 * 20
                        col_lable += 1
                    row_lable = 0

                    config_values = config.alert_history.filter(created_at__range=(start_date, end_date)).order_by('-created_at')
                    list_values = list(config_values.values_list('value', 'message', 'created_at'))

                    for i in range(3):
                        for list_value in list_values:
                            if i == 2:
                                format = list_value[i]
                                format = format.strftime("%H:%M:%S  %d-%m-%Y")
                                ws.write(row, col, format)
                                ws.row(row).height = 25 * 20
                            else:
                                ws.write(row, col, list_value[i], style)
                                ws.row(row).height = 25 * 20
                            row += 1
                        col += 1
                        row = 1
                row = 1


    def get(self, request, **kwargs):
        station = Station.objects.get(pk=kwargs['pk'])
        start_date = request.GET.get('startdate', False)
        end_date = request.GET.get('enddate', False)
        self.check_permission_user(request)
        if not start_date or not end_date:
            raise Http404()
        response = HttpResponse(content_type='application/ms-excel')
        station_name = self.remove_accents(station.name)
        filename = f'attachment; filename="Alert_history_{station_name}.xls"'
        response['Content-Disposition'] = filename
        wb = xlwt.Workbook(encoding='utf-8')
        ws = wb.add_sheet(f'Alert_history_{station.name}')
        self.data(ws, station, start_date, end_date)
        wb.save(response)
        return response

Я пытаюсь разделить функцию ws.write, но данные очень сложны и повторяются в цикле еще раз. Есть ли другой лучший способ в этом случае?

...