Skip to content

Add proxy package test coverage and fix IntelliJ inspections in grails-datamapping-core - #16155

Merged
jdaugherty merged 6 commits into
8.0.xfrom
chore/lint-proxy-package
Oct 1, 2026
Merged

jdaugherty merged 6 commits into
8.0.xfrom
chore/lint-proxy-package

Conversation

@borinquenkid

Copy link
Copy Markdown
Member

Summary

  • Adds unit test coverage for GroovyProxyFactory and ProxyInstanceMetaClass in grails-datamapping-core, which previously had none in this module despite implementing the core Groovy-based proxy contract used outside Hibernate/Neo4j.
  • Fixes IntelliJ inspection warnings in both classes: methods with no instance-state dependency marked static, replaces deprecated Class.newInstance() with getDeclaredConstructor().newInstance(), makes never-reassigned fields final, suppresses the unchecked-generics warning inherent to MetaClass.getTheClass()'s raw return type, and fills in missing Javadoc tag descriptions.

Test plan

  • ./gradlew :grails-datamapping-core:test --tests "org.grails.datastore.gorm.proxy.*" — 29 tests pass
  • ./gradlew :grails-datamapping-core:test — full module suite passes
  • ./gradlew :grails-datamapping-core:codeStyle — no Checkstyle/CodeNarc violations

🤖 Generated with Claude Code

Copilot AI lite review requested due to automatic review settings August 15, 2026 23:54

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR improves grails-datamapping-core’s Groovy proxy support by adding missing unit coverage for the proxy implementation and applying a set of code adjustments aimed at addressing IntelliJ inspection warnings.

Changes:

  • Added new Spock specs covering GroovyProxyFactory and ProxyInstanceMetaClass behavior (lazy resolution, proxy metadata, delegation paths).
  • Refactored ProxyInstanceMetaClass (final fields, Javadoc tag descriptions, switch expressions, warning suppression) to reduce inspection noise and modernize code.
  • Refactored GroovyProxyFactory to replace deprecated instantiation and adjust helper methods/annotations (with a potential API-compatibility concern noted in comments).

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

File Description
grails-datamapping-core/src/test/groovy/org/grails/datastore/gorm/proxy/ProxyInstanceMetaClassSpec.groovy Adds focused unit coverage for proxy metaclass behavior (method/property/attribute resolution semantics).
grails-datamapping-core/src/test/groovy/org/grails/datastore/gorm/proxy/GroovyProxyFactorySpec.groovy Adds unit coverage for proxy factory creation/unwrap/identifier/initialization paths.
grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/proxy/ProxyInstanceMetaClass.java Cleans up implementation details (final fields, switch refactor, warning suppression, Javadoc completeness).
grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/proxy/GroovyProxyFactory.groovy Updates proxy factory internals (constructor instantiation, annotation import usage) and changes helper methods to static (flagged).
Suppressed comments (2)

grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/proxy/GroovyProxyFactory.groovy:128

  • Same concern here: making a protected method static breaks subclasses that might override it to customize proxy metaClass installation. Consider keeping it non-static and suppressing IntelliJ’s “method may be static” inspection instead.
    @CompileDynamic
    protected static void setMetaClassDynamic(Object proxy, MetaClass proxyMc) {
        proxy.setMetaClass(proxyMc)
    }

grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/proxy/GroovyProxyFactory.groovy:170

  • Making this protected method static is also a potential breaking change for subclasses (cannot be overridden). If the goal is just to satisfy IntelliJ’s inspection, keep it as an instance method and suppress GrMethodMayBeStatic on the method.
    protected static MetaClass unwrapHandleMetaClass(MetaClass mc) {
        if (mc instanceof HandleMetaClass) {
            return ((HandleMetaClass) mc).getAdaptee()
        }
        return mc
    }

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@bito-code-review

Copy link
Copy Markdown

The concern regarding the conversion of protected instance methods to static is valid. In Groovy, changing an instance method to static breaks binary compatibility for any subclasses that override these methods, as static methods are not polymorphic and cannot be overridden.

If these changes were made solely to satisfy static analysis inspections, it is recommended to revert them to instance methods and suppress the inspection, consistent with existing patterns in the repository.

grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/proxy/GroovyProxyFactory.groovy

@CompileDynamic
    protected Serializable getIdDynamic(obj) {
        if (obj.respondsTo('getId')) {
            return (Serializable)obj.invokeMethod('getId', null)
        }

@codecov

codecov Bot commented Aug 16, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 59.6545%. Comparing base (80d171d) to head (c70c206).
⚠️ Report is 14 commits behind head on 8.0.x.

Additional details and impacted files

Impacted file tree graph

@@                 Coverage Diff                 @@
##                8.0.x     #16155         +/-   ##
===================================================
+ Coverage     32.8401%   59.6545%   +26.8145%     
- Complexity        563      25441      +24878     
===================================================
  Files              84       2215       +2131     
  Lines            4933     108892     +103959     
  Branches          864      19790      +18926     
===================================================
+ Hits             1620      64959      +63339     
- Misses           3053      35058      +32005     
- Partials          260       8875       +8615     
Files with missing lines Coverage Δ
...ils/datastore/gorm/proxy/GroovyProxyFactory.groovy 95.6522% <100.0000%> (ø)
...s/datastore/gorm/proxy/ProxyInstanceMetaClass.java 100.0000% <100.0000%> (ø)
...ails/data/testing/tck/tests/GroovyProxySpec.groovy 100.0000% <100.0000%> (ø)

... and 2129 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@borinquenkid borinquenkid added this to the grails:8.1.0-M1 milestone Aug 16, 2026
@borinquenkid
borinquenkid requested review from jdaugherty and a lite review from Copilot August 16, 2026 01:06

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 4 out of 4 changed files in this pull request and generated no new comments.

Suppressed comments (1)

grails-datamapping-core/src/test/groovy/org/grails/datastore/gorm/proxy/ProxyInstanceMetaClassSpec.groovy:103

  • The test name says the call “delegates” for getTarget/initialize, but ProxyInstanceMetaClass.invokeMethod returns getProxyTarget() directly for those method names (no delegate.invokeMethod call). Removing the unused delegate stub and renaming the test avoids misleading future readers.
    void "invokeMethod resolves the target and delegates for getTarget/initialize"() {
        given:
        ProxyInstanceMetaClass metaClass = newMetaClass()
        session.retrieve(ProxyInstanceTestTarget, 11L) >> target
        delegate.invokeMethod(target, methodName, [] as Object[]) >> target

@borinquenkid borinquenkid moved this to In Progress in Apache Grails Aug 16, 2026
@jdaugherty
jdaugherty force-pushed the chore/lint-proxy-package branch from 55d4b81 to 7b33002 Compare September 30, 2026 16:24

@jdaugherty jdaugherty left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Rebased onto current 8.1.x (clean, no conflicts) and pushed as 7b33002. The author's five commits are unchanged; the sixth commit holds the review fixes so they can be inspected separately.

While extending the new specs to drive a real proxy through Groovy dispatch, one of them exposed a pre-existing bug in ProxyInstanceMetaClass: property assignment (proxy.name = 'x') and field access (proxy.@name) never reached the proxy rules. Groovy 5 routes those through the sender-aware MetaClass variants (the ones taking a Class sender), and DelegatingMetaClass forwards them straight to the delegate with the proxy shell as receiver, so only the three-argument overrides this class had were bypassed. Writes landed on the proxy shell and the proxy stayed uninitialized. The fix shares the proxy rules between both arities; details inline.

Verified locally:

  • :grails-datamapping-core:test (full module, 1787 tests) and codeStyle for grails-datamapping-core and grails-datamapping-tck pass.
  • :grails-datamapping-core-test:test --tests "*GroovyProxySpec*" (TCK against SimpleMapDatastore) passes; the new write case fails against the unfixed metaclass for the GroovyProxyFactory row.
  • Not run locally: the Neo4j suite, which also executes the TCK spec. CI covers it.

}

@Override
public void setProperty(Class sender, Object object, String property, Object newValue, boolean useSuper,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is the fix for the bug the new dispatch tests exposed. ScriptBytecodeAdapter.setGroovyObjectProperty checks whether the receiver's setProperty is the GroovyObject default method (true for every modern POGO, including GORM entities: Location in the TCK has no generated setProperty) and then calls getMetaClass().setProperty(senderClass, receiver, name, value, false, false). DelegatingMetaClass implements that six-argument variant by forwarding to the delegate with the proxy as receiver, so the three-argument override above was never consulted for proxy.name = 'x'. The same applies to getGroovyObjectProperty (five-argument getProperty), getGroovyObjectField (four-argument getAttribute) and setGroovyObjectField (six-argument setAttribute); the six-argument invokeMethod is covered too for consistency.

Rather than duplicate the rules, each pair of overrides now shares a private lookup (proxyPropertyValue etc.) that returns the proxy-handled value or the DELEGATE marker, plus a receiver-selection helper. The sender/useSuper/fromInsideClass arguments are passed through unchanged so delegate semantics are preserved.


@groovy.transform.CompileDynamic
@CompileDynamic
@SuppressWarnings('GrMethodMayBeStatic')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Keeping these as instance methods with the suppression was the right call: protected hooks that subclasses may override must stay virtual. The suppression matches the existing GrMethodMayBeStatic usage in GrailsBanner and AbstractDatastoreInitializer, so no convention concern here.

proxy.target.is(target)
}

void "writing a regular property through Groovy dispatch loads the target and writes to it"() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is the case that first exposed the dispatch bug. Against the PR's original ProxyInstanceMetaClass it failed with session.retrieve never invoked: the assignment wrote changed into the proxy shell's own name field, target.name stayed loaded, and the proxy remained uninitialized. proxy.setName(...) and proxy.setProperty(...) did work, which is why the mock-delegate spec could not see it.


GroovyProxyFactory proxyFactory = new GroovyProxyFactory()

void "createProxy returns an uninitialized proxy whose identifier is available without loading"() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Renamed from "returns an initialized-looking instance": the feature asserts !isInitialized(proxy), so the old name said the opposite of what it checks.

Session session = Mock(Session)
MetaClass delegate = Mock(MetaClass)
ProxyInstanceTestTarget target = new ProxyInstanceTestTarget()
Object proxy = new Object()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Worth being aware of when reading this spec: with a Mock(MetaClass) delegate and a plain Object receiver, it can only verify the three-argument methods it calls directly. It cannot detect which MetaClass variant Groovy actually dispatches through, which is how the property-assignment bug slipped past full line and branch coverage. The cases that drive a real proxy through Groovy dispatch (proxy.name, proxy.name = ..., proxy.@name, proxy.describe()) live in GroovyProxyFactorySpec; this spec now also pins the sender-aware variants directly.

0 * session.retrieve(_, _)
}

