Skip to content

Commit d83e3e8

Browse files
authored
Fix a crash when expanding two years in a post's Months and Years stats (#26415)
* Keep the year on Post Stats month rows Month rows in Months and Years and Avg. Views Per Day showed only the month name and views, so the same month with the same views in two expanded years produced equal rows. The diffable detail table rejected them as duplicate items and the app crashed. Month rows now carry their year and month, and row equality compares it. * Add the PR number to the release note * Rename the month row key to yearMonth and shorten its comments * Move the release note to 27.6 Trunk is on 27.6 since the 27.5 code freeze.
1 parent 2717f5d commit d83e3e8

4 files changed

Lines changed: 155 additions & 2 deletions

File tree

‎RELEASE-NOTES.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
27.6
22
-----
3+
* [*] Stats: Fix a crash when expanding two years with the same month and views in a post's Months and Years or Avg. Views Per Day details [#26415]
34
* [*] Application Passwords: Revoke passwords for other apps from the password details screen.
45
* [*] Fix signing in to WordPress.com taking longer than it needs to, and waiting on the login screen while the device is busy [#26121]
56
* [*] Notifications: Comment and like notifications from private sites you can't access now show their content instead of an error [#26432]
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
import Foundation
2+
import Testing
3+
import UIKit
4+
import WordPressKit
5+
@testable import WordPress
6+
7+
/// Covers the Months and Years and Avg. Views Per Day detail tables, where month rows
8+
/// from different years can show the same month name and the same count.
9+
///
10+
/// The suite is serialized because expanded years live in the static
11+
/// `StatsDataHelper.expandedRowLabelsDetails`.
12+
@MainActor
13+
@Suite(.serialized)
14+
struct SiteStatsDetailsPostStatsTests {
15+
16+
@Test(arguments: [StatSection.postStatsMonthsYears, .postStatsAverageViews])
17+
func equalMonthsInTwoExpandedYearsAreSeparateRows(section: StatSection) throws {
18+
let table = PostStatsTable(section: section, april2025: 12)
19+
20+
table.expand(["2026", "2025"])
21+
22+
#expect(monthCounts(in: try table.snapshot()) == ["12", "16", "12", "15"])
23+
}
24+
25+
@Test func collapsingAndReopeningAYearKeepsBothMonths() throws {
26+
let table = PostStatsTable(section: .postStatsMonthsYears, april2025: 12)
27+
28+
table.expand(["2026", "2025"])
29+
#expect(monthCounts(in: try table.snapshot()) == ["12", "16", "12", "15"])
30+
31+
table.expand(["2026"])
32+
#expect(monthCounts(in: try table.snapshot()) == ["12", "16"])
33+
34+
table.expand(["2026", "2025"])
35+
#expect(monthCounts(in: try table.snapshot()) == ["12", "16", "12", "15"])
36+
}
37+
38+
@Test func changedCountReplacesOnlyThatMonth() throws {
39+
let table = PostStatsTable(section: .postStatsMonthsYears, april2025: 12)
40+
table.expand(["2026", "2025"])
41+
let beforeMonths = monthItems(in: try table.snapshot())
42+
43+
table.setPostDetails(april2025: 13)
44+
let after = try table.snapshot()
45+
46+
#expect(monthCounts(in: after) == ["12", "16", "13", "15"])
47+
// The diffable data source replaces an item only when it no longer finds an equal one.
48+
#expect(beforeMonths.map { after.indexOfItem($0) != nil } == [true, true, false, true])
49+
}
50+
}
51+
52+
// MARK: - Helpers
53+
54+
private extension SiteStatsDetailsPostStatsTests {
55+
func monthItems(in snapshot: ImmuTableDiffableDataSourceSnapshot) -> [AnyHashableImmuTableRow] {
56+
snapshot.itemIdentifiers.filter { $0.immuTableRow is DetailExpandableChildRow }
57+
}
58+
59+
func monthCounts(in snapshot: ImmuTableDiffableDataSourceSnapshot) -> [String] {
60+
monthItems(in: snapshot).compactMap { ($0.immuTableRow as? DetailExpandableChildRow)?.rowData.data }
61+
}
62+
}
63+
64+
/// A post stats detail table backed by a real `StatsPeriodStore`.
65+
///
66+
/// Each test creates its own instance and releases it on the main actor: the store's
67+
/// `Dispatcher` asserts when its receipts are released on another thread.
68+
@MainActor
69+
private final class PostStatsTable {
70+
private let postID = 1046
71+
private let section: StatSection
72+
private let periodStore = StatsPeriodStore()
73+
private let viewModel: SiteStatsDetailsViewModel
74+
// Strong references: the view model keeps its delegates weak.
75+
private let detailsHandler = MockDetailsDelegate()
76+
private let referrerHandler = MockReferrerDelegate()
77+
private let savedExpandedRows = StatsDataHelper.expandedRowLabelsDetails
78+
79+
init(section: StatSection, april2025: Int) {
80+
self.section = section
81+
viewModel = SiteStatsDetailsViewModel(
82+
detailsDelegate: detailsHandler,
83+
referrerDelegate: referrerHandler,
84+
insightsStore: StatsInsightsStore(),
85+
periodStore: periodStore
86+
)
87+
viewModel.fetchDataFor(statSection: section, postID: postID)
88+
// Set the data after `fetchDataFor`, which can mark the post stats as loading.
89+
setPostDetails(april2025: april2025)
90+
}
91+
92+
deinit {
93+
StatsDataHelper.expandedRowLabelsDetails = savedExpandedRows
94+
}
95+
96+
func expand(_ years: [String]) {
97+
StatsDataHelper.expandedRowLabelsDetails[section] = years
98+
}
99+
100+
/// Seven years with positive totals. 2026 and 2025 both have April, with April 2025
101+
/// set by the caller. Averages use the same numbers.
102+
func setPostDetails(april2025: Int) {
103+
var years: [String: [String: Int]] = [
104+
"2026": ["3": 16, "4": 12],
105+
"2025": ["3": 15, "4": april2025]
106+
]
107+
for (offset, year) in (2020...2024).enumerated() {
108+
years[String(year)] = ["3": 10 + offset, "4": 6 + offset]
109+
}
110+
let months = years.mapValues { ["months": $0, "total": $0.values.reduce(0, +)] as [String: Any] }
111+
let json: [String: AnyObject] = [
112+
"date": "2026-11-18" as AnyObject,
113+
"views": 0 as AnyObject,
114+
"years": months as AnyObject,
115+
"averages": months as AnyObject,
116+
"weeks": [Any]() as AnyObject,
117+
"data": [Any]() as AnyObject
118+
]
119+
periodStore.state.postStats[postID] = StatsPostDetails(jsonDictionary: json)
120+
periodStore.state.postStatsFetchingStatuses[postID] = .success
121+
}
122+
123+
/// Returns the view model's real snapshot after checking that the expanded month rows differ.
124+
///
125+
/// UIKit raises `NSInternalInconsistencyException` for duplicate snapshot items, which ends
126+
/// the test process. The view model's row builders are private, so the check builds the
127+
/// month rows with the same `StatsDataHelper` methods and fails the test instead.
128+
func snapshot() throws -> ImmuTableDiffableDataSourceSnapshot {
129+
let details = try #require(periodStore.getPostStats(for: postID))
130+
let yearsData = section == .postStatsAverageViews ? details.dailyAveragesPerMonth : details.monthlyBreakdown
131+
let rows = (StatsDataHelper.expandedRowLabelsDetails[section] ?? []).compactMap(Int.init)
132+
.flatMap {
133+
StatsDataHelper.childRowsForYear(StatsDataHelper.monthsFrom(yearsData: yearsData, forYear: $0))
134+
}
135+
for (index, row) in rows.enumerated() {
136+
try #require(!rows[..<index].contains(row), "Two month rows are equal, so the snapshot would reject them")
137+
}
138+
return viewModel.tableViewSnapshot()
139+
}
140+
141+
private final class MockDetailsDelegate: SiteStatsDetailsDelegate {}
142+
143+
private final class MockReferrerDelegate: SiteStatsReferrerDelegate {
144+
func showReferrerDetails(_ data: StatsTotalRowData) {}
145+
}
146+
}

‎WordPress/Classes/ViewRelated/Stats/Helpers/StatsDataHelper.swift‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,8 @@ import WordPressShared
119119
class func childRowsForYear(_ months: [StatsPostViews]) -> [StatsTotalRowData] {
120120
return months.map {
121121
StatsTotalRowData(name: StatsDataHelper.displayMonth(forDate: $0.date),
122-
data: $0.viewsCount.abbreviatedString())
122+
data: $0.viewsCount.abbreviatedString(),
123+
yearMonth: $0.date)
123124
}
124125
}
125126

