|
| 1 | +/******************************************************************************* |
| 2 | + * Copyright (c) 2025 Vector Informatik and others. |
| 3 | + * |
| 4 | + * This program and the accompanying materials |
| 5 | + * are made available under the terms of the Eclipse Public License 2.0 |
| 6 | + * which accompanies this distribution, and is available at |
| 7 | + * https://www.eclipse.org/legal/epl-2.0/ |
| 8 | + * |
| 9 | + * SPDX-License-Identifier: EPL-2.0 |
| 10 | + *******************************************************************************/ |
| 11 | +package org.eclipse.ui.tests.harness.util; |
| 12 | + |
| 13 | +import org.eclipse.jface.preference.IPreferenceStore; |
| 14 | +import org.eclipse.jface.preference.PreferenceMemento; |
| 15 | +import org.junit.jupiter.api.extension.AfterEachCallback; |
| 16 | +import org.junit.jupiter.api.extension.BeforeEachCallback; |
| 17 | +import org.junit.jupiter.api.extension.ExtensionContext; |
| 18 | + |
| 19 | +/** |
| 20 | + * Preference helper to restore changed preference values after test run. |
| 21 | + */ |
| 22 | +public class PreferenceMementoExtension implements BeforeEachCallback, AfterEachCallback { |
| 23 | + |
| 24 | + private PreferenceMemento prefMemento; |
| 25 | + |
| 26 | + @Override |
| 27 | + public void beforeEach(ExtensionContext context) { |
| 28 | + prefMemento = new PreferenceMemento(); |
| 29 | + } |
| 30 | + |
| 31 | + @Override |
| 32 | + public void afterEach(ExtensionContext context) { |
| 33 | + if (prefMemento != null) { |
| 34 | + prefMemento.resetPreferences(); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * Change a preference value for the associated test run. The preference will |
| 40 | + * automatically be reset to the value it had before starting when executing |
| 41 | + * {@link #afterEach(ExtensionContext)}. |
| 42 | + * |
| 43 | + * @param <T> preference value type. The type must have a corresponding |
| 44 | + * {@link IPreferenceStore} setter. |
| 45 | + * @param store preference store to manipulate (must not be <code>null</code>) |
| 46 | + * @param name preference to change |
| 47 | + * @param value new preference value |
| 48 | + * @throws IllegalArgumentException when setting a type which is not supported |
| 49 | + * by {@link IPreferenceStore} |
| 50 | + * |
| 51 | + * @see IPreferenceStore#setValue(String, double) |
| 52 | + * @see IPreferenceStore#setValue(String, float) |
| 53 | + * @see IPreferenceStore#setValue(String, int) |
| 54 | + * @see IPreferenceStore#setValue(String, long) |
| 55 | + * @see IPreferenceStore#setValue(String, boolean) |
| 56 | + * @see IPreferenceStore#setValue(String, String) |
| 57 | + */ |
| 58 | + public <T> void setPreference(IPreferenceStore store, String name, T value) { |
| 59 | + if (prefMemento == null) { |
| 60 | + prefMemento = new PreferenceMemento(); |
| 61 | + } |
| 62 | + prefMemento.setValue(store, name, value); |
| 63 | + } |
| 64 | +} |
0 commit comments