Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update StringMatchFilter builder API (#3509) #3510

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
/*
* 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 org.apache.logging.log4j.core.filter;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;

import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.test.junit.LoggerContextSource;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

/**
* Unit tests for {@link StringMatchFilter}.
*/
class StringMatchFilterTest {

/**
* Test the normal valid programmatic instantiation of a {@link StringMatchFilter} via its builder.
*/
@Test
void testFilterBuilderOK() {
StringMatchFilter.Builder stringMatchFilterBuilder = StringMatchFilter.newBuilder();
stringMatchFilterBuilder.setText("foo");
StringMatchFilter stringMatchFilter = stringMatchFilterBuilder.build();
assertNotNull(stringMatchFilter, "The filter should not be null.");
assertEquals("foo", stringMatchFilter.getText());
}

/**
* Test that if no match-string is set on the builder, the '{@link StringMatchFilter.Builder#build()}' returns
* {@code null}.
*/
@Test
void testFilterBuilderFailsWithNullText() {
StringMatchFilter.Builder stringMatchFilterBuilder = StringMatchFilter.newBuilder();
Assertions.assertNull(stringMatchFilterBuilder.build());
}

/**
* Test that if a {@code null} string is set as a match-pattern, an {@code IllegalArgumentExeption} is thrown.
*/
@Test
@SuppressWarnings({"DataFlowIssue" // invalid null parameter explicitly being tested
})
void testFilterBuilderFailsWithExceptionOnNullText() {
StringMatchFilter.Builder stringMatchFilterBuilder = StringMatchFilter.newBuilder();
Assertions.assertThrows(IllegalArgumentException.class, () -> stringMatchFilterBuilder.setText(null));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is certainly debatable, but I would rather expect NPE to be thrown here.

The way I see it, there are two levels of validation:

  • The parameter is annotated as @NonNull and we expect the programmer to check for that. In this case NPE seems appropriate.
  • There is a more involved validation process that requires a non-empty string. In this case IllegalArgumentException seems appropriate.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is only because I used the Log4j Assert which throws IllegalArgumentException.

    public Builder setText(final String text) {
            this.text = Assert.requireNonEmpty(text, "The 'text' argument must not be null or empty.");
            return this;
        }

I could of course add an extra Objects.requiresNonNull if you think that is better?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we can modify Assert.requireNonEmpty? What do you think?

It is mostly a question of convention (and we have none), but I think that it is worth differentiating the null and empty cases, since there are plenty of tools that do static analysis on nulls and the caller could use one.

}

/**
* Test that if an empty ({@code ""}) string is set as a match-pattern, an {@code IllegalArgumentException} is thrown.
*/
@Test
void testFilterBuilderFailsWithExceptionOnEmptyText() {
StringMatchFilter.Builder stringMatchFilterBuilder = StringMatchFilter.newBuilder();
Assertions.assertThrows(IllegalArgumentException.class, () -> stringMatchFilterBuilder.setText(""));
}

/**
* Test that if a {@link StringMatchFilter} is specified with a 'text' attribute it is correctly instantiated.
*
* @param configuration the configuration
*/
@Test
@LoggerContextSource("log4j2-stringmatchfilter-3153-ok.xml")
void testConfigurationWithTextPOS(final Configuration configuration) {
final Filter filter = configuration.getFilter();
assertNotNull(filter, "The filter should not be null.");
assertInstanceOf(
StringMatchFilter.class, filter, "Expected a StringMatchFilter, but got: " + filter.getClass());
assertEquals("FooBar", ((StringMatchFilter) filter).getText());
}

/**
* Test that if a {@link StringMatchFilter} is specified without a 'text' attribute it is not instantiated.
*
* @param configuration the configuration
*/
@Test
@LoggerContextSource("log4j2-stringmatchfilter-3153-nok.xml")
void testConfigurationWithTextNEG(final Configuration configuration) {
final Filter filter = configuration.getFilter();
assertNull(filter, "The filter should be null.");
}
Comment on lines +99 to +102
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would rather belong in a unit test for PluginBuilder or similar.
The fact that the user misspells StringMatchFilter or another name, doesn't seem relevant.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this simply tests that a misconfigured (or not at all) fails on build and returns null I think.

A "" invalid name would throw in an entirely different locattion I think - unresolved plugin type.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unless I am mistaken this tests that a misspelled plugin name (StringMatchFfilter) will be ignored.

Since the plugin name is misspelled PluginBuilder will not find the plugin and return null. No code in StringMatchFilter.java will be executed.

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<Configuration status="warn">
<StringMatchFfilter/> <!-- this typo is intentional! -->
<Loggers>
<Root/> <!-- one logger to avoid test warning about no defined loggers -->
</Loggers>
</Configuration>
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<Configuration status="warn">
<StringMatchFilter text="FooBar"/>
<Loggers>
<Root/> <!-- one logger to avoid test warning about no defined loggers -->
</Loggers>
</Configuration>
Original file line number Diff line number Diff line change
Expand Up @@ -47,21 +47,24 @@ protected static org.apache.logging.log4j.Logger getStatusLogger() {

private volatile LifeCycle.State state = LifeCycle.State.INITIALIZED;

protected boolean equalsImpl(final Object obj) {
if (this == obj) {
/**
* Indicates whether some other object is "equal to" this one.
* @param other the other object to compare to
* @return {@code true} if this object is the same as the obj argument; {@code false} otherwise.
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
protected boolean equalsImpl(final Object other) {
// identity check - fast exit
if (this == other) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
// exact class check
if (other == null || this.getClass() != other.getClass()) {
return false;
}
final LifeCycle other = (LifeCycle) obj;
if (state != other.getState()) {
return false;
}
return true;
// field check
final AbstractLifeCycle that = (AbstractLifeCycle) other;
return (this.state == that.state);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,25 +110,29 @@ protected AbstractFilter(final Result onMatch, final Result onMismatch) {
this.onMismatch = onMismatch == null ? Result.DENY : onMismatch;
}

/**
* Constructor which obtains its parameterization from the given builder.
* @param builder the builder
*/
protected AbstractFilter(final AbstractFilterBuilder<?> builder) {
this(builder.getOnMatch(), builder.getOnMismatch());
}

/** {@inheritDoc} */
@Override
protected boolean equalsImpl(final Object obj) {
if (this == obj) {
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
protected boolean equalsImpl(final Object other) {
// identity check - fast exit
if (this == other) {
return true;
}
if (!super.equalsImpl(obj)) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final AbstractFilter other = (AbstractFilter) obj;
if (onMatch != other.onMatch) {
return false;
}
if (onMismatch != other.onMismatch) {
// type check and superclass
if (other == null || this.getClass() != other.getClass()) {
return false;
}
return true;
// field equality
final AbstractFilter that = (AbstractFilter) other;
return super.equalsImpl(that) && this.onMatch == that.onMatch && this.onMismatch == that.onMismatch;
}

/**
Expand Down
Loading