Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
1665fdf
Conviva: allow injecting CISAnalytics into ConvivaEndpoints for tests
ceyhun-o Nov 18, 2026
c73f78e
Conviva: add THEOplayerConnectorConvivaTests target with recording an…
ceyhun-o Nov 18, 2026
51081e6
Conviva: test session lifecycle, source change, persistent metadata, …
ceyhun-o Nov 18, 2026
d5f680b
Conviva: test live detection and encoding_type reporting
ceyhun-o Nov 18, 2026
e47f3af
Conviva: test bitrate routing to content and ad endpoints
ceyhun-o Nov 18, 2026
8635126
Conviva: test ad break reporting and failed ad break reporting
ceyhun-o Nov 18, 2026
e6e4d92
Conviva: test live HLS and HESP encoding_type on the THEOlive demo ch…
ceyhun-o Nov 18, 2026
b14d8cd
Conviva: test that a network error is reported as a warning and keeps…
ceyhun-o Nov 18, 2026
8084130
Conviva: fix Xcode test setup and playback fixtures
ceyhun-o Nov 18, 2026
7a37809
Conviva: compile the OptiView Ads interstitial tests
ceyhun-o Nov 19, 2026
efd5d7b
Conviva: add Google IMA to the test target for the OptiView Ads integ…
ceyhun-o Nov 19, 2026
1cc08d2
Conviva tests: rely on the connector target for THEOplayerSDK and Con…
ceyhun-o Nov 23, 2026
5e8d2c8
Wait for playback before seeking to the end in Conviva tests
ceyhun-o Nov 23, 2026
d6a1de6
Synchronize Conviva ad tests on player events
ceyhun-o Nov 23, 2026
c5cb1e2
Observe the SDK active-quality event before testing bitrate replay
ceyhun-o Nov 23, 2026
5f0c2fa
Drive Conviva bitrate routing and replay with deterministic SDK events
ceyhun-o Nov 23, 2026
d070025
Synchronize failed-ad-break coverage on ad lifecycle events
ceyhun-o Nov 23, 2026
df8f306
Drive Conviva content bitrate conversion from SDK track events
ceyhun-o Nov 23, 2026
3af3e2b
Exercise ad pause forwarding without native playback
ceyhun-o Nov 23, 2026
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
1 change: 1 addition & 0 deletions .github/workflows/build-and-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ jobs:
THEOplayerConnectorUplynk
# Test schemes to run
TEST_SCHEMES: >-
THEOplayerConnectorConvivaTests
THEOplayerConnectorSideloadedSubtitleTests
THEOplayerConnectorUplynkTests

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1500"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "THEOplayerConnectorConvivaTests"
BuildableName = "THEOplayerConnectorConvivaTests"
BlueprintName = "THEOplayerConnectorConvivaTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
8 changes: 6 additions & 2 deletions Code/Conviva/Source/Base/ConvivaEndpoints.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,16 @@ class ConvivaEndpoints {
let videoAnalytics: CISVideoAnalytics
let adAnalytics: CISAdAnalytics

init?(configuration: ConvivaConfiguration) {
convenience init?(configuration: ConvivaConfiguration) {
guard let analytics = CISAnalyticsCreator.create(withCustomerKey: configuration.customerKey,
settings: configuration.convivaSettingsDictionary) else {
return nil
}

self.init(analytics: analytics)
}

/// Lets tests inject a recording `CISAnalytics` instead of the Conviva SDK one.
init(analytics: CISAnalytics) {
self.analytics = analytics
self.videoAnalytics = self.analytics.createVideoAnalytics()
self.adAnalytics = self.analytics.createAdAnalytics(withVideoAnalytics: videoAnalytics)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
//
// AdBreakTests.swift
//

import XCTest
@_spi(Core) import THEOplayerSDK
import ConvivaSDK
@testable import THEOplayerConnectorConviva

@MainActor
final class AdBreakTests: XCTestCase {
// C9
func testPodPositionFollowsTimeOffset() {
XCTAssertEqual(MockAdBreak(timeOffset: 0).calculateCurrentAdBreakPosition(), "Pre-roll")
XCTAssertEqual(MockAdBreak(timeOffset: 30).calculateCurrentAdBreakPosition(), "Mid-roll")
XCTAssertEqual(MockAdBreak(timeOffset: -1).calculateCurrentAdBreakPosition(), "Post-roll")
}

// C9 — pod values must not depend on the device locale (e.g. "," as decimal separator).
func testSerializationUsesDotWithoutGrouping() {
let formatter = AdHandler.createSerializationFormatter()
XCTAssertEqual(formatter.decimalSeparator, ".")
XCTAssertFalse(formatter.usesGroupingSeparator)
XCTAssertEqual(AdHandler.serialize(number: 12.5), "12.5")
XCTAssertEqual(AdHandler.serialize(number: 1234567.25), "1234567.25")
XCTAssertEqual(AdHandler.serialize(number: 30), "30")
}

// C9
func testAdBreaksReportIncrementingPodIndexAndPosition() {
let harness = makeHarness()
let controller = harness.registerCustomAdIntegration()

guard playAdBreak(timeOffset: 0, maxDuration: 15, on: harness.player, using: controller),
playAdBreak(timeOffset: 60, maxDuration: 10, on: harness.player, using: controller) else { return }

let started = harness.video.adBreaksStarted
XCTAssertEqual(started.map { $0.info[CIS_SSDK_AD_BREAK_POD_INDEX] as? String }, ["1", "2"])
XCTAssertEqual(started.map { $0.info[CIS_SSDK_AD_BREAK_POD_POSITION] as? String }, ["Pre-roll", "Mid-roll"])
XCTAssertEqual(started.map { $0.info[CIS_SSDK_AD_BREAK_POD_DURATION] as? String }, ["15", "10"])
XCTAssertEqual(started.map { $0.info["podTechnology"] as? String }, ["Server Side", "Server Side"])
XCTAssertEqual(started.map(\.adType), [.SERVER_SIDE, .SERVER_SIDE])
XCTAssertEqual(harness.video.adBreakEndedCount, 2)
}

// C9
func testAdPlaybackEventsAreOnlyForwardedDuringAdBreak() {
let harness = makeHarness()
let player = harness.player
let controller = harness.registerCustomAdIntegration()
let dispatchPause = { player.theoplayer.eventDispatcher.dispatchEvent(event: PauseEvent(currentTime: 1)) }

guard waitForEvent(PlayerEventTypes.PAUSE, on: player, afterAdForwarding: true, after: dispatchPause) != nil else { return }
XCTAssertTrue(harness.ad.playerStates.isEmpty)

let adBreak = controller.createAdBreak(params: AdBreakInit(timeOffset: 0, maxDuration: 30))
let ad = controller.createAd(params: AdInit(type: "linear", duration: 30), adBreak: adBreak)
guard waitForEvent(AdsEventTypes.AD_BREAK_BEGIN, on: player.ads, afterAdForwarding: true, after: {
controller.beginAd(ad: ad)
}) != nil else { return }

guard waitForEvent(PlayerEventTypes.PAUSE, on: player, afterAdForwarding: true, after: dispatchPause) != nil else { return }

XCTAssertEqual(harness.ad.playerStates.last, .CONVIVA_PAUSED)
}

private func playAdBreak(timeOffset: Int, maxDuration: Int, on player: THEOplayer, using controller: ServerSideAdIntegrationController) -> Bool {
let adBreak = controller.createAdBreak(params: AdBreakInit(timeOffset: timeOffset, maxDuration: maxDuration))
let ad = controller.createAd(params: AdInit(type: "linear", duration: maxDuration), adBreak: adBreak)
guard waitForEvent(AdsEventTypes.AD_BREAK_BEGIN, on: player.ads, afterAdForwarding: true, after: {
controller.beginAd(ad: ad)
}) != nil else { return false }
return waitForEvent(AdsEventTypes.AD_BREAK_END, on: player.ads, afterAdForwarding: true, after: {
controller.endAd(ad: ad)
}) != nil
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
//
// BitrateTests.swift
//

import XCTest
@_spi(Core) import THEOplayerSDK
import ConvivaSDK
@testable import THEOplayerConnectorConviva

@MainActor
final class BitrateTests: XCTestCase {
// C8
func testActiveQualityIsReportedInKbpsToContentEndpoint() {
let harness = makeHarness()
let player = harness.player
player.theoplayer.eventDispatcher.dispatchEvent(event: PlayEvent(currentTime: 0))

selectTestQuality(on: player)

XCTAssertEqual(harness.video.metricValues(CIS_SSDK_PLAYBACK_METRIC_BITRATE).compactMap { $0 as? Int }, [1234])
XCTAssertTrue(harness.ad.metricValues(CIS_SSDK_PLAYBACK_METRIC_BITRATE).isEmpty)
}

// C8
func testActiveQualityDuringAdIsReportedToAdEndpoint() {
let harness = makeHarness()
let controller = harness.registerCustomAdIntegration()
let adBreak = controller.createAdBreak(params: AdBreakInit(timeOffset: 0, maxDuration: 30))
controller.beginAd(ad: controller.createAd(params: AdInit(type: "linear", duration: 30), adBreak: adBreak))
XCTAssertTrue(harness.player.ads.playing)

selectTestQuality(on: harness.player)

XCTAssertEqual(harness.ad.metricValues(CIS_SSDK_PLAYBACK_METRIC_BITRATE).compactMap { $0 as? Int }, [1234])
XCTAssertTrue(harness.video.metricValues(CIS_SSDK_PLAYBACK_METRIC_BITRATE).isEmpty)
}

// C8
func testBitrateIsReportedAgainForNewSession() throws {
let harness = makeHarness()
let player = harness.player
player.theoplayer.eventDispatcher.dispatchEvent(event: PlayEvent(currentTime: 0))
selectTestQuality(on: player)
player.theoplayer.eventDispatcher.dispatchEvent(event: PauseEvent(currentTime: 1))

let reportedBefore = harness.video.metricValues(CIS_SSDK_PLAYBACK_METRIC_BITRATE)
let lastBitrate = try XCTUnwrap(reportedBefore.last as? NSNumber)
XCTAssertEqual(harness.video.playbackRequested.count, 1)
XCTAssertEqual(harness.video.playerStates.last, .CONVIVA_PAUSED)

harness.connector.stopAndStartNewSession(contentInfo: [:])

let reported = harness.video.metricValues(CIS_SSDK_PLAYBACK_METRIC_BITRATE)
XCTAssertEqual(harness.video.playbackEndedCount, 1)
XCTAssertEqual(reported.count, reportedBefore.count + 1)
XCTAssertEqual(reported.last as? NSNumber, lastBitrate)
}

private struct TestQuality: Quality {
let bandwidth = 1_234_567
let averageBandwidth: Int? = nil
}

private func selectTestQuality(on player: THEOplayer) {
let quality = TestQuality()
let track = VideoTrackImpl(kind: "main", label: "", language: "", qualities: [quality])
player.theoplayer.contentPlayer.videoTracks.addTrack(track)
track.activeQualityChanged(bandwidth: quality.bandwidth)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
//
// ConvivaTestSupport.swift
//

import XCTest
import THEOplayerSDK
@testable import THEOplayerConnectorConviva

enum TestSources {
// The default (unlicensed) player only plays sources hosted on theoplayer.com.
static let bigBuckBunny = "https://cdn.theoplayer.com/video/big_buck_bunny/big_buck_bunny.m3u8"
static let elephantsDream = "https://cdn.theoplayer.com/video/elephants-dream/playlist.m3u8"
// Segment 4 (18-24 s) of every video variant returns HTTP 403.
static let missingSegment = "https://cdn.theoplayer.com/video/elephants-dream/404/index.m3u8"
static let theoliveDemoChannel = "demo"

static func hls(_ url: String = bigBuckBunny) -> SourceDescription {
SourceDescription(source: TypedSource(src: url, type: "application/x-mpegurl"))
}
}

/// The public THEOlive demo channel. The default license implicitly allows theo.live sources.
struct THEOliveDemoEndpoint: Decodable {
let hlsSrc: String
}

/// A real player with a `ConvivaConnector` that reports to a `RecordingAnalytics`.
final class ConvivaHarness {
let player = THEOplayer(with: nil)
let analytics = RecordingAnalytics()
let connector: ConvivaConnector
var video: RecordingVideoAnalytics { analytics.video }
var ad: RecordingAdAnalytics { analytics.ad }

init(convivaMetadata: [String: Any] = [:]) {
connector = ConvivaConnector(conviva: ConvivaEndpoints(analytics: analytics), player: player, convivaMetadata: convivaMetadata)
}

/// Registers a custom server-side ad integration so tests can drive real ad break and ad events.
func registerCustomAdIntegration() -> ServerSideAdIntegrationController {
var controller: ServerSideAdIntegrationController!
player.ads.registerServerSideIntegration(integrationId: "conviva-tests") {
controller = $0
return NoopAdIntegrationHandler()
}
return controller
}
}

struct NoopAdIntegrationHandler: ServerSideAdIntegrationHandler {}

struct MockAdBreak: AdBreak {
var id: String?
var ads: [Ad] = []
var maxDuration: Int = 0
var maxRemainingDuration: Double = 0
var timeOffset: Int = 0
var integration: AdIntegrationKind = .custom
var customIntegration: String?
}

extension XCTestCase {
func makeHarness(convivaMetadata: [String: Any] = [:]) -> ConvivaHarness {
let harness = ConvivaHarness(convivaMetadata: convivaMetadata)
addTeardownBlock {
harness.connector.destroy()
harness.player.stop()
}
return harness
}

/// Waits for the next matching event, optionally after Conviva's queued ad forwarding.
@discardableResult
func waitForEvent<E: EventProtocol>(
_ type: EventType<E>,
on dispatcher: EventDispatcherProtocol,
timeout: TimeInterval = 30,
afterAdForwarding: Bool = false,
file: StaticString = #filePath,
line: UInt = #line,
matching: @escaping (E) -> Bool = { _ in true },
after trigger: () -> Void = {}
) -> E? {
let eventReceived = expectation(description: "\(type.name) event")
var received: E?
let listener = dispatcher.addEventListener(type: type) { event in
guard received == nil, matching(event) else { return }
received = event
if afterAdForwarding {
DispatchQueue.main.async { eventReceived.fulfill() }
} else {
eventReceived.fulfill()
}
}
trigger()
wait(for: [eventReceived], timeout: timeout)
dispatcher.removeEventListener(type: type, listener: listener)
if received == nil {
XCTFail("No \(type.name) event within \(timeout)s", file: file, line: line)
}
return received
}

/// Asks THEOlive discovery for the demo channel's current endpoint, so tests don't depend on its engine path.
func fetchTHEOliveDemoEndpoint(file: StaticString = #filePath, line: UInt = #line) throws -> THEOliveDemoEndpoint {
struct Distribution: Decodable { let endpoints: [THEOliveDemoEndpoint] }
let fetched = expectation(description: "THEOlive discovery response")
let url = URL(string: "https://discovery.theo.live/v2/distributions/\(TestSources.theoliveDemoChannel)")!
var result: Result<Data, Error> = .failure(URLError(.timedOut))
let task = URLSession.shared.dataTask(with: url) { data, response, error in
DispatchQueue.main.async {
if let data, (response as? HTTPURLResponse)?.statusCode == 200 {
result = .success(data)
} else {
result = .failure(error ?? URLError(.badServerResponse))
}
fetched.fulfill()
}
}
task.resume()
defer { task.cancel() }
wait(for: [fetched], timeout: 30)
let distribution = try JSONDecoder().decode(Distribution.self, from: result.get())
return try XCTUnwrap(distribution.endpoints.first, "No THEOlive demo endpoint", file: file, line: line)
}

func waitUntil(_ description: String, timeout: TimeInterval = 30, _ condition: @escaping () -> Bool) {
let conditionMet = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in condition() }, object: nil)
conditionMet.expectationDescription = description
wait(for: [conditionMet], timeout: timeout)
}
}
Loading
Loading