1. 程式人生 > >Allure報告開發自定義外掛

Allure報告開發自定義外掛

當報告無法滿足當前專案的需求,需要自定義內容來展示在報告中,即需要開發自己的自定義外掛

最終結果 圖 :demo的結果是新增了一個My Tab 目錄欄,(demo未做有意義資料和css樣式)

1.建立一個外掛專案

  基本上外掛專案包含2部分

java classess : 處理報告結果的類

Js script: 主要用於頁面展示,widget或者一些額外的tab

典型目錄

/my-plugin
    /src
        /dist
            /static
            allure-plugin.yml
        /main
            /java
                /my.company.plugin
    build.gradle

 src/dist/static  .js 和 .css 的檔案

src/main/java  java程式碼

allure-plugin.yml  配置檔案

id: my-plugin
name: Plugin name goes here
description: More detailed explanation of what does this plugin do.
extensions:
- my.company.allure.CustomPlugin // - Fully qualified names of classes that implement `Extension` interface and comprise data processing functionality.
- my.company.allure.CustomWidget
jsFiles:
- index.js
cssFiles:
- styles.css

我的目錄結構

增加 allure-plugin-api 依賴

我使用maven工程

   <dependency>
            <groupId>io.qameta.allure</groupId>
            <artifactId>allure-plugin-api</artifactId>
            <version>${allureVersion}</version>
            <scope>provided</scope>
        </dependency>

2 寫java類處理測試結果

    自定義外掛類需要實現你需要的介面功能

   Aggregator 的aggregate  方法可以實現資料的提取處理,這裡我把我想要的結果儲存到myplugin.json檔案內

   Widget 的getData  將資料填充到前端js內

package com.fengtai.allure.plugins;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import io.qameta.allure.Aggregator;
import io.qameta.allure.Widget;
import io.qameta.allure.context.JacksonContext;
import io.qameta.allure.core.Configuration;
import io.qameta.allure.core.LaunchResults;
import io.qameta.allure.entity.TestResult;

public class MyPlugin implements Aggregator, Widget {

	@Override
	public void aggregate(final Configuration configuration, final List<LaunchResults> launches,
			final Path outputDirectory) throws IOException {
		final JacksonContext jacksonContext = configuration.requireContext(JacksonContext.class);
		final Path dataFolder = Files.createDirectories(outputDirectory.resolve("data"));
		final Path dataFile = dataFolder.resolve("myplugindata.json");
		final Stream<TestResult> resultsStream = launches.stream().flatMap(launch -> launch.getAllResults().stream());
		try (OutputStream os = Files.newOutputStream(dataFile)) {
			jacksonContext.getValue().writeValue(os, extractData(resultsStream));
		}
	}

	private Collection<Map> extractData(final Stream<TestResult> testResults) {

		Collection<Map> collection = new ArrayList<Map>();
		List<TestResult> results = testResults.collect(Collectors.toList());
		for (TestResult rs : results) {
			try {
				collection.add(objectToMap(rs));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return collection;// TODO
	}

	@Override
	public Object getData(Configuration configuration, List<LaunchResults> launches) {
		// Stream<TestResult> filteredResults = launches.stream().flatMap(launch
		// -> launch.getAllResults().stream())
		// .filter(result -> result.getStatus().equals(Status.FAILED));
		Stream<TestResult> filteredResults = launches.stream().flatMap(launch -> launch.getAllResults().stream());
		return extractData(filteredResults);
	}

	/***
	 * 物件 轉換成 map
	 */
	public static Map<String, Object> objectToMap(Object obj) throws Exception {
		if (obj == null)
			return null;

		Map<String, Object> map = new HashMap<String, Object>();

		BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
		for (PropertyDescriptor property : propertyDescriptors) {
			String key = property.getName();
			if (key.compareToIgnoreCase("class") == 0) {
				continue;
			}
			Method getter = property.getReadMethod();
			Object value = getter != null ? getter.invoke(obj) : null;
			map.put(key, value);
		}

		return map;
	}

	@Override
	public String getName() {
		return "mywidget";
	}
}

3. 在報告中新增一個新tab

   JS程式碼 index.js

var MyTabModel = Backbone.Collection.extend({
    url: 'data/myplugindata.json'
})

class MyLayout extends allure.components.AppLayout {

    initialize() {
        this.model = new MyTabModel();
    }

    loadData() {
        return this.model.fetch();
    }

    getContentView() {
        return new MyView({items: this.model.models});
    }
}

const template = function (data) {
    html = '<h3 class="pane__title">My Tab</h3>';
    for (var item of data.items) {
        html += '<p>' + item.attributes.name + ' says: ' + item.attributes.sounds + '</p>';
    }
    return html;
}
//在allure報告的左邊增加一個tab按鈕
var MyView = Backbone.Marionette.View.extend({
    template: template,

    render: function () {
        this.$el.html(this.template(this.options));
        return this;
    }
})

//
allure.api.addTab('mytab', {
    title: 'My Tab', icon: 'fa fa-trophy',
    route: 'mytab',
    onEnter: (function () {
        return new MyLayout()
    })
});

//wiget中展示
class MyWidget extends Backbone.Marionette.View {

    template(data) {
            return widgetTemplate(data)
    }

    serializeData() {
        return {
            items: this.model.get('items'),
        }
    }
}

allure.api.addWidget('mywidget', MyWidget);

4.打包外掛

直接使用maven build jar包

外掛存放路徑,安裝的allure 命令列 下的plugins資料夾,並且將 config下的allure.yml檔案中增加自定義外掛

外掛的開發和安裝就已經完成了。

如何使用

使用命令,操作測試結果,並生成報告 generate的時候會呼叫外掛功能 , open直接開啟報告

allure generate ./allure-result -c

allure open ./allure-report