All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.hamcrest.core.DescribedAs Maven / Gradle / Ivy

Go to download

Statistical sampling library for use in virtualdataset libraries, based on apache commons math 4

There is a newer version: 2.12.15
Show newest version
/*  Copyright (c) 2000-2006 hamcrest.org
 */
package org.hamcrest.core;

import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;

import java.util.regex.Pattern;

import static java.lang.Integer.parseInt;

/**
 * Provides a custom description to another matcher.
 */
public class DescribedAs extends BaseMatcher {
    private final String descriptionTemplate;
    private final Matcher matcher;
    private final Object[] values;
    
    private final static Pattern ARG_PATTERN = Pattern.compile("%([0-9]+)"); 
    
    public DescribedAs(String descriptionTemplate, Matcher matcher, Object[] values) {
        this.descriptionTemplate = descriptionTemplate;
        this.matcher = matcher;
        this.values = values.clone();
    }
    
    @Override
    public boolean matches(Object o) {
        return matcher.matches(o);
    }

    @Override
    public void describeTo(Description description) {
        java.util.regex.Matcher arg = ARG_PATTERN.matcher(descriptionTemplate);
        
        int textStart = 0;
        while (arg.find()) {
            description.appendText(descriptionTemplate.substring(textStart, arg.start()));
            description.appendValue(values[parseInt(arg.group(1))]);
            textStart = arg.end();
        }
        
        if (textStart < descriptionTemplate.length()) {
            description.appendText(descriptionTemplate.substring(textStart));
        }
    }
    
    @Override
    public void describeMismatch(Object item, Description description) {
        matcher.describeMismatch(item, description);
    }

    /**
     * Wraps an existing matcher, overriding its description with that specified.  All other functions are
     * delegated to the decorated matcher, including its mismatch description.
     * 

* For example: *

describedAs("a big decimal equal to %0", equalTo(myBigDecimal), myBigDecimal.toPlainString())
* * @param description * the new description for the wrapped matcher * @param matcher * the matcher to wrap * @param values * optional values to insert into the tokenised description */ @Factory public static Matcher describedAs(String description, Matcher matcher, Object... values) { return new DescribedAs(description, matcher, values); } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy