001/*
002 * (C) Copyright 2019 Nuxeo (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 *
016 *  Contributors:
017 *      Kevin Leturc <kleturc@nuxeo.com>
018 */
019
020package org.nuxeo.runtime.test.runner;
021
022import java.util.Properties;
023
024import org.junit.runners.model.FrameworkMethod;
025import org.nuxeo.runtime.api.Framework;
026
027/**
028 * Features handling {@link WithFrameworkProperty} annotations.
029 *
030 * @since 11.1
031 */
032public class WithFrameworkPropertyFeature implements RunnerFeature {
033
034    protected Properties previousProperties = new Properties();
035
036    @Override
037    public void beforeSetup(FeaturesRunner runner, FrameworkMethod method, Object test) {
038        Properties properties = Framework.getProperties();
039        for (var annot : method.getMethod().getAnnotationsByType(WithFrameworkProperty.class)) {
040            String propertyKey = annot.name();
041            Object previousProperty = properties.remove(propertyKey);
042            if (previousProperty != null) {
043                previousProperties.put(propertyKey, previousProperty);
044            }
045            properties.put(propertyKey, annot.value());
046        }
047    }
048
049    @Override
050    public void afterTeardown(FeaturesRunner runner, FrameworkMethod method, Object test) {
051        Properties properties = Framework.getProperties();
052        for (var annot : method.getMethod().getAnnotationsByType(WithFrameworkProperty.class)) {
053            String propertyKey = annot.name();
054            if (previousProperties.contains(propertyKey)) {
055                properties.put(propertyKey, previousProperties.get(propertyKey));
056            } else {
057                properties.remove(propertyKey);
058            }
059        }
060        previousProperties.clear();
061    }
062
063}