// // ServerDataTests.swift // PadelClubTests // // Created by Laurent Morvillier on 08/05/2024. // import XCTest import LeStorage @testable import PadelClub final class ServerDataTests: XCTestCase { let username: String = "UserDataTests" let password: String = "MyPass1234--" override func setUpWithError() throws { // StoreCenter.main.synchronizationApiURL = "http://127.0.0.1:8000/roads/" StoreCenter.main.configureURLs(secureScheme: false, domain: "127.0.0.1:8000") Task { do { try await self.login() } catch { assertionFailure(error.localizedDescription) } } } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func login() async throws { // print("LOGIN!") let _: CustomUser = try await StoreCenter.main.service().login(username: self.username, password: self.password) } func testClub() async throws { let club = Club(name: "Aix Universite Club") club.acronym = "AUC" club.city = "Aix en provence" club.zipCode = "13100" club.code = "abc" club.address = "2 avenue de la vie" club.latitude = 13 club.longitude = 10 club.phone = "061234567890" club.courtCount = 3 if let inserted_club: Club = try await StoreCenter.main.service().post(club) { assert(inserted_club.lastUpdate == club.lastUpdate) assert(inserted_club.name == club.name) assert(inserted_club.acronym == club.acronym) assert(inserted_club.zipCode == club.zipCode) assert(inserted_club.address == club.address) assert(inserted_club.latitude == club.latitude) assert(inserted_club.longitude == club.longitude) assert(inserted_club.phone == club.phone) assert(inserted_club.courtCount == club.courtCount) assert(inserted_club.broadcastCode != nil) assert(inserted_club.timezone != club.timezone) inserted_club.phone = "123456" inserted_club.lastUpdate = Date() if let updated_club: Club = try await StoreCenter.main.service().put(inserted_club) { assert(updated_club.phone == inserted_club.phone) } else { XCTFail("missing data") } } else { XCTFail("missing data") } } func testLogin() async throws { let service = try StoreCenter.main.service() let user: CustomUser = try await service.login(username: self.username, password: self.password) assert(user.username == self.username) } func testEvent() async throws { guard let userId = StoreCenter.main.userId else { assertionFailure("missing user UUID") return } let clubs: [Club] = try await StoreCenter.main.service().get() guard let clubId = clubs.first?.id else { assertionFailure("missing club in database") return } let event = Event(creator: userId, club: clubId, name: "Roland Garros", tenupId: "abc") if let e = try await StoreCenter.main.service().post(event){ assert(e.name == event.name) assert(e.lastUpdate == event.lastUpdate) assert(e.tenupId == event.tenupId) } else { XCTFail("missing data") } } func testTournament() async throws { let event: [Event] = try await StoreCenter.main.service().get() guard let eventId = event.first?.id else { assertionFailure("missing event in database") return } let tournament = Tournament(event: eventId, name: "RG Homme", startDate: Date(), endDate: nil, creationDate: Date(), isPrivate: false, groupStageFormat: MatchFormat.megaTie, roundFormat: MatchFormat.nineGames, loserRoundFormat: MatchFormat.nineGamesDecisivePoint, groupStageSortMode: GroupStageOrderingMode.snake, groupStageCount: 2, rankSourceDate: Date(), dayDuration: 5, teamCount: 3, teamSorting: TeamSortingType.rank, federalCategory: TournamentCategory.mix, federalLevelCategory: TournamentLevel.p1000, federalAgeCategory: FederalTournamentAge.a45, closedRegistrationDate: Date(), groupStageAdditionalQualified: 4, courtCount: 9, prioritizeClubMembers: true, qualifiedPerGroupStage: 1, teamsPerGroupStage: 2, entryFee: 30.0, additionalEstimationDuration: 5, isDeleted: true, publishTeams: true, publishSummons: true, publishGroupStages: true, publishBrackets: true, shouldVerifyGroupStage: true, shouldVerifyBracket: true, hideTeamsWeight: true, publishTournament: true, hidePointsEarned: true, publishRankings: true, loserBracketMode: .manual, initialSeedRound: 8, initialSeedCount: 4, accountIsRequired: false, licenseIsRequired: false, minimumPlayerPerTeam: 3, maximumPlayerPerTeam: 5, information: "Super", umpireCustomMail: "razmig@padelclub.app", umpireCustomContact: "Raz", umpireCustomPhone: "+33681598193", hideUmpireMail: true, hideUmpirePhone: true, disableRankingFederalRuling: true, teamCountLimit: false, enableOnlinePayment: false, onlinePaymentIsMandatory: false, enableOnlinePaymentRefund: false, refundDateLimit: nil, stripeAccountId: nil, enableTimeToConfirm: false, isCorporateTournament: false, isTemplate: false, publishProg: true, showTeamsInProg: true, currencyCode: "USD") ) tournament.isCanceled = true tournament.payment = .subscriptionUnit if let t = try await StoreCenter.main.service().post(tournament) { assert(t.isCanceled == tournament.isCanceled) assert(t.payment == tournament.payment) assert(t.lastUpdate.formatted() == tournament.lastUpdate.formatted()) assert(t.event == tournament.event) assert(t.name == tournament.name) assert(t.startDate.formatted() == tournament.startDate.formatted()) assert(t.endDate?.formatted() == tournament.endDate?.formatted()) assert(t.creationDate.formatted() == tournament.creationDate.formatted()) assert(t.isPrivate == tournament.isPrivate) assert(t.groupStageFormat == tournament.groupStageFormat) assert(t.roundFormat == tournament.roundFormat) assert(t.loserRoundFormat == tournament.loserRoundFormat) assert(t.groupStageSortMode == tournament.groupStageSortMode) assert(t.groupStageCount == tournament.groupStageCount) assert(t.rankSourceDate?.formatted() == tournament.rankSourceDate?.formatted()) assert(t.dayDuration == tournament.dayDuration) assert(t.teamCount == tournament.teamCount) assert(t.teamSorting == tournament.teamSorting) assert(t.federalCategory == tournament.federalCategory) assert(t.federalLevelCategory == tournament.federalLevelCategory) assert(t.federalAgeCategory == tournament.federalAgeCategory) assert(t.closedRegistrationDate?.formatted() == tournament.closedRegistrationDate?.formatted()) assert(t.groupStageAdditionalQualified == tournament.groupStageAdditionalQualified) assert(t.courtCount == tournament.courtCount) assert(t.prioritizeClubMembers == tournament.prioritizeClubMembers) assert(t.qualifiedPerGroupStage == tournament.qualifiedPerGroupStage) assert(t.teamsPerGroupStage == tournament.teamsPerGroupStage) assert(t.entryFee == tournament.entryFee) assert(t.additionalEstimationDuration == tournament.additionalEstimationDuration) assert(t.isDeleted == tournament.isDeleted) assert(t.publishTeams == tournament.publishTeams) assert(t.publishSummons == tournament.publishSummons) assert(t.publishGroupStages == tournament.publishGroupStages) assert(t.publishBrackets == tournament.publishBrackets) assert(t.shouldVerifyBracket == tournament.shouldVerifyBracket) assert(t.shouldVerifyGroupStage == tournament.shouldVerifyGroupStage) assert(t.hideTeamsWeight == tournament.hideTeamsWeight) assert(t.publishTournament == tournament.publishTournament) assert(t.hidePointsEarned == tournament.hidePointsEarned) assert(t.publishRankings == tournament.publishRankings) assert(t.loserBracketMode == tournament.loserBracketMode) assert(t.initialSeedCount == tournament.initialSeedCount) assert(t.initialSeedRound == tournament.initialSeedRound) assert(t.accountIsRequired == tournament.accountIsRequired) assert(t.licenseIsRequired == tournament.licenseIsRequired) assert(t.minimumPlayerPerTeam == tournament.minimumPlayerPerTeam) assert(t.maximumPlayerPerTeam == tournament.maximumPlayerPerTeam) assert(t.information == tournament.information) assert(t.umpireCustomMail == tournament.umpireCustomMail) assert(t.umpireCustomContact == tournament.umpireCustomContact) assert(t.umpireCustomPhone == tournament.umpireCustomPhone) assert(t.hideUmpireMail == tournament.hideUmpireMail) assert(t.hideUmpirePhone == tournament.hideUmpirePhone) assert(t.disableRankingFederalRuling == tournament.disableRankingFederalRuling) assert(t.teamCountLimit == tournament.teamCountLimit) assert(t.enableOnlinePayment == tournament.enableOnlinePayment) assert(t.onlinePaymentIsMandatory == tournament.onlinePaymentIsMandatory) assert(t.enableOnlinePaymentRefund == tournament.enableOnlinePaymentRefund) assert(t.refundDateLimit?.formatted() == tournament.refundDateLimit?.formatted()) assert(t.stripeAccountId == tournament.stripeAccountId) assert(t.enableTimeToConfirm == tournament.enableTimeToConfirm) assert(t.isCorporateTournament == tournament.isCorporateTournament) assert(t.isTemplate == tournament.isTemplate) assert(t.publishProg == tournament.publishProg) assert(t.showTeamsInProg == tournament.showTeamsInProg) assert(t.currencyCode == tournament.currencyCode) } else { XCTFail("missing data") } } func testGroupStage() async throws { let tournament: [Tournament] = try await StoreCenter.main.service().get() guard let tournamentId = tournament.first?.id else { assertionFailure("missing tournament in database") return } let groupStage = GroupStage(tournament: tournamentId, index: 2, size: 3, format: MatchFormat.nineGames, startDate: Date(), name: "Yeah!", step: 1, plannedStartDate: Date() ) groupStage.storeId = "123" if let gs: GroupStage = try await StoreCenter.main.service().post(groupStage) { assert(gs.tournament == groupStage.tournament) assert(gs.storeId == groupStage.storeId) assert(gs.lastUpdate == groupStage.lastUpdate) assert(gs.name == groupStage.name) assert(gs.index == groupStage.index) assert(gs.size == groupStage.size) assert(gs.matchFormat == groupStage.matchFormat) assert(gs.startDate != nil) assert(gs.step == groupStage.step) assert(r.plannedStartDate != nil) } else { XCTFail("missing data") } } func testRound() async throws { let tournament: [Tournament] = try await StoreCenter.main.service().get() guard let tournamentId = tournament.first?.id else { assertionFailure("missing tournament in database") return } let rounds: [Round] = try await StoreCenter.main.service().get() let parentRoundId = rounds.first?.id let round = Round(tournament: tournamentId, index: 1, parent: parentRoundId, format: MatchFormat.nineGames, startDate: Date(), groupStageLoserBracket: false, loserBracketMode: .manual, plannedStartDate: Date()) round.storeId = "abc" if let r: Round = try await StoreCenter.main.service().post(round) { assert(r.storeId == round.storeId) assert(r.tournament == round.tournament) assert(r.lastUpdate == round.lastUpdate) assert(r.index == round.index) assert(r.parent == round.parent) assert(r.matchFormat == round.matchFormat) assert(r.startDate != nil) assert(r.groupStageLoserBracket == round.groupStageLoserBracket) assert(r.loserBracketMode == round.loserBracketMode) assert(r.plannedStartDate != nil) } else { XCTFail("missing data") } } func testTeamRegistration() async throws { let tournament: [Tournament] = try await StoreCenter.main.service().get() guard let tournamentId = tournament.first?.id else { assertionFailure("missing tournament in database") return } let groupStages: [GroupStage] = try await StoreCenter.main.service().get() guard let groupStageId = groupStages.first?.id else { assertionFailure("missing groupStage in database") return } let teamRegistration = TeamRegistration(tournament: tournamentId, groupStage: groupStageId, registrationDate: Date(), callDate: Date(), bracketPosition: 1, groupStagePosition: 2, comment: "comment", source: "source", sourceValue: "source V", logo: "logo", name: "Stax", walkOut: true, wildCardBracket: true, wildCardGroupStage: true, weight: 1, lockedWeight: 11, confirmationDate: Date(), qualified: true, finalRanking: 100, pointsEarned: 10, uniqueRandomIndex: 1) teamRegistration.storeId = "123" if let tr: TeamRegistration = try await StoreCenter.main.service().post(teamRegistration) { assert(tr.storeId == teamRegistration.storeId) assert(tr.tournament == teamRegistration.tournament) assert(tr.lastUpdate == teamRegistration.lastUpdate) assert(tr.groupStage == teamRegistration.groupStage) assert(tr.registrationDate != nil) assert(tr.callDate != nil) assert(tr.bracketPosition == teamRegistration.bracketPosition) assert(tr.groupStagePosition == teamRegistration.groupStagePosition) assert(tr.comment == teamRegistration.comment) assert(tr.source == teamRegistration.source) assert(tr.sourceValue == teamRegistration.sourceValue) assert(tr.logo == teamRegistration.logo) assert(tr.name == teamRegistration.name) assert(tr.walkOut == teamRegistration.walkOut) assert(tr.wildCardBracket == teamRegistration.wildCardBracket) assert(tr.wildCardGroupStage == teamRegistration.wildCardGroupStage) assert(tr.weight == teamRegistration.weight) assert(tr.lockedWeight == teamRegistration.lockedWeight) assert(tr.confirmationDate?.formatted() == teamRegistration.confirmationDate?.formatted()) assert(tr.qualified == teamRegistration.qualified) assert(tr.finalRanking == teamRegistration.finalRanking) assert(tr.pointsEarned == teamRegistration.pointsEarned) assert(tr.uniqueRandomIndex == teamRegistration.uniqueRandomIndex) } else { XCTFail("missing data") } } func testPlayerRegistration() async throws { let teamRegistrations: [TeamRegistration] = try await StoreCenter.main.service().get() guard let teamRegistrationId = teamRegistrations.first?.id else { assertionFailure("missing teamRegistrations in database") return } let playerRegistration = PlayerRegistration(teamRegistration: teamRegistrationId, firstName: "juan", lastName: "lebron", licenceId: "123", rank: 11, paymentType: PlayerPaymentType.cash, sex: PlayerSexType.male, tournamentPlayed: 2, points: 33, clubName: "le club", ligueName: "la league", assimilation: "ass", phoneNumber: "123123", email: "email@email.com", birthdate: nil, computedRank: 222, source: PlayerRegistration.PlayerDataSource.frenchFederation, hasArrived: true, coach: false, captain: false, registeredOnline: false, timeToConfirm: nil, registrationStatus: PlayerRegistration.RegistrationStatus.waiting, paymentId: nil, contactName: "coach juan", contactPhoneNumber: "4587654321", contactEmail: "juana@email.com") playerRegistration.storeId = "123" if let pr: PlayerRegistration = try await StoreCenter.main.service().post(playerRegistration) { assert(pr.storeId == playerRegistration.storeId) assert(pr.lastName == playerRegistration.lastName) assert(pr.teamRegistration == playerRegistration.teamRegistration) assert(pr.firstName == playerRegistration.firstName) assert(pr.lastName == playerRegistration.lastName) assert(pr.licenceId == playerRegistration.licenceId) assert(pr.rank == playerRegistration.rank) assert(pr.paymentType == playerRegistration.paymentType) assert(pr.sex == playerRegistration.sex) assert(pr.tournamentPlayed == playerRegistration.tournamentPlayed) assert(pr.points == playerRegistration.points) assert(pr.clubName == playerRegistration.clubName) assert(pr.ligueName == playerRegistration.ligueName) assert(pr.assimilation == playerRegistration.assimilation) assert(pr.phoneNumber == playerRegistration.phoneNumber) assert(pr.birthdate == playerRegistration.birthdate) assert(pr.computedRank == playerRegistration.computedRank) assert(pr.source == playerRegistration.source) assert(pr.hasArrived == playerRegistration.hasArrived) assert(pr.captain == playerRegistration.captain) assert(pr.coach == playerRegistration.coach) assert(pr.registeredOnline == playerRegistration.registeredOnline) assert(pr.captain == playerRegistration.captain) assert(pr.coach == playerRegistration.coach) assert(pr.registeredOnline == playerRegistration.registeredOnline) assert(pr.timeToConfirm == playerRegistration.timeToConfirm) assert(pr.registrationStatus == playerRegistration.registrationStatus) assert(pr.paymentId == playerRegistration.paymentId) assert(pr.contactName == playerRegistration.contactName) assert(pr.contactEmail == playerRegistration.contactEmail) assert(pr.contactPhoneNumber == playerRegistration.contactPhoneNumber) } else { XCTFail("missing data") } } func testMatch() async throws { let teamRegistrations: [TeamRegistration] = try await StoreCenter.main.service().get() guard let teamRegistrationId = teamRegistrations.first?.id else { assertionFailure("missing teamRegistrations in database") return } let rounds: [Round] = try await StoreCenter.main.service().get() let parentRoundId = rounds.first?.id let match: Match = Match(round: parentRoundId, groupStage: nil, startDate: Date(), endDate: Date(), index: 2, format: MatchFormat.twoSets, servingTeamId: teamRegistrationId, winningTeamId: teamRegistrationId, losingTeamId: teamRegistrationId, disabled: true, courtIndex: 1, confirmed: true) match.storeId = "123" if let m: Match = try await StoreCenter.main.service().post(match) { assert(m.storeId == match.storeId) assert(m.lastUpdate == match.lastUpdate) assert(m.round == match.round) assert(m.groupStage == match.groupStage) assert(m.startDate != nil) assert(m.endDate != nil) assert(m.index == match.index) assert(m.matchFormat == match.matchFormat) assert(m.servingTeamId == match.servingTeamId) assert(m.winningTeamId == match.winningTeamId) assert(m.losingTeamId == match.losingTeamId) assert(m.disabled == match.disabled) assert(m.courtIndex == match.courtIndex) assert(m.confirmed == match.confirmed) } else { XCTFail("missing data") } } func testTeamScore() async throws { let matches: [Match] = try await StoreCenter.main.service().get() guard let matchId = matches.first?.id else { assertionFailure("missing match in database") return } let teamRegistrations: [TeamRegistration] = try await StoreCenter.main.service().get() guard let teamRegistrationId = teamRegistrations.first?.id else { assertionFailure("missing teamRegistrations in database") return } let teamScore = TeamScore(match: matchId, teamRegistration: teamRegistrationId, score: "6/6", walkOut: 1, luckyLoser: 1) teamScore.storeId = "!23" if let ts: TeamScore = try await StoreCenter.main.service().post(teamScore) { assert(ts.storeId == teamScore.storeId) assert(ts.lastUpdate == teamScore.lastUpdate) assert(ts.match == teamScore.match) assert(ts.teamRegistration == teamScore.teamRegistration) assert(ts.score == teamScore.score) assert(ts.walkOut == teamScore.walkOut) assert(ts.luckyLoser == teamScore.luckyLoser) } else { XCTFail("missing data") } } func testCourt() async throws { let clubs: [Club] = try await StoreCenter.main.service().get() guard let clubId = clubs.first?.id else { assertionFailure("missing club in database") return } let court = Court(index: 1, club: clubId, name: "Philippe Chatrier", exitAllowed: true, indoor: true) if let c: Court = try await StoreCenter.main.service().post(court) { assert(c.lastUpdate == court.lastUpdate) assert(c.club == court.club) assert(c.name == court.name) assert(c.index == court.index) assert(c.exitAllowed == court.exitAllowed) assert(c.indoor == court.indoor) } else { XCTFail("missing data") } } func testDateInterval() async throws { let event: [Event] = try await StoreCenter.main.service().get() guard let eventId = event.first?.id else { assertionFailure("missing event in database") return } let dateInterval = DateInterval(event: eventId, courtIndex: 1, startDate: Date(), endDate: Date()) if let di: PadelClub.DateInterval = try await StoreCenter.main.service().post(dateInterval) { assert(di.lastUpdate == dateInterval.lastUpdate) assert(di.event == dateInterval.event) assert(di.courtIndex == dateInterval.courtIndex) assert(di.startDate.formatted() == dateInterval.startDate.formatted()) assert(di.endDate.formatted() == dateInterval.endDate.formatted()) } else { XCTFail("missing data") } } func testPurchase() async throws { guard let userId = StoreCenter.main.userId else { assertionFailure("missing user UUID") return } let transactionId = UInt64.random(in: 0...100000) let quantity = Int.random(in: 0...10) let purchase: Purchase = Purchase(transactionId: transactionId, user: userId, purchaseDate: Date(), productId: "app.padelclub.productId", quantity: quantity, revocationDate: Date(), expirationDate: Date()) if let p: Purchase = try await StoreCenter.main.service().post(purchase) { assert(p.id == purchase.id) assert(p.lastUpdate == purchase.lastUpdate) assert(p.user == purchase.user) assert(p.productId == purchase.productId) assert(p.purchaseDate.formatted() == purchase.purchaseDate.formatted()) assert(p.quantity == purchase.quantity) assert(p.revocationDate?.formatted() == purchase.revocationDate?.formatted()) assert(p.expirationDate?.formatted() == purchase.expirationDate?.formatted()) } else { XCTFail("missing data") } } func testDrawLog() async throws { let tournament: [Tournament] = try await StoreCenter.main.service().get() guard let tournamentId = tournament.first?.id else { assertionFailure("missing tournament in database") return } let drawLog = DrawLog(tournament: tournamentId, drawSeed: 1, drawMatchIndex: 1, drawTeamPosition: .two, drawType: .court) drawLog.storeId = "!23" if let d: DrawLog = try await StoreCenter.main.service().post(drawLog) { assert(d.tournament == drawLog.tournament) assert(d.drawDate.formatted() == drawLog.drawDate.formatted()) assert(d.drawSeed == drawLog.drawSeed) assert(d.drawTeamPosition == drawLog.drawTeamPosition) assert(d.drawMatchIndex == drawLog.drawMatchIndex) assert(d.drawType == drawLog.drawType) } else { XCTFail("missing data") } } /// needs a user with the licenceId set to "5186803D" to suceed func testTryPutBeforeUpdating() async throws { let service = try StoreCenter.main.service() let user: CustomUser = try await service.login(username: self.username, password: self.password) let copy: CustomUser = user.copy() copy.licenceId = "5186803D" do { _ = try await DataStore.shared.tryUserUpdate(userCopy: copy) XCTFail("should fail because licenceId is the same than dummy's") } catch { Logger.error(error) } } }