Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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,73 @@
//
// AdBreakTests.swift
//

import XCTest
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()
harness.player.source = TestSources.hls()

playAdBreak(timeOffset: 0, maxDuration: 15, using: controller)
playAdBreak(timeOffset: 60, maxDuration: 10, using: controller)
drainMainQueue()

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 controller = harness.registerCustomAdIntegration()
harness.player.source = TestSources.hls()

waitForEvent(PlayerEventTypes.PLAY, on: harness.player) { harness.player.play() }
waitForEvent(PlayerEventTypes.PAUSE, on: harness.player) { harness.player.pause() }
XCTAssertTrue(harness.ad.playerStates.isEmpty)

let adBreak = controller.createAdBreak(params: AdBreakInit(timeOffset: 0, maxDuration: 30))
controller.beginAd(ad: controller.createAd(params: AdInit(type: "linear", duration: 30), adBreak: adBreak))
drainMainQueue()
waitForEvent(PlayerEventTypes.PLAY, on: harness.player) { harness.player.play() }
waitForEvent(PlayerEventTypes.PAUSE, on: harness.player) { harness.player.pause() }

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

private func playAdBreak(timeOffset: Int, maxDuration: Int, using controller: ServerSideAdIntegrationController) {
let adBreak = controller.createAdBreak(params: AdBreakInit(timeOffset: timeOffset, maxDuration: maxDuration))
let ad = controller.createAd(params: AdInit(type: "linear", duration: maxDuration), adBreak: adBreak)
controller.beginAd(ad: ad)
controller.endAd(ad: ad)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
//
// BitrateTests.swift
//

import XCTest
import THEOplayerSDK
import ConvivaSDK
@testable import THEOplayerConnectorConviva

/// These tests need real playback: the player only reports an active quality once it renders media.
@MainActor
final class BitrateTests: XCTestCase {
// C8
func testActiveQualityIsReportedInKbpsToContentEndpoint() {
let harness = makeHarness()
let bandwidths = recordActiveQualityBandwidths(of: harness.player)
harness.player.source = TestSources.hls()
harness.player.play()

waitUntil("content bitrate reported") { !harness.video.metricValues(CIS_SSDK_PLAYBACK_METRIC_BITRATE).isEmpty }

let reported = harness.video.metricValues(CIS_SSDK_PLAYBACK_METRIC_BITRATE).compactMap { ($0 as? NSNumber)?.intValue }
XCTAssertEqual(reported.first, bandwidths.values.first.map { $0 / 1000 })
XCTAssertTrue(harness.ad.metricValues(CIS_SSDK_PLAYBACK_METRIC_BITRATE).isEmpty)
}

// C8
func testActiveQualityDuringAdIsReportedToAdEndpoint() {
let harness = makeHarness()
let controller = harness.registerCustomAdIntegration()
harness.player.source = TestSources.hls()
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)
harness.player.play()

waitUntil("ad bitrate reported") { !harness.ad.metricValues(CIS_SSDK_PLAYBACK_METRIC_BITRATE).isEmpty }

XCTAssertTrue(harness.video.metricValues(CIS_SSDK_PLAYBACK_METRIC_BITRATE).isEmpty)
}

// C8
func testBitrateIsReportedAgainForNewSession() {
let harness = makeHarness()
harness.player.source = TestSources.hls()
harness.player.play()
waitUntil("content bitrate reported") { !harness.video.metricValues(CIS_SSDK_PLAYBACK_METRIC_BITRATE).isEmpty }
let lastBitrate = harness.video.metricValues(CIS_SSDK_PLAYBACK_METRIC_BITRATE).last as? NSNumber
harness.player.pause()
drainMainQueue()
let reportedBefore = harness.video.metricValues(CIS_SSDK_PLAYBACK_METRIC_BITRATE).count

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

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

private final class Bandwidths { var values: [Int] = [] }

private func recordActiveQualityBandwidths(of player: THEOplayer) -> Bandwidths {
let bandwidths = Bandwidths()
_ = player.videoTracks.addEventListener(type: VideoTrackListEventTypes.ADD_TRACK) { event in
_ = (event.track as? VideoTrack)?.addEventListener(type: MediaTrackEventTypes.ACTIVE_QUALITY_CHANGED) {
bandwidths.values.append($0.quality.bandwidth)
}
}
return bandwidths
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
//
// 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 `type` event, triggered by `trigger`, and lets the main queue drain afterwards.
@discardableResult
func waitForEvent<E: EventProtocol>(
_ type: EventType<E>,
on dispatcher: EventDispatcherProtocol,
timeout: TimeInterval = 30,
file: StaticString = #filePath,
line: UInt = #line,
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 else { return }
received = event
eventReceived.fulfill()
}
trigger()
wait(for: [eventReceived], timeout: timeout)
dispatcher.removeEventListener(type: type, listener: listener)
drainMainQueue()
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)
}

/// The connector forwards ad events through `DispatchQueue.main.async`; this lets those run.
func drainMainQueue() {
let drained = expectation(description: "main queue drained")
DispatchQueue.main.async { DispatchQueue.main.async { drained.fulfill() } }
wait(for: [drained], timeout: 5)
}
}
Loading
Loading