pointfreeco / swift-composable-architecture

A library for building applications in a consistent and understandable way, with composition, testing, and ergonomics in mind.
https://www.pointfree.co/collections/composable-architecture
MIT License
12.22k stars 1.42k forks source link

Exhaustive testing @Shared variable mutating before action received #3064

Closed Muhammed9991 closed 4 months ago

Muhammed9991 commented 4 months ago

Description

I've come across a weird issue when trying to write exhaustive testing when using @Shared.

@Reducer
struct SomeReducer {
    @ObservableState
    struct State: Equatable, Sendable {
        var isOn = false
        var variable1: String = ""
        @Shared(.inMemory("variable2")) var variable2: String = ""
    }

    enum Action: Equatable, Sendable, BindableAction {
        case binding(BindingAction<State>)
        case onAppear
        case action1
        case action2
        case onButtonTapped
    }

    var body: some Reducer<State, Action> {
        Reduce<State, Action> { state, action in
            switch action {
            case .onAppear:
                return .run { send in
                    await send(.action1)
                    await send(.action2)
                }
            case .action1:
                state.variable1 = "Updated by method 1"
                return .none
            case .action2:
                state.variable2 = "Updated by method 2"
                return .none

            case .onButtonTapped:
                state.isOn.toggle()
                return .none
            case .binding:
                return .none
            }
        }
    }
}

Example test:

    @MainActor
    func testOnAppear() async {
        let store = TestStore(initialState: SomeReducer.State()) {
            SomeReducer()
        }

        await store.send(.onAppear)

        await store.receive(.action1) {
            $0.variable1 = "Updated by method 1"
            $0.variable2 = "Updated by method 2" // This should be mutated in action2
        }
        await store.receive(.action2)
    }

Here's the attached repro https://github.com/Muhammed9991/SharedStateExhaustiveTestingExample.

Checklist

Expected behavior

No response

Actual behavior

No response

Steps to reproduce

No response

The Composable Architecture version information

1.10.3

Destination operating system

iOS 17.3

Xcode version information

XCode 15.3

Swift Compiler version information

swift-driver version: 1.90.11.1 Apple Swift version 5.10 (swiftlang-5.10.0.13 clang-1500.3.9.4)
Target: arm64-apple-macosx14.0
juliensagot commented 4 months ago

I was about to create an issue for the exact same bug! Here's another sample of code to reproduce it:

@Reducer
struct MainFeature {
  @ObservableState
  struct State: Equatable {
    var childFeature: ChildFeature.State
    @Shared var selectedDate: Date

    init(selectedDate: Date) {
      let sharedSelectedDate = Shared(selectedDate)
      self._selectedDate = sharedSelectedDate
      self.childFeature = ChildFeature.State(selectedDate: sharedSelectedDate.reader)
    }
  }

  enum Action {
    case childFeature(ChildFeature.Action)
  }

  var body: some ReducerOf<Self> {
    Scope(state: \.childFeature, action: \.childFeature) {
      ChildFeature()
    }
    Reduce<State, Action> { state, action in
      switch action {
      case let .childFeature(.delegate(.didSelectDate(selectedDate))):
        state.selectedDate = selectedDate
        return .none
      case .childFeature:
        return .none
      }
    }
  }
}

@Reducer
struct ChildFeature {
  @ObservableState
  struct State: Equatable {
    @SharedReader var selectedDate: Date
  }

  enum Action {
    @CasePathable
    enum Delegate {
      case didSelectDate(Date)
    }
    case delegate(Delegate)
    case buttonTapped
  }

  @Dependency(\.date.now) private var now

  var body: some ReducerOf<Self> {
    Reduce<State, Action> { state, action in
      switch action {
      case .buttonTapped:
        return .send(.delegate(.didSelectDate(now)))
      case .delegate:
        return .none
      }
    }
  }
}

final class MainFeatureTests: XCTestCase {

  @MainActor
  func testMainFeature() async throws {
    let store = TestStore(initialState: MainFeature.State(selectedDate: Date(timeIntervalSince1970: 0))) {
      MainFeature()
    } withDependencies: {
      $0.date.now = Date(timeIntervalSince1970: 84000)
    }

    await store.send(\.childFeature.buttonTapped) // ⚠️ State was not expected to change, but a change occurred
    await store.receive(\.childFeature.delegate.didSelectDate) {
      $0.selectedDate = Date(timeIntervalSince1970: 84000)
    }
  }
}
mbrandonw commented 4 months ago

Hi @Muhammed9991 and @juliensagot, unfortunately this is intended behavior for the time being. We would like for it to not be, but in order to fix it it will actually potentially cause tests that pass today to fail. Since that's a breaking change we are going to need to wait to 2.0.

The problem is that currently TestStore eagerly runs the reducer on actions received from effects. So that is why you are seeing share state change from the send even though the state is actually changed when the effect action is processed.

The fix is to make TestStore not process effect actions right away, and instead wait until one does store.receive. But, as mentioned above, that is a breaking change and so will have to wait until 2.0.

For the time being you will just need to assert on shared state a little more eagerly. Luckily this is really only a problem for synchronous effects (like delegate actions), and so hopefully it's not too much of an inconvenience for now.

Since this is not an issue with the library I am going to convert it to a discussion. Feel free to continue the conversation over there.