content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package ch.epfl.skysync.database.tables
import androidx.test.ext.junit.runners.AndroidJUnit4
import ch.epfl.skysync.database.DatabaseSetup
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.database.schemas.FlightMemberSchema
import ch.epfl.skysync.models.flight.Flight
import ch.epfl.skysync.models.flight.Role
import ch.epfl.skysync.models.flight.RoleType
import ch.epfl.skysync.models.flight.Team
import kotlinx.coroutines.test.runTest
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class FlightTableUnitTest {
private val db = FirestoreDatabase(useEmulator = true)
private val dbs = DatabaseSetup()
private val flightTable = FlightTable(db)
private val flightMemberTable = FlightMemberTable(db)
@Before
fun testSetup() = runTest {
dbs.clearDatabase(db)
dbs.fillDatabase(db)
}
@Test
fun getTest() = runTest {
val flight = flightTable.get(dbs.flight1.id, onError = { assertNull(it) })
assertEquals(dbs.flight1, flight)
}
@Test
fun updateTest() = runTest {
val newTeam = Team(roles = listOf(Role(RoleType.PILOT, dbs.pilot2)))
val updateFlight1 = dbs.flight1.copy(nPassengers = dbs.flight1.nPassengers + 1, team = newTeam)
flightTable.update(dbs.flight1.id, updateFlight1, onError = { assertNull(it) })
val flight = flightTable.get(dbs.flight1.id, onError = { assertNull(it) })
assertEquals(updateFlight1, flight)
var flightMembers = flightMemberTable.getAll(onError = { assertNull(it) })
assertEquals(1, flightMembers.size)
assertEquals(dbs.flight1.id, flightMembers[0].flightId)
assertEquals(dbs.pilot2.id, flightMembers[0].userId)
}
@Test
fun deleteTest() = runTest {
flightTable.delete(dbs.flight1.id, onError = { assertNull(it) })
val flightMembers = flightMemberTable.getAll(onError = { assertNull(it) })
val flights = flightTable.getAll(onError = { assertNull(it) })
assertEquals(listOf<FlightMemberSchema>(), flightMembers)
assertEquals(listOf<Flight>(), flights)
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/database/tables/FlightTableUnitTest.kt | 1247563624 |
package ch.epfl.skysync.database.tables
import androidx.test.ext.junit.runners.AndroidJUnit4
import ch.epfl.skysync.database.DatabaseSetup
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.models.flight.RoleType
import com.google.firebase.firestore.Filter
import kotlinx.coroutines.test.runTest
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class UserTableUnitTest {
private val db = FirestoreDatabase(useEmulator = true)
private val dbs = DatabaseSetup()
private val userTable = UserTable(db)
private val availabilityTable = AvailabilityTable(db)
private val flightTable = FlightTable(db)
private val flightMemberTable = FlightMemberTable(db)
@Before
fun testSetup() = runTest {
dbs.clearDatabase(db)
dbs.fillDatabase(db)
}
@Test
fun getTest() = runTest {
var user = userTable.get(dbs.admin1.id, onError = { assertNull(it) })
assertEquals(dbs.admin1, user)
user = userTable.get(dbs.admin2.id, onError = { assertNull(it) })
assertEquals(dbs.admin2, user)
user = userTable.get(dbs.crew1.id, onError = { assertNull(it) })
assertEquals(dbs.crew1, user)
user = userTable.get(dbs.pilot1.id, onError = { assertNull(it) })
assertEquals(dbs.pilot1, user)
}
@Test
fun queryTest() = runTest {
val users = userTable.query(Filter.equalTo("lastname", "Bob"), onError = { assertNull(it) })
assertTrue(listOf(dbs.crew1, dbs.pilot1).containsAll(users))
}
@Test
fun updateTest() = runTest {
val newAdmin2 = dbs.admin2.copy(firstname = "new-admin-2")
userTable.update(newAdmin2.id, newAdmin2, onError = { assertNull(it) })
val user = userTable.get(newAdmin2.id, onError = { assertNull(it) })
assertEquals(newAdmin2, user)
}
@Test
fun deleteTest() = runTest {
userTable.delete(dbs.crew1.id, onError = { assertNull(it) })
val availabilities = availabilityTable.getAll(onError = { assertNull(it) })
assertTrue(
listOf(dbs.availability2, dbs.availability3, dbs.availability4, dbs.availability5)
.containsAll(availabilities))
val flightMembers =
flightMemberTable.query(
Filter.equalTo("flightId", dbs.flight1.id), onError = { assertNull(it) })
assertEquals(2, flightMembers.size)
assertEquals(dbs.pilot1.id, flightMembers.find { it.roleType == RoleType.PILOT }?.userId)
assertEquals(null, flightMembers.find { it.roleType == RoleType.CREW }?.userId)
val user = userTable.get(dbs.crew1.id, onError = { assertNull(it) })
assertEquals(null, user)
}
@Test
fun retrieveAssignedFlightsTest() = runTest {
val flights =
userTable.retrieveAssignedFlights(flightTable, dbs.pilot1.id, onError = { assertNull(it) })
assertTrue(flights.contains(dbs.flight1))
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/database/tables/UserTableUnitTest.kt | 3742126796 |
package ch.epfl.skysync.database
import ch.epfl.skysync.database.tables.AvailabilityTable
import ch.epfl.skysync.database.tables.BalloonTable
import ch.epfl.skysync.database.tables.BasketTable
import ch.epfl.skysync.database.tables.FlightMemberTable
import ch.epfl.skysync.database.tables.FlightTable
import ch.epfl.skysync.database.tables.FlightTypeTable
import ch.epfl.skysync.database.tables.MessageGroupTable
import ch.epfl.skysync.database.tables.MessageTable
import ch.epfl.skysync.database.tables.UserTable
import ch.epfl.skysync.database.tables.VehicleTable
import ch.epfl.skysync.models.UNSET_ID
import ch.epfl.skysync.models.calendar.Availability
import ch.epfl.skysync.models.calendar.AvailabilityCalendar
import ch.epfl.skysync.models.calendar.AvailabilityStatus
import ch.epfl.skysync.models.calendar.FlightGroupCalendar
import ch.epfl.skysync.models.calendar.TimeSlot
import ch.epfl.skysync.models.flight.Balloon
import ch.epfl.skysync.models.flight.BalloonQualification
import ch.epfl.skysync.models.flight.Basket
import ch.epfl.skysync.models.flight.FlightType
import ch.epfl.skysync.models.flight.PlannedFlight
import ch.epfl.skysync.models.flight.Role
import ch.epfl.skysync.models.flight.RoleType
import ch.epfl.skysync.models.flight.Team
import ch.epfl.skysync.models.flight.Vehicle
import ch.epfl.skysync.models.message.Message
import ch.epfl.skysync.models.message.MessageGroup
import ch.epfl.skysync.models.user.Admin
import ch.epfl.skysync.models.user.Crew
import ch.epfl.skysync.models.user.Pilot
import java.time.Instant
import java.time.LocalDate
import java.util.Date
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
/**
* Represent a mock database setup
*
* Define sample data and a standard database state ([fillDatabase]). Designed to be used on a blank
* database, use [clearDatabase] to clear any existing data.
*/
class DatabaseSetup {
var admin1 =
Admin(
id = "id-admin-1",
firstname = "admin-1",
lastname = "lastname",
availabilities = AvailabilityCalendar(),
assignedFlights = FlightGroupCalendar())
var admin2 =
Admin(
id = "id-admin-2",
firstname = "admin-2",
lastname = "lastname",
availabilities = AvailabilityCalendar(),
assignedFlights = FlightGroupCalendar())
var crew1 =
Crew(
id = "id-crew-1",
firstname = "crew-1",
lastname = "Bob",
availabilities = AvailabilityCalendar(),
assignedFlights = FlightGroupCalendar())
var pilot1 =
Pilot(
id = "id-pilot-1",
firstname = "pilot-1",
lastname = "Bob",
availabilities = AvailabilityCalendar(),
assignedFlights = FlightGroupCalendar(),
qualification = BalloonQualification.LARGE)
var pilot2 =
Pilot(
id = "id-pilot-2",
firstname = "pilot-2",
lastname = "lastname",
availabilities = AvailabilityCalendar(),
assignedFlights = FlightGroupCalendar(),
qualification = BalloonQualification.SMALL)
var availability1 =
Availability(
status = AvailabilityStatus.MAYBE,
timeSlot = TimeSlot.AM,
date = LocalDate.of(2024, 8, 12))
var availability2 =
Availability(
status = AvailabilityStatus.MAYBE,
timeSlot = TimeSlot.AM,
date = LocalDate.of(2024, 8, 12))
var availability3 =
Availability(
status = AvailabilityStatus.NO, timeSlot = TimeSlot.AM, date = LocalDate.of(2024, 8, 14))
var availability4 =
Availability(
status = AvailabilityStatus.OK, timeSlot = TimeSlot.PM, date = LocalDate.of(2024, 8, 15))
var availability5 =
Availability(
status = AvailabilityStatus.MAYBE,
timeSlot = TimeSlot.PM,
date = LocalDate.of(2024, 8, 16))
var balloon1 = Balloon(name = "balloon-1", qualification = BalloonQualification.MEDIUM)
var balloon2 = Balloon(name = "balloon-2", qualification = BalloonQualification.LARGE)
var basket1 = Basket(name = "basket-1", hasDoor = false)
var basket2 = Basket(name = "basket-2", hasDoor = true)
var flightType1 = FlightType.DISCOVERY
var flightType2 = FlightType.FONDUE
var vehicle1 = Vehicle(name = "vehicle-1")
var vehicle2 = Vehicle(name = "vehicle-2")
var flight1 =
PlannedFlight(
nPassengers = 2,
team = Team(roles = listOf(Role(RoleType.PILOT, pilot1), Role(RoleType.CREW, crew1))),
flightType = flightType1,
balloon = balloon1,
basket = basket1,
date = LocalDate.of(2024, 8, 12),
timeSlot = TimeSlot.AM,
vehicles = listOf(vehicle1),
id = UNSET_ID)
var messageGroup1 = MessageGroup(userIds = setOf(admin2.id, pilot1.id, crew1.id))
var messageGroup2 = MessageGroup(userIds = setOf(admin1.id, admin2.id))
var message1 =
Message(
userId = admin2.id, date = Date.from(Instant.now().minusSeconds(20)), content = "Hello")
var message2 =
Message(
userId = pilot1.id, date = Date.from(Instant.now().minusSeconds(10)), content = "World")
var message3 =
Message(userId = admin2.id, date = Date.from(Instant.now()), content = "Some stuff")
/**
* Delete all items in all tables of the database
*
* @param db Firestore database instance
*/
suspend fun clearDatabase(db: FirestoreDatabase) = coroutineScope {
listOf(
launch { FlightTypeTable(db).deleteTable(onError = null) },
launch { BalloonTable(db).deleteTable(onError = null) },
launch { BasketTable(db).deleteTable(onError = null) },
launch { VehicleTable(db).deleteTable(onError = null) },
launch { FlightMemberTable(db).deleteTable(onError = null) },
launch { UserTable(db).deleteTable(onError = null) },
launch { FlightTable(db).deleteTable(onError = null) },
launch { AvailabilityTable(db).deleteTable(onError = null) },
launch { MessageTable(db).deleteTable(onError = null) },
launch { MessageGroupTable(db).deleteTable(onError = null) },
)
.forEach { it.join() }
}
/**
* Fill the database with a standard state
*
* @param db Firestore database instance
*/
suspend fun fillDatabase(db: FirestoreDatabase) = coroutineScope {
val flightTypeTable = FlightTypeTable(db)
val balloonTable = BalloonTable(db)
val basketTable = BasketTable(db)
val vehicleTable = VehicleTable(db)
val userTable = UserTable(db)
val flightTable = FlightTable(db)
val availabilityTable = AvailabilityTable(db)
val messageTable = MessageTable(db)
val messageGroupTable = MessageGroupTable(db)
listOf(
launch { flightType1 = flightType1.copy(id = flightTypeTable.add(flightType1)) },
launch { flightType2 = flightType2.copy(id = flightTypeTable.add(flightType2)) },
launch { balloon1 = balloon1.copy(id = balloonTable.add(balloon1)) },
launch { balloon2 = balloon2.copy(id = balloonTable.add(balloon2)) },
launch { basket1 = basket1.copy(id = basketTable.add(basket1)) },
launch { basket2 = basket2.copy(id = basketTable.add(basket2)) },
launch { vehicle1 = vehicle1.copy(id = vehicleTable.add(vehicle1)) },
launch { vehicle2 = vehicle2.copy(id = vehicleTable.add(vehicle2)) },
launch {
messageGroup1 = messageGroup1.copy(id = messageGroupTable.add(messageGroup1))
},
launch {
messageGroup2 = messageGroup2.copy(id = messageGroupTable.add(messageGroup2))
},
launch {
userTable.set(admin1.id, admin1)
availability3 =
availability3.copy(id = availabilityTable.add(admin1.id, availability3))
availability4 =
availability4.copy(id = availabilityTable.add(admin1.id, availability4))
admin1.availabilities.addCells(listOf(availability3, availability4))
},
launch { userTable.set(admin2.id, admin2) },
launch {
userTable.set(crew1.id, crew1)
availability1 =
availability1.copy(id = availabilityTable.add(crew1.id, availability1))
crew1.availabilities.addCells(listOf(availability1))
},
launch {
userTable.set(pilot1.id, pilot1)
availability2 =
availability2.copy(id = availabilityTable.add(pilot1.id, availability2))
pilot1.availabilities.addCells(listOf(availability2))
},
launch {
userTable.set(pilot2.id, pilot2)
availability5 =
availability5.copy(id = availabilityTable.add(pilot2.id, availability5))
pilot2.availabilities.addCells(listOf(availability5))
},
)
.forEach { it.join() }
// re-set all the objects that have been added in the db -> they now have IDs
flight1 =
flight1.copy(
team = Team(roles = listOf(Role(RoleType.PILOT, pilot1), Role(RoleType.CREW, crew1))),
flightType = flightType1,
balloon = balloon1,
basket = basket1,
vehicles = listOf(vehicle1),
)
// now that the IDs are set, add the flights/messages
listOf(
launch { flight1 = flight1.copy(id = flightTable.add(flight1)) },
launch { message1 = message1.copy(id = messageTable.add(messageGroup1.id, message1)) },
launch { message2 = message2.copy(id = messageTable.add(messageGroup1.id, message2)) },
launch { message3 = message3.copy(id = messageTable.add(messageGroup2.id, message3)) },
)
.forEach { it.join() }
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/database/DatabaseSetup.kt | 2794520100 |
package ch.epfl.skysync
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.rules.TestWatcher
import org.junit.runner.Description
/**
* Source:
* https://stackoverflow.com/questions/71807957/how-test-a-viewmodel-function-that-launch-a-viewmodelscope-coroutine-android-ko
*/
@ExperimentalCoroutinesApi
class MainCoroutineRule(private val dispatcher: TestDispatcher = StandardTestDispatcher()) :
TestWatcher() {
override fun starting(description: Description?) {
super.starting(description)
Dispatchers.setMain(dispatcher)
}
override fun finished(description: Description?) {
super.finished(description)
Dispatchers.resetMain()
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/MainCoroutineRule.kt | 3948930892 |
package ch.epfl.skysync.end_to_end
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.test.hasTestTag
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performScrollToNode
import androidx.compose.ui.test.performTextClearance
import androidx.compose.ui.test.performTextInput
import androidx.navigation.compose.ComposeNavigator
import androidx.navigation.compose.NavHost
import androidx.navigation.testing.TestNavHostController
import ch.epfl.skysync.Repository
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.navigation.Route
import ch.epfl.skysync.navigation.homeGraph
import junit.framework.TestCase.assertNull
import kotlinx.coroutines.test.runTest
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class E2EAddFlights {
@get:Rule val composeTestRule = createComposeRule()
lateinit var navController: TestNavHostController
private val db = FirestoreDatabase()
private val repository = Repository(db)
@Before
fun setUpNavHost() {
composeTestRule.setContent {
navController = TestNavHostController(LocalContext.current)
navController.navigatorProvider.addNavigator(ComposeNavigator())
NavHost(navController = navController, startDestination = Route.MAIN) {
homeGraph(repository, navController, null)
}
}
}
@Test
fun addFlightAsAdmin() {
composeTestRule.onNodeWithTag("addFlightButton").performClick()
var route = navController.currentBackStackEntry?.destination?.route
Assert.assertEquals(Route.ADD_FLIGHT, route)
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Number of passengers"))
composeTestRule.onNodeWithTag("Number of passengers").performClick()
composeTestRule.onNodeWithTag("Number of passengers").performTextClearance()
composeTestRule.onNodeWithTag("Number of passengers").performTextInput("13")
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Date Field"))
composeTestRule.onNodeWithTag("Date Field").performClick()
composeTestRule.onNodeWithText("OK").performClick()
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Flight Type Menu"))
composeTestRule.onNodeWithTag("Flight Type Menu").performClick()
composeTestRule.waitForIdle()
composeTestRule.onNodeWithTag("Flight Type 1").performClick()
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Vehicle 0 Menu"))
composeTestRule.onNodeWithTag("Vehicle 0 Menu").performClick()
composeTestRule.onNodeWithTag("Vehicle 0 1").performClick()
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Time Slot Menu"))
composeTestRule.onNodeWithTag("Time Slot Menu").performClick()
composeTestRule.onNodeWithTag("Time Slot 1").performClick()
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Balloon Menu"))
composeTestRule.onNodeWithTag("Balloon Menu").performClick()
composeTestRule.onNodeWithTag("Balloon 1").performClick()
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Basket Menu"))
composeTestRule.onNodeWithTag("Basket Menu").performClick()
composeTestRule.onNodeWithTag("Basket 1").performClick()
val title1 = "Add Flight"
composeTestRule.onNodeWithTag("$title1 Button").performClick()
route = navController.currentBackStackEntry?.destination?.route
Assert.assertEquals(Route.HOME, route)
var flightIsCreated = false
runTest {
val flights = repository.flightTable.getAll(onError = { assertNull(it) })
flightIsCreated = flights.any { it.nPassengers == 13 }
}
Assert.assertEquals(true, flightIsCreated)
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/end_to_end/E2EAddFlights.kt | 1733410249 |
package ch.epfl.skysync.chat
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.test.assertHasClickAction
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.hasTestTag
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performScrollToNode
import androidx.compose.ui.test.performTextInput
import androidx.compose.ui.unit.dp
import androidx.navigation.testing.TestNavHostController
import ch.epfl.skysync.components.GroupChat
import ch.epfl.skysync.components.GroupDetail
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class GroupChatTest {
@get:Rule val composeTestRule = createComposeRule()
lateinit var navController: TestNavHostController
val image: ImageVector? = null
val group = GroupDetail("Group", image, "Last message", "Last message time")
val searchGroup = GroupDetail("GroupSearch", image, "Last message", "Last message time")
val groups =
listOf(
group,
group,
group,
group,
group,
group,
group,
group,
group,
group,
group,
group,
group,
group,
group,
group,
group,
searchGroup)
@Before
fun setUpNavHost() {
composeTestRule.setContent {
GroupChat(groupList = groups, onClick = {}, paddingValues = PaddingValues(0.dp))
}
}
@Test
fun testGroupSearchIsDisplayed() {
composeTestRule.onNodeWithTag("Search").assertIsDisplayed()
}
@Test
fun testGroupCardIsDisplayed() {
for (i in groups.indices) {
composeTestRule.onNodeWithTag("GroupChatBody").performScrollToNode(hasTestTag("GroupCard$i"))
composeTestRule.onNodeWithTag("GroupCard$i").assertIsDisplayed()
}
}
@Test
fun testGroupCardIsClickable() {
for (i in groups.indices) {
composeTestRule.onNodeWithTag("GroupChatBody").performScrollToNode(hasTestTag("GroupCard$i"))
composeTestRule.onNodeWithTag("GroupCard$i").assertHasClickAction()
}
}
@Test
fun testGroupCardIsDisplayedAfterSearch() {
composeTestRule.onNodeWithTag("Search").performTextInput("Search")
composeTestRule.onNodeWithText("GroupSearch").assertIsDisplayed()
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/chat/GroupChatTest.kt | 671702929 |
package ch.epfl.skysync.navigation
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.navigation.compose.ComposeNavigator
import androidx.navigation.compose.NavHost
import androidx.navigation.testing.TestNavHostController
import ch.epfl.skysync.Repository
import ch.epfl.skysync.database.FirestoreDatabase
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class HomeNavigationTest {
@get:Rule val composeTestRule = createComposeRule()
lateinit var navController: TestNavHostController
@Before
fun setUpNavHost() {
composeTestRule.setContent {
val repository = Repository(FirestoreDatabase(useEmulator = true))
navController = TestNavHostController(LocalContext.current)
navController.navigatorProvider.addNavigator(ComposeNavigator())
NavHost(navController = navController, startDestination = Route.MAIN) {
homeGraph(repository, navController, null)
}
}
}
@Test
fun verifyHomeIsStartDestination() {
val route = navController.currentBackStackEntry?.destination?.route
Assert.assertEquals(route, Route.HOME)
}
@Test
fun routeIsRightIfClickOnCalendar() {
composeTestRule.onNodeWithText("Calendar").performClick()
val route = navController.currentBackStackEntry?.destination?.route
Assert.assertEquals(route, Route.AVAILABILITY_CALENDAR)
}
@Test
fun routeIsRightIfClickOnFlight() {
composeTestRule.onNodeWithText("Flight").performClick()
val route = navController.currentBackStackEntry?.destination?.route
Assert.assertEquals(route, Route.FLIGHT)
}
@Test
fun routeIsRightIfClickOnChat() {
composeTestRule.onNodeWithText("Chat").performClick()
val route = navController.currentBackStackEntry?.destination?.route
Assert.assertEquals(route, Route.CHAT)
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/navigation/HomeNavigationTest.kt | 2745102966 |
package ch.epfl.skysync.flightdetail
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onAllNodesWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.navigation.compose.ComposeNavigator
import androidx.navigation.compose.NavHost
import androidx.navigation.testing.TestNavHostController
import ch.epfl.skysync.Repository
import ch.epfl.skysync.database.DatabaseSetup
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.navigation.Route
import ch.epfl.skysync.navigation.homeGraph
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class IntegrateFlightDetailTest {
@get:Rule val composeTestRule = createComposeRule()
lateinit var navController: TestNavHostController
@Before
fun setUpNavHost() {
runTest {
val db = FirestoreDatabase(useEmulator = true)
val repository = Repository(db)
val dbs = DatabaseSetup()
dbs.clearDatabase(db)
dbs.fillDatabase(db)
composeTestRule.setContent {
navController = TestNavHostController(LocalContext.current)
navController.navigatorProvider.addNavigator(ComposeNavigator())
NavHost(navController = navController, startDestination = Route.MAIN) {
homeGraph(repository, navController, null)
}
}
}
}
// @Test
// fun modifyConfirm() {
// composeTestRule.onNodeWithText("Home").performClick()
// val nodes = composeTestRule.onAllNodesWithTag("flightCard")
// nodes[0].performClick()
// var route = navController.currentBackStackEntry?.destination?.route
// assertEquals(route, Route.FLIGHT_DETAILS + "/{Flight ID}")
// composeTestRule.onNodeWithTag("EditButton").performClick()
// route = navController.currentBackStackEntry?.destination?.route
// assertEquals(route, Route.MODIFY_FLIGHT + "/{Flight ID}")
// composeTestRule.onNodeWithTag("BackButton").performClick()
// route = navController.currentBackStackEntry?.destination?.route
// assertEquals(route, Route.FLIGHT_DETAILS + "/{Flight ID}")
// composeTestRule.onNodeWithTag("ConfirmButton").performClick()
// route = navController.currentBackStackEntry?.destination?.route
// assertEquals(route, Route.CONFIRM_FLIGHT + "/{Flight ID}")
// }
// @Test
// fun testDelete() {
// composeTestRule.onNodeWithText("Home").performClick()
// val nodes = composeTestRule.onAllNodesWithTag("flightCard")
// nodes[0].performClick()
// var route = navController.currentBackStackEntry?.destination?.route
// assertEquals(route, Route.FLIGHT_DETAILS + "/{Flight ID}")
// composeTestRule.onNodeWithTag("DeleteButton").performClick()
// route = navController.currentBackStackEntry?.destination?.route
// assertEquals(route, Route.HOME)
// }
@Test
fun backStackIsRightIfClickOnFlightDetails() {
composeTestRule.onNodeWithText("Home").performClick()
val nodes = composeTestRule.onAllNodesWithTag("flightCard")
for (i in 0 until nodes.fetchSemanticsNodes().size) {
nodes[i].performClick()
var route = navController.currentBackStackEntry?.destination?.route
assertEquals(route, Route.FLIGHT_DETAILS + "/{Flight ID}")
composeTestRule.onNodeWithText("Back").performClick()
route = navController.currentBackStackEntry?.destination?.route
assertEquals(route, Route.HOME)
}
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/flightdetail/IntegrateFlightDetailTest.kt | 4044821898 |
package ch.epfl.skysync.flightdetail
import android.util.Log
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.test.assertHasClickAction
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.hasTestTag
import androidx.compose.ui.test.hasText
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performScrollToNode
import androidx.compose.ui.unit.dp
import androidx.navigation.testing.TestNavHostController
import ch.epfl.skysync.models.UNSET_ID
import ch.epfl.skysync.models.calendar.TimeSlot
import ch.epfl.skysync.models.flight.FlightType
import ch.epfl.skysync.models.flight.PlannedFlight
import ch.epfl.skysync.models.flight.Role
import ch.epfl.skysync.models.flight.RoleType
import ch.epfl.skysync.models.flight.Team
import ch.epfl.skysync.models.flight.Vehicle
import ch.epfl.skysync.screens.flightDetail.FlightDetailUi
import java.time.LocalDate
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class FlightDetailUiTest {
@get:Rule val composeTestRule = createComposeRule()
val pilot = Role(RoleType.PILOT, null)
val crew = Role(RoleType.CREW, null)
val car = Vehicle("Car")
lateinit var navController: TestNavHostController
var dummyFlight =
mutableStateOf(
PlannedFlight(
UNSET_ID,
1,
FlightType.FONDUE,
Team(listOf()),
null,
null,
LocalDate.now(),
TimeSlot.AM,
listOf(
car,
car,
car,
car,
car,
car,
car,
car,
car,
car,
car,
car,
car,
car,
car,
car,
car)))
@Before
fun setUpNavHost() {
composeTestRule.setContent {
FlightDetailUi(
backClick = {},
deleteClick = {},
editClick = {},
confirmClick = {},
padding = PaddingValues(0.dp),
flight = dummyFlight.value,
flightId = dummyFlight.value.id)
}
}
@Test
fun BackButtonIsDisplayed() {
composeTestRule.onNodeWithText("Back").assertIsDisplayed()
}
@Test
fun BackButtonIsClickable() {
composeTestRule.onNodeWithText("Back").assertHasClickAction()
}
@Test
fun DeleteButtonIsDisplayed() {
composeTestRule.onNodeWithText("Delete").assertIsDisplayed()
}
@Test
fun DeletButtonIsClickable() {
composeTestRule.onNodeWithText("Delete").assertHasClickAction()
}
@Test
fun EditButtonIsDisplayed() {
composeTestRule.onNodeWithText("Edit").assertIsDisplayed()
}
@Test
fun EditButtonIsClickable() {
composeTestRule.onNodeWithText("Edit").assertHasClickAction()
}
@Test
fun ConfirmButtonIsDisplayed() {
composeTestRule.onNodeWithText("Confirm").assertIsDisplayed()
}
@Test
fun ConfirmButtonIsClickable() {
composeTestRule.onNodeWithText("Confirm").assertHasClickAction()
}
@Test
fun NumberOfPaxValueIsDisplayed() {
val expected = dummyFlight.value.nPassengers.toString()
composeTestRule.onNodeWithText("$expected Pax").assertIsDisplayed()
}
@Test
fun FlightTypeValueIsDisplayed() {
val expected = dummyFlight.value.flightType.name
composeTestRule.onNodeWithText(expected).assertIsDisplayed()
}
@Test
fun DateValueIsDisplayed() {
val expected = dummyFlight.value.date.toString()
composeTestRule.onNodeWithText(expected).assertIsDisplayed()
}
@Test
fun BalloonIsDisplayed() {
composeTestRule.onNodeWithText("Balloon").assertIsDisplayed()
}
@Test
fun BalloonValueIsDisplayed() {
val expected = dummyFlight.value.balloon?.name ?: "None"
composeTestRule.onNodeWithTag("Balloon$expected").assertIsDisplayed()
}
@Test
fun BasketIsDisplayed() {
composeTestRule.onNodeWithText("Basket").assertIsDisplayed()
}
@Test
fun BasketValueIsDisplayed() {
val expected = dummyFlight.value.basket?.name ?: "None"
composeTestRule.onNodeWithTag("Basket$expected").assertIsDisplayed()
}
@Test
fun TimeSlotIsDisplayed() {
composeTestRule.onNodeWithText(dummyFlight.value.timeSlot.name).assertIsDisplayed()
}
@Test
fun TeamButtonIsDisplayed() {
composeTestRule.onNodeWithText("Team").assertIsDisplayed()
}
@Test
fun TeamButtonIsClickable() {
composeTestRule.onNodeWithText("Team").assertHasClickAction()
}
@Test
fun TeamIsDisplayed() {
composeTestRule.onNodeWithText("Team").performClick()
composeTestRule.onNodeWithText("No team member").assertIsDisplayed()
}
@Test
fun VehiclesButtonIsDisplayed() {
composeTestRule.onNodeWithText("Vehicles").assertIsDisplayed()
}
@Test
fun VehiclesButtonIsClickable() {
composeTestRule.onNodeWithText("Vehicles").assertHasClickAction()
}
@Test
fun VehiclesAfterTeamIsDisplayed() {
composeTestRule.onNodeWithText("Team").performClick()
composeTestRule.onNodeWithText("Vehicles").assertIsDisplayed()
}
@Test
fun VehiclesAreDisplayed() {
composeTestRule.onNodeWithText("Vehicles").performClick()
for (index in dummyFlight.value.vehicles.indices) {
composeTestRule
.onNodeWithTag("VehicleList")
.performScrollToNode(hasText("Vehicle $index"))
.assertIsDisplayed()
}
}
@Test
fun VehiclesValueAreDisplayed() {
composeTestRule.onNodeWithText("Vehicles").performClick()
for (index in dummyFlight.value.vehicles.indices) {
composeTestRule
.onNodeWithTag("VehicleList")
.performScrollToNode(
hasTestTag("Vehicle $index" + dummyFlight.value.vehicles[index].name))
.assertIsDisplayed()
}
}
@Test
fun testNoVehiclesButManyTeamMembers() {
val teamMembers = List(100) { Role(RoleType.CREW, null) }
val flightWithNoVehiclesButManyTeamMembers =
PlannedFlight(
UNSET_ID,
1,
FlightType.FONDUE,
Team(teamMembers),
null,
null,
LocalDate.now(),
TimeSlot.AM,
listOf())
// Change the dummyFlight variable before running the test
dummyFlight.value = flightWithNoVehiclesButManyTeamMembers
composeTestRule.waitForIdle()
composeTestRule.onNodeWithText("Vehicles").performClick()
composeTestRule.onNodeWithText("No vehicle").assertIsDisplayed()
composeTestRule.onNodeWithText("Team").performClick()
for (index in teamMembers.indices) {
val firstname = dummyFlight.value.team.roles[index].assignedUser?.firstname ?: ""
val lastname = dummyFlight.value.team.roles[index].assignedUser?.lastname ?: ""
val name = "$firstname $lastname"
Log.d(
"TeamMember",
"Member $index: ${dummyFlight.value.team.roles[index].roleType.name}" + name)
composeTestRule
.onNodeWithTag("TeamList")
.performScrollToNode(
hasText("Member $index: ${dummyFlight.value.team.roles[index].roleType.name}"))
.assertIsDisplayed()
}
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/flightdetail/FlightDetailUiTest.kt | 2795792918 |
package ch.epfl.skysync
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.hasText
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onAllNodesWithTag
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performScrollToNode
import androidx.navigation.compose.ComposeNavigator
import androidx.navigation.compose.NavHost
import androidx.navigation.testing.TestNavHostController
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.navigation.Route
import ch.epfl.skysync.navigation.homeGraph
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class ConfirmFlightScreenTest {
@get:Rule val composeTestRule = createComposeRule()
lateinit var navController: TestNavHostController
@Before
fun setUpNavHost() {
composeTestRule.setContent {
val repository = Repository(FirestoreDatabase(useEmulator = true))
navController = TestNavHostController(LocalContext.current)
navController.navigatorProvider.addNavigator(ComposeNavigator())
NavHost(navController = navController, startDestination = Route.MAIN) {
homeGraph(repository, navController, null)
}
}
}
@Test
fun backStackIsRightIfClickOnFlightDetailsThenFlightConfirm() {
composeTestRule.onNodeWithText("Home").performClick()
val nodes = composeTestRule.onAllNodesWithTag("flightCard")
for (i in 0 until nodes.fetchSemanticsNodes().size) {
nodes[i].performClick()
var route = navController.currentBackStackEntry?.destination?.route
Assert.assertEquals(Route.FLIGHT_DETAILS + "/{Flight ID}", route)
composeTestRule.onNodeWithText("Confirm").performClick()
composeTestRule.waitForIdle()
route = navController.currentBackStackEntry?.destination?.route
Assert.assertEquals(Route.CONFIRM_FLIGHT + "/{Flight ID}", route)
composeTestRule
.onNodeWithTag("LazyList")
.performScrollToNode(hasText("Confirm"))
.assertIsDisplayed()
composeTestRule.onNodeWithText("Confirm").performClick()
composeTestRule.waitForIdle()
route = navController.currentBackStackEntry?.destination?.route
Assert.assertEquals(Route.HOME, route)
}
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/ConfirmFlightScreenTest.kt | 1737989397 |
package ch.epfl.skysync.screens.home
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import ch.epfl.skysync.models.calendar.TimeSlot
import ch.epfl.skysync.models.flight.FlightType
import ch.epfl.skysync.models.flight.PlannedFlight
import ch.epfl.skysync.screens.UpcomingFlights
import java.time.LocalDate
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
class UpcomingFlightsTests {
@get:Rule val composeTestRule = createComposeRule()
@Test
fun upcomingFlightsDisplaysNoFlightsWhenListIsEmpty() {
composeTestRule.setContent { UpcomingFlights(flights = emptyList(), onFlightClick = {}) }
composeTestRule.onNodeWithText("No upcoming flights").assertIsDisplayed()
}
@Test
fun upcomingFlightsDisplaysFlightsWhenListIsNotEmpty() {
val testFlight =
PlannedFlight(
// Assuming your Flight data class constructor and properties
nPassengers = 1,
date = LocalDate.now(),
timeSlot = TimeSlot.AM,
flightType = FlightType.DISCOVERY, // Assuming enum or similar for flight types
vehicles = emptyList(),
balloon = null,
basket = null,
id = "testFlightId")
composeTestRule.setContent { UpcomingFlights(flights = listOf(testFlight), onFlightClick = {}) }
composeTestRule.onNodeWithText("Discovery - 1 pax").assertIsDisplayed()
}
@Test
fun clickingOnFlightTriggersCallback() {
var wasClicked = false
val testFlight =
PlannedFlight(
// Same assumptions as above
nPassengers = 1,
date = LocalDate.now(),
timeSlot = TimeSlot.AM,
flightType = FlightType.DISCOVERY, // Assuming enum or similar for flight types
vehicles = emptyList(),
balloon = null,
basket = null,
id = "testFlightId")
composeTestRule.setContent {
UpcomingFlights(flights = listOf(testFlight)) { wasClicked = it == testFlight.id }
}
composeTestRule.onNodeWithText("Discovery - 1 pax").performClick()
assertTrue("Flight click callback was not triggered with the correct flight", wasClicked)
}
/*@Test
fun floatingActionButton_onClick_logsMessage() {
val navController = TestNavHostController(ApplicationProvider.getApplicationContext())
val flights = mutableListOf<PlannedFlight>()
composeTestRule.setContent { HomeScreen(navController, flights) }
// Perform a click on the FAB
composeTestRule.onNodeWithContentDescription("Add").performClick()
// This is where you'd verify the expected behavior. Since we can't directly check Logcat output
// here,
// consider verifying navigation or state changes instead. For demonstration purposes, we'll
// assume
// a successful test if the FAB is clickable, which has already been performed above.
// In real-world scenarios, replace this with actual verification logic.
}*/
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/screens/home/UpcomingFlightsTests.kt | 4054792490 |
package ch.epfl.skysync.screens.chat
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.hasTestTag
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.navigation.compose.ComposeNavigator
import androidx.navigation.testing.TestNavHostController
import ch.epfl.skysync.screens.ChatScreen
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class ChatScreenTest {
@get:Rule val composeTestRule = createComposeRule()
lateinit var navController: TestNavHostController
@Before
fun setUpNavHost() {
composeTestRule.setContent {
navController = TestNavHostController(LocalContext.current)
navController.navigatorProvider.addNavigator(ComposeNavigator())
ChatScreen(navController)
}
}
@Test
fun chatScreenIsDisplayed() {
composeTestRule.onNode(hasTestTag("ChatScreenScaffold")).assertIsDisplayed()
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/screens/chat/ChatScreenTest.kt | 2372030687 |
package ch.epfl.skysync.screens.flight
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertIsNotDisplayed
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.navigation.compose.rememberNavController
import androidx.test.rule.GrantPermissionRule
import ch.epfl.skysync.screens.FlightScreen
import org.junit.Rule
import org.junit.Test
class FlightScreenPermissionTest {
@get:Rule val composeTestRule = createComposeRule()
@get:Rule
var permissionRule: GrantPermissionRule =
GrantPermissionRule.grant(android.Manifest.permission.ACCESS_FINE_LOCATION)
@Test
fun flightScreen_PermissionGranted_ShowsMapAndFAB() {
composeTestRule.setContent {
val navController = rememberNavController()
FlightScreen(navController)
}
composeTestRule.onNodeWithTag("LoadingIndicator").assertIsNotDisplayed()
composeTestRule.onNodeWithTag("Timer").assertExists()
composeTestRule.onNodeWithTag("Map").assertExists()
composeTestRule.onNodeWithContentDescription("Locate Me").assertIsDisplayed()
composeTestRule.onNodeWithContentDescription("Flight infos").performClick()
composeTestRule
.onNodeWithText("X Speed: 0.0 m/s\nY Speed: 0.0 m/s\nAltitude: 0.0 m\nBearing: 0.0 °")
.assertIsDisplayed()
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/screens/flight/FlightScreenPermissionTest.kt | 2645250650 |
package ch.epfl.skysync.screens.flight
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.navigation.compose.rememberNavController
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.uiautomator.UiDevice
import androidx.test.uiautomator.UiSelector
import ch.epfl.skysync.screens.FlightScreen
import org.junit.Rule
import org.junit.Test
class FlightScreenNoPermissionTest {
@get:Rule val composeTestRule = createComposeRule()
@Test
fun flightScreen_PermissionRequested_AndDenied() {
val uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
composeTestRule.setContent {
val navController = rememberNavController()
FlightScreen(navController)
}
val denyButton = uiDevice.findObject(UiSelector().text("Don’t allow"))
if (denyButton.exists() && denyButton.isEnabled) {
denyButton.click()
}
composeTestRule
.onNodeWithText("Access to location is required to use this feature.")
.assertIsDisplayed()
composeTestRule
.onNodeWithText("Please enable location permissions in settings.")
.assertIsDisplayed()
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/screens/flight/FlightScreenNoPermissionTest.kt | 3794114300 |
package ch.epfl.skysync.screens
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertIsNotDisplayed
import androidx.compose.ui.test.hasTestTag
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performScrollToNode
import androidx.compose.ui.test.performTextInput
import androidx.navigation.NavHostController
import io.mockk.mockk
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class AddUserTest {
@get:Rule val composeTestRule = createComposeRule()
val navController: NavHostController = mockk("NavController", relaxed = true)
@Before
fun setUp() {
composeTestRule.setContent { AddUserScreen(navController) }
}
@Test
fun isFirstNameFieldDisplayed() {
composeTestRule
.onNodeWithTag("Add User Lazy Column")
.performScrollToNode(hasTestTag("First Name"))
composeTestRule.onNodeWithTag("First Name").assertIsDisplayed()
}
@Test
fun isLastNameFieldDisplayed() {
composeTestRule
.onNodeWithTag("Add User Lazy Column")
.performScrollToNode(hasTestTag("Last Name"))
composeTestRule.onNodeWithTag("Last Name").assertIsDisplayed()
}
@Test
fun isEmailFieldDisplayed() {
composeTestRule.onNodeWithTag("Add User Lazy Column").performScrollToNode(hasTestTag("E-mail"))
composeTestRule.onNodeWithTag("E-mail").assertIsDisplayed()
}
@Test
fun isRoleFieldDisplayed() {
composeTestRule
.onNodeWithTag("Add User Lazy Column")
.performScrollToNode(hasTestTag("Role Menu"))
composeTestRule.onNodeWithTag("Role Menu").assertIsDisplayed()
}
@Test
fun isBalloonQualificationFieldDisplayed() {
composeTestRule.onNodeWithTag("Balloon Qualification Menu").assertDoesNotExist()
composeTestRule
.onNodeWithTag("Add User Lazy Column")
.performScrollToNode(hasTestTag("Role Menu"))
composeTestRule.onNodeWithTag("Role Menu").performClick()
composeTestRule.onNodeWithText("Pilot", true).performClick()
composeTestRule
.onNodeWithTag("Add User Lazy Column")
.performScrollToNode(hasTestTag("Balloon Qualification Menu"))
composeTestRule.onNodeWithTag("Balloon Qualification Menu").assertIsDisplayed()
}
@Test
fun isButtonClickable() {
composeTestRule.onNodeWithTag("Add User Button").performClick()
}
@Test
fun doesErrorWorksCorrectly() {
composeTestRule.onNodeWithTag("Add User Button").performClick()
composeTestRule
.onNodeWithTag("Add User Lazy Column")
.performScrollToNode(hasTestTag("Role Menu"))
composeTestRule.onNodeWithText("Select a role", true).assertIsDisplayed()
composeTestRule.onNodeWithTag("Role Menu").performClick()
composeTestRule.onNodeWithText("Pilot", true).performClick()
composeTestRule
.onNodeWithTag("Add User Lazy Column")
.performScrollToNode(hasTestTag("First Name"))
composeTestRule.onNodeWithText("Enter a first name").assertIsDisplayed()
composeTestRule.onNodeWithTag("First Name").performTextInput("John")
composeTestRule
.onNodeWithTag("Add User Lazy Column")
.performScrollToNode(hasTestTag("Last Name"))
composeTestRule.onNodeWithText("Enter a last name").assertIsDisplayed()
composeTestRule.onNodeWithTag("Last Name").performTextInput("Doe")
composeTestRule.onNodeWithTag("Add User Lazy Column").performScrollToNode(hasTestTag("E-mail"))
composeTestRule.onNodeWithText("Invalid email").assertIsDisplayed()
composeTestRule.onNodeWithTag("E-mail").performTextInput("[email protected]")
composeTestRule.onNodeWithTag("Add User Button").performClick()
composeTestRule
.onNodeWithTag("Add User Lazy Column")
.performScrollToNode(hasTestTag("Balloon Qualification Menu"))
composeTestRule.onNodeWithText("Select a balloon type").assertIsDisplayed()
composeTestRule.onNodeWithTag("Balloon Qualification Menu").performClick()
composeTestRule.onNodeWithTag("Balloon Qualification 0").performClick()
composeTestRule.onNodeWithTag("Add User Button").performClick()
composeTestRule
.onNodeWithTag("Add User Lazy Column")
.performScrollToNode(hasTestTag("Balloon Qualification Menu"))
composeTestRule.onNodeWithText("Select a balloon type").assertIsNotDisplayed()
composeTestRule.onNodeWithTag("Add User Lazy Column").performScrollToNode(hasTestTag("E-mail"))
composeTestRule.onNodeWithText("Invalid email").assertIsNotDisplayed()
composeTestRule
.onNodeWithTag("Add User Lazy Column")
.performScrollToNode(hasTestTag("Last Name"))
composeTestRule.onNodeWithText("Enter a last name").assertIsNotDisplayed()
composeTestRule
.onNodeWithTag("Add User Lazy Column")
.performScrollToNode(hasTestTag("First Name"))
composeTestRule.onNodeWithText("Enter a first name").assertIsNotDisplayed()
composeTestRule
.onNodeWithTag("Add User Lazy Column")
.performScrollToNode(hasTestTag("Role Menu"))
composeTestRule.onNodeWithText("Select a role", true).assertIsNotDisplayed()
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/screens/AddUserTest.kt | 266278808 |
package ch.epfl.skysync.screens.login
import androidx.compose.ui.test.SemanticsNodeInteractionsProvider
import io.github.kakaocup.compose.node.element.ComposeScreen
import io.github.kakaocup.compose.node.element.KNode
/**
* This class represents the Login Screen and the elements it contains.
*
* It is used to interact with the UI elements during UI tests, incl. grading! You can adapt the
* test tags if necessary to suit your own implementation, but the class properties need to stay the
* same.
*
* You can refer to Figma for the naming conventions.
* https://www.figma.com/file/PHSAMl7fCpqEkkSHGeAV92/TO-DO-APP-Mockup?type=design&node-id=435%3A3350&mode=design&t=GjYE8drHL1ACkQnD-1
*/
class LoginScreenNodes(semanticsProvider: SemanticsNodeInteractionsProvider) :
ComposeScreen<LoginScreenNodes>(
semanticsProvider = semanticsProvider, viewBuilderAction = { hasTestTag("LoginScreen") }) {
// Structural elements of the UI
val loginButton: KNode = child { hasTestTag("LoginButton") }
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/screens/login/LoginScreenNodes.kt | 3019454593 |
package ch.epfl.skysync.screens.login
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.test.espresso.intent.rule.IntentsTestRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import ch.epfl.skysync.MainActivity
import com.kaspersky.kaspresso.testcases.api.testcase.TestCase
import io.github.kakaocup.compose.node.element.ComposeScreen
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class LoginScreenTest : TestCase() {
@get:Rule val composeTestRule = createAndroidComposeRule<MainActivity>()
// The IntentsTestRule simply calls Intents.init() before the @Test block
// and Intents.release() after the @Test block is completed. IntentsTestRule
// is deprecated, but it was MUCH faster than using IntentsRule in our tests
@get:Rule val intentsTestRule = IntentsTestRule(MainActivity::class.java)
@Test
fun buttonIsCorrectlyDisplayedAndIsClickable() {
ComposeScreen.onComposeScreen<LoginScreenNodes>(composeTestRule) {
loginButton {
assertIsDisplayed()
assertHasClickAction()
performClick()
}
}
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/screens/login/LoginScreenTest.kt | 2267353044 |
package ch.epfl.skysync.components
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.test.assertHasClickAction
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.hasTestTag
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.performScrollToNode
import androidx.compose.ui.unit.dp
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class ChatTextUiTest {
@get:Rule val composeTestRule = createComposeRule()
val image: ImageVector? = null
private val fakeText =
ChatMessage(
"him",
MessageType.RECEIVED,
image,
"Hi",
"11:11",
)
private val myFakeText =
ChatMessage(
"me",
MessageType.SENT,
image,
"Hello",
"12:12",
)
private val list =
listOf(
fakeText,
myFakeText,
fakeText,
myFakeText,
fakeText,
myFakeText,
fakeText,
myFakeText,
fakeText,
myFakeText,
fakeText,
myFakeText,
fakeText,
myFakeText,
fakeText,
myFakeText,
fakeText,
myFakeText,
fakeText,
myFakeText,
fakeText,
myFakeText,
fakeText,
myFakeText,
fakeText,
myFakeText,
fakeText,
myFakeText,
fakeText,
myFakeText,
fakeText,
myFakeText,
fakeText,
myFakeText,
fakeText,
myFakeText,
fakeText,
myFakeText,
fakeText,
myFakeText,
fakeText,
myFakeText,
fakeText,
myFakeText,
)
@Before
fun setUpNavHost() {
composeTestRule.setContent {
ChatText(
groupName = "Name",
messages = list,
onBack = {},
onSend = {},
paddingValues = PaddingValues(0.dp))
}
}
@Test
fun verifyChatText() {
composeTestRule.onNodeWithTag("HeaderTitle").assertIsDisplayed()
}
@Test
fun verifyChatBackButton() {
composeTestRule.onNodeWithTag("BackButton").assertIsDisplayed()
}
@Test
fun verifyChatBackButtonIsClickable() {
composeTestRule.onNodeWithTag("BackButton").assertHasClickAction()
}
@Test
fun verifyChatInput() {
composeTestRule.onNodeWithTag("ChatInput").assertIsDisplayed()
}
@Test
fun verifyChatTextBody() {
composeTestRule.onNodeWithTag("ChatTextBody").assertIsDisplayed()
}
@Test
fun verifyChatBubble() {
for (index in list.indices) {
composeTestRule
.onNodeWithTag("ChatTextBody")
.performScrollToNode(hasTestTag("ChatBubbleMessage$index"))
.assertIsDisplayed()
}
}
@Test
fun verifyChatBubbleTime() {
for (index in list.indices) {
composeTestRule
.onNodeWithTag("ChatTextBody")
.performScrollToNode(hasTestTag("ChatBubbleTime$index"))
.assertIsDisplayed()
}
}
@Test
fun verifyChatSendButton() {
composeTestRule.onNodeWithTag("SendButton").assertIsDisplayed()
}
@Test
fun verifyChatSendButtonIsClickable() {
composeTestRule.onNodeWithTag("SendButton").assertHasClickAction()
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/components/ChatTextUiTest.kt | 3338658998 |
package ch.epfl.skysync.screens.calendar
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.hasTestTag
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performScrollToNode
import androidx.navigation.compose.ComposeNavigator
import androidx.navigation.compose.NavHost
import androidx.navigation.testing.TestNavHostController
import ch.epfl.skysync.Repository
import ch.epfl.skysync.components.getStartOfWeek
import ch.epfl.skysync.database.DatabaseSetup
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.models.calendar.TimeSlot
import ch.epfl.skysync.navigation.Route
import ch.epfl.skysync.navigation.homeGraph
import java.time.LocalDate
import kotlinx.coroutines.test.runTest
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class FlightCalendarTest {
@get:Rule val composeTestRule = createComposeRule()
lateinit var navController: TestNavHostController
val dbs = DatabaseSetup()
@Before
fun setUpNavHost() = runTest {
val db = FirestoreDatabase(useEmulator = true)
val repository = Repository(db)
dbs.clearDatabase(db)
dbs.fillDatabase(db)
composeTestRule.setContent {
navController = TestNavHostController(LocalContext.current)
navController.navigatorProvider.addNavigator(ComposeNavigator())
NavHost(navController = navController, startDestination = Route.MAIN) {
homeGraph(repository, navController, dbs.admin1.id)
}
}
}
@Test
fun swipeTest() {
composeTestRule.onNodeWithText("Calendar").performClick()
var route = navController.currentBackStackEntry?.destination?.route
Assert.assertEquals(route, Route.AVAILABILITY_CALENDAR)
composeTestRule.onNodeWithTag(Route.FLIGHT_CALENDAR).performClick()
route = navController.currentBackStackEntry?.destination?.route
Assert.assertEquals(route, Route.FLIGHT_CALENDAR)
var date = LocalDate.now()
date = getStartOfWeek(date).minusWeeks(1)
val nextWeek = date.toString() + TimeSlot.AM.toString()
composeTestRule
.onNodeWithTag("HorizontalPager")
.performScrollToNode(hasTestTag(nextWeek))
.assertIsDisplayed()
date = LocalDate.now()
date = getStartOfWeek(date).plusWeeks(1)
val previousWeek = date.toString() + TimeSlot.AM.toString()
composeTestRule
.onNodeWithTag("HorizontalPager")
.performScrollToNode(hasTestTag(previousWeek))
.assertIsDisplayed()
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/components/calendar/FlightCalendarTest.kt | 1278633928 |
package ch.epfl.skysync.screens.calendar
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.navigation.compose.ComposeNavigator
import androidx.navigation.compose.NavHost
import androidx.navigation.testing.TestNavHostController
import ch.epfl.skysync.Repository
import ch.epfl.skysync.database.DatabaseSetup
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.navigation.Route
import ch.epfl.skysync.navigation.homeGraph
import kotlinx.coroutines.test.runTest
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class CalendarTopBarTest {
@get:Rule val composeTestRule = createComposeRule()
lateinit var navController: TestNavHostController
val dbs = DatabaseSetup()
@Before
fun setUpNavHost() = runTest {
val db = FirestoreDatabase(useEmulator = true)
val repository = Repository(db)
dbs.clearDatabase(db)
dbs.fillDatabase(db)
composeTestRule.setContent {
navController = TestNavHostController(LocalContext.current)
navController.navigatorProvider.addNavigator(ComposeNavigator())
NavHost(navController = navController, startDestination = Route.MAIN) {
homeGraph(repository, navController, dbs.admin1.id)
}
}
}
@Test
fun switchBetweenCalendars() {
composeTestRule.onNodeWithText("Calendar").performClick()
var route = navController.currentBackStackEntry?.destination?.route
Assert.assertEquals(route, Route.AVAILABILITY_CALENDAR)
composeTestRule.onNodeWithTag(Route.FLIGHT_CALENDAR).performClick()
route = navController.currentBackStackEntry?.destination?.route
Assert.assertEquals(route, Route.FLIGHT_CALENDAR)
composeTestRule.onNodeWithTag(Route.AVAILABILITY_CALENDAR).performClick()
route = navController.currentBackStackEntry?.destination?.route
Assert.assertEquals(route, Route.AVAILABILITY_CALENDAR)
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/components/calendar/CalendarTopBarTest.kt | 246703246 |
package ch.epfl.skysync.screens.calendar
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertIsEnabled
import androidx.compose.ui.test.assertIsNotEnabled
import androidx.compose.ui.test.hasTestTag
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performScrollToNode
import androidx.navigation.compose.ComposeNavigator
import androidx.navigation.compose.NavHost
import androidx.navigation.testing.TestNavHostController
import ch.epfl.skysync.Repository
import ch.epfl.skysync.components.getStartOfWeek
import ch.epfl.skysync.database.DatabaseSetup
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.models.calendar.TimeSlot
import ch.epfl.skysync.navigation.Route
import ch.epfl.skysync.navigation.homeGraph
import java.time.LocalDate
import kotlinx.coroutines.test.runTest
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class AvailabiltyCalendarTest {
@get:Rule val composeTestRule = createComposeRule()
lateinit var navController: TestNavHostController
val dbs = DatabaseSetup()
@Before
fun setUpNavHost() = runTest {
val db = FirestoreDatabase(useEmulator = true)
val repository = Repository(db)
dbs.clearDatabase(db)
dbs.fillDatabase(db)
composeTestRule.setContent {
navController = TestNavHostController(LocalContext.current)
navController.navigatorProvider.addNavigator(ComposeNavigator())
NavHost(navController = navController, startDestination = Route.MAIN) {
homeGraph(repository, navController, dbs.admin1.id)
}
}
composeTestRule.onNodeWithText("Calendar").performClick()
}
@Test
fun cancelSaveButtonShouldNotWork() {
composeTestRule.onNodeWithTag("CancelButton").assertIsDisplayed()
composeTestRule.onNodeWithTag("CancelButton").assertIsNotEnabled()
composeTestRule.onNodeWithTag("SaveButton").assertIsDisplayed()
composeTestRule.onNodeWithTag("SaveButton").assertIsNotEnabled()
}
@Test
fun cancelSaveButtonShouldWorkAfterClickOnTile() {
val today = LocalDate.now().toString() + TimeSlot.AM.toString()
val route = navController.currentBackStackEntry?.destination?.route
Assert.assertEquals(route, Route.AVAILABILITY_CALENDAR)
composeTestRule.onNodeWithTag(today).performClick()
composeTestRule.onNodeWithTag("CancelButton").assertIsEnabled()
composeTestRule.onNodeWithTag("SaveButton").assertIsEnabled()
}
@Test
fun swipeTest() {
var date = LocalDate.now()
date = getStartOfWeek(date).minusWeeks(1)
val nextWeek = date.toString() + TimeSlot.AM.toString()
composeTestRule
.onNodeWithTag("HorizontalPager")
.performScrollToNode(hasTestTag(nextWeek))
.assertIsDisplayed()
date = LocalDate.now()
date = getStartOfWeek(date).plusWeeks(1)
val previousWeek = date.toString() + TimeSlot.AM.toString()
composeTestRule
.onNodeWithTag("HorizontalPager")
.performScrollToNode(hasTestTag(previousWeek))
.assertIsDisplayed()
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/components/calendar/AvailabiltyCalendarTest.kt | 89687264 |
package ch.epfl.skysync.components
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.test.assertIsNotDisplayed
import androidx.compose.ui.test.assertTextContains
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performTextClearance
import androidx.compose.ui.test.performTextInput
import ch.epfl.skysync.components.forms.SearchBarCustom
import ch.epfl.skysync.models.flight.RoleType
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class SearchBarCustomTest {
@get:Rule val composeTestRule = createComposeRule()
private val propositions = RoleType.entries
@Before
fun setUp() {
composeTestRule.setContent {
var query by remember { mutableStateOf("") }
var active by remember { mutableStateOf(false) }
SearchBarCustom(
query = query,
onQueryChange = { query = it },
onSearch = { active = false },
active = active,
onActiveChange = { active = it },
onElementClick = {
active = false
query = it.toString()
},
propositions = propositions,
showProposition = { it.toString() },
placeholder = "Test Name")
}
}
@Test
fun isPlaceHolderDisplayed() {
composeTestRule.onNodeWithTag("Search Bar Input").assertTextContains("Test Name")
}
@Test
fun doesSearchBarActiveWorks() {
composeTestRule.onNodeWithTag("Search Bar Input").performClick()
composeTestRule.onNodeWithText(propositions[0].toString()).performClick()
composeTestRule.onNodeWithTag("Search Propositions").assertIsNotDisplayed()
}
@Test
fun doesQueryWorksWell() {
composeTestRule.onNodeWithTag("Search Bar Input").performClick()
composeTestRule.onNodeWithText(propositions[0].toString()).performClick()
composeTestRule.onNodeWithTag("Search Bar Input").assertTextContains(propositions[0].toString())
composeTestRule.onNodeWithTag("Search Bar Input").performClick()
composeTestRule.onNodeWithTag("Search Bar Input").performTextClearance()
composeTestRule.onNodeWithTag("Search Bar Input").assertTextContains("")
composeTestRule.onNodeWithTag("Search Bar Input").performTextInput("Test")
composeTestRule.onNodeWithTag("Search Bar Input").assertTextContains("Test")
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/components/SearchBarCustomTest.kt | 428698830 |
package ch.epfl.skysync.components
import androidx.compose.ui.test.assertHasClickAction
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.navigation.testing.TestNavHostController
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class BackButtonTest {
@get:Rule val composeTestRule = createComposeRule()
lateinit var navController: TestNavHostController
@Before
fun setUpNavHost() {
composeTestRule.setContent { Backbutton(backClick = {}) }
}
@Test
fun verifyBackButton() {
composeTestRule.onNodeWithTag("BackButton").assertIsDisplayed()
}
@Test
fun verifyBackButtonIsClickable() {
composeTestRule.onNodeWithTag("BackButton").assertHasClickAction()
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/components/BackButtonTest.kt | 2608131764 |
package ch.epfl.skysync.components
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertIsNotDisplayed
import androidx.compose.ui.test.assertTextContains
import androidx.compose.ui.test.assertTextEquals
import androidx.compose.ui.test.hasTestTag
import androidx.compose.ui.test.hasText
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performScrollToNode
import androidx.compose.ui.test.performTextClearance
import androidx.compose.ui.test.performTextInput
import androidx.navigation.testing.TestNavHostController
import ch.epfl.skysync.components.forms.FlightForm
import ch.epfl.skysync.models.flight.Balloon
import ch.epfl.skysync.models.flight.BalloonQualification
import ch.epfl.skysync.models.flight.Basket
import ch.epfl.skysync.models.flight.FlightType
import ch.epfl.skysync.models.flight.RoleType
import ch.epfl.skysync.models.flight.Vehicle
import io.mockk.mockk
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class FlightFormTest {
@get:Rule val composeTestRule = createComposeRule()
private var navController: TestNavHostController = mockk("navController", relaxed = true)
private val title: String = "Modify Flight"
@Before
fun setup() {
composeTestRule.setContent {
val allFlights = FlightType.ALL_FLIGHTS
val allVehicles =
listOf(
Vehicle("Vehicle 1"),
Vehicle("Vehicle 2"),
)
val allBalloons =
listOf(
Balloon("Balloon 1", BalloonQualification.SMALL),
Balloon("Balloon 2", BalloonQualification.MEDIUM),
)
val allBaskets =
listOf(
Basket("Basket 1", true),
Basket("Basket 2", false),
)
val allRoleTypes = RoleType.entries
navController = TestNavHostController(LocalContext.current)
FlightForm(
currentFlight = null,
navController = navController,
modifyMode = false,
title = title,
allFlightTypes = allFlights,
allRoleTypes = allRoleTypes,
allVehicles = allVehicles,
allBalloons = allBalloons,
allBaskets = allBaskets,
flightAction = { _ -> })
}
}
@Test
fun nbPassengerFieldIsDisplayed() {
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Number of passengers"))
composeTestRule.onNodeWithTag("Number of passengers").assertIsDisplayed()
}
@Test
fun nbPassengerFieldWorksCorrectly() {
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Number of passengers"))
composeTestRule.onNodeWithTag("Number of passengers").performClick()
composeTestRule.onNodeWithTag("Number of passengers").performTextClearance()
composeTestRule.onNodeWithTag("Number of passengers").performTextInput("1")
composeTestRule.onNodeWithTag("Number of passengers").assertTextEquals("1")
}
@Test
fun dateFieldIsDisplayed() {
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Date Field"))
composeTestRule.onNodeWithTag("Date Field").assertIsDisplayed()
}
@Test
fun dateFieldIsClickable() {
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Date Field"))
composeTestRule.onNodeWithTag("Date Field").performClick()
composeTestRule.onNodeWithText("OK").performClick()
}
@Test
fun flightTypeFieldIsDisplayed() {
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Flight Type Menu"))
composeTestRule.onNodeWithTag("Flight Type Menu").assertIsDisplayed()
}
@Test
fun vehicleFieldIsDisplayed() {
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Vehicle 0 Menu"))
composeTestRule.onNodeWithTag("Vehicle 0 Menu").assertIsDisplayed()
}
@Test
fun timeSlotFieldIsDisplayed() {
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Time Slot Menu"))
composeTestRule.onNodeWithTag("Time Slot Menu").assertIsDisplayed()
}
@Test
fun timeSlotFieldIsClickable() {
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Time Slot Menu"))
composeTestRule.onNodeWithTag("Time Slot Menu").performClick()
composeTestRule.onNodeWithTag("Time Slot 1").performClick()
}
@Test
fun balloonFieldIsDisplayed() {
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Balloon Menu"))
composeTestRule.onNodeWithTag("Balloon Menu").assertIsDisplayed()
}
@Test
fun basketFieldIsDisplayed() {
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Basket Menu"))
composeTestRule.onNodeWithTag("Basket Menu").assertIsDisplayed()
}
@Test
fun fondueFieldIsDisplayedCorrectly() {
composeTestRule.onNodeWithText(RoleType.MAITRE_FONDUE.name).assertIsNotDisplayed()
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Flight Type Menu"))
composeTestRule.onNodeWithTag("Flight Type Menu").performClick()
composeTestRule.onNodeWithText("Fondue").performClick()
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasText(RoleType.MAITRE_FONDUE.name))
composeTestRule.onNodeWithText(RoleType.MAITRE_FONDUE.name).assertIsDisplayed()
}
@Test
fun mainButtonIsDisplayed() {
composeTestRule.onNodeWithTag("$title Button").assertIsDisplayed()
}
@Test
fun checkAddAFlightWorksCorrectly() {
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Number of passengers"))
composeTestRule.onNodeWithTag("Number of passengers").performClick()
composeTestRule.onNodeWithTag("Number of passengers").performTextClearance()
composeTestRule.onNodeWithTag("Number of passengers").performTextInput("1")
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Date Field"))
composeTestRule.onNodeWithTag("Date Field").performClick()
composeTestRule.onNodeWithText("OK").performClick()
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Flight Type Menu"))
composeTestRule.onNodeWithTag("Flight Type Menu").performClick()
composeTestRule.onNodeWithTag("Flight Type 1").performClick()
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Vehicle 0 Menu"))
composeTestRule.onNodeWithTag("Vehicle 0 Menu").performClick()
composeTestRule.onNodeWithTag("Vehicle 0 1").performClick()
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Time Slot Menu"))
composeTestRule.onNodeWithTag("Time Slot Menu").performClick()
composeTestRule.onNodeWithTag("Time Slot 1").performClick()
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Balloon Menu"))
composeTestRule.onNodeWithTag("Balloon Menu").performClick()
composeTestRule.onNodeWithTag("Balloon 1").performClick()
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Basket Menu"))
composeTestRule.onNodeWithTag("Basket Menu").performClick()
composeTestRule.onNodeWithTag("Basket 1").performClick()
composeTestRule.onNodeWithTag("$title Button").performClick()
}
@Test
fun addATeamRoleWorksCorrectly() {
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Add Crew Button"))
composeTestRule.onNodeWithTag("Add Crew Button").performClick()
composeTestRule.onNodeWithTag("Role Type Menu").performClick()
composeTestRule.onNodeWithText(RoleType.SERVICE_ON_BOARD.name).performClick()
composeTestRule.onNodeWithTag("User Dialog Field").performClick()
composeTestRule.onNodeWithTag("User Dialog Field").performTextInput("test")
composeTestRule.onNodeWithTag("User Dialog Field").assertTextContains("test")
composeTestRule.onNode(hasText("Add")).performClick()
composeTestRule.onNodeWithTag("Flight Lazy Column").performScrollToNode(hasTestTag(" User 2"))
composeTestRule.onNodeWithText(RoleType.SERVICE_ON_BOARD.name).assertIsDisplayed()
}
@Test
fun addAVehicleWorksCorrectly() {
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Vehicle 0 Menu"))
composeTestRule.onNodeWithTag("Vehicle 0 Menu").performClick()
composeTestRule.onNodeWithTag("Vehicle 0 0").performClick()
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Add Vehicle Button"))
composeTestRule.onNodeWithTag("Add Vehicle Button").performClick()
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Vehicle 1 Menu"))
composeTestRule.onNodeWithTag("Vehicle 1 Menu").performClick()
composeTestRule.onNodeWithTag("Vehicle 1 1").performClick()
}
@Test
fun isErrorDisplayedCorrectly() {
composeTestRule.onNodeWithTag("$title Button").performClick()
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Number of passengers"))
composeTestRule.onNodeWithText("Please enter a valid number", true).assertIsDisplayed()
composeTestRule.onNodeWithTag("Number of passengers").performTextInput("1")
composeTestRule.onNodeWithTag("$title Button").performClick()
composeTestRule
.onNodeWithTag("Flight Lazy Column")
.performScrollToNode(hasTestTag("Flight Type Menu"))
composeTestRule.onNodeWithText("Please choose a flight type", true).assertIsDisplayed()
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/components/flightFormTest.kt | 243427294 |
package ch.epfl.skysync.components
import androidx.compose.material.Text
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import org.junit.Rule
import org.junit.Test
class LoadingTest {
@get:Rule val composeTestRule = createComposeRule()
@Test
fun loadingComponent_ShouldDisplayProgressIndicator_WhenIsLoadingIsTrue() {
composeTestRule.setContent {
LoadingComponent(isLoading = true, onRefresh = {}) { Text("Content goes here") }
}
composeTestRule.onNodeWithTag("LoadingIndicator").assertIsDisplayed()
}
@Test
fun loadingComponent_ShouldNotDisplayProgressIndicator_WhenIsLoadingIsFalse() {
composeTestRule.setContent {
LoadingComponent(isLoading = false, onRefresh = {}) { Text("Content goes here") }
}
composeTestRule.onNodeWithContentDescription("Progress Indicator").assertDoesNotExist()
}
@Test
fun loadingComponent_ShouldDisplayContent() {
composeTestRule.setContent {
LoadingComponent(isLoading = false, onRefresh = {}) { Text("Test Content") }
}
composeTestRule.onNodeWithText("Test Content").assertIsDisplayed()
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/components/LoadingTest.kt | 4155464649 |
package ch.epfl.skysync.components
import androidx.compose.ui.Modifier
import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.assertTextContains
import androidx.compose.ui.test.hasText
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.performClick
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class TimerTest {
@get:Rule val composeTestRule = createComposeRule()
@Before
fun setUp() {
composeTestRule.setContent { Timer(modifier = Modifier) }
}
@Test
fun timerIsDisplayed() {
composeTestRule.onNodeWithTag("Timer").assertExists()
}
@Test
fun timerValueIsDisplayed() {
composeTestRule.onNodeWithTag("Timer Value").assertExists()
}
@Test
fun timerStartButtonIsDisplayed() {
composeTestRule.onNodeWithTag("Start Button").assertExists()
}
@OptIn(ExperimentalTestApi::class)
@Test
fun timerResetButtonIsDisplayed() {
composeTestRule.onNodeWithTag("Timer Value").assertTextContains("00:00:00")
composeTestRule.onNodeWithTag("Start Button").performClick()
composeTestRule.waitUntilAtLeastOneExists(
hasText("00:00:02", substring = true), timeoutMillis = 2010)
composeTestRule.onNodeWithTag("Reset Button").assertExists()
}
@Test
fun timerValueIsUpdated() {
composeTestRule.onNodeWithTag("Start Button").performClick()
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/components/TimerTest.kt | 19557930 |
package ch.epfl.skysync.components
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
@ExperimentalCoroutinesApi
class SnackbarManagerTest {
@Test
fun testMessagesFlow_emitsMessages() = runBlockingTest {
SnackbarManager.showMessage("Another test message")
val flowResult = SnackbarManager.messagesFlow.first()
assertEquals("Another test message", flowResult)
}
}
@ExperimentalCoroutinesApi
class GlobalSnackbarHostTest {
@get:Rule val composeTestRule = createComposeRule()
@Test
fun snackbarHost_displaysMessage() {
// Use a test tag or text matcher to find the snackbar in the UI
SnackbarManager.showMessage("Visible snackbar message")
composeTestRule.setContent { GlobalSnackbarHost() }
// Assert that the snackbar appears with the correct text.
composeTestRule.onNodeWithText("Visible snackbar message").assertExists()
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/components/SnackbarTest.kt | 1195612268 |
package ch.epfl.skysync.components
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.navigation.testing.TestNavHostController
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class HeaderTest {
@get:Rule val composeTestRule = createComposeRule()
lateinit var navController: TestNavHostController
@Before
fun setUpNavHost() {
composeTestRule.setContent { Header(backClick = {}, title = "Test Title") }
}
@Test
fun verifyHeader() {
composeTestRule.onNodeWithTag("HeaderTitle").assertIsDisplayed()
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/components/HeaderTest.kt | 3364271798 |
package ch.epfl.skysync
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertIsNotDisplayed
import androidx.compose.ui.test.hasText
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performScrollToNode
import androidx.compose.ui.test.performTextClearance
import androidx.compose.ui.test.performTextInput
import androidx.navigation.compose.ComposeNavigator
import androidx.navigation.testing.TestNavHostController
import ch.epfl.skysync.components.confirmation
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.models.calendar.TimeSlot
import ch.epfl.skysync.models.flight.Balloon
import ch.epfl.skysync.models.flight.BalloonQualification
import ch.epfl.skysync.models.flight.Basket
import ch.epfl.skysync.models.flight.FlightType
import ch.epfl.skysync.models.flight.PlannedFlight
import ch.epfl.skysync.models.flight.Role
import ch.epfl.skysync.models.flight.RoleType
import ch.epfl.skysync.models.flight.Team
import ch.epfl.skysync.models.flight.Vehicle
import java.time.LocalDate
import java.time.LocalTime
import java.time.format.DateTimeFormatter
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class ConfirmFlightUITest {
@get:Rule val composeTestRule = createComposeRule()
lateinit var navController: TestNavHostController
private var planedFlight =
mutableStateOf(
PlannedFlight(
"1234",
26,
FlightType.DISCOVERY,
Team(listOf(Role(RoleType.CREW))),
Balloon("Ballon Name", BalloonQualification.LARGE, "Ballon Name"),
Basket("Basket Name", true, "1234"),
LocalDate.now().plusDays(3),
TimeSlot.PM,
listOf(Vehicle("Peugeot 308", "1234"))))
@Before
fun setUpNavHost() {
composeTestRule.setContent {
val repository = Repository(FirestoreDatabase(useEmulator = true))
navController = TestNavHostController(LocalContext.current)
navController.navigatorProvider.addNavigator(ComposeNavigator())
confirmation(plannedFlight = planedFlight.value) {}
}
}
// test of info to verify by a user
@Test
fun verifyTitle() {
val id = planedFlight.value.id
composeTestRule.onNodeWithText("Confirmation of Flight $id").assertIsDisplayed()
}
@Test
fun verifyNbPassengers() {
val passengerNb = planedFlight.value.nPassengers
composeTestRule.onNodeWithText(passengerNb.toString()).assertIsDisplayed()
}
@Test
fun verifyFlightType() {
val flightType = planedFlight.value.flightType
composeTestRule.onNodeWithText(flightType.name).assertIsDisplayed()
}
@Test
fun verifyRoles() {
val rolesLists = planedFlight.value.team.roles
rolesLists.forEach() { (role) -> composeTestRule.onNodeWithText(role.name).assertIsDisplayed() }
}
@Test
fun verifyBalloon() {
val balloon = planedFlight.value.balloon
if (balloon != null) {
composeTestRule.onNodeWithText(balloon.name).assertIsDisplayed()
}
}
@Test
fun verifyBasket() {
val basket = planedFlight.value.basket
if (basket != null) {
composeTestRule.onNodeWithText(basket.name).assertIsDisplayed()
}
}
@Test
fun verifyNullValues() {
planedFlight.value =
PlannedFlight(
"1234",
3,
FlightType.DISCOVERY,
Team(listOf(Role(RoleType.CREW))),
null,
null,
LocalDate.now().plusDays(3),
TimeSlot.PM,
listOf(Vehicle("Peugeot 308", "1234")))
composeTestRule.onNodeWithText("Basket").assertIsNotDisplayed()
composeTestRule.onNodeWithText("Balloon").assertIsNotDisplayed()
}
@Test
fun verifyDateAndTimeSlotShown() {
val date = planedFlight.value.date
val timeSlot = planedFlight.value.timeSlot
composeTestRule
.onNodeWithText(
(date.dayOfMonth.toString() + " " + date.month.toString() + " $timeSlot").lowercase())
.assertIsDisplayed()
}
@Test
fun verifyVehicles() {
val vehicles = planedFlight.value.vehicles
vehicles.forEach() { (vehicle) -> composeTestRule.onNodeWithText(vehicle).assertIsDisplayed() }
}
// test of info to enter by user
@Test
fun canColorsBeChoosen() {
composeTestRule.onNodeWithText("Select Option").performClick()
composeTestRule.onNodeWithText("RED").performClick()
composeTestRule.onNodeWithText("RED").assertIsDisplayed()
}
@Test
fun verifyGoodColorChoosing() {
composeTestRule.onNodeWithText("Select Option").performClick()
composeTestRule.onNodeWithText("RED").performClick()
composeTestRule.onNodeWithText("BLUE").assertIsNotDisplayed()
}
@Test
fun verifyTimeSettingForMeetUpTime() {
val wantedTimeSet = LocalTime.of(21, 25)
val wantedHour = wantedTimeSet.hour
val wantedMinute = wantedTimeSet.minute
val tag = "MeetUp"
composeTestRule.onNodeWithTag(tag + "/Hours").performTextClearance()
composeTestRule.onNodeWithTag(tag + "/Hours").performTextInput(wantedHour.toString())
composeTestRule.onNodeWithTag(tag + "/Minutes").performTextClearance()
composeTestRule.onNodeWithTag(tag + "/Minutes").performTextInput(wantedMinute.toString())
composeTestRule.onNodeWithTag(tag + "/SetTime").performClick()
composeTestRule
.onNodeWithText(
"Selected Time: ${wantedTimeSet.format(DateTimeFormatter.ofPattern("HH:mm"))}")
.assertIsDisplayed()
}
@Test
fun verifyTimeSettingForDepartureTime() {
val wantedTimeSet = LocalTime.of(23, 22)
val wantedHour = wantedTimeSet.hour
val wantedMinute = wantedTimeSet.minute
val tag = "Departure"
composeTestRule.onNodeWithTag("LazyList").performScrollToNode(hasText("Confirm"))
composeTestRule.onNodeWithTag(tag + "/Hours").performTextClearance()
composeTestRule.onNodeWithTag(tag + "/Hours").performTextInput(wantedHour.toString())
composeTestRule.onNodeWithTag(tag + "/Minutes").performTextClearance()
composeTestRule.onNodeWithTag(tag + "/Minutes").performTextInput(wantedMinute.toString())
composeTestRule.onNodeWithTag(tag + "/SetTime").performClick()
composeTestRule
.onNodeWithText(
"Selected Time: ${wantedTimeSet.format(DateTimeFormatter.ofPattern("HH:mm"))}")
.assertIsDisplayed()
}
@Test
fun verifyTimeSettingForPassengersMeetUpTimeWithNonproperValues() {
val tag = "MeetUp pass."
composeTestRule.onNodeWithTag(tag + "/Hours").performTextClearance()
composeTestRule.onNodeWithTag(tag + "/Hours").performTextInput("This isn't a number")
composeTestRule.onNodeWithTag(tag + "/Minutes").performTextClearance()
composeTestRule.onNodeWithTag(tag + "/Minutes").performTextInput("this neither")
composeTestRule.onNodeWithTag(tag + "/SetTime").performClick()
}
@Test
fun verifyLocationAdding() {
val wantedLocation = "VernierZoo"
composeTestRule.onNodeWithText("Enter MeetUp Location").performTextInput(wantedLocation)
composeTestRule.onNodeWithText("Add MeetUp Location").performClick()
composeTestRule.onNodeWithText(wantedLocation).assertIsDisplayed()
}
@Test
fun verifyRemarkAdding() {
val wantedRemark = "We're on the capital"
composeTestRule.onNodeWithText("Enter Remark").performTextInput(wantedRemark)
composeTestRule.onNodeWithText("Add Remark").performClick()
composeTestRule.onNodeWithText(wantedRemark).assertIsDisplayed()
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/ConfirmFlightUITest.kt | 1749018242 |
package ch.epfl.skysync.database.schemas
import ch.epfl.skysync.models.calendar.Availability
import ch.epfl.skysync.models.calendar.AvailabilityStatus
import ch.epfl.skysync.models.calendar.TimeSlot
import java.time.LocalDate
import java.time.ZoneOffset
import java.util.Date
import org.junit.Assert.*
import org.junit.Test
class AvailabilityUnitTest {
/**
* Test that both the casting from the schema format to the model format and from the model format
* to the schema format work.
*/
@Test
fun modelSchemaCastingTest() {
val userId = "userId"
val localDate = LocalDate.now()
val date = Date.from(localDate.atStartOfDay(ZoneOffset.UTC).toInstant())
val availabilitySchema =
AvailabilitySchema(
id = "id",
userId = userId,
status = AvailabilityStatus.MAYBE,
timeSlot = TimeSlot.PM,
date = date)
val availability =
Availability(
id = "id", status = AvailabilityStatus.MAYBE, timeSlot = TimeSlot.PM, date = localDate)
assertEquals(availability, availabilitySchema.toModel())
assertEquals(availabilitySchema, AvailabilitySchema.fromModel(userId, availability))
}
}
| skysync/app/src/test/java/ch/epfl/skysync/database/schemas/AvailabilityUnitTest.kt | 1367594962 |
package ch.epfl.skysync.model.calendar
import ch.epfl.skysync.models.calendar.Availability
import ch.epfl.skysync.models.calendar.AvailabilityCalendar
import ch.epfl.skysync.models.calendar.AvailabilityStatus
import ch.epfl.skysync.models.calendar.TimeSlot
import java.time.LocalDate
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class TestAvailabilityCalendar {
var defaultAvailabilities = listOf<Availability>()
var calendar = AvailabilityCalendar()
var someDate = LocalDate.of(2024, 4, 1)
@Before
fun setUp() {
someDate = LocalDate.of(2024, 4, 1)
val defaultAvailability1 = Availability("1", AvailabilityStatus.OK, TimeSlot.AM, someDate)
val defaultAvailability2 =
Availability("2", AvailabilityStatus.MAYBE, TimeSlot.PM, someDate.plusDays(1))
defaultAvailabilities = listOf(defaultAvailability1, defaultAvailability2)
calendar = AvailabilityCalendar()
}
@Test
fun `finds an availability status by date and time slot`() {
val calendar = AvailabilityCalendar()
calendar.addCells(defaultAvailabilities)
val av1 = defaultAvailabilities[0]
val av2 = defaultAvailabilities[1]
assertEquals(calendar.getAvailabilityStatus(av1.date, av1.timeSlot), av1.status)
assertEquals(calendar.getAvailabilityStatus(av2.date, av2.timeSlot), av2.status)
}
@Test
fun `add a new availability by date and time slot`() {
val calendar = AvailabilityCalendar()
val newStatus = AvailabilityStatus.OK
val timeSlot = TimeSlot.PM
calendar.setAvailabilityByDate(someDate, timeSlot, newStatus)
assertEquals(calendar.getAvailabilityStatus(someDate, timeSlot), newStatus)
}
@Test
fun `change an availability status by date and time slot without changing others`() {
val initAvailability = Availability("1", AvailabilityStatus.MAYBE, TimeSlot.AM, someDate)
val initAvailability2 = Availability("1", AvailabilityStatus.OK, TimeSlot.PM, someDate)
calendar.addCells(listOf(initAvailability, initAvailability2))
val new_status = AvailabilityStatus.NO
calendar.setAvailabilityByDate(initAvailability.date, initAvailability.timeSlot, new_status)
// check availability is changed
assertEquals(
calendar.getAvailabilityStatus(initAvailability.date, initAvailability.timeSlot),
new_status)
// check other availability is not changed
assertEquals(
calendar.getAvailabilityStatus(initAvailability2.date, initAvailability2.timeSlot),
AvailabilityStatus.OK)
}
@Test
fun `nextAvailabilityStatus updates existing entry to next status and returns correctly`() {
val calendar = AvailabilityCalendar()
val availability1 = Availability("1", AvailabilityStatus.MAYBE, TimeSlot.AM, someDate)
calendar.addCells(listOf(availability1))
assertEquals(
calendar.nextAvailabilityStatus(availability1.date, availability1.timeSlot),
availability1.status.next())
}
@Test
fun `nextAvailabilityStatus initialises non-existing entry to OK and returns correctly`() {
val calendar = AvailabilityCalendar()
val availability1 = Availability("1", AvailabilityStatus.MAYBE, TimeSlot.AM, someDate)
assertEquals(
calendar.nextAvailabilityStatus(availability1.date, availability1.timeSlot),
AvailabilityStatus.OK)
}
@Test
fun `nextAvailabilityStatus removes NO and returns UNDEFINED`() {
val calendar = AvailabilityCalendar()
val availability1 = Availability("1", AvailabilityStatus.NO, TimeSlot.AM, someDate)
calendar.addCells(listOf(availability1))
assertEquals(
calendar.nextAvailabilityStatus(availability1.date, availability1.timeSlot),
AvailabilityStatus.UNDEFINED)
assertEquals(calendar.getSize(), 0)
}
@Test
fun `size is correctly returned`() {
val calendar = AvailabilityCalendar()
val availability1 = Availability("1", AvailabilityStatus.NO, TimeSlot.AM, someDate)
calendar.addCells(listOf(availability1))
assertEquals(calendar.getSize(), 1)
val availability2 = Availability("2", AvailabilityStatus.MAYBE, TimeSlot.PM, someDate)
calendar.addCells(listOf(availability2))
assertEquals(calendar.getSize(), 2)
}
}
| skysync/app/src/test/java/ch/epfl/skysync/model/calendar/TestAvailabilityCalendar.kt | 942901720 |
package ch.epfl.skysync.model.calendar
import ch.epfl.skysync.models.calendar.Availability
import ch.epfl.skysync.models.calendar.AvailabilityStatus
import ch.epfl.skysync.models.calendar.TimeSlot
import java.time.LocalDate
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class TestAvailability {
lateinit var initAvailability: Availability
@Before
fun setUp() {
initAvailability =
Availability(
status = AvailabilityStatus.MAYBE,
timeSlot = TimeSlot.AM,
date = LocalDate.of(2024, 4, 1))
}
@Test
fun `setStatus changes status immutably`() {
val oldStatus = initAvailability.status
val newStatus = AvailabilityStatus.OK
val newAvailability = initAvailability.copy(status = newStatus)
assertEquals(newAvailability.status, newStatus)
// check that old object remains unchanged
assertEquals(initAvailability.status, oldStatus)
}
@Test
fun `setStatus for same status is secure`() {
val oldStatus = initAvailability.status
val newAvailability = initAvailability.copy(status = oldStatus)
assertEquals(newAvailability.status, oldStatus)
}
}
| skysync/app/src/test/java/ch/epfl/skysync/model/calendar/TestAvailability.kt | 1813645656 |
package ch.epfl.skysync.model.calendar
import ch.epfl.skysync.models.calendar.FlightGroup
import ch.epfl.skysync.models.calendar.FlightGroupCalendar
import ch.epfl.skysync.models.calendar.TimeSlot
import ch.epfl.skysync.models.flight.Flight
import ch.epfl.skysync.models.flight.FlightType
import ch.epfl.skysync.models.flight.PlannedFlight
import java.time.LocalDate
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class TestFlightGroupCalendar {
lateinit var calendar: FlightGroupCalendar
lateinit var testFlight: Flight
lateinit var testFlight2: Flight
lateinit var emptyFlightGroup: FlightGroup
@Before
fun setUp() {
testFlight =
PlannedFlight(
"y",
1,
FlightType.FONDUE,
balloon = null,
basket = null,
date = LocalDate.of(2024, 4, 1),
timeSlot = TimeSlot.AM,
vehicles = listOf())
testFlight2 =
PlannedFlight(
"x",
2,
FlightType.DISCOVERY,
basket = null,
balloon = null,
date = LocalDate.of(2024, 4, 1),
timeSlot = TimeSlot.AM,
vehicles = listOf())
emptyFlightGroup = FlightGroup(LocalDate.of(2024, 4, 1), TimeSlot.AM, listOf())
calendar = FlightGroupCalendar()
}
@Test
fun `getFirstFlightByDate() returns null if no flights found `() {
calendar.addCells(listOf(emptyFlightGroup))
calendar.getFirstFlightByDate(emptyFlightGroup.date, emptyFlightGroup.timeSlot)
assertEquals(
calendar.getFirstFlightByDate(emptyFlightGroup.date, emptyFlightGroup.timeSlot), null)
}
@Test
fun `getFlightGroupByDate() returns null if no flight found for date`() {
val someDate = LocalDate.of(2024, 4, 1)
assertNull(calendar.getFlightGroupByDate(someDate, TimeSlot.AM))
}
@Test
fun `getFlightGroupByDate() returns the flight group if found`() {
val flightGroup = FlightGroup(testFlight.date, testFlight.timeSlot, listOf(testFlight))
calendar.addCells(listOf(flightGroup))
val foundFlightGroup = calendar.getFlightGroupByDate(testFlight.date, testFlight.timeSlot)
assertEquals(foundFlightGroup, flightGroup)
}
@Test
fun `getFirstFlightByDate() returns first flight if flight found`() {
calendar.addCells(listOf(FlightGroup(testFlight.date, testFlight.timeSlot, listOf(testFlight))))
val foundFlight = calendar.getFirstFlightByDate(testFlight.date, testFlight.timeSlot)
assertNotNull(foundFlight)
if (foundFlight != null) {
assertEquals(foundFlight, testFlight)
}
}
@Test
fun `add flight to an existing flight group`() {
calendar.addCells(listOf(FlightGroup(testFlight.date, testFlight.timeSlot, listOf(testFlight))))
calendar.addFlightByDate(testFlight2.date, testFlight2.timeSlot, testFlight2)
assertEquals(calendar.getSize(), 1)
val foundGroup = calendar.getFlightGroupByDate(testFlight2.date, testFlight2.timeSlot)
assertNotNull(foundGroup)
if (foundGroup != null) {
assertTrue(foundGroup.flights.contains(testFlight2))
assertTrue(foundGroup.flights.contains(testFlight))
}
}
}
| skysync/app/src/test/java/ch/epfl/skysync/model/calendar/TestFlightGroupCalendar.kt | 2645432533 |
package ch.epfl.skysync.model.calendar
import ch.epfl.skysync.models.UNSET_ID
import ch.epfl.skysync.models.calendar.FlightGroup
import ch.epfl.skysync.models.calendar.TimeSlot
import ch.epfl.skysync.models.flight.FlightType
import ch.epfl.skysync.models.flight.PlannedFlight
import java.time.LocalDate
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class TestFlightGroup {
lateinit var testFlight: PlannedFlight
lateinit var emptyGroup: FlightGroup
@Before
fun setUp() {
emptyGroup = FlightGroup(LocalDate.of(2024, 4, 1), TimeSlot.AM, emptyList())
testFlight =
PlannedFlight(
UNSET_ID,
1,
FlightType.FONDUE,
balloon = null,
basket = null,
date = LocalDate.of(2024, 4, 1),
timeSlot = TimeSlot.AM,
vehicles = listOf())
}
@Test
fun `addFlight adds new flight to current`() {
val newGroup = emptyGroup.addFlight(testFlight)
assertEquals(newGroup.flights.size, 1)
assertEquals(newGroup.flights[0], testFlight)
}
@Test
fun `isEmpty is true if no flights are in the group `() {
assertTrue(emptyGroup.isEmpty())
}
}
| skysync/app/src/test/java/ch/epfl/skysync/model/calendar/TestFlightGroup.kt | 1423855307 |
package ch.epfl.skysync.model.flight
import ch.epfl.skysync.models.UNSET_ID
import ch.epfl.skysync.models.calendar.AvailabilityCalendar
import ch.epfl.skysync.models.calendar.FlightGroupCalendar
import ch.epfl.skysync.models.flight.Role
import ch.epfl.skysync.models.flight.RoleType
import ch.epfl.skysync.models.user.Crew
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class TestRole {
lateinit var unassignedCrewRole: Role
val testUser = Crew("jo", "blunt", UNSET_ID, AvailabilityCalendar(), FlightGroupCalendar())
@Before
fun setUp() {
unassignedCrewRole = Role(RoleType.CREW)
}
@Test
fun `assign() assigns user to role`() {
assertEquals(unassignedCrewRole.assignedUser, null)
val newRole = unassignedCrewRole.assign(testUser)
assertEquals(testUser, newRole.assignedUser)
// check that initial remains unchanged
assertEquals(unassignedCrewRole.assignedUser, null)
}
@Test
fun `isAssigned() returns if assigned or not`() {
assertFalse(unassignedCrewRole.isAssigned())
val newRole = unassignedCrewRole.assign(testUser)
assertTrue(newRole.isAssigned())
// check that initial remains unchanged
assertFalse(unassignedCrewRole.isAssigned())
}
@Test
fun `initRoles() returns correct list of roles`() {
val roleTypeList = listOf<RoleType>(RoleType.CREW, RoleType.OXYGEN_MASTER)
val roleList: List<Role> = Role.initRoles(roleTypeList)
assertEquals(roleList.size, roleTypeList.size)
for (i in roleTypeList) {
assertTrue(roleList.any { it.isOfRoleType(i) })
}
}
@Test
fun `isOfRoleType() returns true if of same role type`() {
val roleType = RoleType.CREW
val role = Role(roleType)
assertTrue(role.isOfRoleType(roleType))
}
@Test
fun `isOfRoleType() returns false if not of same role type`() {
val role = Role(RoleType.OXYGEN_MASTER)
assertFalse(role.isOfRoleType(RoleType.CREW))
}
}
| skysync/app/src/test/java/ch/epfl/skysync/model/flight/TestRole.kt | 4293176315 |
package ch.epfl.skysync.model.flight
import ch.epfl.skysync.models.UNSET_ID
import ch.epfl.skysync.models.calendar.AvailabilityCalendar
import ch.epfl.skysync.models.calendar.FlightGroupCalendar
import ch.epfl.skysync.models.flight.Role
import ch.epfl.skysync.models.flight.RoleType
import ch.epfl.skysync.models.flight.Team
import ch.epfl.skysync.models.user.Crew
import org.junit.Assert.*
import org.junit.Test
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class TestTeam {
val testUser1 = Crew("jo", "blunt", UNSET_ID, AvailabilityCalendar(), FlightGroupCalendar())
val testUser2 = Crew("peter", "brown", UNSET_ID, AvailabilityCalendar(), FlightGroupCalendar())
@Test
fun `isComplete() returns true if all roles assigned`() {
val team1 =
Team(listOf(Role(RoleType.CREW, testUser1), Role(RoleType.OXYGEN_MASTER, testUser2)))
assertTrue(team1.isComplete())
val team2 = Team(listOf(Role(RoleType.CREW, testUser1)))
assertTrue(team2.isComplete())
}
@Test
fun `isComplete() returns false if no role present`() {
val team = Team(listOf())
assertFalse(team.isComplete())
}
@Test
fun `isComplete() returns false not all roles assigned`() {
val unassignedCrewRole = Role(RoleType.CREW)
val team1 = Team(listOf(Role(RoleType.CREW, testUser1), unassignedCrewRole))
assertFalse(team1.isComplete())
}
@Test
fun `addRoles() returns team with added roles`() {
val role1 = Role(RoleType.OXYGEN_MASTER)
val role2 = Role(RoleType.CREW)
val team = Team(listOf(role1))
val expandedTeam = team.addRoles(listOf(role2))
assertEquals(expandedTeam.roles.size, 2)
assertTrue(expandedTeam.roles.any { it.roleType == role1.roleType })
assertTrue(expandedTeam.roles.any { it.roleType == role2.roleType })
}
@Test
fun `addRoles() returns team with added duplicate roles`() {
val role1 = Role(RoleType.OXYGEN_MASTER)
val team = Team(listOf(role1))
val expandedTeam = team.addRoles(listOf(role1, role1))
assertEquals(expandedTeam.roles.size, 3)
assertTrue(expandedTeam.roles.all { it.roleType == role1.roleType })
}
}
| skysync/app/src/test/java/ch/epfl/skysync/model/flight/TestTeam.kt | 2715410387 |
package ch.epfl.skysync.model.flight
import ch.epfl.skysync.models.flight.BalloonQualification
import org.junit.Assert.*
import org.junit.Test
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class TestBalloonQualification {
@Test
fun `greater equal compares correctly`() {
assertTrue(BalloonQualification.LARGE.greaterEqual(BalloonQualification.LARGE))
assertTrue(BalloonQualification.LARGE.greaterEqual(BalloonQualification.MEDIUM))
assertTrue(BalloonQualification.LARGE.greaterEqual(BalloonQualification.SMALL))
assertTrue(BalloonQualification.MEDIUM.greaterEqual(BalloonQualification.SMALL))
assertFalse(BalloonQualification.MEDIUM.greaterEqual(BalloonQualification.LARGE))
}
}
| skysync/app/src/test/java/ch/epfl/skysync/model/flight/TestBalloonQualification.kt | 1420034012 |
package ch.epfl.skysync.model.flight
import ch.epfl.skysync.models.calendar.AvailabilityCalendar
import ch.epfl.skysync.models.calendar.FlightGroupCalendar
import ch.epfl.skysync.models.calendar.TimeSlot
import ch.epfl.skysync.models.flight.Balloon
import ch.epfl.skysync.models.flight.BalloonQualification
import ch.epfl.skysync.models.flight.Basket
import ch.epfl.skysync.models.flight.FlightStatus
import ch.epfl.skysync.models.flight.FlightType
import ch.epfl.skysync.models.flight.PlannedFlight
import ch.epfl.skysync.models.flight.Role
import ch.epfl.skysync.models.flight.RoleType
import ch.epfl.skysync.models.flight.Team
import ch.epfl.skysync.models.flight.Vehicle
import ch.epfl.skysync.models.user.Crew
import ch.epfl.skysync.models.user.User
import java.time.LocalDate
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class TestPlannedFlight {
lateinit var user: User
lateinit var initFlight: PlannedFlight
@Before
fun setUp() {
user =
Crew(
id = "1",
firstname = "Paul",
lastname = "Panzer",
availabilities = AvailabilityCalendar(),
assignedFlights = FlightGroupCalendar())
initFlight =
PlannedFlight(
id = "1",
nPassengers = 2,
flightType = FlightType.DISCOVERY,
balloon = Balloon("QQP", BalloonQualification.LARGE, ""),
basket = Basket("basket 1", hasDoor = false),
date = LocalDate.of(2024, 4, 1),
timeSlot = TimeSlot.AM,
vehicles = listOf(Vehicle("sprinter 1")))
}
@Test
fun `getFlightStatus returns correct status`() {
val plannedFlight = initFlight
assertEquals(plannedFlight.getFlightStatus(), FlightStatus.IN_PLANNING)
val readyFlight = initFlight.copy(team = Team(listOf(Role(RoleType.PILOT, user))))
assertEquals(readyFlight.getFlightStatus(), FlightStatus.READY_FOR_CONFIRMATION)
}
@Test
fun `addRoles adds a new role of a new roleType to the team`() {
val plannedFlight = initFlight.copy(team = Team(listOf()))
assertEquals(plannedFlight.team.roles.size, 0)
val roleTypeToAdd = RoleType.PILOT
val plannedFlightWithRole = plannedFlight.addRoles(listOf(RoleType.PILOT))
assertEquals(plannedFlightWithRole.team.roles.size, 1)
plannedFlightWithRole.team.roles.forEach { assertEquals(it.roleType, roleTypeToAdd) }
}
@Test
fun `addRoles adds a role of a an already existing roleType to the team`() {
val roleTypeToAdd = RoleType.PILOT
val plannedFlight = initFlight.copy(team = Team(listOf(Role(roleTypeToAdd))))
val plannedFlightWithRole = plannedFlight.addRoles(listOf(roleTypeToAdd))
assertEquals(plannedFlightWithRole.team.roles.size, 2)
plannedFlightWithRole.team.roles.forEach { assertEquals(it.roleType, roleTypeToAdd) }
}
@Test
fun `readyToBeConfirmed returns false if not yet ready`() {
assertFalse(initFlight.readyToBeConfirmed())
val readyFlight = initFlight.copy(team = Team(listOf(Role(RoleType.PILOT, user))))
val plannedFlightNoBasket = readyFlight.copy(basket = null)
assertFalse(plannedFlightNoBasket.readyToBeConfirmed())
val plannedFlightNoBalloon = readyFlight.copy(balloon = null)
assertFalse(plannedFlightNoBalloon.readyToBeConfirmed())
val plannedFlightNoVehicles = readyFlight.copy(vehicles = emptyList())
assertFalse(plannedFlightNoVehicles.readyToBeConfirmed())
val multipleFaults = plannedFlightNoBasket.copy(balloon = null, vehicles = emptyList())
assertFalse(multipleFaults.readyToBeConfirmed())
}
@Test
fun `readyToBeConfirmed returns true if ready`() {
val completeTeam =
Team(
listOf(
Role(RoleType.PILOT, user),
))
val readyFlight = initFlight.copy(team = completeTeam)
assertTrue(readyFlight.readyToBeConfirmed())
}
}
| skysync/app/src/test/java/ch/epfl/skysync/model/flight/TestPlannedFlight.kt | 3703860719 |
package ch.epfl.skysync.model.flight
import ch.epfl.skysync.models.calendar.AvailabilityCalendar
import ch.epfl.skysync.models.calendar.FlightGroupCalendar
import ch.epfl.skysync.models.calendar.TimeSlot
import ch.epfl.skysync.models.flight.Balloon
import ch.epfl.skysync.models.flight.BalloonQualification
import ch.epfl.skysync.models.flight.Basket
import ch.epfl.skysync.models.flight.ConfirmedFlight
import ch.epfl.skysync.models.flight.FlightColor
import ch.epfl.skysync.models.flight.FlightStatus
import ch.epfl.skysync.models.flight.FlightType
import ch.epfl.skysync.models.flight.PlannedFlight
import ch.epfl.skysync.models.flight.Role
import ch.epfl.skysync.models.flight.RoleType
import ch.epfl.skysync.models.flight.Team
import ch.epfl.skysync.models.flight.Vehicle
import ch.epfl.skysync.models.user.Crew
import ch.epfl.skysync.models.user.User
import java.time.LocalDate
import java.time.LocalTime
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class TestConfirmedFlight {
lateinit var user: User
lateinit var confirmedFlight: ConfirmedFlight
@Before
fun setUp() {
user =
Crew(
id = "1",
firstname = "Paul",
lastname = "Panzer",
availabilities = AvailabilityCalendar(),
assignedFlights = FlightGroupCalendar())
confirmedFlight =
ConfirmedFlight(
id = "1",
nPassengers = 2,
team = Team(listOf(Role(RoleType.PILOT, user))),
flightType = FlightType.DISCOVERY,
balloon = Balloon("QQP", BalloonQualification.LARGE, ""),
basket = Basket("basket 1", hasDoor = false),
date = LocalDate.of(2024, 4, 1),
timeSlot = TimeSlot.AM,
vehicles = listOf(Vehicle("sprinter 1")),
remarks = listOf("remark 1"),
color = FlightColor.BLUE,
meetupTimeTeam = LocalTime.of(10, 10),
departureTimeTeam = LocalTime.of(10, 30),
meetupTimePassenger = LocalTime.of(10, 40),
meetupLocationPassenger = "EPFL")
}
@Test
fun `getFlightStatus returns correct status`() {
assertEquals(confirmedFlight.getFlightStatus(), FlightStatus.CONFIRMED)
}
@Test
fun `throw error if tries to confirm flight that is not ready`() {
val plannedFlight =
PlannedFlight(
id = "1",
nPassengers = 2,
flightType = FlightType.DISCOVERY,
balloon = Balloon("QQP", BalloonQualification.LARGE, ""),
basket = Basket("basket 1", hasDoor = false),
date = LocalDate.of(2024, 4, 1),
timeSlot = TimeSlot.AM,
vehicles = listOf(Vehicle("sprinter 1")))
val meetUpTimeTeam = LocalTime.of(10, 10)
val departureTimeTeam = LocalTime.of(10, 30)
val meetUpTimePassenger = LocalTime.of(10, 40)
val meetUpLocation = "EPFL"
val remarks = listOf("remark 1")
val color = FlightColor.BLUE
assertThrows(IllegalStateException::class.java) {
plannedFlight.confirmFlight(
meetupTimeTeam = meetUpTimeTeam,
departureTimeTeam = departureTimeTeam,
meetupTimePassenger = meetUpTimePassenger,
meetupLocationPassenger = meetUpLocation,
remarks = remarks,
color = color)
}
}
@Test
fun `confirmed flight is correctly created from plannedFlight`() {
val completeTeam =
Team(
listOf(
Role(RoleType.PILOT, user),
))
val plannedFlight =
PlannedFlight(
id = "1",
nPassengers = 2,
flightType = FlightType.DISCOVERY,
team = completeTeam,
balloon = Balloon("QQP", BalloonQualification.LARGE, ""),
basket = Basket("basket 1", hasDoor = false),
date = LocalDate.of(2024, 4, 1),
timeSlot = TimeSlot.AM,
vehicles = listOf(Vehicle("sprinter 1")))
val meetUpTimeTeam = LocalTime.of(10, 10)
val departureTimeTeam = LocalTime.of(10, 30)
val meetUpTimePassenger = LocalTime.of(10, 40)
val meetUpLocation = "EPFL"
val remarks = listOf("remark 1")
val color = FlightColor.BLUE
val confirmedFlight =
plannedFlight.confirmFlight(
meetupTimeTeam = meetUpTimeTeam,
departureTimeTeam = departureTimeTeam,
meetupTimePassenger = meetUpTimePassenger,
meetupLocationPassenger = meetUpLocation,
remarks = remarks,
color = color)
assertEquals(plannedFlight.id, confirmedFlight.id)
assertEquals(plannedFlight.nPassengers, confirmedFlight.nPassengers)
assertEquals(plannedFlight.flightType, confirmedFlight.flightType)
assertEquals(plannedFlight.balloon, confirmedFlight.balloon)
assertEquals(plannedFlight.basket, confirmedFlight.basket)
assertEquals(plannedFlight.date, confirmedFlight.date)
assertEquals(plannedFlight.timeSlot, confirmedFlight.timeSlot)
assertEquals(plannedFlight.vehicles, confirmedFlight.vehicles)
assertEquals(plannedFlight.team, confirmedFlight.team)
assertEquals(meetUpTimeTeam, confirmedFlight.meetupTimeTeam)
assertEquals(departureTimeTeam, confirmedFlight.departureTimeTeam)
assertEquals(meetUpTimePassenger, confirmedFlight.meetupTimePassenger)
assertEquals(meetUpLocation, confirmedFlight.meetupLocationPassenger)
assertEquals(remarks, confirmedFlight.remarks)
assertEquals(color, confirmedFlight.color)
}
}
| skysync/app/src/test/java/ch/epfl/skysync/model/flight/TestConfirmedFlight.kt | 1032471067 |
package ch.epfl.skysync.model.user
import ch.epfl.skysync.models.UNSET_ID
import ch.epfl.skysync.models.calendar.AvailabilityCalendar
import ch.epfl.skysync.models.calendar.FlightGroupCalendar
import ch.epfl.skysync.models.flight.BalloonQualification
import ch.epfl.skysync.models.flight.RoleType
import ch.epfl.skysync.models.user.Admin
import ch.epfl.skysync.models.user.Crew
import ch.epfl.skysync.models.user.Pilot
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
class TestUsers {
@Before fun setUp() {}
@Test
fun `create Pilot`() {
val pilot =
Pilot(
"John",
"Deer",
UNSET_ID,
AvailabilityCalendar(),
FlightGroupCalendar(),
setOf(RoleType.PILOT, RoleType.CREW),
BalloonQualification.LARGE)
val pilotWithRoleType = pilot.addRoleType(RoleType.MAITRE_FONDUE)
assertEquals(false, pilot.canAssumeRole(RoleType.MAITRE_FONDUE))
assertEquals(true, pilotWithRoleType.canAssumeRole(RoleType.MAITRE_FONDUE))
assertEquals(
setOf(RoleType.PILOT, RoleType.CREW, RoleType.MAITRE_FONDUE), pilotWithRoleType.roleTypes)
}
@Test
fun `create Crew`() {
val crew = Crew("John", "Deer", UNSET_ID, AvailabilityCalendar(), FlightGroupCalendar())
}
@Test
fun `create Admin`() {
val admin = Admin("John", "Deer", UNSET_ID, AvailabilityCalendar(), FlightGroupCalendar())
}
}
| skysync/app/src/test/java/ch/epfl/skysync/model/user/TestUsers.kt | 1904876755 |
package ch.epfl.skysync.viewmodel
import androidx.compose.runtime.Composable
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import ch.epfl.skysync.Repository
import ch.epfl.skysync.models.flight.Balloon
import ch.epfl.skysync.models.flight.Basket
import ch.epfl.skysync.models.flight.Flight
import ch.epfl.skysync.models.flight.FlightType
import ch.epfl.skysync.models.flight.PlannedFlight
import ch.epfl.skysync.models.flight.Vehicle
import ch.epfl.skysync.util.WhileUiSubscribed
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
/** ViewModel for the user */
class FlightsViewModel(
val repository: Repository,
) : ViewModel() {
companion object {
@Composable
fun createViewModel(
repository: Repository,
): FlightsViewModel {
return viewModel<FlightsViewModel>(
factory =
object : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return FlightsViewModel(repository) as T
}
})
}
}
private val _currentFlights: MutableStateFlow<List<Flight>?> = MutableStateFlow(null)
private val _currentBalloons: MutableStateFlow<List<Balloon>> = MutableStateFlow(emptyList())
private val _currentBaskets: MutableStateFlow<List<Basket>> = MutableStateFlow(emptyList())
private val _currentFlightTypes: MutableStateFlow<List<FlightType>> =
MutableStateFlow(emptyList())
private val _currentVehicles: MutableStateFlow<List<Vehicle>> = MutableStateFlow(emptyList())
val currentFlights = _currentFlights.asStateFlow()
val currentBalloons = _currentBalloons.asStateFlow()
val currentBaskets = _currentBaskets.asStateFlow()
val currentFlightTypes = _currentFlightTypes.asStateFlow()
val currentVehicles = _currentVehicles.asStateFlow()
fun refresh() {
refreshCurrentFlights()
refreshCurrentBalloons()
refreshCurrentBaskets()
refreshCurrentFlightTypes()
refreshCurrentVehicles()
}
fun refreshCurrentBalloons() =
viewModelScope.launch {
_currentBalloons.value = repository.balloonTable.getAll(onError = { onError(it) })
}
fun refreshCurrentVehicles() =
viewModelScope.launch {
_currentVehicles.value = repository.vehicleTable.getAll(onError = { onError(it) })
}
fun refreshCurrentBaskets() =
viewModelScope.launch {
_currentBaskets.value = repository.basketTable.getAll(onError = { onError(it) })
}
fun refreshCurrentFlightTypes() =
viewModelScope.launch {
_currentFlightTypes.value = repository.flightTypeTable.getAll(onError = { onError(it) })
}
fun refreshCurrentFlights() =
viewModelScope.launch {
_currentFlights.value = repository.flightTable.getAll(onError = { onError(it) })
}
/**
* modifies the flight by deleting the old flight and adding a new one in the db and the viewmodel
*/
fun modifyFlight(
newFlight: Flight,
) = viewModelScope.launch { repository.flightTable.update(newFlight.id, newFlight) }
fun deleteFlight(flightId: String) =
viewModelScope.launch { repository.flightTable.delete(flightId, onError = { onError(it) }) }
/** adds the given flight to the db and the viewmodel */
fun addFlight(
flight: PlannedFlight,
) =
viewModelScope.launch {
val flightId = repository.flightTable.add(flight, onError = { onError(it) })
}
fun getFlight(flightId: String): StateFlow<Flight?> {
return _currentFlights
.map { flights -> flights?.find { it.id == flightId } }
.stateIn(scope = viewModelScope, started = WhileUiSubscribed, initialValue = null)
}
/** Callback executed when an error occurs on database-related operations */
private fun onError(e: Exception) {
// TODO: display error message
}
init {
refresh()
}
}
| skysync/app/src/main/java/ch/epfl/skysync/viewmodel/FlightsViewModel.kt | 423194486 |
package ch.epfl.skysync.viewmodel
import androidx.compose.runtime.Composable
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import ch.epfl.skysync.database.tables.AvailabilityTable
import ch.epfl.skysync.database.tables.UserTable
import ch.epfl.skysync.models.calendar.AvailabilityCalendar
import ch.epfl.skysync.models.calendar.CalendarDifferenceType
import ch.epfl.skysync.models.calendar.FlightGroupCalendar
import ch.epfl.skysync.models.user.User
import ch.epfl.skysync.util.WhileUiSubscribed
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
data class CalendarUiState(
val user: User? = null,
val availabilityCalendar: AvailabilityCalendar = AvailabilityCalendar(),
val flightGroupCalendar: FlightGroupCalendar = FlightGroupCalendar(),
val isLoading: Boolean = false,
)
/**
* ViewModel for the Calendar screen
*
* @param uid The Firebase authentication uid of the user
* @param userTable The user table
* @param availabilityTable The availability table
*/
class CalendarViewModel(
private val uid: String,
private val userTable: UserTable,
private val availabilityTable: AvailabilityTable,
) : ViewModel() {
companion object {
@Composable
fun createViewModel(
uid: String,
userTable: UserTable,
availabilityTable: AvailabilityTable,
): CalendarViewModel {
return viewModel<CalendarViewModel>(
factory =
object : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return CalendarViewModel(uid, userTable, availabilityTable) as T
}
})
}
}
private val user: MutableStateFlow<User?> = MutableStateFlow(null)
private val loadingCounter = MutableStateFlow(0)
private var originalAvailabilityCalendar = AvailabilityCalendar()
val uiState: StateFlow<CalendarUiState> =
combine(user, loadingCounter) { user, loadingCounter ->
CalendarUiState(
user,
user?.availabilities ?: AvailabilityCalendar(),
user?.assignedFlights ?: FlightGroupCalendar(),
loadingCounter > 0)
}
.stateIn(
scope = viewModelScope,
started = WhileUiSubscribed,
initialValue = CalendarUiState(isLoading = true))
init {
refresh()
}
/**
* Fetch the user from the database. Update asynchronously the [CalendarUiState.user] reference
*
* (Starts a new coroutine)
*/
fun refresh() = viewModelScope.launch { refreshUser() }
/** Fetch the user from the database Update asynchronously the [CalendarUiState.user] reference */
private suspend fun refreshUser() {
loadingCounter.value += 1
val newUser = userTable.get(uid, this::onError)
loadingCounter.value -= 1
if (newUser == null) {
// TODO: display not found message
} else {
user.value = newUser
originalAvailabilityCalendar = newUser.availabilities.copy()
}
}
/** Callback executed when an error occurs on database-related operations */
private fun onError(e: Exception) {
// TODO: display error message
}
/**
* Save the current availability calendar to the database by adding, updating, deleting
* availabilities as needed
*/
fun saveAvailabilities() =
viewModelScope.launch {
val user = user.value ?: return@launch
val availabilityCalendar = user.availabilities
val differences =
originalAvailabilityCalendar.getDifferencesWithOtherCalendar(availabilityCalendar)
loadingCounter.value += 1
val jobs = mutableListOf<Job>()
for ((difference, availability) in differences) {
when (difference) {
CalendarDifferenceType.ADDED -> {
jobs.add(
launch {
availabilityTable.add(user.id, availability, onError = { onError(it) })
})
}
CalendarDifferenceType.UPDATED -> {
jobs.add(
launch {
availabilityTable.update(
user.id, availability.id, availability, onError = { onError(it) })
})
}
CalendarDifferenceType.DELETED -> {
jobs.add(
launch { availabilityTable.delete(availability.id, onError = { onError(it) }) })
}
}
}
jobs.forEach { it.join() }
loadingCounter.value -= 1
// we refresh the user to make sure that we have the latest version of
// the availability calendar, by doing it that way we also have the IDs
// of all availabilities and we reset the originalAvailabilityCalendar attribute
// However this might be unnecessary
refreshUser()
}
}
| skysync/app/src/main/java/ch/epfl/skysync/viewmodel/CalendarViewModel.kt | 2180620628 |
package ch.epfl.skysync.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
val veryLightOrange = Color(0xfffad282)
val lightOrange = Color(0xFFFFA726)
val darkOrange = Color(0xFFE39B00)
val lightGray = Color(0xFFF5F5F5)
val lightRed = Color(0xFFEF5350)
val lightBlue = Color(0xFFB0E0E6)
val lightBrown = Color(0xFFD2B48C)
val lightGreen = Color(0xFFAAEE7B)
val lightViolet = Color(0xFFE6E6FA)
val veryLightBlue = Color(0xFFDBFFFD)
| skysync/app/src/main/java/ch/epfl/skysync/ui/theme/Color.kt | 541470073 |
package ch.epfl.skysync.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme =
darkColorScheme(primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80)
private val LightColorScheme =
lightColorScheme(
primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun SkySyncTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme =
when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(colorScheme = colorScheme, typography = Typography, content = content)
}
| skysync/app/src/main/java/ch/epfl/skysync/ui/theme/Theme.kt | 1290398451 |
package ch.epfl.skysync.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography =
Typography(
bodyLarge =
TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
)
| skysync/app/src/main/java/ch/epfl/skysync/ui/theme/Type.kt | 2279123122 |
package ch.epfl.skysync.database
import java.time.LocalDate
import java.time.ZoneOffset
import java.util.Date
/**
* Utility object for converting between [Date] and [LocalDate]. Firestore stores [Date] as a
* string, simplifying queries. [LocalDate], on the other hand, is stored as a collection of fields,
* which can complicate querying in Firestore.
*/
object DateLocalDateConverter {
/**
* Converts a [Date] object to a [LocalDate] object.
*
* @param date The [Date] object to be converted.
* @return The equivalent [LocalDate] object.
*/
fun dateToLocalDate(date: Date): LocalDate {
return date.toInstant().atZone(ZoneOffset.systemDefault()).toLocalDate()
}
/**
* Converts a [LocalDate] object to a [Date] object.
*
* @param localDate The [LocalDate] object to be converted.
* @return The equivalent [Date] object.
*/
fun localDateToDate(localDate: LocalDate): Date {
return Date.from(localDate.atStartOfDay(ZoneOffset.UTC).toInstant())
}
}
| skysync/app/src/main/java/ch/epfl/skysync/database/DateLocalDateConverter.kt | 3352141061 |
package ch.epfl.skysync.database.tables
import ch.epfl.skysync.database.DateLocalDateConverter
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.database.FlightStatus
import ch.epfl.skysync.database.Table
import ch.epfl.skysync.database.schemas.FlightMemberSchema
import ch.epfl.skysync.database.schemas.FlightSchema
import ch.epfl.skysync.models.flight.Balloon
import ch.epfl.skysync.models.flight.Basket
import ch.epfl.skysync.models.flight.Flight
import ch.epfl.skysync.models.flight.FlightType
import ch.epfl.skysync.models.flight.PlannedFlight
import ch.epfl.skysync.models.flight.Role
import ch.epfl.skysync.models.flight.Team
import ch.epfl.skysync.models.flight.Vehicle
import ch.epfl.skysync.models.user.User
import com.google.firebase.firestore.Filter
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
/** Represent the "flight" table */
class FlightTable(db: FirestoreDatabase) :
Table<Flight, FlightSchema>(db, FlightSchema::class, PATH) {
private val flightTypeTable = FlightTypeTable(db)
private val balloonTable = BalloonTable(db)
private val basketTable = BasketTable(db)
private val vehicleTable = VehicleTable(db)
private val flightMemberTable = FlightMemberTable(db)
private val userTable = UserTable(db)
/** Create a [Flight] instance from the flight schema and the retrieved entities */
private fun makeFlight(
schema: FlightSchema,
flightType: FlightType,
balloon: Balloon?,
basket: Basket?,
vehicles: List<Vehicle>,
team: Team
): Flight {
return when (schema.status!!) {
FlightStatus.PLANNED ->
PlannedFlight(
id = schema.id!!,
nPassengers = schema.numPassengers!!,
team = team,
flightType = flightType,
balloon = balloon,
basket = basket,
date = DateLocalDateConverter.dateToLocalDate(schema.date!!),
timeSlot = schema.timeSlot!!,
vehicles = vehicles)
FlightStatus.CONFIRMED -> throw NotImplementedError()
FlightStatus.FINISHED -> throw NotImplementedError()
}
}
/**
* Add items to the flight-member relation for each role defined in the team, whether or not it
* has a user assigned.
*/
private suspend fun addTeam(
flightId: String,
team: Team,
): Unit = coroutineScope {
team.roles
.map { role ->
async {
flightMemberTable.add(
FlightMemberSchema(
userId = role.assignedUser?.id, flightId = flightId, roleType = role.roleType))
}
}
.awaitAll()
}
/**
* Set items to the flight-member relation for each role defined in the team, whether or not it
* has a user assigned.
*/
private suspend fun setTeam(
flightId: String,
team: Team,
) {
flightMemberTable.queryDelete(Filter.equalTo("flightId", flightId))
addTeam(flightId, team)
}
/**
* Retrieve the team members of the flight
*
* First query the flight-member relation then for the roles which have a user assigned, query the
* user table.
*/
private suspend fun retrieveTeam(schema: FlightSchema): Team = coroutineScope {
val members = flightMemberTable.query(Filter.equalTo("flightId", schema.id))
val roles = mutableListOf<Role>()
val deferreds = mutableListOf<Job>()
for (member in members) {
if (member.userId == null) {
roles.add(Role(member.roleType!!, null))
continue
}
deferreds.add(
launch {
val user = userTable.get(member.userId)
if (user == null) {
// report
} else {
roles.add(Role(member.roleType!!, user))
}
})
}
deferreds.forEach { it.join() }
Team(roles)
}
/** Retrieve the vehicles linked to the flight */
private suspend fun retrieveVehicles(schema: FlightSchema): List<Vehicle> = coroutineScope {
schema.vehicleIds!!
.map { vehicleId ->
async {
val vehicle = vehicleTable.get(vehicleId)
if (vehicle == null) {
// report
}
vehicle
}
}
.awaitAll()
.filterNotNull()
}
/** Retrieve all the entities linked to the flight */
private suspend fun retrieveFlight(flightSchema: FlightSchema): Flight? = coroutineScope {
var flightType: FlightType? = null
var balloon: Balloon? = null
var basket: Basket? = null
var vehicles: List<Vehicle>? = null
var team: Team? = null
val jobs =
listOf(
launch {
flightType = flightTypeTable.get(flightSchema.flightTypeId!!)
if (flightType == null) {
// report
}
},
launch {
if (flightSchema.balloonId == null) return@launch
balloon = balloonTable.get(flightSchema.balloonId!!)
if (balloon == null) {
// report
}
},
launch {
if (flightSchema.basketId == null) return@launch
basket = basketTable.get(flightSchema.basketId!!)
if (basket == null) {
// report
}
},
launch { vehicles = retrieveVehicles(flightSchema) },
launch { team = retrieveTeam(flightSchema) })
jobs.forEach { it.join() }
makeFlight(flightSchema, flightType!!, balloon, basket, vehicles!!, team!!)
}
override suspend fun get(id: String, onError: ((Exception) -> Unit)?): Flight? {
return withErrorCallback(onError) {
val schema = db.getItem(path, id, clazz) ?: return@withErrorCallback null
retrieveFlight(schema)
}
}
override suspend fun getAll(onError: ((Exception) -> Unit)?): List<Flight> = coroutineScope {
withErrorCallback(onError) {
val schemas = db.getAll(path, clazz)
schemas
.map { schema ->
async {
val flight = retrieveFlight(schema)
if (flight == null) {
// report
}
flight!!
}
}
.awaitAll()
}
}
override suspend fun query(filter: Filter, onError: ((Exception) -> Unit)?): List<Flight> =
coroutineScope {
withErrorCallback(onError) {
val schemas = db.query(path, filter, clazz)
schemas
.map { schema ->
async {
val flight = retrieveFlight(schema)
if (flight == null) {
// report
}
flight!!
}
}
.awaitAll()
}
}
/**
* Add a new flight to the database
*
* This will generate a new id for this flight and disregard any previously set id. This will
* create the [Flight.team] (and in the process the [User.assignedFlights])
*
* @param item The flight to add to the database
* @param onError Callback called when an error occurs
*/
suspend fun add(item: Flight, onError: ((Exception) -> Unit)? = null): String {
return withErrorCallback(onError) {
val flightId = db.addItem(path, FlightSchema.fromModel(item))
addTeam(flightId, item.team)
flightId
}
}
/**
* Update a flight
*
* This will overwrite the flight at the given id.
*
* @param id The id of the flight
* @param item The flight to update in the database
* @param onError Callback called when an error occurs
*/
suspend fun update(id: String, item: Flight, onError: ((Exception) -> Unit)? = null) =
coroutineScope {
withErrorCallback(onError) {
listOf(
launch { db.setItem(path, id, FlightSchema.fromModel(item)) },
launch { setTeam(id, item.team) })
.forEach { it.join() }
}
}
override suspend fun delete(id: String, onError: ((Exception) -> Unit)?) = coroutineScope {
withErrorCallback(onError) {
listOf(
launch { super.delete(id, onError = null) },
launch { flightMemberTable.queryDelete(Filter.equalTo("flightId", id)) })
.forEach { it.join() }
}
}
companion object {
const val PATH = "flight"
}
}
| skysync/app/src/main/java/ch/epfl/skysync/database/tables/FlightTable.kt | 2213751262 |
package ch.epfl.skysync.database.tables
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.database.ListenerUpdate
import ch.epfl.skysync.database.Table
import ch.epfl.skysync.database.schemas.MessageGroupSchema
import ch.epfl.skysync.models.message.Message
import ch.epfl.skysync.models.message.MessageGroup
import com.google.firebase.firestore.Filter
import com.google.firebase.firestore.ListenerRegistration
import com.google.firebase.firestore.Query
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
class MessageGroupTable(db: FirestoreDatabase) :
Table<MessageGroup, MessageGroupSchema>(db, MessageGroupSchema::class, PATH) {
private val messageTable = MessageTable(db)
/**
* Add a listener on a message group
*
* The listener will be triggered each time a new message is sent/received
*
* @param groupId The ID of the group
* @param onChange Callback called each time the listener is triggered, passed the adds, updates,
* deletes that happened since the last listener trigger.
*/
fun addGroupListener(
groupId: String,
onChange: (ListenerUpdate<Message>) -> Unit,
): ListenerRegistration {
// the query limit is there to avoid wasting resources
// as the callback will receive the result of the query
// the first time it is triggered, we could theoretically
// set the limit to 1 as the callback is called on each new
// message, for now set 10 as a safety precaution for if
// multiple messages get sent at the same time
val limit = 10L
return messageTable.queryListener(
Filter.equalTo("groupId", groupId),
limit = limit,
orderBy = "date",
orderByDirection = Query.Direction.DESCENDING,
onChange = { update ->
onChange(
ListenerUpdate(
isFirstUpdate = update.isFirstUpdate,
isLocalUpdate = update.isLocalUpdate,
adds = update.adds.map { it.toModel() },
updates = update.updates.map { it.toModel() },
deletes = update.deletes.map { it.toModel() },
))
})
}
/**
* Retrieve all messages of a message group
*
* @param groupId The ID of the group
* @param onError Callback called when an error occurs
*/
suspend fun retrieveMessages(
groupId: String,
onError: ((Exception) -> Unit)? = null
): List<Message> {
return withErrorCallback(onError) { messageTable.query(Filter.equalTo("groupId", groupId)) }
}
/**
* Get an message group by ID
*
* This will not load the group messages, this has to be done separately using [retrieveMessages].
*
* @param id The id of the message group
* @param onError Callback called when an error occurs
*/
override suspend fun get(id: String, onError: ((Exception) -> Unit)?): MessageGroup? {
return super.get(id, onError)
}
/**
* Add a new message group to the database
*
* This will generate a new id for this message group and disregard any previously set id. This
* will not add any message in this message group, this has to be done separately (see
* [MessageTable.add]).
*
* @param item The message group to add to the database
* @param onError Callback called when an error occurs
*/
suspend fun add(item: MessageGroup, onError: ((Exception) -> Unit)? = null): String {
return withErrorCallback(onError) { db.addItem(path, MessageGroupSchema.fromModel(item)) }
}
/**
* Update a message group
*
* This will not update the group messages, only the list of users who are part of it.
*
* @param item The message group to update
* @param id The id of the message group
* @param onError Callback called when an error occurs
*/
suspend fun updateGroupUsers(
id: String,
item: MessageGroup,
onError: ((Exception) -> Unit)? = null
) {
return withErrorCallback(onError) { db.setItem(path, id, MessageGroupSchema.fromModel(item)) }
}
override suspend fun delete(id: String, onError: ((Exception) -> Unit)?) = coroutineScope {
withErrorCallback(onError) {
listOf(
launch { super.delete(id, onError = null) },
launch { messageTable.queryDelete(Filter.equalTo("groupId", id)) })
.forEach { it.join() }
}
}
companion object {
const val PATH = "message-group"
}
}
| skysync/app/src/main/java/ch/epfl/skysync/database/tables/MessageGroupTable.kt | 2638343829 |
package ch.epfl.skysync.database.tables
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.database.Table
import ch.epfl.skysync.database.schemas.FlightMemberSchema
/** Represent the "flight-member" relation */
class FlightMemberTable(db: FirestoreDatabase) :
Table<FlightMemberSchema, FlightMemberSchema>(db, FlightMemberSchema::class, PATH) {
/**
* Add a new flight member to the database
*
* @param item The flight member to add to the database
* @param onError Callback called when an error occurs
*/
suspend fun add(item: FlightMemberSchema, onError: ((Exception) -> Unit)? = null): String {
return withErrorCallback(onError) { db.addItem(path, item) }
}
/**
* Update a flight member item
*
* This will override the existing item and replace it with the new one
*
* @param item The item to update
* @param id the id of the item
* @param onError Callback called when an error occurs
*/
suspend fun update(id: String, item: FlightMemberSchema, onError: ((Exception) -> Unit)? = null) {
return withErrorCallback(onError) { db.setItem(path, id, item) }
}
companion object {
const val PATH = "flight-member"
}
}
| skysync/app/src/main/java/ch/epfl/skysync/database/tables/FlightMemberTable.kt | 3653718102 |
package ch.epfl.skysync.database.tables
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.database.Table
import ch.epfl.skysync.database.schemas.VehicleSchema
import ch.epfl.skysync.models.flight.Vehicle
/** Represent the "vehicle" table */
class VehicleTable(db: FirestoreDatabase) :
Table<Vehicle, VehicleSchema>(db, VehicleSchema::class, PATH) {
/**
* Add a new vehicle to the database
*
* @param item The vehicle to add to the database
* @param onError Callback called when an error occurs
*/
suspend fun add(item: Vehicle, onError: ((Exception) -> Unit)? = null): String {
return withErrorCallback(onError) { db.addItem(path, VehicleSchema.fromModel(item)) }
}
companion object {
const val PATH = "vehicle"
}
}
| skysync/app/src/main/java/ch/epfl/skysync/database/tables/VehicleTable.kt | 2938622521 |
package ch.epfl.skysync.database.tables
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.database.Table
import ch.epfl.skysync.database.schemas.BalloonSchema
import ch.epfl.skysync.models.flight.Balloon
/** Represent the "balloon" table */
class BalloonTable(db: FirestoreDatabase) :
Table<Balloon, BalloonSchema>(db, BalloonSchema::class, PATH) {
/**
* Add a new balloon to the database
*
* @param item The balloon to add to the database
* @param onError Callback called when an error occurs
*/
suspend fun add(item: Balloon, onError: ((Exception) -> Unit)? = null): String {
return withErrorCallback(onError) { db.addItem(path, BalloonSchema.fromModel(item)) }
}
companion object {
const val PATH = "balloon"
}
}
| skysync/app/src/main/java/ch/epfl/skysync/database/tables/BalloonTable.kt | 3140447185 |
package ch.epfl.skysync.database.tables
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.database.Table
import ch.epfl.skysync.database.schemas.FlightTypeSchema
import ch.epfl.skysync.models.flight.FlightType
/** Represent the "flight-type" table */
class FlightTypeTable(db: FirestoreDatabase) :
Table<FlightType, FlightTypeSchema>(db, FlightTypeSchema::class, PATH) {
/**
* Add a new flight type to the database
*
* @param item The flight type to add to the database
* @param onError Callback called when an error occurs
*/
suspend fun add(item: FlightType, onError: ((Exception) -> Unit)? = null): String {
return withErrorCallback(onError) { db.addItem(path, FlightTypeSchema.fromModel(item)) }
}
companion object {
const val PATH = "flight-type"
}
}
| skysync/app/src/main/java/ch/epfl/skysync/database/tables/FlightTypeTable.kt | 2614790060 |
package ch.epfl.skysync.database.tables
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.database.Table
import ch.epfl.skysync.database.schemas.MessageSchema
import ch.epfl.skysync.models.message.Message
class MessageTable(db: FirestoreDatabase) :
Table<Message, MessageSchema>(db, MessageSchema::class, PATH) {
/**
* Add a new message to the database
*
* This will generate a new id for this message and disregard any previously set id.
*
* @param groupId The ID of the group the message is sent to
* @param item The message to add to the database
* @param onError Callback called when an error occurs
*/
suspend fun add(groupId: String, item: Message, onError: ((Exception) -> Unit)? = null): String {
return withErrorCallback(onError) { db.addItem(path, MessageSchema.fromModel(groupId, item)) }
}
companion object {
const val PATH = "message"
}
}
| skysync/app/src/main/java/ch/epfl/skysync/database/tables/MessageTable.kt | 2391586384 |
package ch.epfl.skysync.database.tables
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.database.Table
import ch.epfl.skysync.database.schemas.AvailabilitySchema
import ch.epfl.skysync.models.calendar.Availability
/** Represent the "availability" table */
class AvailabilityTable(db: FirestoreDatabase) :
Table<Availability, AvailabilitySchema>(db, AvailabilitySchema::class, PATH) {
/**
* Add a new availability to the database
*
* This will generate a new id for this availability and disregard any previously set id.
*
* @param userId The ID of the user whose availability it is
* @param item The availability to add to the database
* @param onError Callback called when an error occurs
*/
suspend fun add(
userId: String,
item: Availability,
onError: ((Exception) -> Unit)? = null
): String {
return withErrorCallback(onError) {
db.addItem(path, AvailabilitySchema.fromModel(userId, item))
}
}
/**
* Update a availability
*
* This will overwrite the availability at the given id.
*
* @param userId The ID of the user whose availability it is
* @param availabilityId The id of the availability to update
* @param item The new availability item
* @param onError Callback called when an error occurs
*/
suspend fun update(
userId: String,
availabilityId: String,
item: Availability,
onError: ((Exception) -> Unit)? = null
) {
return withErrorCallback(onError) {
db.setItem(path, availabilityId, AvailabilitySchema.fromModel(userId, item))
}
}
companion object {
const val PATH = "availability"
}
}
| skysync/app/src/main/java/ch/epfl/skysync/database/tables/AvailabilityTable.kt | 519591463 |
package ch.epfl.skysync.database.tables
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.database.Table
import ch.epfl.skysync.database.schemas.UserSchema
import ch.epfl.skysync.models.calendar.Availability
import ch.epfl.skysync.models.flight.Flight
import ch.epfl.skysync.models.user.User
import com.google.firebase.firestore.Filter
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
/** Represent the "user" table */
class UserTable(db: FirestoreDatabase) : Table<User, UserSchema>(db, UserSchema::class, PATH) {
private val availabilityTable = AvailabilityTable(db)
private val flightMemberTable = FlightMemberTable(db)
/** Retrieve and set all availabilities linked to the user */
private suspend fun retrieveAvailabilities(userId: String): List<Availability> {
return availabilityTable.query(Filter.equalTo("userId", userId))
}
/** Delete all availabilities linked to the user */
private suspend fun deleteAvailabilities(id: String) {
availabilityTable.queryDelete(Filter.equalTo("userId", id))
}
/**
* Retrieve all assigned flights linked to a user
*
* @param flightTable The flight table is passed as dependency injection to prevent a circular
* reference between [FlightTable] and [UserTable]
* @param id The id of the user
* @param onError Callback called when an error occurs
*/
suspend fun retrieveAssignedFlights(
flightTable: FlightTable,
id: String,
onError: ((Exception) -> Unit)? = null
): List<Flight> = coroutineScope {
withErrorCallback(onError) {
val memberships = flightMemberTable.query(Filter.equalTo("userId", id), onError = null)
val flights =
memberships
.map { membership ->
async {
val flight = flightTable.get(membership.flightId!!)
if (flight == null) {
// report
}
flight
}
}
.awaitAll()
flights.filterNotNull()
}
}
/** Remove user from all its flight assignments */
private suspend fun removeUserFromFlightMemberSchemas(id: String): Unit = coroutineScope {
val memberships = flightMemberTable.query(Filter.equalTo("userId", id))
memberships
.map { membership ->
async { flightMemberTable.update(membership.id!!, membership.copy(userId = null)) }
}
.awaitAll()
}
/**
* Get an user by ID
*
* This will get the user and its availabilities but not its assigned flights, this has to be done
* separately using [retrieveAssignedFlights].
*
* @param id The id of the user
* @param onError Callback called when an error occurs
*/
override suspend fun get(id: String, onError: ((Exception) -> Unit)?): User? {
return withErrorCallback(onError) {
val user = super.get(id, onError = null) ?: return@withErrorCallback null
user.availabilities.addCells(retrieveAvailabilities(user.id))
user
}
}
override suspend fun getAll(onError: ((Exception) -> Unit)?): List<User> = coroutineScope {
withErrorCallback(onError) {
val users = super.getAll(onError = null)
users
.map { user -> async { user.availabilities.addCells(retrieveAvailabilities(user.id)) } }
.awaitAll()
users
}
}
override suspend fun query(filter: Filter, onError: ((Exception) -> Unit)?): List<User> =
coroutineScope {
withErrorCallback(onError) {
val users = super.query(filter, onError = null)
users
.map { user ->
async { user.availabilities.addCells(retrieveAvailabilities(user.id)) }
}
.awaitAll()
users
}
}
override suspend fun delete(id: String, onError: ((Exception) -> Unit)?): Unit = coroutineScope {
withErrorCallback(onError) {
listOf(
async { super.delete(id, onError = null) },
async { deleteAvailabilities(id) },
async { removeUserFromFlightMemberSchemas(id) },
)
.awaitAll()
}
}
/**
* Set a new user to the database
*
* Set item at id and override any previously set id. This will not add availabilities or assigned
* flights to the database, it must be done separately.
*
* @param item The user to add to the database
* @param id The id of the user
* @param onError Callback called when an error occurs
*/
suspend fun set(id: String, item: User, onError: ((Exception) -> Unit)? = null) {
return withErrorCallback(onError) { db.setItem(path, id, UserSchema.fromModel(item)) }
}
/**
* Update a user
*
* Update the user at the given id.
*
* @param item The user to update
* @param id The id of the user
* @param onError Callback called when an error occurs
*/
suspend fun update(id: String, item: User, onError: ((Exception) -> Unit)? = null) {
return withErrorCallback(onError) { db.setItem(path, id, UserSchema.fromModel(item)) }
}
companion object {
const val PATH = "user"
}
}
| skysync/app/src/main/java/ch/epfl/skysync/database/tables/UserTable.kt | 983569481 |
package ch.epfl.skysync.database.tables
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.database.Table
import ch.epfl.skysync.database.schemas.BasketSchema
import ch.epfl.skysync.models.flight.Basket
/** Represent the "basket" table */
class BasketTable(db: FirestoreDatabase) :
Table<Basket, BasketSchema>(db, BasketSchema::class, PATH) {
/**
* Add a new basket to the database
*
* @param item The basket to add to the database
* @param onError Callback called when an error occurs
*/
suspend fun add(item: Basket, onError: ((Exception) -> Unit)? = null): String {
return withErrorCallback(onError) { db.addItem(path, BasketSchema.fromModel(item)) }
}
companion object {
const val PATH = "basket"
}
}
| skysync/app/src/main/java/ch/epfl/skysync/database/tables/BasketTable.kt | 32453170 |
package ch.epfl.skysync.database
/** Represent the flight status */
enum class FlightStatus {
PLANNED,
CONFIRMED,
FINISHED
}
| skysync/app/src/main/java/ch/epfl/skysync/database/FlightStatus.kt | 1655111396 |
package ch.epfl.skysync.database
/** Implemented by schema classes that can be casted to a model class. */
interface Schema<Model> {
/** Create a new instance of the `Model` class derived from this schema instance */
fun toModel(): Model
}
| skysync/app/src/main/java/ch/epfl/skysync/database/Schema.kt | 1531526899 |
package ch.epfl.skysync.database
import com.google.firebase.firestore.Filter
import com.google.firebase.firestore.ListenerRegistration
import com.google.firebase.firestore.Query
import kotlin.reflect.KClass
/**
* Represent a table in the database
*
* @param db The Firestore database connection
* @param clazz The class of the schema of the table
* @param path A filesystem-like path that specify the location of the table
*/
abstract class Table<M, S : Schema<M>>(
protected val db: FirestoreDatabase,
protected val clazz: KClass<S>,
protected val path: String
) {
/**
* Wrap the [run] code in a try/catch block and, if given, call the [onError] callback when an
* exception is thrown in [run], in any case throw the exception
*
* @param onError The callback called when an exception is thrown
* @param run The code to run in the try/catch
* @throws Exception Any exception thrown in [run]
*/
protected suspend fun <T> withErrorCallback(
onError: ((Exception) -> Unit)?,
run: suspend () -> T
): T {
try {
return run()
} catch (e: Exception) {
if (onError != null) {
onError(e)
}
throw e
}
}
/**
* Get an item by ID
*
* @param id The id of the item
* @param onError Callback called when an error occurs
*/
open suspend fun get(id: String, onError: ((Exception) -> Unit)? = null): M? {
return db.getItem(path, id, clazz)?.toModel()
}
/**
* Get all the items
*
* @param onError Callback called when an error occurs
*/
open suspend fun getAll(onError: ((Exception) -> Unit)? = null): List<M> {
return db.getAll(path, clazz).map { it.toModel() }
}
/**
* Query items based on a filter
*
* @param filter The filter to apply to the query
* @param onError Callback called when an error occurs
*/
open suspend fun query(filter: Filter, onError: ((Exception) -> Unit)? = null): List<M> {
return db.query(path, filter, clazz).map { it.toModel() }
}
/**
* Delete an item
*
* @param id The id of the item
* @param onError Callback called when an error occurs
*/
open suspend fun delete(id: String, onError: ((Exception) -> Unit)? = null) {
db.deleteItem(path, id)
}
/**
* Execute a query and delete the resulting items
*
* Note: this only delete the items, not their potential dependencies. To delete items with
* dependencies, call [query], then [delete] for each item.
*
* @param filter The filter to apply to the query
* @param onError Callback called when an error occurs
*/
open suspend fun queryDelete(filter: Filter, onError: ((Exception) -> Unit)? = null) {
db.queryDelete(path, filter)
}
/**
* Add a listener on a query
*
* The listener will be triggered each time the result of the query changes on the database.
*
* @param filter The filter to apply to the query
* @param onChange Callback called each time the listener is triggered, passed the adds, updates,
* deletes that happened since the last listener trigger.
* @param limit If specified, the maximum number of items to includes in the query
* @param orderBy If specified, sort the items of the query by the given field
* @param orderByDirection The direction to sort
*/
open fun queryListener(
filter: Filter,
onChange: (ListenerUpdate<S>) -> Unit,
limit: Long? = null,
orderBy: String? = null,
orderByDirection: Query.Direction = Query.Direction.ASCENDING,
): ListenerRegistration {
return db.queryListener(path, filter, clazz, onChange, limit, orderBy, orderByDirection)
}
/**
* Delete the table
*
* This is only used for testing, as such it is only supported if using the emulator.
*
* @param onError Callback called when an error occurs
*/
open suspend fun deleteTable(onError: ((Exception) -> Unit)? = null) {
db.deleteTable(path)
}
}
| skysync/app/src/main/java/ch/epfl/skysync/database/Table.kt | 4036507128 |
package ch.epfl.skysync.database.schemas
import ch.epfl.skysync.database.DateLocalDateConverter
import ch.epfl.skysync.database.FlightStatus
import ch.epfl.skysync.database.Schema
import ch.epfl.skysync.models.calendar.TimeSlot
import ch.epfl.skysync.models.flight.Flight
import ch.epfl.skysync.models.flight.PlannedFlight
import com.google.firebase.firestore.DocumentId
import java.lang.UnsupportedOperationException
import java.util.Date
data class FlightSchema(
@DocumentId val id: String? = null,
val flightTypeId: String? = null,
/** Nullable */
val balloonId: String? = null,
/** Nullable */
val basketId: String? = null,
val vehicleIds: List<String>? = null,
val status: FlightStatus? = null,
// Note: this is called numPassengers and not nPassengers because
// nPassengers is wrongly mapped to "npassengers" by the firestore class mapper
// whereas numPassenger is correctly mapped as "numPassengers"
// (which makes no sense but at least it works)
val numPassengers: Int? = null,
val timeSlot: TimeSlot? = null,
/** We use the Date class instead of the LocalDate for Firestore see [DateLocalDateConverter] */
val date: Date? = null
) : Schema<Flight> {
override fun toModel(): Flight {
throw NotImplementedError()
}
companion object {
fun fromModel(model: Flight): FlightSchema {
val status =
when (model) {
is PlannedFlight -> FlightStatus.PLANNED
else ->
throw UnsupportedOperationException(
"Unexpected class ${model.javaClass.simpleName}")
}
return FlightSchema(
id = model.id,
flightTypeId = model.flightType.id,
balloonId = model.balloon?.id,
basketId = model.basket?.id,
vehicleIds = model.vehicles.map { it.id },
status = status,
numPassengers = model.nPassengers,
timeSlot = model.timeSlot,
date = DateLocalDateConverter.localDateToDate(model.date),
)
}
}
}
| skysync/app/src/main/java/ch/epfl/skysync/database/schemas/FlightSchema.kt | 2397556391 |
package ch.epfl.skysync.database.schemas
import ch.epfl.skysync.database.DateLocalDateConverter
import ch.epfl.skysync.database.Schema
import ch.epfl.skysync.models.calendar.Availability
import ch.epfl.skysync.models.calendar.AvailabilityStatus
import ch.epfl.skysync.models.calendar.TimeSlot
import com.google.firebase.firestore.DocumentId
import java.util.Date
data class AvailabilitySchema(
@DocumentId val id: String? = null,
val userId: String? = null,
val status: AvailabilityStatus? = null,
val timeSlot: TimeSlot? = null,
/** We use the Date class instead of the LocalDate for Firestore see [DateLocalDateConverter] */
val date: Date? = null
) : Schema<Availability> {
override fun toModel(): Availability {
return Availability(
id!!,
status!!,
timeSlot!!,
DateLocalDateConverter.dateToLocalDate(date!!),
)
}
companion object {
fun fromModel(userId: String, model: Availability): AvailabilitySchema {
return AvailabilitySchema(
model.id,
userId,
model.status,
model.timeSlot,
DateLocalDateConverter.localDateToDate(model.date),
)
}
}
}
| skysync/app/src/main/java/ch/epfl/skysync/database/schemas/AvailabilitySchema.kt | 3455314164 |
package ch.epfl.skysync.database.schemas
import ch.epfl.skysync.database.Schema
import ch.epfl.skysync.database.UserRole
import ch.epfl.skysync.models.calendar.AvailabilityCalendar
import ch.epfl.skysync.models.calendar.FlightGroupCalendar
import ch.epfl.skysync.models.flight.BalloonQualification
import ch.epfl.skysync.models.flight.RoleType
import ch.epfl.skysync.models.user.Admin
import ch.epfl.skysync.models.user.Crew
import ch.epfl.skysync.models.user.Pilot
import ch.epfl.skysync.models.user.User
import com.google.firebase.firestore.DocumentId
import java.lang.UnsupportedOperationException
data class UserSchema(
@DocumentId val id: String? = null,
val userRole: UserRole? = null,
val firstname: String? = null,
val lastname: String? = null,
val roleTypes: List<RoleType>? = null,
val balloonQualification: BalloonQualification? = null,
) : Schema<User> {
override fun toModel(): User {
return when (userRole!!) {
UserRole.ADMIN ->
Admin(
id = id!!,
firstname = firstname!!,
lastname = lastname!!,
availabilities = AvailabilityCalendar(),
assignedFlights = FlightGroupCalendar(),
roleTypes = roleTypes!!.toSet(),
)
UserRole.CREW ->
Crew(
id = id!!,
firstname = firstname!!,
lastname = lastname!!,
availabilities = AvailabilityCalendar(),
assignedFlights = FlightGroupCalendar(),
roleTypes = roleTypes!!.toSet(),
)
UserRole.PILOT ->
Pilot(
id = id!!,
firstname = firstname!!,
lastname = lastname!!,
availabilities = AvailabilityCalendar(),
assignedFlights = FlightGroupCalendar(),
roleTypes = roleTypes!!.toSet(),
qualification = balloonQualification!!)
}
}
companion object {
fun fromModel(model: User): UserSchema {
val (userRole, qualification) =
when (model) {
is Admin -> Pair(UserRole.ADMIN, null)
is Crew -> Pair(UserRole.CREW, null)
is Pilot -> Pair(UserRole.PILOT, model.qualification)
else ->
throw UnsupportedOperationException(
"Unexpected class ${model.javaClass.simpleName}")
}
return UserSchema(
id = model.id,
userRole = userRole,
firstname = model.firstname,
lastname = model.lastname,
roleTypes = model.roleTypes.toList(),
balloonQualification = qualification)
}
}
}
| skysync/app/src/main/java/ch/epfl/skysync/database/schemas/UserSchema.kt | 465580887 |
package ch.epfl.skysync.database.schemas
import ch.epfl.skysync.database.Schema
import ch.epfl.skysync.models.flight.RoleType
import com.google.firebase.firestore.DocumentId
data class FlightMemberSchema(
@DocumentId val id: String? = null,
/** Nullable */
val userId: String? = null,
val flightId: String? = null,
val roleType: RoleType? = null,
) : Schema<FlightMemberSchema> {
override fun toModel(): FlightMemberSchema {
return this
}
}
| skysync/app/src/main/java/ch/epfl/skysync/database/schemas/FlightMemberSchema.kt | 3978335479 |
package ch.epfl.skysync.database.schemas
import ch.epfl.skysync.database.Schema
import ch.epfl.skysync.models.message.Message
import com.google.firebase.firestore.DocumentId
import java.util.Date
data class MessageSchema(
@DocumentId val id: String? = null,
val groupId: String? = null,
val userId: String? = null,
val date: Date? = null,
val content: String? = null,
) : Schema<Message> {
override fun toModel(): Message {
return Message(
id!!,
userId!!,
date!!,
content!!,
)
}
companion object {
fun fromModel(groupId: String, model: Message): MessageSchema {
return MessageSchema(model.id, groupId, model.userId, model.date, model.content)
}
}
}
| skysync/app/src/main/java/ch/epfl/skysync/database/schemas/MessageSchema.kt | 760861174 |
package ch.epfl.skysync.database.schemas
import ch.epfl.skysync.database.Schema
import ch.epfl.skysync.models.flight.FlightType
import ch.epfl.skysync.models.flight.RoleType
import com.google.firebase.firestore.DocumentId
data class FlightTypeSchema(
@DocumentId val id: String? = null,
val name: String? = null,
val specialRoles: List<RoleType>? = null
) : Schema<FlightType> {
override fun toModel(): FlightType {
return FlightType(
id = id!!,
name = name!!,
specialRoles = specialRoles!!,
)
}
companion object {
fun fromModel(model: FlightType): FlightTypeSchema {
return FlightTypeSchema(id = model.id, name = model.name, specialRoles = model.specialRoles)
}
}
}
| skysync/app/src/main/java/ch/epfl/skysync/database/schemas/FlightTypeSchema.kt | 2980070965 |
package ch.epfl.skysync.database.schemas
import ch.epfl.skysync.database.Schema
import ch.epfl.skysync.models.flight.Balloon
import ch.epfl.skysync.models.flight.BalloonQualification
import com.google.firebase.firestore.DocumentId
data class BalloonSchema(
@DocumentId val id: String? = null,
val name: String? = null,
val qualification: BalloonQualification? = null,
) : Schema<Balloon> {
override fun toModel(): Balloon {
return Balloon(
id = id!!,
name = name!!,
qualification = qualification!!,
)
}
companion object {
fun fromModel(model: Balloon): BalloonSchema {
return BalloonSchema(
id = model.id,
name = model.name,
qualification = model.qualification,
)
}
}
}
| skysync/app/src/main/java/ch/epfl/skysync/database/schemas/BalloonSchema.kt | 2678597340 |
package ch.epfl.skysync.database.schemas
import ch.epfl.skysync.database.Schema
import ch.epfl.skysync.models.message.MessageGroup
import com.google.firebase.firestore.DocumentId
data class MessageGroupSchema(
@DocumentId val id: String? = null,
val userIds: List<String>? = null,
) : Schema<MessageGroup> {
override fun toModel(): MessageGroup {
return MessageGroup(
id!!,
userIds!!.toSet(),
listOf(),
)
}
companion object {
fun fromModel(model: MessageGroup): MessageGroupSchema {
return MessageGroupSchema(
model.id,
model.userIds.toList(),
)
}
}
}
| skysync/app/src/main/java/ch/epfl/skysync/database/schemas/MessageGroupSchema.kt | 3783256463 |
package ch.epfl.skysync.database.schemas
import ch.epfl.skysync.database.Schema
import ch.epfl.skysync.models.flight.Vehicle
import com.google.firebase.firestore.DocumentId
data class VehicleSchema(
@DocumentId val id: String? = null,
val name: String? = null,
) : Schema<Vehicle> {
override fun toModel(): Vehicle {
return Vehicle(
id = id!!,
name = name!!,
)
}
companion object {
fun fromModel(model: Vehicle): VehicleSchema {
return VehicleSchema(
id = model.id,
name = model.name,
)
}
}
}
| skysync/app/src/main/java/ch/epfl/skysync/database/schemas/VehicleSchema.kt | 2993534924 |
package ch.epfl.skysync.database.schemas
import ch.epfl.skysync.database.Schema
import ch.epfl.skysync.models.flight.Basket
import com.google.firebase.firestore.DocumentId
data class BasketSchema(
@DocumentId val id: String? = null,
val name: String? = null,
val hasDoor: Boolean? = null,
) : Schema<Basket> {
override fun toModel(): Basket {
return Basket(
id = id!!,
name = name!!,
hasDoor = hasDoor!!,
)
}
companion object {
fun fromModel(model: Basket): BasketSchema {
return BasketSchema(id = model.id, name = model.name, hasDoor = model.hasDoor)
}
}
}
| skysync/app/src/main/java/ch/epfl/skysync/database/schemas/BasketSchema.kt | 1187924573 |
package ch.epfl.skysync.database
/**
* Represent the role of the user
*
* It is the authentication role, as such, it is used to define the permissions of the user. It is
* not the same as models.flight.RoleType which define the role of a user on a particular flight.
*/
enum class UserRole {
ADMIN,
CREW,
PILOT,
}
| skysync/app/src/main/java/ch/epfl/skysync/database/UserRole.kt | 1502666916 |
package ch.epfl.skysync.database
/**
* Represents the changes on a query listener
*
* @param isFirstUpdate If the listener is triggered for the first time, which correspond to simply
* fetching the query
* @param isLocalUpdate If the listener is triggered by a local update, which happens on write
* operations
* ([doc](https://firebase.google.com/docs/firestore/query-data/listen#events-local-changes))
* @param adds The items that have been added since the last update
* @param updates The items that have been updated since the last update
* @param deletes The items that have been deleted since the last update
*/
data class ListenerUpdate<T : Any>(
val isFirstUpdate: Boolean,
val isLocalUpdate: Boolean,
val adds: List<T>,
val updates: List<T>,
val deletes: List<T>
)
| skysync/app/src/main/java/ch/epfl/skysync/database/ListenerUpdate.kt | 2632471664 |
package ch.epfl.skysync.database
/**
* Represents a mechanism for the case when n operations with callback are executed in parallel,
* where a specific callback should be called once by the last of the n operation finishes.
*
* @property numParallelOperations The number of operations executed in parallel
* @property callback The callback function to be executed once by the last operation.
*/
class ParallelOperationsEndCallback(
private var numParallelOperations: Int,
private val callback: () -> Unit
) {
init {
if (numParallelOperations < 1) {
callback()
}
}
/** To be executed at the end of each parallel operation at the last one, execute the callback */
fun run() {
if (numParallelOperations <= 1) {
callback()
} else {
numParallelOperations -= 1
}
}
}
| skysync/app/src/main/java/ch/epfl/skysync/database/ParallelOperationsEndCallback.kt | 3372296016 |
package ch.epfl.skysync.database
import android.util.Log
import com.google.firebase.Firebase
import com.google.firebase.firestore.DocumentChange
import com.google.firebase.firestore.Filter
import com.google.firebase.firestore.ListenerRegistration
import com.google.firebase.firestore.MemoryCacheSettings
import com.google.firebase.firestore.Query
import com.google.firebase.firestore.firestore
import com.google.firebase.firestore.firestoreSettings
import com.google.firebase.firestore.toObject
import java.lang.UnsupportedOperationException
import kotlin.reflect.KClass
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await
/**
* Represent a connection to a Firestore database
*
* @param useEmulator If true, it will try to connect to Firestore database of a local emulator
*/
class FirestoreDatabase(private val useEmulator: Boolean = false) {
private val db = Firebase.firestore
private val TAG = "Firebase"
init {
if (useEmulator) {
// can only be called once but there is no method to check if already called
try {
db.useEmulator("10.0.2.2", 5002)
} catch (_: IllegalStateException) {
// this occurs when the FirebaseDatabase is instanced twice
}
db.firestoreSettings = firestoreSettings {
setLocalCacheSettings(MemoryCacheSettings.newBuilder().build())
}
}
}
/**
* Add a new item to the database
*
* This will generate a new id for this item and override any previously set id.
*
* @param path A filesystem-like path that specify the location of the table
* @param item The item to add to the database, the types of the attributes have to be Firestore
* types
*/
suspend fun <T : Any> addItem(
path: String,
item: T,
): String {
val res = db.collection(path).add(item).await()
Log.d(TAG, "Added $path/${res.id}")
return res.id
}
/**
* Set a new item to the database
*
* Set item at id and override any previously set id.
*
* @param path A filesystem-like path that specify the location of the table
* @param item The item to set to the database, the types of the attributes have to be Firestore
* @param id the id of the item
*/
suspend fun <T : Any> setItem(
path: String,
id: String,
item: T,
) {
db.collection(path).document(id).set(item).await()
Log.d(TAG, "Created $path/${id}")
}
/**
* Get an item from the database
*
* @param path A filesystem-like path that specify the location of the table
* @param id The id of the item
* @param clazz The class of the item, this is used to reconstruct an instance of the item class
*/
suspend fun <T : Any> getItem(
path: String,
id: String,
clazz: KClass<T>,
): T? {
val documentSnapshot = db.collection(path).document(id).get().await()
Log.d(TAG, "Got $path/${documentSnapshot.id}")
return documentSnapshot.toObject(clazz.java)
}
/**
* Get all items from a table
*
* @param path A filesystem-like path that specify the location of the table
* @param clazz The class of the item, this is used to reconstruct an instance of the item class
*/
suspend fun <T : Any> getAll(
path: String,
clazz: KClass<T>,
): List<T> {
val querySnapshot = db.collection(path).get().await()
Log.d(TAG, "Got $path (x${querySnapshot.size()})")
return querySnapshot.documents.mapNotNull {
val res = it.toObject(clazz.java)
if (res == null) {
Log.w(TAG, "Casting failed for $path/${it.id}")
}
res
}
}
/**
* Query items from a table based on a filter
*
* @param path A filesystem-like path that specify the location of the table
* @param filter The filter to apply to the query
* @param clazz The class of the item, this is used to reconstruct an instance of the item class
* @param limit If specified, the maximum number of items to includes in the query
* @param orderBy If specified, sort the items of the query by the given field
* @param orderByDirection The direction to sort
*/
suspend fun <T : Any> query(
path: String,
filter: Filter,
clazz: KClass<T>,
limit: Long? = null,
orderBy: String? = null,
orderByDirection: Query.Direction = Query.Direction.ASCENDING,
): List<T> {
var query = db.collection(path).where(filter)
if (orderBy != null) {
query = query.orderBy(orderBy, orderByDirection)
}
if (limit != null) {
query = query.limit(limit)
}
val querySnapshot = query.get().await()
Log.d(TAG, "Got $path (x${querySnapshot.size()})")
return querySnapshot.documents.mapNotNull {
val res = it.toObject(clazz.java)
if (res == null) {
Log.w(TAG, "Casting failed for $path/${it.id}")
}
res
}
}
/**
* Delete an item from the database
*
* @param path A filesystem-like path that specify the location of the table
* @param id The id of the item
*/
suspend fun deleteItem(
path: String,
id: String,
) {
db.collection(path).document(id).delete().await()
Log.d(TAG, "Deleted $path/$id")
}
/**
* Execute a query on a table and delete the resulting items
*
* @param path A filesystem-like path that specify the location of the table
* @param filter The filter to apply to the query
*/
suspend fun queryDelete(
path: String,
filter: Filter,
) {
coroutineScope {
val querySnapshot = db.collection(path).where(filter).get().await()
querySnapshot.documents
.map { document ->
launch {
document.reference.delete().await()
Log.d(TAG, "Deleted $path/${document.id}")
}
}
.forEach { it.join() }
}
}
/**
* Add a listener on a query
*
* The listener will be triggered each time the result of the query changes on the database.
*
* @param path A filesystem-like path that specify the location of the table
* @param filter The filter to apply to the query
* @param clazz The class of the item, this is used to reconstruct an instance of the item class
* @param onChange Callback called each time the listener is triggered, passed the adds, updates,
* deletes that happened since the last listener trigger.
* @param limit If specified, the maximum number of items to includes in the query
* @param orderBy If specified, sort the items of the query by the given field
* @param orderByDirection The direction to sort
*/
fun <T : Any> queryListener(
path: String,
filter: Filter,
clazz: KClass<T>,
onChange: (ListenerUpdate<T>) -> Unit,
limit: Long? = null,
orderBy: String? = null,
orderByDirection: Query.Direction = Query.Direction.ASCENDING,
): ListenerRegistration {
var query = db.collection(path).where(filter)
if (orderBy != null) {
query = query.orderBy(orderBy, orderByDirection)
}
if (limit != null) {
query = query.limit(limit)
}
var isFirstUpdate = true
val listener =
query.addSnapshotListener { snapshot, e ->
if (e != null) {
Log.e(TAG, "Listen failed ($path).", e)
return@addSnapshotListener
}
if (snapshot == null) {
Log.d(TAG, "Listen null ($path)")
return@addSnapshotListener
}
val adds = mutableListOf<T>()
val updates = mutableListOf<T>()
val deletes = mutableListOf<T>()
for (dc in snapshot.documentChanges) {
when (dc.type) {
DocumentChange.Type.ADDED -> adds.add(dc.document.toObject(clazz.java))
DocumentChange.Type.MODIFIED -> updates.add(dc.document.toObject(clazz.java))
DocumentChange.Type.REMOVED -> deletes.add(dc.document.toObject(clazz.java))
}
}
val listenerUpdate =
ListenerUpdate(
isFirstUpdate = isFirstUpdate,
isLocalUpdate = snapshot.metadata.hasPendingWrites(),
adds = adds,
updates = updates,
deletes = deletes)
Log.d(TAG, "Listen update: x${adds.size} x${updates.size} x${deletes.size} ($path)")
isFirstUpdate = false
onChange(listenerUpdate)
}
Log.d(TAG, "Added listener ($path)")
return listener
}
/**
* Delete a table (collection of items)
*
* This is only used for testing, as such it is only supported if using the emulator.
*
* @param path A filesystem-like path that specify the location of the table
*/
suspend fun deleteTable(path: String) {
if (!useEmulator) {
throw UnsupportedOperationException("Can only delete collection on the emulator.")
}
coroutineScope {
val querySnapshot = db.collection(path).get().await()
Log.d(TAG, "Delete table $path")
querySnapshot.documents
.map { document -> launch { document.reference.delete().await() } }
.forEach { it.join() }
}
}
}
| skysync/app/src/main/java/ch/epfl/skysync/database/FirestoreDatabase.kt | 5684752 |
package ch.epfl.skysync
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.ActivityResultLauncher
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.mutableStateOf
import androidx.navigation.compose.rememberNavController
import ch.epfl.skysync.components.GlobalSnackbarHost
import ch.epfl.skysync.components.SnackbarManager
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.navigation.MainGraph
import ch.epfl.skysync.ui.theme.SkySyncTheme
import com.firebase.ui.auth.FirebaseAuthUIActivityResultContract
import com.firebase.ui.auth.data.model.FirebaseAuthUIAuthenticationResult
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
class MainActivity : ComponentActivity() {
private lateinit var signInLauncher: ActivityResultLauncher<Intent>
private val user = mutableStateOf<FirebaseUser?>(null)
private val db: FirestoreDatabase = FirestoreDatabase()
private val repository: Repository = Repository(db)
private fun onSignInResult(result: FirebaseAuthUIAuthenticationResult) {
if (result.resultCode == RESULT_OK) {
user.value = FirebaseAuth.getInstance().currentUser
SnackbarManager.showMessage("Successfully signed in")
} else {
SnackbarManager.showMessage("Authentication failed")
}
}
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Initialize the signInLauncher
signInLauncher =
registerForActivityResult(FirebaseAuthUIActivityResultContract()) { res ->
this.onSignInResult(res)
}
setContent {
SkySyncTheme {
val navController = rememberNavController()
Scaffold(snackbarHost = { GlobalSnackbarHost() }) {
MainGraph(
repository = repository,
navHostController = navController,
signInLauncher = signInLauncher,
uid = user.value?.uid)
}
}
}
}
}
| skysync/app/src/main/java/ch/epfl/skysync/MainActivity.kt | 206032206 |
/*
* Source file: https://github.com/android/architecture-samples/blob/main/app/src/main/java/com/example/android/architecture/blueprints/todoapp/util/CoroutinesUtils.kt
*/
package ch.epfl.skysync.util
import kotlinx.coroutines.flow.SharingStarted
private const val StopTimeoutMillis: Long = 5000
/**
* A [SharingStarted] meant to be used with a [StateFlow] to expose data to the UI.
*
* When the UI stops observing, upstream flows stay active for some time to allow the system to come
* back from a short-lived configuration change (such as rotations). If the UI stops observing for
* longer, the cache is kept but the upstream flows are stopped. When the UI comes back, the latest
* value is replayed and the upstream flows are executed again. This is done to save resources when
* the app is in the background but let users switch between apps quickly.
*/
val WhileUiSubscribed: SharingStarted = SharingStarted.WhileSubscribed(StopTimeoutMillis)
| skysync/app/src/main/java/ch/epfl/skysync/util/CoroutinesUtil.kt | 900960284 |
package ch.epfl.skysync.navigation
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import androidx.navigation.compose.composable
import androidx.navigation.navigation
import ch.epfl.skysync.Repository
import ch.epfl.skysync.screens.CalendarScreen
import ch.epfl.skysync.viewmodel.CalendarViewModel
fun NavGraphBuilder.personalCalendar(
repository: Repository,
navController: NavHostController,
uid: String?
) {
navigation(startDestination = Route.AVAILABILITY_CALENDAR, route = Route.CALENDAR) {
composable(Route.AVAILABILITY_CALENDAR) {
val viewModel =
CalendarViewModel.createViewModel(
uid!!, repository.userTable, repository.availabilityTable)
CalendarScreen(navController, Route.AVAILABILITY_CALENDAR, viewModel)
}
composable(Route.FLIGHT_CALENDAR) {
val viewModel =
CalendarViewModel.createViewModel(
uid!!, repository.userTable, repository.availabilityTable)
CalendarScreen(navController, Route.FLIGHT_CALENDAR, viewModel)
}
}
}
| skysync/app/src/main/java/ch/epfl/skysync/navigation/PersonalCalendars.kt | 437116425 |
package ch.epfl.skysync.navigation
import androidx.annotation.DrawableRes
import androidx.compose.foundation.layout.RowScope
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.res.painterResource
import androidx.navigation.NavController
import androidx.navigation.NavDestination
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState
import ch.epfl.skysync.R
@Composable
fun BottomBar(navController: NavHostController) {
val screens =
listOf(
BottomBarScreen.Home,
BottomBarScreen.Flight,
BottomBarScreen.Chat,
BottomBarScreen.Calendar,
)
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentDestination = navBackStackEntry?.destination
NavigationBar {
screens.forEach { screen ->
AddItem(
screen = screen, currentDestination = currentDestination, navController = navController)
}
}
}
@Composable
fun RowScope.AddItem(
screen: BottomBarScreen,
currentDestination: NavDestination?,
navController: NavController
) {
NavigationBarItem(
label = { Text(text = screen.title) },
icon = {
Icon(painter = painterResource(id = screen.icon), contentDescription = "Navigation Icon")
},
selected = currentDestination?.hierarchy?.any { it.route == screen.route } == true,
onClick = {
if (currentDestination?.route != screen.route) {
navController.navigate(screen.route) {
popUpTo(navController.graph.findStartDestination().id)
launchSingleTop = true
}
}
})
}
sealed class BottomBarScreen(val route: String, val title: String, @DrawableRes val icon: Int) {
data object Home :
BottomBarScreen(route = Route.HOME, title = "Home", icon = R.drawable.baseline_home_24)
data object Flight :
BottomBarScreen(route = Route.FLIGHT, title = "Flight", icon = R.drawable.baseline_flight_24)
data object Chat :
BottomBarScreen(route = Route.CHAT, title = "Chat", icon = R.drawable.baseline_chat_24)
data object Calendar :
BottomBarScreen(
route = Route.CALENDAR, title = "Calendar", icon = R.drawable.baseline_calendar_month_24)
}
| skysync/app/src/main/java/ch/epfl/skysync/navigation/BottomNavigationBar.kt | 549258505 |
package ch.epfl.skysync.navigation
import android.content.Intent
import androidx.activity.result.ActivityResultLauncher
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import ch.epfl.skysync.Repository
import ch.epfl.skysync.screens.LoginScreen
/** Graph of the whole navigation of the app */
@Composable
fun MainGraph(
repository: Repository,
navHostController: NavHostController,
signInLauncher: ActivityResultLauncher<Intent>,
uid: String?
) {
NavHost(
navController = navHostController,
startDestination = if (uid == null) Route.LOGIN else Route.MAIN) {
homeGraph(repository, navHostController, uid)
composable(Route.LOGIN) { LoginScreen(signInLauncher = signInLauncher) }
}
}
| skysync/app/src/main/java/ch/epfl/skysync/navigation/MainGraph.kt | 1899680347 |
package ch.epfl.skysync.navigation
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.composable
import androidx.navigation.navArgument
import androidx.navigation.navigation
import ch.epfl.skysync.Repository
import ch.epfl.skysync.models.UNSET_ID
import ch.epfl.skysync.screens.AddFlightScreen
import ch.epfl.skysync.screens.AddUserScreen
import ch.epfl.skysync.screens.ChatScreen
import ch.epfl.skysync.screens.FlightScreen
import ch.epfl.skysync.screens.HomeScreen
import ch.epfl.skysync.screens.ModifyFlightScreen
import ch.epfl.skysync.screens.TextScreen
import ch.epfl.skysync.screens.confirmationScreen
import ch.epfl.skysync.screens.flightDetail.FlightDetailScreen
import ch.epfl.skysync.viewmodel.FlightsViewModel
/** Graph of the main screens of the app */
fun NavGraphBuilder.homeGraph(
repository: Repository,
navController: NavHostController,
uid: String?
) {
navigation(startDestination = Route.HOME, route = Route.MAIN) {
personalCalendar(repository, navController, uid)
composable(Route.CHAT) { ChatScreen(navController) }
composable(Route.FLIGHT) { FlightScreen(navController) }
composable(Route.HOME) {
val flightsViewModel = FlightsViewModel.createViewModel(repository)
flightsViewModel.refresh()
HomeScreen(navController, flightsViewModel)
}
composable(
route = Route.FLIGHT_DETAILS + "/{Flight ID}",
arguments = listOf(navArgument("Flight ID") { type = NavType.StringType })) { backStackEntry
->
val flightId = backStackEntry.arguments?.getString("Flight ID") ?: UNSET_ID
val flightsViewModel = FlightsViewModel.createViewModel(repository)
FlightDetailScreen(
navController = navController, flightId = flightId, viewModel = flightsViewModel)
}
composable(Route.ADD_FLIGHT) {
val flightsViewModel = FlightsViewModel.createViewModel(repository)
AddFlightScreen(navController, flightsViewModel)
}
composable(
Route.CONFIRM_FLIGHT + "/{Flight ID}",
arguments = listOf(navArgument("Flight ID") { type = NavType.StringType })) { backStackEntry
->
val flightId = backStackEntry.arguments?.getString("Flight ID") ?: UNSET_ID
val flightsViewModel = FlightsViewModel.createViewModel(repository)
confirmationScreen(navController, flightId, flightsViewModel)
}
composable(
route = Route.MODIFY_FLIGHT + "/{Flight ID}",
arguments = listOf(navArgument("Flight ID") { type = NavType.StringType })) { backStackEntry
->
val flightId = backStackEntry.arguments?.getString("Flight ID") ?: UNSET_ID
val flightsViewModel = FlightsViewModel.createViewModel(repository)
ModifyFlightScreen(navController, flightsViewModel, flightId)
}
composable(Route.ADD_USER) { AddUserScreen(navController = navController) }
composable(
Route.TEXT + "/{Group Name}",
arguments = listOf(navArgument("Group Name") { type = NavType.StringType })) {
backStackEntry ->
val groupName = backStackEntry.arguments?.getString("Group Name") ?: "No Name"
TextScreen(navController, groupName)
}
}
}
| skysync/app/src/main/java/ch/epfl/skysync/navigation/HomeGraph.kt | 364106651 |
package ch.epfl.skysync.navigation
/** Define the paths used for the navigation in the app */
object Route {
const val MAIN = "Main graph"
const val HOME = "Home"
const val CALENDAR = "Calendar"
const val AVAILABILITY_CALENDAR = "Availability Calendar"
const val PERSONAL_FLIGHT_CALENDAR = "Personal Flight Calendar"
const val FLIGHT_CALENDAR = "Flight Calendar"
const val FLIGHT = "Flight"
const val ADD_FLIGHT = "Add Flight"
const val MODIFY_FLIGHT = "Modify Flight"
const val CHAT = "Chat"
const val FLIGHT_DETAILS = "Flight Details"
const val CONFIRM_FLIGHT = "Confirm Flight"
const val ADD_USER = "Add User"
const val TEXT = "Text"
const val LOGIN = "Login"
}
| skysync/app/src/main/java/ch/epfl/skysync/navigation/Route.kt | 213648171 |
package ch.epfl.skysync
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.database.tables.AvailabilityTable
import ch.epfl.skysync.database.tables.BalloonTable
import ch.epfl.skysync.database.tables.BasketTable
import ch.epfl.skysync.database.tables.FlightTable
import ch.epfl.skysync.database.tables.FlightTypeTable
import ch.epfl.skysync.database.tables.UserTable
import ch.epfl.skysync.database.tables.VehicleTable
/** Container class that store all database tables */
class Repository(db: FirestoreDatabase) {
val availabilityTable: AvailabilityTable = AvailabilityTable(db)
val balloonTable: BalloonTable = BalloonTable(db)
val basketTable: BasketTable = BasketTable(db)
val flightTable: FlightTable = FlightTable(db)
val flightTypeTable: FlightTypeTable = FlightTypeTable(db)
val userTable: UserTable = UserTable(db)
val vehicleTable: VehicleTable = VehicleTable(db)
}
| skysync/app/src/main/java/ch/epfl/skysync/Repository.kt | 2541455282 |
package ch.epfl.skysync.models.calendar
import ch.epfl.skysync.models.UNSET_ID
import java.time.LocalDate
/** Represents the type of a cell difference between two calendar */
enum class CalendarDifferenceType {
ADDED,
UPDATED,
DELETED,
}
/** represents a calendar for availabilities */
class AvailabilityCalendar(cells: MutableList<Availability> = mutableListOf()) :
CalendarModel<Availability>(cells = cells) {
/**
* changes the status of the availability of given date and timeSlot if found in the calendar
*
* @param date: the date of the availability to change
* @param timeSlot: the timeSlot of the availability to change
* @param status: the new status
*/
fun setAvailabilityByDate(date: LocalDate, timeSlot: TimeSlot, status: AvailabilityStatus) {
setByDate(date, timeSlot) { d, t, old ->
old?.copy(status = status) ?: Availability(UNSET_ID, status, t, d)
}
}
/** @return current AvailabilityStatus for given date and timeSlot if any, else UNDEFINED */
fun getAvailabilityStatus(date: LocalDate, timeSlot: TimeSlot): AvailabilityStatus {
return getByDate(date, timeSlot)?.status ?: AvailabilityStatus.UNDEFINED
}
/**
* changes the AvailabilityStatus of the Availability for the given date and timeSlot (if found)
* to the next AvailabilityStatus (round robin)
*
* @param date: date of the Availability of which to change the status
* @param timeSlot: timeSlot of the Availability of which to change the status
* @return the new AvailabilityStatus if successfully modified, else null
*/
fun nextAvailabilityStatus(date: LocalDate, timeSlot: TimeSlot): AvailabilityStatus {
val currentAvailability = getByDate(date, timeSlot)
val nextAvailabilityStatus: AvailabilityStatus =
currentAvailability?.status?.next()
?: AvailabilityStatus.OK // non-existing entries get init by OK
if (nextAvailabilityStatus == AvailabilityStatus.UNDEFINED) {
removeByDate(date, timeSlot)
} else {
setAvailabilityByDate(date, timeSlot, nextAvailabilityStatus)
}
return nextAvailabilityStatus
}
/**
* Returns the differences between this and the other calendar, from the point of view of the
* other calendar (that is, [CalendarDifferenceType.ADDED] means that [other] has an added
* availability compared to this)
*
* @param other The other calendar
*/
fun getDifferencesWithOtherCalendar(
other: AvailabilityCalendar
): List<Pair<CalendarDifferenceType, Availability>> {
val differences = mutableListOf<Pair<CalendarDifferenceType, Availability>>()
for (otherAvailability in other.cells) {
val date = otherAvailability.date
val timeSlot = otherAvailability.timeSlot
val thisAvailability = getByDate(date, timeSlot)
if (otherAvailability == thisAvailability) {
continue
}
if (thisAvailability == null || thisAvailability.status == AvailabilityStatus.UNDEFINED) {
differences.add(Pair(CalendarDifferenceType.ADDED, otherAvailability))
} else if (otherAvailability.status == AvailabilityStatus.UNDEFINED) {
differences.add(Pair(CalendarDifferenceType.DELETED, thisAvailability))
} else {
differences.add(Pair(CalendarDifferenceType.UPDATED, otherAvailability))
}
}
for (thisAvailability in cells) {
val date = thisAvailability.date
val timeSlot = thisAvailability.timeSlot
val otherAvailability = other.getByDate(date, timeSlot)
if (otherAvailability == null) {
differences.add(Pair(CalendarDifferenceType.DELETED, thisAvailability))
}
}
return differences
}
fun copy(): AvailabilityCalendar {
return AvailabilityCalendar(cells.toMutableList())
}
}
| skysync/app/src/main/java/ch/epfl/skysync/models/calendar/AvailabilityCalendar.kt | 341938328 |
package ch.epfl.skysync.models.calendar
import ch.epfl.skysync.models.flight.Flight
import java.time.LocalDate
/** group of flights per date and timeSlot */
data class FlightGroup(
override val date: LocalDate,
override val timeSlot: TimeSlot,
val flights: List<Flight>,
) : CalendarViewable {
/**
* adds the given flight to the group of flights
*
* @param flight the flight to add
* @return a new FlightGroup with the added flight
*/
fun addFlight(flight: Flight): FlightGroup {
return FlightGroup(date, timeSlot, flights + flight)
}
fun isEmpty(): Boolean {
return flights.isEmpty()
}
fun firstFlight(): Flight? {
return if (!isEmpty()) flights[0] else null
}
}
| skysync/app/src/main/java/ch/epfl/skysync/models/calendar/FlightGroup.kt | 628963251 |
package ch.epfl.skysync.models.calendar
import ch.epfl.skysync.models.UNSET_ID
import java.time.LocalDate
/** Represent the availability of a person for some period (immutable class) */
data class Availability(
val id: String = UNSET_ID,
val status: AvailabilityStatus,
override val timeSlot: TimeSlot,
override val date: LocalDate
) : CalendarViewable
| skysync/app/src/main/java/ch/epfl/skysync/models/calendar/Availability.kt | 2495380861 |
package ch.epfl.skysync.models.calendar
/**
* Represent three statuses: "OK" for available, "MAYBE" for pending confirmation, and "NO" for not
* available
*/
enum class AvailabilityStatus {
OK,
MAYBE,
NO,
UNDEFINED;
fun next(): AvailabilityStatus {
return when (this) {
UNDEFINED -> OK
OK -> MAYBE
MAYBE -> NO
NO -> UNDEFINED
}
}
}
| skysync/app/src/main/java/ch/epfl/skysync/models/calendar/AvailabilityStatus.kt | 2828739084 |
package ch.epfl.skysync.models.calendar
import java.time.LocalDate
/** defines a slot of a calendar that must be uniquely identified by its date and timeSlot */
interface CalendarViewable {
val date: LocalDate
val timeSlot: TimeSlot
}
| skysync/app/src/main/java/ch/epfl/skysync/models/calendar/CalendarViewable.kt | 1548334048 |
package ch.epfl.skysync.models.calendar
import ch.epfl.skysync.models.flight.Flight
import java.time.LocalDate
/** calendar for a group of flights per slot (admin view) */
class FlightGroupCalendar : CalendarModel<FlightGroup>() {
private fun setFlightGroupByDate(date: LocalDate, timeSlot: TimeSlot, flightGroup: FlightGroup) {
setByDate(date, timeSlot) { d, t, old -> flightGroup }
}
/**
* adds the given flight to the existing FlightGroup at slot for (date, timeSlot) or adds a new
* FlightGroup if non exists
*
* @param date the date coordinate of the slot to add the flight to
* @param timeSlot the timeSlot coordinate of the slot to add the flight to
* @param flight the flight to add
*/
fun addFlightByDate(date: LocalDate, timeSlot: TimeSlot, flight: Flight) {
val currentFlightGroup = getByDate(date, timeSlot)
if (currentFlightGroup == null) {
setFlightGroupByDate(date, timeSlot, FlightGroup(date, timeSlot, listOf(flight)))
} else {
setFlightGroupByDate(date, timeSlot, currentFlightGroup.addFlight(flight))
}
}
/**
* @param date date calendar slot coordinate
* @param timeSlot timeSlot calendar slot coordinate
* @return first flight of the FlightGroup for the given slot coordinates
*/
fun getFirstFlightByDate(date: LocalDate, timeSlot: TimeSlot): Flight? {
val flightGroup = getByDate(date, timeSlot) ?: return null
return flightGroup.firstFlight()
}
/**
* @param date date calendar slot coordinate
* @param timeSlot timeSlot calendar slot coordinate
* @return the FlightGroup for the given slot coordinates or null if none exists
*/
fun getFlightGroupByDate(date: LocalDate, timeSlot: TimeSlot): FlightGroup? {
return getByDate(date, timeSlot)
}
}
| skysync/app/src/main/java/ch/epfl/skysync/models/calendar/FlightGroupCalendar.kt | 3605869875 |
package ch.epfl.skysync.models.calendar
/** Represent the day in two time slots, morning (AM) and afternoon (PM) */
enum class TimeSlot {
AM,
PM
}
| skysync/app/src/main/java/ch/epfl/skysync/models/calendar/TimeSlot.kt | 2333230432 |
package ch.epfl.skysync.models.calendar
import java.time.LocalDate
import java.util.SortedSet
/**
* represents a calendar where each slot uniquely defined by its date and timeslot contains a
* CalendarViewable object. Each slot can have exactly one object.
*
* @property cells: the Collection that contains the cells
*
* (mutable class)
*/
abstract class CalendarModel<T : CalendarViewable>(
protected val cells: MutableList<T> = mutableListOf()
) {
/** @return number of entries in calendar */
fun getSize(): Int {
return cells.size
}
/**
* adds the given slots by checking that there are not duplicate slots
*
* @param toAdd the slots to add
* @exception IllegalArgumentException: if multiple slots have the same coordinate (date,
* timeSlot)
*/
fun addCells(toAdd: List<T>) {
for (t in toAdd) {
if (cells.any { it.date == t.date && it.timeSlot == t.timeSlot }) {
throw IllegalArgumentException("Cannot add cells for the same date and time slot twice")
}
cells.add(t)
}
}
/**
* updates the slot (if present) or creates new slot by the given coordinates with the output of
* produceNewValue
*
* @param date the date coordinate of the slot
* @param timeSlot the timeSlot coordinate of the slot
* @param produceNewValue computes a new value as function of the coordinates and the old value
*/
protected fun setByDate(
date: LocalDate,
timeSlot: TimeSlot,
produceNewValue: (LocalDate, TimeSlot, oldValue: T?) -> T
) {
val oldValue = removeByDate(date, timeSlot)
val newValue = produceNewValue(date, timeSlot, oldValue)
cells.add(newValue)
}
/**
* @param date the date of the cell to remove
* @param timeSlot the timeSlot of the cell to remove
* @return the removed value if it was found, null otherwise
*/
protected fun removeByDate(date: LocalDate, timeSlot: TimeSlot): T? {
val oldValue = getByDate(date, timeSlot)
if (oldValue != null) {
cells.remove(oldValue)
}
return oldValue
}
/**
* @param date date coordinate of slot
* @param timeSlot timeSlot coordinate of slot
* @return slot for given coordinates if found, else null
*/
protected fun getByDate(date: LocalDate, timeSlot: TimeSlot): T? {
return cells.firstOrNull { it.date == date && it.timeSlot == timeSlot }
}
/** Return a set of the cells, sorted by date and time slot */
private fun getSortedSetOfCells(): SortedSet<T> {
return cells.toSortedSet(
Comparator<T> { a, b -> a.date.compareTo(b.date) }.thenBy { it.timeSlot })
}
override fun hashCode(): Int {
return getSortedSetOfCells().hashCode()
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (other::class != this::class) return false
// we do not take into account the order in which the cells have been added
// when performing equality check
return (other as CalendarModel<*>).getSortedSetOfCells() == this.getSortedSetOfCells()
}
}
| skysync/app/src/main/java/ch/epfl/skysync/models/calendar/CalendarModel.kt | 1030409618 |
package ch.epfl.skysync.models.flight
import ch.epfl.skysync.models.UNSET_ID
data class Basket(val name: String, val hasDoor: Boolean, val id: String = UNSET_ID)
| skysync/app/src/main/java/ch/epfl/skysync/models/flight/Basket.kt | 3481446590 |
package ch.epfl.skysync.models.flight
import androidx.compose.ui.graphics.Color
import ch.epfl.skysync.ui.theme.lightBlue
import ch.epfl.skysync.ui.theme.lightGray
import ch.epfl.skysync.ui.theme.lightGreen
enum class FlightStatus(val text: String, val displayColor: Color) {
IN_PLANNING("planned", lightGray), // still missing some information
READY_FOR_CONFIRMATION("ready", lightBlue), // has all the information needed to be confirmed
CONFIRMED("confirmed", lightGreen); // has been confirmed
// IN_PROGRESS("in progress", lightOrange), // is currently happening (flight day)
// MISSING_REPORT("missing report", lightBrown), // landed but missing the report
// COMPLETED("completed", lightViolet);
override fun toString(): String {
return text
}
}
| skysync/app/src/main/java/ch/epfl/skysync/models/flight/FlightStatus.kt | 2161077085 |
package ch.epfl.skysync.models.flight
/**
* defines the different balloon sizes/qualifications with the natural ordering small < medium <
* large
*/
enum class BalloonQualification {
SMALL,
MEDIUM,
LARGE;
/** returns true if this qualification >= givenQualification */
fun greaterEqual(qualification: BalloonQualification): Boolean {
return this.ordinal >= qualification.ordinal
}
}
| skysync/app/src/main/java/ch/epfl/skysync/models/flight/BalloonQualification.kt | 2044149937 |
package ch.epfl.skysync.models.flight
import ch.epfl.skysync.models.UNSET_ID
/**
* represents a particular flight type
*
* @property name name of the type
* @property specialRoles roles in addition to the BASE_ROLES(crew, pilot)
*/
data class FlightType(
val name: String,
val specialRoles: List<RoleType> = emptyList(),
val id: String = UNSET_ID
) {
companion object {
val DISCOVERY = FlightType("Discovery")
val PREMIUM = FlightType("Premium")
val FONDUE = FlightType("Fondue", listOf(RoleType.MAITRE_FONDUE))
val HIGH_ALTITUDE = FlightType("High Altitude", listOf(RoleType.OXYGEN_MASTER))
val ALL_FLIGHTS =
listOf(
DISCOVERY,
PREMIUM,
FONDUE,
HIGH_ALTITUDE,
)
}
}
/** Minimal set of roles present in each FlightType => PILOT and CREW */
val BASE_ROLES =
listOf(
RoleType.PILOT,
RoleType.CREW,
)
| skysync/app/src/main/java/ch/epfl/skysync/models/flight/FlightType.kt | 2748928252 |
package ch.epfl.skysync.models.flight
import ch.epfl.skysync.models.UNSET_ID
/**
* represents a balloon (envelope)
*
* @property name the name id of the balloon
* @property qualification classification of balloon size
* @property id: the db id
*/
data class Balloon(
val name: String,
val qualification: BalloonQualification,
val id: String = UNSET_ID
)
| skysync/app/src/main/java/ch/epfl/skysync/models/flight/Balloon.kt | 2767977563 |
package ch.epfl.skysync.models.flight
import ch.epfl.skysync.models.calendar.TimeSlot
import java.time.LocalDate
import java.time.LocalTime
data class ConfirmedFlight(
override val id: String,
override val nPassengers: Int,
override val team: Team,
override val flightType: FlightType,
override val balloon: Balloon,
override val basket: Basket,
override val date: LocalDate,
override val timeSlot: TimeSlot,
override val vehicles: List<Vehicle>,
val remarks: List<String>,
val color: FlightColor = FlightColor.NO_COLOR,
val meetupTimeTeam: LocalTime,
val departureTimeTeam: LocalTime,
val meetupTimePassenger: LocalTime,
val meetupLocationPassenger: String,
) : Flight {
override fun getFlightStatus(): FlightStatus {
return FlightStatus.CONFIRMED
}
}
| skysync/app/src/main/java/ch/epfl/skysync/models/flight/ConfirmedFlight.kt | 2437268184 |
package ch.epfl.skysync.models.flight
import ch.epfl.skysync.models.UNSET_ID
/**
* represents a vehicle
*
* @property name of the vehicle
* @property id firebase id
*/
data class Vehicle(val name: String, val id: String = UNSET_ID)
| skysync/app/src/main/java/ch/epfl/skysync/models/flight/Vehicle.kt | 1368067338 |
package ch.epfl.skysync.models.flight
import ch.epfl.skysync.models.user.User
/**
* represents group of roles that belong to one flight operation
*
* @property roles the list of roles that belong to one flight operation (immutable class)
*/
data class Team(val roles: List<Role>) {
/**
* checks if every role has a user assigned to it.
*
* @return True if at least one role and every role has a user assigned to it.
*/
fun isComplete(): Boolean {
return roles.isNotEmpty() && roles.all { it.isAssigned() }
}
/** assigns the given user to the first role with the given role type */
fun assign(user: User, roleType: RoleType): Team {
// Todo: to be implemented
throw NotImplementedError()
}
/**
* @param rolesToAdd: the roles that will be added to this team
* @return new team instance with the added roles
*/
fun addRoles(rolesToAdd: List<Role>): Team {
val newRoles = rolesToAdd + roles
return Team(newRoles)
}
/**
* @param rolesToAdd: the roleTypes for which a role will be added to this team
* @return new team instance with the added roles
*/
fun addRolesFromRoleType(rolesToAdd: List<RoleType>): Team {
if (rolesToAdd.isEmpty()) return this
return addRoles(Role.initRoles(rolesToAdd))
}
override fun hashCode(): Int {
return roles.sortedBy { it.roleType }.hashCode()
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (other::class != this::class) return false
// we do not take into account the order in which the roles have been added
// when performing equality check
return (other as Team).roles.sortedBy { it.roleType } == this.roles.sortedBy { it.roleType }
}
}
| skysync/app/src/main/java/ch/epfl/skysync/models/flight/Team.kt | 897995669 |
package ch.epfl.skysync.models.flight
enum class RoleType {
PILOT,
CREW,
SERVICE_ON_BOARD,
MAITRE_FONDUE,
OXYGEN_MASTER,
TRANSLATION,
ON_BOARD // if no other more specific role applies
}
| skysync/app/src/main/java/ch/epfl/skysync/models/flight/RoleType.kt | 2712337092 |
package ch.epfl.skysync.models.flight
import ch.epfl.skysync.models.user.User
/**
* represents a role as part of a flight that needs to be assumed by some user
*
* @property roleType the type of this role
* @property assignedUser the user that will assume this role
* @property confirmedAttendance one flight is confirmed keeps track if the assuming user has
* confirmed his presence
*
* (immutable class)
*/
data class Role(
val roleType: RoleType,
var assignedUser: User? = null,
) {
/**
* assigns a given user to this role
*
* @param user: the user to assign to this role
*/
fun assign(user: User): Role {
return Role(roleType, user)
}
/** return true if this role was assumed by some user */
fun isAssigned(): Boolean {
return assignedUser != null
}
/**
* @param roleType the RoleType to compare with this role's RoleType
* @return true if this role has the given role type
*/
fun isOfRoleType(roleType: RoleType): Boolean {
return roleType == this.roleType
}
companion object {
/**
* produces a list of Role from a list of RoleTypes. If a RoleType R appears X times, the
* returned list will contain X distinct roles of RoleType R
*
* @param roleList the list of RoleTypes for which to create roles
* @return list of initialised roles (one role for each role type)
*/
fun initRoles(roleList: List<RoleType>): List<Role> {
return roleList.map { Role(it) }
}
}
}
| skysync/app/src/main/java/ch/epfl/skysync/models/flight/Role.kt | 3776835960 |
package ch.epfl.skysync.models.flight
import ch.epfl.skysync.models.calendar.TimeSlot
import java.time.LocalDate
import java.time.LocalTime
data class PlannedFlight(
override val id: String,
override val nPassengers: Int,
override val flightType: FlightType,
override val team: Team =
Team(listOf())
.addRolesFromRoleType(BASE_ROLES)
.addRolesFromRoleType(flightType.specialRoles),
override val balloon: Balloon?,
override val basket: Basket?,
override val date: LocalDate,
override val timeSlot: TimeSlot,
override val vehicles: List<Vehicle>
) : Flight {
fun readyToBeConfirmed(): Boolean {
return team.isComplete() &&
nPassengers > 0 &&
balloon != null &&
basket != null &&
vehicles.isNotEmpty()
}
/** returns a new flight with a role added to the team for each roleType in the given list to */
fun addRoles(roles: List<RoleType>): PlannedFlight {
return copy(team = team.addRolesFromRoleType(roles))
}
fun confirmFlight(
meetupTimeTeam: LocalTime,
departureTimeTeam: LocalTime,
meetupTimePassenger: LocalTime,
meetupLocationPassenger: String,
remarks: List<String>,
color: FlightColor
): ConfirmedFlight {
if (!readyToBeConfirmed()) {
throw IllegalStateException("Flight is not ready to be confirmed")
}
return ConfirmedFlight(
id,
nPassengers,
team,
flightType,
balloon!!,
basket!!,
date,
timeSlot,
vehicles,
remarks = remarks,
color = color,
meetupTimeTeam = meetupTimeTeam,
departureTimeTeam = departureTimeTeam,
meetupTimePassenger = meetupTimePassenger,
meetupLocationPassenger = meetupLocationPassenger)
}
override fun getFlightStatus(): FlightStatus {
return if (readyToBeConfirmed()) {
FlightStatus.READY_FOR_CONFIRMATION
} else {
FlightStatus.IN_PLANNING
}
}
fun setId(id: String): PlannedFlight {
return copy(id = id)
}
}
| skysync/app/src/main/java/ch/epfl/skysync/models/flight/PlannedFlight.kt | 832982349 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.