ProtoMatchers.java

/*
 * Copyright 2022 Proto Utils Authors
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package net.morimekta.proto.testing;

import com.google.protobuf.Message;
import net.morimekta.collect.UnmodifiableSet;
import net.morimekta.proto.testing.matchers.EqualMessageIgnoring;
import org.hamcrest.Matcher;

/**
 * Matchers for proto buffers.
 */
public class ProtoMatchers {
    /**
     * Expect a message, with optional fields to be ignored. Ignored fields will both be
     * ignored in comparison and in diff output.
     *
     * @param expected Expected message.
     * @param ignoring Ignored fields. This is a set of field paths following
     *                 the same path spec as in {@link com.google.protobuf.FieldMask}.
     * @param <M>      Message type.
     * @return The matcher.
     */
    public static <M extends Message> Matcher<M> equalToMessage(
            M expected,
            String... ignoring) {
        return new EqualMessageIgnoring<>(
                expected,
                false,
                UnmodifiableSet.asSet(ignoring));
    }

    /**
     * Expect a message, with optional fields to be ignored. Ignored fields will both be
     * ignored in comparison and in diff output. Also ignoring all extensions.
     *
     * @param expected Expected message.
     * @param ignoring Ignored fields. This can be any field descriptor, including extensions.
     * @param <M>      Message type.
     * @return The matcher.
     */
    public static <M extends Message> Matcher<M> equalToMessageIgnoreExtensions(
            M expected,
            String... ignoring) {
        return new EqualMessageIgnoring<>(
                expected,
                true,
                UnmodifiableSet.asSet(ignoring));
    }
}