void "invokeMethod returns the resolved target for getTarget/initialize without delegating"() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

getTarget/initialize return getProxyTarget() directly without calling the delegate, so the previous delegate.invokeMethod(...) >> target stub was never hit and the old name ("delegates") was misleading. Now asserts the retrieve, that the delegate is not invoked, and that the proxy is initiated afterwards.

useGroovyProxyFactory << [true, false]
}

void 'Test writing a property through a proxy updates the proxied instance'() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

End-to-end regression case for the dispatch fix, running for both GroovyProxyFactory and the default Javassist factory. Against the unfixed metaclass the useGroovyProxyFactory: true row fails at location.isInitialized() (the write went to the shell). Runs under grails-datamapping-core-test (SimpleMapDatastore) and the Neo4j suite; the Hibernate suites skip this spec via the existing @IgnoreIf.

@testlens-app

This comment has been minimized.

@jamesfredley

Copy link
Copy Markdown
Contributor

I see a good case to move this from 8.1.x to 8.0.0.

borinquenkid and others added 6 commits October 1, 2026 00:45
GroovyProxyFactory and ProxyInstanceMetaClass had no tests in this
module despite implementing the core Groovy-based proxy contract used
outside Hibernate/Neo4j. Also picks up a CodeNarc auto-fix replacing a
fully-qualified @CompileDynamic annotation with an import.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Mark instance-state-free helper methods static and replace the
deprecated Class.newInstance() with getDeclaredConstructor().newInstance().

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Make the never-reassigned session/key fields final, suppress the
unchecked-generics warning inherent to MetaClass.getTheClass()'s raw
Class return type, fill in missing Javadoc tag descriptions on
invokeMethod, and switch to switch-expressions for getProperty/
setProperty/getAttribute.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Making protected getIdDynamic/setMetaClassDynamic/unwrapHandleMetaClass
static would silently break binary compatibility for any subclass
overriding them, since static methods aren't polymorphic. Suppress the
IntelliJ inspection instead, matching the existing
@SuppressWarnings('GrMethodMayBeStatic') convention used elsewhere in
the repo.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Cover the previously-untested target property/attribute cases in
getProperty/getAttribute, the already-initiated branch of the
class/domainClass ternary, and the remaining argument-shape branches
of the setMetaClass special case in invokeMethod/setProperty. File is
now fully line- and branch-covered.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
…tend proxy coverage

Groovy dispatches property assignment, field access and non-indy property
reads on GroovyObject instances through the sender-aware MetaClass variants
(getProperty/setProperty/getAttribute/setAttribute taking a sender Class).
DelegatingMetaClass forwards those straight to the delegate with the proxy
as the receiver, so the three-argument overrides in ProxyInstanceMetaClass
were skipped: `proxy.name = 'x'` wrote to the proxy shell instead of the
proxied instance and left the proxy uninitialized, and `proxy.@name` read
the shell's field. Share the proxy rules between both arities so every
dispatch path resolves the target consistently.

Extend the coverage added by this PR to exercise real Groovy dispatch
through a proxy (property and field reads and writes, method calls, proxy
state queries), the mapping-context and direct-id fallbacks in
GroovyProxyFactory, association initialization checks, null handling and
the sender-aware MetaClass variants. Add a TCK case that writes a property
through a proxy for both proxy factories. Rename the misleading
'initialized-looking' feature and drop the unused delegate stub from the
getTarget/initialize case, which returns the target without delegating.
@jdaugherty
jdaugherty force-pushed the chore/lint-proxy-package branch from 7b33002 to c70c206 Compare October 1, 2026 04:48
@jdaugherty
jdaugherty changed the base branch from 8.1.x to 8.0.x October 1, 2026 04:48
@jdaugherty

Copy link
Copy Markdown
Contributor

per weekly, we've pulled this into the 8.0.x branch.

@jdaugherty
jdaugherty merged commit afbfed3 into 8.0.x Oct 1, 2026
84 checks passed
@jdaugherty
jdaugherty deleted the chore/lint-proxy-package branch October 1, 2026 04:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants