Make TelemetryService testable (#276)

* Make TelemetryService testable

Timer is extracted for better testability of telemetryservice.

Divided TelemetryService to internal part that:
- contains business logic
- does not contain timer
- and therefore testable

and external part that:
- does not contain business logic
- contains timer to send analytics every 10 seconds for all participants.
- does not need tests

* Add Test_AnalyticsSentWhenParticipantLeaves

* Fix test
This commit is contained in:
Artur Shellunts
2021-12-28 12:54:56 +01:00
committed by GitHub
parent 3108ef22ad
commit 2209edce20
6 changed files with 229 additions and 123 deletions
+30 -10
View File
@@ -3,7 +3,6 @@ package telemetrytest
import (
"context"
"testing"
"time"
"github.com/livekit/protocol/livekit"
"github.com/stretchr/testify/require"
@@ -13,36 +12,57 @@ import (
)
type telemetryServiceFixture struct {
sut telemetry.TelemetryService
sut telemetry.TelemetryServiceInternal
analytics *telemetryfakes.FakeAnalyticsService
}
func createFixture() *telemetryServiceFixture {
fixture := &telemetryServiceFixture{}
fixture.analytics = &telemetryfakes.FakeAnalyticsService{}
fixture.sut = telemetry.NewTelemetryService(nil, fixture.analytics)
fixture.sut = telemetry.NewTelemetryServiceInternal(nil, fixture.analytics)
return fixture
}
func Test_TelemetryService_Downstream_Stats(t *testing.T) {
func Test_OnDownstreamPacket(t *testing.T) {
fixture := createFixture()
//prepare
room := &livekit.Room{}
partSID := "part1"
clientInfo := &livekit.ClientInfo{Sdk: 2}
participantInfo := &livekit.ParticipantInfo{Sid: partSID}
fixture.sut.ParticipantJoined(context.Background(), room, participantInfo, clientInfo)
totalBytes := 33
fixture.sut.OnDownstreamPacket(partSID, totalBytes)
// call participant left to trigger sending of analytics
fixture.sut.ParticipantLeft(context.Background(), room, participantInfo)
time.Sleep(time.Millisecond * 100) // wait for Update function to be called in go routine
//do
packets := []int{33, 23}
totalBytes := packets[0] + packets[1]
totalPackets := len(packets)
for i := range packets {
fixture.sut.OnDownstreamPacket(partSID, packets[i])
}
fixture.sut.SendAnalytics()
//test
require.Equal(t, 1, fixture.analytics.SendStatsCallCount())
_, stats := fixture.analytics.SendStatsArgsForCall(0)
require.Equal(t, 1, len(stats))
require.Equal(t, livekit.StreamType_DOWNSTREAM, stats[0].Kind)
require.Equal(t, totalBytes, int(stats[0].TotalBytes))
require.Equal(t, totalPackets, int(stats[0].TotalPackets))
}
func Test_AnalyticsSentWhenParticipantLeaves(t *testing.T) {
fixture := createFixture()
//prepare
room := &livekit.Room{}
partSID := "part1"
participantInfo := &livekit.ParticipantInfo{Sid: partSID}
fixture.sut.ParticipantJoined(context.Background(), room, participantInfo, nil)
//do
fixture.sut.ParticipantLeft(context.Background(), room, participantInfo)
//test
require.Equal(t, 1, fixture.analytics.SendStatsCallCount())
}