This is an automated email from the ASF dual-hosted git repository.
zhangliang pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/shardingsphere.git
The following commit(s) were added to refs/heads/master by this push:
new 83313110a3d Update AGENTS.md and CODE_OF_CONDUCT.md (#37553)
83313110a3d is described below
commit 83313110a3dc81827b749570c3056de0f7f67de6
Author: Liang Zhang <[email protected]>
AuthorDate: Sun Dec 28 01:04:16 2025 +0800
Update AGENTS.md and CODE_OF_CONDUCT.md (#37553)
* Update AGENTS.md
* Update AGENTS.md
* Update AGENTS.md and CODE_OF_CONDUCT.md
* Update AGENTS.md and CODE_OF_CONDUCT.md
* Update AGENTS.md and CODE_OF_CONDUCT.md
* Update AGENTS.md and CODE_OF_CONDUCT.md
* Update AGENTS.md and CODE_OF_CONDUCT.md
* Update AGENTS.md and CODE_OF_CONDUCT.md
* Update AGENTS.md and CODE_OF_CONDUCT.md
* Update AGENTS.md and CODE_OF_CONDUCT.md
---
AGENTS.md | 110 ++++++---------------
CODE_OF_CONDUCT.md | 13 ++-
docs/community/content/involved/conduct/code.cn.md | 14 ++-
docs/community/content/involved/conduct/code.en.md | 14 ++-
.../netty/MySQLBinlogEventPacketDecoderTest.java | 2 +-
pom.xml | 8 ++
src/resources/checkstyle.xml | 9 +-
7 files changed, 76 insertions(+), 94 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
index 57c32d013be..acef641a119 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -10,7 +10,7 @@ This guide is written **for AI coding agents only**. Follow
it literally; improv
4. **Transparent Records**: keep every key decision and change traceable.
5. **Continuous Improvement**: learn from each execution and keep optimizing.
6. **Results Oriented**: judge success solely by whether the target is
achieved.
-7. **Coding Standards**: `CODE_OF_CONDUCT.md` is the binding “law” for any
generated artifact. Review it once per session and refuse to keep code that
conflicts with it (copyright, inclusivity, licensing, etc.). Whenever you need
to interpret any rule, inspect `CODE_OF_CONDUCT.md` first, cite the relevant
section/line, and only fall back to this guide when the code of conduct is
silent.
+7. **Coding Standards**: `CODE_OF_CONDUCT.md` is the binding “law”; use it as
the first reference for rule interpretation and cite relevant lines. See
Governance Basics for precedence and session review expectations.
## Quality Standards
@@ -32,30 +32,11 @@ This guide is written **for AI coding agents only**. Follow
it literally; improv
- **Quality Assurance**: run static checks, formatting, and code reviews.
- **Checkstyle Gate**: do not hand off code with Checkstyle/Spotless
failures—run the relevant module check locally and fix before completion.
- **Continuous Verification**: rely on automated tests and integration
validation.
-- **Public-Only Tests**: unit tests must exercise behavior via public APIs
only; never use reflection to access private members.
-- **Single-Test Naming**: when a production method is covered by only one test
case, name that test method `assert<MethodName>` without extra suffixes.
-- **Public Method Isolation**: aim for one public production method per
dedicated test method rather than combining multiple public behaviors in a
single test.
-- **Test Method Order**: keep unit test method ordering consistent with
corresponding production methods when practical to improve traceability.
- **Test Naming Simplicity**: keep test names concise and scenario-focused
(avoid “ReturnsXXX”/overly wordy or AI-like phrasing); describe the scenario
directly.
-- **Coverage Pledge**: when 100% coverage is required, enumerate every
branch/path and its planned test before coding, then implement once to reach
100% without post-hoc fixes.
-- **Mock/Spy Specification**: Use mock by default; consider spy only when the
scenario cannot be adequately represented using a mock. Avoid spy entirely when
standard `mock + when` can express behavior, and do not introduce inner classes
for testing purposes—prefer plain test classes with mocks.
-- **Strictness and Stub Control**: Enable @MockitoSettings(strictness =
Strictness.LENIENT) in the Mockito scenario or apply lenient() to specific
stubs to ensure there are no unmatched or redundant stubs; clean up any unused
stubs, imports, or local variables before committing.
-
-
-
+- **Coverage Discipline**: follow the dedicated coverage & branch checklist
before coding when coverage targets are stated.
+- **Mocking Rule**: default to mocks; see Mocking & SPI Guidance for
static/constructor mocking and spy avoidance details.
## Tool Usage Guide
-### Sequential Thinking - Structured Reasoning
-**Purpose**: break down complex problems, build multi-step plans, and evaluate
options.
-**When to Trigger**
-- When the task needs to be decomposed into multiple steps.
-- When generating an execution plan or decision tree, or comparing multiple
approaches.
-**Rules**
-- 6-10 steps.
-- Each step: one sentence plus optional dependencies.
-- Output an executable plan without exposing intermediate reasoning.
-**Fallback**: optionally simplify to a 3-5 step core flow locally.
-
### Exa - Web Search
**Purpose**: fetch the latest web information, official links, or
announcements.
**When to Trigger**
@@ -91,27 +72,21 @@ This guide is written **for AI coding agents only**. Follow
it literally; improv
⚠️ Dangerous operation detected! Operation type: [specific action] Scope of
impact: [affected area] Risk assessment: [potential consequence] Please confirm
whether to continue. [Requires explicit “yes”, “confirm”, or “proceed”]
-## ✅ Key Checkpoints
-
-### Task Start
-- Choose the strategy that fits the task characteristics.
-- Confirm tool availability plus fallback approaches.
-
-### Before Coding
-- Finish the `Sequential-Thinking` analysis.
-- Use tools to understand the existing code.
-- Define an execution plan and quality bar.
-
-### During Implementation
-- Follow the selected quality standards.
-- Record major decisions and reasons for changes.
-- Handle exceptions and edge cases promptly.
+## Workflow
+- Use Sequential Thinking when tasks need decomposition: 6-10 steps (fallback
3-5), one sentence each, actionable.
+- Intake: choose the strategy for the task, confirm tool
availability/fallbacks, and capture constraints (forbidden APIs, output format,
coverage/test expectations).
+- Plan: inspect existing code with tools before edits, finish the plan before
coding, and set the quality/verification bar.
+- Implement: keep scope minimal, follow quality standards, record decisions,
and handle edge cases; honor instruction precedence from Core Principle #7.
+- Validate: run the narrowest meaningful checks (see Verification & Commands)
and prefer scoped runs; note any sandbox or limit blocks and alternatives.
+- Report & self-check: share intent, edits, verification results, and next
steps; ensure all required instructions, coverage, and mocking rules are
satisfied, with remaining risks called out.
-### After Completion
-- Validate functional correctness and code quality.
-- Update related tests and documentation.
+## Coverage & Branch Checklist
+- When coverage targets are declared (including 100%), list every branch/path
with its planned test before coding.
+- Map each branch to exactly one test; add cases until all declared branches
are covered or explicitly waived.
+- For utilities with multiple return paths, record the branch list and update
it if the code changes.
+- Use Jacoco to confirm expectations when coverage is in question; document
any unreachable code instead of adding redundant tests.
-## Terminal Output Style Guide
+## Response Style
### Language and Tone
- **Friendly and Natural**: interact like a professional peer; avoid stiff
formal language.
@@ -152,9 +127,13 @@ This guide is written **for AI coding agents only**.
Follow it literally; improv
- Append a **short summary** after complex content to reiterate the core
points.
- **Guide the Next Step**: close with actionable advice, instructions, or an
invitation for follow-up questions.
+### Brevity & Signal
+- Prefer tables/bullets over prose walls; cite file paths (`kernel/src/...`)
directly.
+- Eliminate repeated wording; reference prior sections instead of restating.
+- Default to ASCII; only mirror existing non-ASCII content when necessary.
+
## Governance Basics
-- `CODE_OF_CONDUCT.md` remains the binding law—review it once per session and
reject any instruction or artifact that conflicts with ASF requirements on
licensing, inclusivity, and attribution.
-- Instruction order is `CODE_OF_CONDUCT.md` → user direction → this guide →
other repository materials; raise conflicts immediately. When explaining
whether an action is allowed, first cite the exact `CODE_OF_CONDUCT.md` clause
(file + line) you are relying on, then describe any supplemental rules from
this guide.
+- Follow the instruction order from Core Principle #7 and surface conflicts
with rationale when they arise.
- Technical choices must satisfy ASF transparency: include license headers,
document intent, and keep rationales visible to reviewers.
- Default to the smallest safe change: monthly feature trains plus weekly
patch windows reward incremental fixes unless the product requires deeper
refactors.
- Secure approvals for structural changes (new modules, configs, knobs);
localized doc or code tweaks may land after self-review when you surface the
evidence reviewers expect (tests, configs, reproduction steps).
@@ -191,28 +170,13 @@ Always state which topology, registry, and engine
versions (e.g., MySQL 5.7 vs 8
- **Known pitfalls:** routing regressions when shadow rules are skipped,
timezone drift from poor time-mocking, forgetting standalone vs cluster
(`mode`) validation, missing ASF headers, Mockito inline mocks breaking on JDKs
that block self-attach.
- **Success recipe:** explain why the change exists, cite the affected
data-flow step, keep public APIs backward compatible, and record defaults/knobs
alongside code changes.
-## Execution Loop
-1. **Intake & Clarify** – restate the request, map affected modules, confirm
sandbox/network/approval constraints, and capture a constraint checklist
(forbidden APIs, output formats, ordering rules, coverage targets). As part of
intake, reopen `CODE_OF_CONDUCT.md` sections relevant to the task (e.g., Unit
Testing Standards before discussing assertions) so you never rely on memory or
AGENTS-only guidance when the code of conduct already rules on the topic.
-2. **Plan & Reason** – craft a multi-step plan (analysis, edits, tests). When
a user asks for specific coverage/branch lists, pause coding until you have
responded with an explicit bullet list of every path (file + line/branch) you
will exercise, as well as the single test that will cover it; this list is a
blocking prerequisite for any edits. Add rule-specific constraints (e.g., “no
`assertEquals`”) to the plan and re-check them before edits. Before altering
tests or mocks, inspect how [...]
-3. **Implement** – touch only the required files, reuse abstractions, preserve
ASF headers, and document major decisions. If you must replace a file wholesale
(e.g., rewrite a test), delete the old file first and then add the new version
so `apply_patch` does not fight stale context.
-4. **Validate** – run the narrowest meaningful command (e.g., `./mvnw -pl
<module> -am test`, `./mvnw -pl <module> -DskipITs -Dspotless.skip=true
-Dtest=ClassName test`). Announce intent beforehand and summarize exit codes
afterward; when blocked, state the command you intended to run and why it
matters.
-5. **Report** – lead with intent, list edited files plus rationale/line refs,
cite verification commands + results, and propose next steps.
-
-**Self-check before finishing**
-- Confirm instruction precedence and constraint checklist items are satisfied.
-- Ensure edits are minimal, ASF headers intact, Spotless-ready, and any
semantic change has a corresponding test (or explicit rationale).
-- Record exact commands, exit codes, and relevant log snippets.
-- Highlight remaining risks or follow-ups and keep ASCII-only output unless
non-ASCII already existed.
-
-## Tooling & Testing Essentials
-- **Go-to commands:** `./mvnw clean install -B -T1C -Pcheck` (full build),
`./mvnw test -pl <module>[-am]` (scoped unit tests), `./mvnw spotless:apply
-Pcheck [-pl <module>]` (format), `./mvnw -pl <module> -DskipITs
-Dspotless.skip=true -Dtest=ClassName test` (fast verification), and `./mvnw
-pl proxy -am -DskipTests package` (proxy packaging/perf smoke).
-- **Coverage verification:** before finishing any task that adds or changes
tests, run the coverage check (e.g., `./mvnw test jacoco:check@jacoco-check
-Pcoverage-check` or scoped `-pl <module> -am`) and explicitly confirm whether
the targeted code reaches 100% when required.
-- **Checkstyle command:** run `./mvnw checkstyle:check -Pcheck` (or with `-pl
<module> -am -Pcheck` for scoped runs) unless explicitly instructed otherwise.
-- **Default verification commands:** prefer scoped runs `./mvnw -pl <module>
-am -DskipITs -Djacoco.skip=false -Dsurefire.failIfNoSpecifiedTests=false test
jacoco:report` for coverage and `./mvnw -pl <module> checkstyle:check -Pcheck`
for style; avoid whole-repo builds unless the user requests them.
-- **Testing ground rules:** JUnit 5 + Mockito, `ClassNameTest` naming,
Arrange–Act–Assert structure, mocks for databases/time/network, reset static
caches between cases, and prefer existing swapper/helpers for complex configs.
-- **Coverage discipline:** run Jacoco (`./mvnw -pl <module> -am
-Djacoco.skip=false test jacoco:report`) when coverage is in question; describe
any uncovered branches with file/line reasoning.
-- **Branch-focused work:** when asked for “minimal branch coverage” or
similar, list every branch upfront, map each to a single test, and document
unreachable code explicitly instead of adding redundant cases.
-- **API bans:** if a user disallows a tool or assertion, add it to your plan,
avoid it during implementation, and cite any verification searches (e.g., `rg
assertEquals`) in the final report.
+## Verification & Commands
+- Core commands: `./mvnw clean install -B -T1C -Pcheck` (full build), `./mvnw
test -pl <module>[-am]` (scoped unit tests), `./mvnw spotless:apply -Pcheck
[-pl <module>]` (format), `./mvnw -pl <module> -DskipITs -Dspotless.skip=true
-Dtest=ClassName test` (fast verification), `./mvnw -pl proxy -am -DskipTests
package` (proxy packaging/perf smoke).
+- Coverage: when tests change or targets demand it, run `./mvnw test
jacoco:check@jacoco-check -Pcoverage-check` or scoped `-pl <module> -am
-Djacoco.skip=false test jacoco:report`; pair with the Coverage & Branch
Checklist.
+- Style: `./mvnw checkstyle:check -Pcheck` (scoped with `-pl <module> -am
-Pcheck` when possible) unless told otherwise.
+- Scoped defaults: prefer module-scoped runs over whole-repo builds; include
`-Dsurefire.failIfNoSpecifiedTests=false` when targeting specific tests.
+- Testing ground rules: JUnit 5 + Mockito, `ClassNameTest` naming,
Arrange–Act–Assert, mock external systems/time/network, reset static caches,
and reuse swappers/helpers for complex configs.
+- API bans: if a user forbids a tool/assertion, add it to the plan, avoid it
during implementation, and cite verification searches (e.g., `rg assertEquals`)
in the final report.
## Run & Triage Quick Sheet
- **Proxy quick start:** `./mvnw -pl proxy -am package` then
`shardingsphere-proxy/bin/start.sh -c conf/server.yaml`; report command, exit
code, config path, and protocol.
@@ -221,9 +185,8 @@ Always state which topology, registry, and engine versions
(e.g., MySQL 5.7 vs 8
- **Failure triage:** collect `proxy/logs/` plus `target/surefire-reports`,
quote the relevant log lines, map them to the data-flow step, and propose the
next diagnostic.
- **Routing mistakes:** check feature-rule configs, metadata freshness, and
parser dialect; include SQL + config snippet plus impacted module (`features`
or `kernel`), and add/plan targeted tests.
- **Proxy won’t start:** verify configs/mode/ports and reuse known-good
example configs; share the log snippet and files inspected without editing
generated artifacts.
-- **Spotless/checkstyle:** run `./mvnw spotless:apply -Pcheck [-pl <module>]`
(or `spotless:check`) and confirm ASF headers/import ordering.
- **Sandbox/network block:** if a command is denied, state what you ran, why
it failed, and the approval or alternative plan required.
-- **Single-module tests:** prefer scoped commands over repo-wide runs; avoid
`-Dtest=Pattern` from repo root unless you know the target exists, otherwise
use the module’s suite or `-Dsurefire.failIfNoSpecifiedTests=false`. When you
must target a single test class, pass the fully-qualified class name (e.g.,
`-Dtest=org.example.FooTest`) so Surefire can locate it deterministically. To
run multiple tests at once, join multiple FQCNs with commas (example:
`-Dtest=a.b.FooTest,a.b.BarTest`) an [...]
+- **Single-module tests:** prefer scoped commands over repo-wide runs; use
fully-qualified test class names and append
`-Dsurefire.failIfNoSpecifiedTests=false` when targeting specific tests (see
Verification & Commands for flags).
## Compatibility, Performance & External Systems
- Specify targeted engines and dialect files (MySQL 5.7/8.0, PostgreSQL 13+,
openGauss, etc.) and guarantee backward-compatible behavior.
@@ -253,23 +216,12 @@ Always state which topology, registry, and engine
versions (e.g., MySQL 5.7 vs 8
- Name tests after the production method under test; never probe private
helpers directly—document unreachable branches instead.
- Mock heavy dependencies (database/cache/registry/network) and prefer mocking
over building deep object graphs.
- For static/constructor mocking, use `@ExtendWith(AutoMockExtension.class)`
with `@StaticMockSettings`; avoid hand-written `mockStatic`/`mockConstruction`
unless you documented why the extension cannot be used.
-- For deep chained interactions, you may use Mockito’s `RETURNS_DEEP_STUBS` to
reduce intermediate mocks; this is independent of the static-mock rule above.
-- Before changing how mocks are created, scan the repository for similar tests
(e.g., other rule decorators or executor tests) and reuse their proven mocking
pattern instead of inventing a new structure.
- When constructors hide collaborators, use `Plugins.getMemberAccessor()` to
inject mocks and document why SPI creation is bypassed.
- When static methods or constructors need mocking, prefer
`@ExtendWith(AutoMockExtension.class)` with `@StaticMockSettings` (or the
extension’s constructor-mocking support); when a class is listed in
`@StaticMockSettings`, do not call `mockStatic`/`mockConstruction`
directly—stub via `when(...)` instead. Only if AutoMockExtension cannot be used
and the reason is documented in the plan may you fall back to
`mockStatic`/`mockConstruction`, wrapped in try-with-resources.
-- Before adding coverage to a utility with multiple return paths, list every
branch (no rule, non-Single config, wildcard blocks, missing data node,
positive path, collection overload) and map each to a test; update the plan
whenever this checklist changes.
-- Prefer imports over fully-qualified class names inside code and tests; if a
class is used, add an import rather than using the full package path inline.
-- Before coding tests, prepare a concise branch-and-data checklist (all
branches, inputs, expected outputs) and keep the plan in sync when the
checklist changes.
+- Before coding tests, follow the Coverage & Branch Checklist to map
inputs/branches to planned assertions.
- When a component is available via SPI (e.g., `TypedSPILoader`,
`DatabaseTypedSPILoader`, `PushDownMetaDataRefresher`), obtain the instance
through SPI by default; note any exceptions in the plan.
- Do not mix Mockito matchers with raw arguments; choose a single style per
invocation, and ensure the Mockito extension aligns with the mocking approach.
-- Never leave fully-qualified class names in production or test code; if a
class is referenced, add an import and verify via a quick scan (`rg "\\."
<path>`) before finishing.
-- When the user requires full branch/line coverage, treat 100% coverage as a
blocking condition: enumerate branches, map tests, and keep adding cases until
all branches are covered or explicitly waived; record the coverage requirement
in the plan and self-check before concluding.
- Compliance is mandatory: before any coding, re-read AGENTS.md and convert
all hard requirements (SPI usage, no FQCN, mocking rules, coverage targets,
planning steps) into a checklist in the plan; do not proceed or report
completion until every item is satisfied or explicitly waived by the user.
-## Brevity & Signal
-- Prefer tables/bullets over prose walls; cite file paths (`kernel/src/...`)
directly.
-- Eliminate repeated wording; reference prior sections instead of restating.
-- Default to ASCII; only mirror existing non-ASCII content when necessary.
-
## Session Notes
- MySQLSchemataQueryExecutorFactoryTest:public 方法分别测试,`accept` 与 `newInstance`
各自使用独立测试方法。
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
index ca4a20a5d9e..90a978ad0fa 100644
--- a/CODE_OF_CONDUCT.md
+++ b/CODE_OF_CONDUCT.md
@@ -17,7 +17,7 @@ The following code of conduct is based on full compliance
with the [Apache Softw
- Ensure compliance with coding standards.
- Ensure all steps in the build process complete successfully, including:
Apache license header check, Checkstyle check, compilation, unit tests, etc.
Build process command: `./mvnw clean install -B -T1C -Pcheck`.
- Unify code style through Spotless, execute `./mvnw spotless:apply -Pcheck`
to format code.
-- Ensure coverage is not lower than the master branch.
+- Ensure coverage is not lower than the master branch, except for simple
`getter /setter` methods, unit tests need full coverage.
- Try to refine design with fine-grained splitting; achieve small
modifications with multiple commits, but ensure the completeness of each commit.
- If you use IDEA, you can import `src/resources/idea/code-style.xml` to
maintain code style consistency.
- If you use IDEA, you can import `src/resources/idea/inspections.xml` to
detect potential code issues.
@@ -60,12 +60,12 @@ The following code of conduct is based on full compliance
with the [Apache Softw
- Private methods used by a method should immediately follow that method. If
there are multiple private methods, they should be written in the same order as
they appear in the original method.
- Method parameters and return values are not allowed to be `null`.
- Prefer using lombok instead of constructors, getter, setter methods and log
variables.
+- Do not leave fully-qualified class names inline; add import statements
instead.
- Consider using `LinkedList` first, only use `ArrayList` when you need to get
element values from the collection by index.
- Collection types that may cause expansion like `ArrayList`, `HashMap` must
specify initial collection size to avoid expansion.
- Prefer using ternary operators instead of if else return and assignment
statements.
- Nested use of ternary operators is forbidden.
- In conditional expressions, prefer positive semantics for easier code logic
understanding. For example: `if (null == param) {} else {}`.
-- Use specific `@SuppressWarnings("xxx")` instead of
`@SuppressWarnings("all")`.
- Use `@HighFrequencyInvocation` annotation reasonably to focus on performance
optimization of key methods.
- When to use `@HighFrequencyInvocation` annotation:
- In frequently called request chains, mark the high-frequency called
classes, methods or constructors, with precise matching of scope;
@@ -91,7 +91,10 @@ The following code of conduct is based on full compliance
with the [Apache Softw
- Correctness testing: Get expected results through correct inputs.
- Reasonable design: Combined with production code design, design
high-quality unit tests.
- Error tolerance testing: Get expected results through incorrect inputs
such as illegal data, exception flows, etc.
-- Except for simple `getter /setter` methods, and static code for declaring
SPIs, such as: `getType / getOrder`, unit tests need full coverage.
+- Use `assert` prefix for all test method names.
+- Unit tests must exercise behavior through public APIs only; do not use
reflection or other means to access private members.
+- When a production method is covered by only one test case, name that test
method `assert<MethodName>` without extra suffixes, and prefer isolating one
public production method per dedicated test method; when practical, keep test
method ordering aligned with the corresponding production methods.
+- For parameterized tests, provide display names via parameters and prefix
each with `{index}:` to include the sequence number.
- Each test case needs precise assertions, try not to use `not`,
`containsString` assertions.
- Separate environment preparation code from test code.
- Only Mockito, junit `Assertions`, hamcrest `CoreMatchers` and
`MatcherAssert` related can use static import.
@@ -99,6 +102,8 @@ The following code of conduct is based on full compliance
with the [Apache Softw
- Boolean type assertions should use `assertTrue` and `assertFalse`;
- Null value assertions should use `assertNull` and `assertNotNull`;
- Other types should use `assertThat(actual, is(expected))` instead of
`assertEquals`;
+ - Use `assertThat(..., isA(...))` instead of `instanceOf`;
+ - Do not use `assertSame` / `assertNotSame`; use instead of
`assertThat(actual, is(expected))` or `assertThat(actual, not(expected))`;
- Use Hamcrest matchers like `is()`, `not()` for precise and readable
assertions.
- The actual values in test cases should be named actual XXX, and expected
values should be named expected XXX.
- Test classes and methods marked with `@Test` do not need JAVADOC.
@@ -107,7 +112,7 @@ The following code of conduct is based on full compliance
with the [Apache Softw
- When unit tests contain objects that are not easy to construct, for
example: objects with more than two levels of nesting and unrelated to testing,
`mock` should be used.
- For mocking static methods or constructors, consider using
`AutoMockExtension` and `StaticMockSettings` provided by the testing framework
for automatic resource release; if using Mockito's `mockStatic` and
`mockConstruction` methods, must be paired with `try-with-resource` or closed
in cleanup methods to avoid leaks.
- When verifying only one call, there's no need to use `times(1)`
parameter, the single-parameter method of `verify` is sufficient.
-- Use `assert` prefix for all test method names.
+- For deep chained interactions, use Mockito’s `RETURNS_DEEP_STUBS` instead of
layering intermediate mocks.
- Test data should use standardized prefixes (e.g., `foo_`/`bar_`) to clearly
identify their test purpose
- Use `PropertiesBuilder` simplify `Properties` building.
diff --git a/docs/community/content/involved/conduct/code.cn.md
b/docs/community/content/involved/conduct/code.cn.md
index 19843393261..032f2e08ff0 100644
--- a/docs/community/content/involved/conduct/code.cn.md
+++ b/docs/community/content/involved/conduct/code.cn.md
@@ -21,7 +21,7 @@ chapter = true
- 确保遵守编码规范。
- 确保构建流程中的各个步骤都成功完成,包括:Apache 协议文件头检查、Checkstyle 检查、编译、单元测试等。构建流程启动命令:`./mvnw
clean install -B -T1C -Pcheck`。
- 通过 Spotless 统一代码风格,执行 `./mvnw spotless:apply -Pcheck` 格式化代码。
- - 确保覆盖率不低于 master 分支。
+ - 确保覆盖率不低于 master 分支,除去简单的 `getter /setter` 方法,单元测试需全覆盖。
- 应尽量将设计精细化拆分;做到小幅度修改,多次数提交,但应保证提交的完整性。
- 如果您使用 IDEA,可导入 `src/resources/idea/code-style.xml`,用于保持代码风格一致性。
- 如果您使用 IDEA,可导入 `src/resources/idea/inspections.xml`,用于检测代码潜在问题。
@@ -64,12 +64,12 @@ chapter = true
- 方法所用到的私有方法应紧跟该方法,如果有多个私有方法,书写私有方法应与私有方法在原方法的出现顺序相同。
- 方法入参和返回值不允许为 `null`。
- 优先使用 lombok 代替构造器,getter, setter 方法和 log 变量。
+ - 禁止内联全限定类名,必须通过 import 引入。
- 优先考虑使用 `LinkedList`,只有在需要通过下标获取集合中元素值时再使用 `ArrayList`。
- `ArrayList`,`HashMap` 等可能产生扩容的集合类型必须指定集合初始大小,避免扩容。
- 优先使用三目运算符代替 if else 的返回和赋值语句。
- 禁止嵌套使用三目运算符。
- 条件表达式中,优先使用正向语义,以便于理解代码逻辑。例如:`if (null == param) {} else {}`。
- - 使用具体的 `@SuppressWarnings("xxx")` 代替 `@SuppressWarnings("all")`。
- 合理使用 `@HighFrequencyInvocation` 注解,用于聚焦关键方法性能的优化。
- 使用 `@HighFrequencyInvocation` 注解的时机:
- 请求频繁调用的链路,标注其中高频调用的类、方法或构造器,标注范围精确匹配;
@@ -95,7 +95,11 @@ chapter = true
- 正确性测试(Correct):通过正确的输入,得到预期结果。
- 合理性设计(Design):与生产代码设计相结合,设计高质量的单元测试。
- 容错性测试(Error):通过非法数据、异常流程等错误的输入,得到预期结果。
- - 除去简单的 `getter /setter` 方法,以及声明 SPI 的静态代码,如:`getType / getOrder`,单元测试需全覆盖。
+ - 使用 `assert` 前缀命名所有的测试用例。
+ - 单元测试必须通过公共 API 验证行为,禁止通过反射等手段访问私有成员。
+ - 当某个生产方法只由一个测试用例覆盖时,测试方法命名为 `assert<MethodName>`,无额外后缀。
+ - 每个公有方法使用一个独立的测试方法,测试方法顺序在可行时与生产方法保持一致。
+ - 参数化测试需通过参数提供显示名,并以 `{index}:` 前缀标注序号。
- 每个测试用例需精确断言,尽量不使用 `not`、`containsString` 断言。
- 准备环境的代码和测试代码分离。
- 只有 Mockito,junit `Assertions`,hamcrest `CoreMatchers` 和 `MatcherAssert`
相关可以使用 static import。
@@ -103,6 +107,8 @@ chapter = true
- 布尔类型断言应使用 `assertTrue` 和 `assertFalse`;
- 空值断言应使用 `assertNull` 和 `assertNotNull`;
- 其他类型断言应使用 `assertThat(actual, is(expected))` 代替 `assertEquals`;
+ - 类型断言使用 `assertThat(..., isA(...))` 代替 `instanceOf`;
+ - 禁用 `assertSame` / `assertNotSame`,使用 `assertThat(actual, is(expected))`
或 `assertThat(actual, not(expected))`;
- 使用 Hamcrest 匹配器(如 `is()`、`not()`)来进行精确且可读性高的断言。
- 测试用例的真实值应名为为 actual XXX,期望值应命名为 expected XXX。
- 测试类和 `@Test` 标注的方法无需 JAVADOC。
@@ -111,7 +117,7 @@ chapter = true
- 单元测试包含不容易构建的对象时,例如:超过两层嵌套并且和测试无关的对象,应使用 `mock`。
- 模拟静态方法或构造器,应优先考虑使用测试框架提供的 `AutoMockExtension` 和 `StaticMockSettings`
自动释放资源;若使用 Mockito `mockStatic` 和 `mockConstruction` 方法,必须搭配
`try-with-resource` 或在清理方法中关闭,避免泄漏。
- 校验仅有一次调用时,无需使用 `times(1)` 参数,使用 `verify` 的单参数方法即可。
- - 使用 `assert` 前缀命名所有的测试用例。
+ - 深度链式交互使用 Mockito 的 `RETURNS_DEEP_STUBS`,不要层层手动 mock。
- 测试数据应使用标准化前缀(如 `foo_`/`bar_`)明确标识其测试用途。
- 使用 `PropertiesBuilder` 简化 `Properties` 构造。
diff --git a/docs/community/content/involved/conduct/code.en.md
b/docs/community/content/involved/conduct/code.en.md
index d3051e1af66..08752da0a08 100644
--- a/docs/community/content/involved/conduct/code.en.md
+++ b/docs/community/content/involved/conduct/code.en.md
@@ -21,7 +21,7 @@ The following code of conduct is based on full compliance
with the [Apache Softw
- Ensure compliance with coding standards.
- Ensure all steps in the build process complete successfully, including:
Apache license header check, Checkstyle check, compilation, unit tests, etc.
Build process command: `./mvnw clean install -B -T1C -Pcheck`.
- Unify code style through Spotless, execute `./mvnw spotless:apply -Pcheck`
to format code.
-- Ensure coverage is not lower than the master branch.
+- Ensure coverage is not lower than the master branch, except for simple
`getter /setter` methods, unit tests need full coverage.
- Try to refine design with fine-grained splitting; achieve small
modifications with multiple commits, but ensure the completeness of each commit.
- If you use IDEA, you can import `src/resources/idea/code-style.xml` to
maintain code style consistency.
- If you use IDEA, you can import `src/resources/idea/inspections.xml` to
detect potential code issues.
@@ -64,12 +64,12 @@ The following code of conduct is based on full compliance
with the [Apache Softw
- Private methods used by a method should immediately follow that method. If
there are multiple private methods, they should be written in the same order as
they appear in the original method.
- Method parameters and return values are not allowed to be `null`.
- Prefer using lombok instead of constructors, getter, setter methods and log
variables.
+- Do not leave fully-qualified class names inline; add import statements
instead.
- Consider using `LinkedList` first, only use `ArrayList` when you need to get
element values from the collection by index.
- Collection types that may cause expansion like `ArrayList`, `HashMap` must
specify initial collection size to avoid expansion.
- Prefer using ternary operators instead of if else return and assignment
statements.
- Nested use of ternary operators is forbidden.
- In conditional expressions, prefer positive semantics for easier code logic
understanding. For example: `if (null == param) {} else {}`.
-- Use specific `@SuppressWarnings("xxx")` instead of
`@SuppressWarnings("all")`.
- Use `@HighFrequencyInvocation` annotation reasonably to focus on performance
optimization of key methods.
- When to use `@HighFrequencyInvocation` annotation:
- In frequently called request chains, mark the high-frequency called
classes, methods or constructors, with precise matching of scope;
@@ -95,7 +95,11 @@ The following code of conduct is based on full compliance
with the [Apache Softw
- Correctness testing: Get expected results through correct inputs.
- Reasonable design: Combined with production code design, design
high-quality unit tests.
- Error tolerance testing: Get expected results through incorrect inputs
such as illegal data, exception flows, etc.
-- Except for simple `getter /setter` methods, and static code for declaring
SPIs, such as: `getType / getOrder`, unit tests need full coverage.
+- Use `assert` prefix for all test method names.
+- Unit tests must exercise behavior through public APIs only; do not use
reflection or other means to access private members.
+- Except for simple `getter /setter` methods, unit tests need full coverage.
+- When a production method is covered by only one test case, name that test
method `assert<MethodName>` without extra suffixes, and prefer isolating one
public production method per dedicated test method; when practical, keep test
method ordering aligned with the corresponding production methods.
+- For parameterized tests, provide display names via parameters and prefix
each with `{index}:` to include the sequence number.
- Each test case needs precise assertions, try not to use `not`,
`containsString` assertions.
- Separate environment preparation code from test code.
- Only Mockito, junit `Assertions`, hamcrest `CoreMatchers` and
`MatcherAssert` related can use static import.
@@ -103,6 +107,8 @@ The following code of conduct is based on full compliance
with the [Apache Softw
- Boolean type assertions should use `assertTrue` and `assertFalse`;
- Null value assertions should use `assertNull` and `assertNotNull`;
- Other types should use `assertThat(actual, is(expected))` instead of
`assertEquals`;
+ - Use `assertThat(..., isA(...))` instead of `instanceOf`;
+ - Do not use `assertSame` / `assertNotSame`; use instead of
`assertThat(actual, is(expected))` or `assertThat(actual, not(expected))`;
- Use Hamcrest matchers like `is()`, `not()` for precise and readable
assertions.
- The actual values in test cases should be named actual XXX, and expected
values should be named expected XXX.
- Test classes and methods marked with `@Test` do not need JAVADOC.
@@ -111,7 +117,7 @@ The following code of conduct is based on full compliance
with the [Apache Softw
- When unit tests contain objects that are not easy to construct, for
example: objects with more than two levels of nesting and unrelated to testing,
`mock` should be used.
- For mocking static methods or constructors, consider using
`AutoMockExtension` and `StaticMockSettings` provided by the testing framework
for automatic resource release; if using Mockito's `mockStatic` and
`mockConstruction` methods, must be paired with `try-with-resource` or closed
in cleanup methods to avoid leaks.
- When verifying only one call, there's no need to use `times(1)`
parameter, the single-parameter method of `verify` is sufficient.
-- Use `assert` prefix for all test method names.
+- For deep chained interactions, use Mockito’s `RETURNS_DEEP_STUBS` instead of
layering intermediate mocks.
- Test data should use standardized prefixes (e.g., `foo_`/`bar_`) to clearly
identify their test purpose
- Use `PropertiesBuilder` simplify `Properties` building.
diff --git
a/kernel/data-pipeline/dialect/mysql/src/test/java/org/apache/shardingsphere/data/pipeline/mysql/ingest/incremental/client/netty/MySQLBinlogEventPacketDecoderTest.java
b/kernel/data-pipeline/dialect/mysql/src/test/java/org/apache/shardingsphere/data/pipeline/mysql/ingest/incremental/client/netty/MySQLBinlogEventPacketDecoderTest.java
index 51080f953c2..3c4e9314c7c 100644
---
a/kernel/data-pipeline/dialect/mysql/src/test/java/org/apache/shardingsphere/data/pipeline/mysql/ingest/incremental/client/netty/MySQLBinlogEventPacketDecoderTest.java
+++
b/kernel/data-pipeline/dialect/mysql/src/test/java/org/apache/shardingsphere/data/pipeline/mysql/ingest/incremental/client/netty/MySQLBinlogEventPacketDecoderTest.java
@@ -78,7 +78,7 @@ class MySQLBinlogEventPacketDecoderTest {
@SuppressWarnings("CollectionWithoutInitialCapacity")
@BeforeEach
- void setUp() throws NoSuchFieldException, IllegalAccessException {
+ void setUp() throws ReflectiveOperationException {
binlogEventPacketDecoder = new MySQLBinlogEventPacketDecoder(4, new
ConcurrentHashMap<>(), true);
binlogContext = (MySQLBinlogContext)
Plugins.getMemberAccessor().get(MySQLBinlogEventPacketDecoder.class.getDeclaredField("binlogContext"),
binlogEventPacketDecoder);
lenient().when(channelHandlerContext.channel().attr(CommonConstants.CHARSET_ATTRIBUTE_KEY).get()).thenReturn(StandardCharsets.UTF_8);
diff --git a/pom.xml b/pom.xml
index d05d87012c3..38f6baba213 100644
--- a/pom.xml
+++ b/pom.xml
@@ -175,6 +175,7 @@
<apache-rat-plugin.version>0.15</apache-rat-plugin.version>
<spotless-maven-plugin.version>2.46.1</spotless-maven-plugin.version>
<maven-checkstyle-plugin.version>3.6.0</maven-checkstyle-plugin.version>
+ <checkstyle.version>10.17.0</checkstyle.version>
<maven-pmd-plugin.version>3.20.0</maven-pmd-plugin.version>
<spotbugs-maven-plugin.version>4.7.2.1</spotbugs-maven-plugin.version>
<fb-contrib.version>7.6.0</fb-contrib.version>
@@ -1345,6 +1346,13 @@
<includeTestSourceDirectory>true</includeTestSourceDirectory>
<excludes>**/autogen/**/*</excludes>
</configuration>
+ <dependencies>
+ <dependency>
+ <groupId>com.puppycrawl.tools</groupId>
+ <artifactId>checkstyle</artifactId>
+ <version>${checkstyle.version}</version>
+ </dependency>
+ </dependencies>
</plugin>
<plugin>
<artifactId>maven-pmd-plugin</artifactId>
diff --git a/src/resources/checkstyle.xml b/src/resources/checkstyle.xml
index ac3fee0f562..41a4661cfea 100644
--- a/src/resources/checkstyle.xml
+++ b/src/resources/checkstyle.xml
@@ -41,9 +41,12 @@
</module>
<module name="Translation" />
<module name="UniqueProperties" />
-
<module name="TreeWalker">
<module name="SuppressionCommentFilter" />
+ <module name="SuppressionXpathSingleFilter">
+ <property name="checks" value="FinalClass" />
+ <property name="query"
value="//CLASS_DEF[./MODIFIERS/LITERAL_PRIVATE]" />
+ </module>
<!-- Annotations -->
<module name="AnnotationLocation">
@@ -59,7 +62,9 @@
<module name="MissingDeprecated" />
<module name="MissingOverride" />
<module name="PackageAnnotation" />
- <module name="SuppressWarnings" />
+ <module name="SuppressWarnings">
+ <property name="format" value="^(?i:all)$" />
+ </module>
<module name="SuppressWarningsHolder" />
<!-- Block Checks -->