xyc
2 天以前 7032f3fb2ff26256e776e04a9bc62c8fab14379a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.trafficaudit.holiday.service;
 
import org.junit.jupiter.api.Test;
 
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
 
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
 
class HolidayTrendChartServiceTest {
 
    @Test
    void rendersLinePieAndStackedChartsAsPng() throws Exception {
        HolidayTrendChartService service = new HolidayTrendChartService();
        HolidayTrendChartService.ChartSeries first = new HolidayTrendChartService.ChartSeries();
        first.setName("2026年");
        first.setValues(java.util.Arrays.asList(
                java.math.BigDecimal.ONE, java.math.BigDecimal.TEN, null));
        HolidayTrendChartService.ChartSeries second = new HolidayTrendChartService.ChartSeries();
        second.setName("2025年");
        second.setValues(java.util.Arrays.asList(
                java.math.BigDecimal.valueOf(2), java.math.BigDecimal.valueOf(8),
                java.math.BigDecimal.valueOf(4)));
 
        byte[] line = service.lineChart("万人次", java.util.Arrays.asList(first, second), false);
        assertPng(line);
        assertNoLargeLightGrayBackground(line);
 
        HolidayTrendChartService.ChartCategory category = new HolidayTrendChartService.ChartCategory();
        category.setName("铁路");
        category.setValue(java.math.BigDecimal.TEN);
        byte[] pie = service.pieChart("人次", java.util.Collections.singletonList(category), 400, 300);
        assertPng(pie);
 
        byte[] stacked = service.stackedBarChart("占比", java.util.Arrays.asList("10月1日", "10月2日"),
                java.util.Arrays.asList(first, second), true, 500, 320);
        assertPng(stacked);
        assertNoLargeLightGrayBackground(stacked);
    }
 
    private void assertNoLargeLightGrayBackground(byte[] data) throws Exception {
        BufferedImage image = ImageIO.read(new ByteArrayInputStream(data));
        int matches = 0;
        for (int y = 0; y < image.getHeight(); y++) {
            for (int x = 0; x < image.getWidth(); x++) {
                int rgb = image.getRGB(x, y) & 0xFFFFFF;
                if (rgb == 0xF3F4F3) matches++;
            }
        }
        assertTrue(matches < image.getWidth() * image.getHeight() / 20,
                "chart still contains a large light-gray background area");
    }
 
    private void assertPng(byte[] data) {
        assertNotNull(data);
        assertTrue(data.length > 100);
        assertTrue(data[0] == (byte) 0x89 && data[1] == 0x50
                && data[2] == 0x4e && data[3] == 0x47);
    }
}