‎WordPress/Classes/ViewRelated/Stats/Shared Views/StatsTotalRow.swift‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ struct StatsTotalRowData: Equatable {
2020
var childRows: [StatsTotalRowData]?
2121
var statSection: StatSection?
2222
var isReferrerSpam: Bool
23+
/// Keeps the same month from different years distinct, since `name` shows only the month.
24+
var yearMonth: DateComponents?
2325

2426
init(
2527
id: UUID? = nil,
@@ -38,7 +40,8 @@ struct StatsTotalRowData: Equatable {
3840
multiline: Bool = true,
3941
childRows: [StatsTotalRowData]? = [StatsTotalRowData](),
4042
statSection: StatSection? = nil,
41-
isReferrerSpam: Bool = false
43+
isReferrerSpam: Bool = false,
44+
yearMonth: DateComponents? = nil
4245
) {
4346
self.id = id
4447
self.name = name
@@ -57,6 +60,7 @@ struct StatsTotalRowData: Equatable {
5760
self.childRows = childRows
5861
self.statSection = statSection
5962
self.isReferrerSpam = isReferrerSpam
63+
self.yearMonth = yearMonth
6064
}
6165

6266
var hasIcon: Bool {
@@ -102,6 +106,7 @@ struct StatsTotalRowData: Equatable {
102106
&& lhs.showDisclosure == rhs.showDisclosure
103107
&& lhs.disclosureURL?.absoluteString == rhs.disclosureURL?.absoluteString && lhs.childRows == rhs.childRows
104108
&& lhs.statSection == rhs.statSection && lhs.isReferrerSpam == rhs.isReferrerSpam
109+
&& lhs.yearMonth == rhs.yearMonth
105110
}
106111
}
107112

0 commit comments

Comments
 (0)