Skip to content

Commit

Permalink
Setting up server filesystem test
Browse files Browse the repository at this point in the history
  • Loading branch information
Wavesonics committed Jul 4, 2024
1 parent f021230 commit 63361e3
Show file tree
Hide file tree
Showing 11 changed files with 242 additions and 0 deletions.
1 change: 1 addition & 0 deletions base/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ kotlin {
dependencies {
implementation(kotlin("test"))
implementation(libs.kotlin.reflect)
implementation(libs.okio)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.darkrockstudios.apps.hammer.project.synchronizers

import PROJECT_1_NAME
import com.darkrockstudios.apps.hammer.base.http.ApiProjectEntity
import com.darkrockstudios.apps.hammer.project.ProjectDefinition
import com.darkrockstudios.apps.hammer.utilities.isFailure
import com.darkrockstudios.apps.hammer.utils.BaseTest
import createProject
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json
import okio.fakefilesystem.FakeFileSystem
import org.junit.Before
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue

class ServerSceneSynchronizerLoadTest : BaseTest() {

protected lateinit var fileSystem: FakeFileSystem
protected lateinit var json: Json
protected lateinit var log: io.ktor.util.logging.Logger

@Before
override fun setup() {
super.setup()

fileSystem = FakeFileSystem()
json = mockk()

log = mockk(relaxed = true)
}

@Test
fun `Decode Scene JSON - SerializationException`() = runTest {
val userId = 1L
val entityId = 1
val projectDef = ProjectDefinition(PROJECT_1_NAME)

createProject(userId, projectDef.name, fileSystem)

val exception = SerializationException("test")
every { json.decodeFromString<ApiProjectEntity.SceneEntity>(any(), any()) } answers {
throw exception
}

val synchronizer = ServerSceneSynchronizer(fileSystem, json, log)
val result = synchronizer.loadEntity(userId, projectDef, entityId)
assertTrue(isFailure(result))
assertEquals(exception, result.exception)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package com.darkrockstudios.apps.hammer.utils

import okio.Path.Companion.toOkioPath
import okio.fakefilesystem.FakeFileSystem
import java.io.File
import java.io.IOException

object FileResourcesUtils {
private fun getResourceFiles(clazz: Class<*>, path: String): List<File> {
val files = mutableListOf<File>()

val dirURL = clazz.classLoader.getResource(path)!!
val file = File(dirURL.toURI())
files.addAll(getResourceFiles(file))

return files
}

private fun getResourceFiles(file: File): List<File> {
val files = mutableListOf<File>()

files.add(file)
if (file.isDirectory) {
val allFiles = file.listFiles()
allFiles?.forEach { child ->
files.addAll(getResourceFiles(child))
}
}

return files
}

@Throws(IOException::class)
fun copyResourceFolderToFakeFileSystem(
from: okio.Path,
to: okio.Path,
ffs: FakeFileSystem
) {
val clazz = FileResourcesUtils::class.java
val resFiles = getResourceFiles(clazz, from.toString())
.filter { it.name != ".gitkeep" }

val dirURL = clazz.classLoader.getResource(from.toString())!!
val fromDir = File(dirURL.toURI())

resFiles.forEach { sourceFile ->
val relPath = sourceFile.toOkioPath().relativeTo(fromDir.toOkioPath())

var targetPath = to / from
relPath.segments.forEach { segment ->
targetPath /= segment
}

if (sourceFile.isDirectory) {
ffs.createDirectories(targetPath)
} else {
ffs.createDirectories(targetPath.parent!!)

sourceFile.bufferedReader().use { reader ->
ffs.write(targetPath.normalized(), false) {
writeUtf8(reader.readText())
}
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import com.darkrockstudios.apps.hammer.project.ProjectDefinition
import com.darkrockstudios.apps.hammer.project.ProjectFilesystemDatasource
import com.darkrockstudios.apps.hammer.projects.ProjectsFileSystemDatasource
import com.darkrockstudios.apps.hammer.utils.FileResourcesUtils
import okio.Path
import okio.Path.Companion.toPath
import okio.fakefilesystem.FakeFileSystem

const val PROJECT_1_NAME = "Test Project 1"
val projectNames = listOf(
PROJECT_1_NAME,
)

fun getRootDirectory(ffs: FakeFileSystem): Path {
val rootDir = ProjectsFileSystemDatasource.getRootDirectory(ffs)
return rootDir
}

fun createRootDirectory(ffs: FakeFileSystem) {
val rootDir = getRootDirectory(ffs)
ffs.createDirectories(rootDir)
}

fun getUserDirectory(userId: Long, ffs: FakeFileSystem): Path {
return ProjectsFileSystemDatasource.getUserDirectory(userId, ffs)
}

fun getProjectDirectory(userId: Long, projectName: String, ffs: FakeFileSystem): Path {
return ProjectFilesystemDatasource.getProjectDirectory(
userId,
ProjectDefinition(projectName),
ffs
)
}

/**
* Create an in-mem project from a predefined resource
*/
fun createProject(userId: Long, projectName: String, ffs: FakeFileSystem) {
val projDir = getProjectDirectory(userId, projectName, ffs)
ffs.createDirectories(projDir)

FileResourcesUtils.copyResourceFolderToFakeFileSystem(
projectName.toPath(),
getUserDirectory(userId, ffs),
ffs
)
}
13 changes: 13 additions & 0 deletions server/src/test/resources/Test Project 1/entities/1-scene.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"type": "SCENE",
"id": 1,
"sceneType": "Scene",
"order": 0,
"name": "Title",
"path": [
0
],
"content": "**ALICE'S ADVENTURES IN WONDERLAND**\n\n Lewis Carroll\n\n**THE MILLENNIUM FULCRUM EDITION 2.9**",
"outline": "",
"notes": ""
}
13 changes: 13 additions & 0 deletions server/src/test/resources/Test Project 1/entities/2-scene.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"type": "SCENE",
"id": 2,
"sceneType": "Group",
"order": 1,
"name": "Chapter I",
"path": [
0
],
"content": "",
"outline": "",
"notes": ""
}
6 changes: 6 additions & 0 deletions server/src/test/resources/Test Project 1/entities/3-note.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"type": "NOTE",
"id": 3,
"content": "Symbolism\nThree cards painting the white rose tree red to cover it up from the Queen of Hearts.\n\nCarroll's biographer Morton N. Cohen reads Alice as a roman à clef populated with real figures from Carroll's life. Alice is based on Alice Liddell; the Dodo is Carroll; Wonderland is Oxford; even the Mad Tea Party, according to Cohen, is a send-up of Alice's own birthday party.[41] The critic Jan Susina rejects Cohen's account, arguing that Alice the character bears a tenuous relationship with Alice Liddell.\n\nBeyond its refashioning of Carroll's everyday life, Cohen argues, Alice critiques Victorian ideals of childhood. It is an account of \"the child's plight in Victorian upper-class society\" in which Alice's mistreatment by the creatures of Wonderland reflects Carroll's own mistreatment by older people as a child.",
"created": "2023-01-30T06:32:42.692656900Z"
}

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"type": "TIMELINE_EVENT",
"id": 6,
"order": 0,
"date": "Sep 1, 1865",
"content": "Alice catches sight of the White Rabbit running down the rabbit-hole. She is curious, and decides to follow him."
}
14 changes: 14 additions & 0 deletions server/src/test/resources/Test Project 1/entities/7-scene.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"type": "SCENE",
"id": 7,
"sceneType": "Scene",
"order": 0,
"name": "At Home",
"path": [
0,
2
],
"content": "**Down the Rabbit-Hole**\n\n Alice was beginning to get very tired of sitting by her sister\non the bank, and of having nothing to do: once or twice she had\npeeped into the book her sister was reading, but it had no\npictures or conversations in it, `and what is the use of a book,'\nthought Alice `without pictures or conversation?'\n\n So she was considering in her own mind (as well as she could,\nfor the hot day made her feel very sleepy and stupid), whether\nthe pleasure of making a daisy-chain would be worth the trouble\nof getting up and picking the daisies, when suddenly a White\nRabbit with pink eyes ran close by her.\n\n There was nothing so VERY remarkable in that; nor did Alice\nthink it so VERY much out of the way to hear the Rabbit say to\nitself, `Oh dear! Oh dear! I shall be late!' (when she thought\nit over afterwards, it occurred to her that she ought to have\nwondered at this, but at the time it all seemed quite natural);\nbut when the Rabbit actually TOOK A WATCH OUT OF ITS WAISTCOAT-\nPOCKET, and looked at it, and then hurried on, Alice started to\nher feet, for it flashed across her mind that she had never\nbefore seen a rabbit with either a waistcoat-pocket, or a watch to\ntake out of it, and burning with curiosity, she ran across the\nfield after it, and fortunately was just in time to see it pop\ndown a large rabbit-hole under the hedge.\n\n In another moment down went Alice after it, never once\nconsidering how in the world she was to get out again.\n\n The rabbit-hole went straight on like a tunnel for some way,\nand then dipped suddenly down, so suddenly that Alice had not a\nmoment to think about stopping herself before she found herself\nfalling down a very deep well.\n\n Either the well was very deep, or she fell very slowly, for she\nhad plenty of time as she went down to look about her and to\nwonder what was going to happen next. First, she tried to look\ndown and make out what she was coming to, but it was too dark to\nsee anything; then she looked at the sides of the well, and\nnoticed that they were filled with cupboards and book-shelves;\nhere and there she saw maps and pictures hung upon pegs. She\ntook down a jar from one of the shelves as she passed; it was\nlabelled `ORANGE MARMALADE', but to her great disappointment it\nwas empty: she did not like to drop the jar for fear of killing\nsomebody, so managed to put it into one of the cupboards as she\nfell past it.\n\n `Well!' thought Alice to herself, `after such a fall as this, I\nshall think nothing of tumbling down stairs! How brave they'll\nall think me at home! Why, I wouldn't say anything about it,\neven if I fell off the top of the house!' (Which was very likely\ntrue.)\n\n Down, down, down. Would the fall NEVER come to an end! `I\nwonder how many miles I've fallen by this time?' she said aloud.\n`I must be getting somewhere near the centre of the earth. Let\nme see: that would be four thousand miles down, I think--' (for,\nyou see, Alice had learnt several things of this sort in her\nlessons in the schoolroom, and though this was not a VERY good\nopportunity for showing off her knowledge, as there was no one to\nlisten to her, still it was good practice to say it over) `--yes,\nthat's about the right distance--but then I wonder what Latitude\nor Longitude I've got to?' (Alice had no idea what Latitude was,\nor Longitude either, but thought they were nice grand words to\nsay.)\n\n Presently she began again. `I wonder if I shall fall right\nTHROUGH the earth! How funny it'll seem to come out among the\npeople that walk with their heads downward! The Antipathies, I\nthink--' (she was rather glad there WAS no one listening, this\ntime, as it didn't sound at all the right word) `--but I shall\nhave to ask them what the name of the country is, you know.\nPlease, Ma'am, is this New Zealand or Australia?' (and she tried\nto curtsey as she spoke--fancy CURTSEYING as you're falling\nthrough the air! Do you think you could manage it?) `And what\nan ignorant little girl she'll think me for asking! No, it'll\nnever do to ask: perhaps I shall see it written up somewhere.'\n\n Down, down, down. There was nothing else to do, so Alice soon\nbegan talking again. `Dinah'll miss me very much to-night, I\nshould think!' (Dinah was the cat.) `I hope they'll remember\nher saucer of milk at tea-time. Dinah my dear! I wish you were\ndown here with me! There are no mice in the air, I'm afraid, but\nyou might catch a bat, and that's very like a mouse, you know.\nBut do cats eat bats, I wonder?' And here Alice began to get\nrather sleepy, and went on saying to herself, in a dreamy sort of\nway, `Do cats eat bats? Do cats eat bats?' and sometimes, `Do\nbats eat cats?' for, you see, as she couldn't answer either\nquestion, it didn't much matter which way she put it. She felt\nthat she was dozing off, and had just begun to dream that she\nwas walking hand in hand with Dinah, and saying to her very\nearnestly, `Now, Dinah, tell me the truth: did you ever eat a\nbat?' when suddenly, thump! thump! down she came upon a heap of\nsticks and dry leaves, and the fall was over.\n\n Alice was not a bit hurt, and she jumped up on to her feet in a\nmoment: she looked up, but it was all dark overhead; before her\nwas another long passage, and the White Rabbit was still in\nsight, hurrying down it. There was not a moment to be lost:\naway went Alice like the wind, and was just in time to hear it\nsay, as it turned a corner, `Oh my ears and whiskers, how late\nit's getting!' She was close behind it when she turned the\ncorner, but the Rabbit was no longer to be seen: she found\nherself in a long, low hall, which was lit up by a row of lamps\nhanging from the roof.\n\n There were doors all round the hall, but they were all locked;\nand when Alice had been all the way down one side and up the\nother, trying every door, she walked sadly down the middle,\nwondering how she was ever to get out again.\n\n Suddenly she came upon a little three-legged table, all made of\nsolid glass; there was nothing on it except a tiny golden key,\nand Alice's first thought was that it might belong to one of the\ndoors of the hall; but, alas! either the locks were too large, or\nthe key was too small, but at any rate it would not open any of\nthem. However, on the second time round, she came upon a low\ncurtain she had not noticed before, and behind it was a little\ndoor about fifteen inches high: she tried the little golden key\nin the lock, and to her great delight it fitted!\n\n Alice opened the door and found that it led into a small\npassage, not much larger than a rat-hole: she knelt down and\nlooked along the passage into the loveliest garden you ever saw.\nHow she longed to get out of that dark hall, and wander about\namong those beds of bright flowers and those cool fountains, but\nshe could not even get her head though the doorway; `and even if\nmy head would go through,' thought poor Alice, `it would be of\nvery little use without my shoulders. Oh, how I wish\nI could shut up like a telescope! I think I could, if I only\nknow how to begin.' For, you see, so many out-of-the-way things\nhad happened lately, that Alice had begun to think that very few\nthings indeed were really impossible.\n\n There seemed to be no use in waiting by the little door, so she\nwent back to the table, half hoping she might find another key on\nit, or at any rate a book of rules for shutting people up like\ntelescopes: this time she found a little bottle on it, (`which\ncertainly was not here before,' said Alice,) and round the neck\nof the bottle was a paper label, with the words `DRINK ME'\nbeautifully printed on it in large letters.\n\n It was all very well to say `Drink me,' but the wise little\nAlice was not going to do THAT in a hurry. `No, I'll look\nfirst,' she said, `and see whether it's marked \"poison\" or not';\nfor she had read several nice little histories about children who\nhad got burnt, and eaten up by wild beasts and other unpleasant\nthings, all because they WOULD not remember the simple rules\ntheir friends had taught them: such as, that a red-hot poker\nwill burn you if you hold it too long; and that if you cut your\nfinger VERY deeply with a knife, it usually bleeds; and she had\nnever forgotten that, if you drink much from a bottle marked\n`poison,' it is almost certain to disagree with you, sooner or\nlater.\n\n However, this bottle was NOT marked `poison,' so Alice ventured\nto taste it, and finding it very nice, (it had, in fact, a sort\nof mixed flavour of cherry-tart, custard, pine-apple, roast\nturkey, toffee, and hot buttered toast,) she very soon finished\nit off.\n\n \n\n \n\n ",
"outline": "",
"notes": ""
}
5 changes: 5 additions & 0 deletions server/src/test/resources/Test Project 1/syncData.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"lastSync": "-100001-12-31T23:59:59.999999999Z",
"deletedProjects": [
]
}

0 comments on commit 63361e3

Please sign in to comment.