How to use char method of test.Open class

Best Mockito-kotlin code snippet using test.Open.char

KosonTest.kt

Source:KosonTest.kt Github

copy

Full Screen

...32 "double" to 7.633 "float" to 3.2f34 "long" to 34L35 "int" to 936 "char" to 'e'37 "short" to 12.toShort()38 "byte" to 0x3239 "boolean" to false40 "object" to obj { }41 "emptyArray" to arr42 "array" to arr["test"]43 "arrayFromIterable" to arr[listOf("test")]44 "null" to null45 "simple" to SimpleObject46 "custom" to CustomizedKoson47 "raw" to rawJson("{}")48 }.toString()49 assertThat(representation).isValidJSON()50 assertThat(representation).isEqualTo("""{"string":"value","double":7.6,"float":3.2,"long":34,"int":9,"char":"e","short":12,"byte":50,"boolean":false,"object":{},"emptyArray":[],"array":["test"],"arrayFromIterable":["test"],"null":null,"simple":"SimpleObject","custom":{"custom":11},"raw":{}}""")51 }52 @Test53 fun `should inline newlines in multi line strings`() {54 val representation = obj {55 "lines" to """56 line 157 line 258 line 359 """.trimIndent()60 }.toString()61 assertThat(representation).isEqualTo("""{"lines":"line 1\nline 2\nline 3"}""")62 }63 @Test64 fun `should inline newlines in strings`() {65 val representation = obj {66 "lines" to "line 1\nline 2\nline 3"67 }.toString()68 assertThat(representation).isEqualTo("""{"lines":"line 1\nline 2\nline 3"}""")69 }70 class Person(71 private val firstName: String,72 private val lastName: String,73 private val age: Int74 ) : CustomKoson {75 override fun serialize() = obj {76 "usualName" to "$firstName $lastName"77 "age" to age78 }79 }80 class Status(private val id: String, private val name: String) : CustomKoson {81 override fun serialize() = obj {82 "id" to id83 "name" to name84 }85 }86 @Test87 fun `CustomKoson should be serialized according to override`() {88 val name = "myName"89 val description = "desc"90 val status = Status("OK", "Nice")91 val representation = obj {92 "data" to obj {93 "name" to name94 "description" to description95 "status" to status96 }97 }.toString()98 assertThat(representation).isEqualTo("""{"data":{"name":"myName","description":"desc","status":{"id":"OK","name":"Nice"}}}""")99 }100 @Test101 fun `nullable CustomKoson should be serialized`() {102 val name = "myName"103 val description = "desc"104 val status: Status? = null105 val representation = obj {106 "data" to obj {107 "name" to name108 "description" to description109 "status" to status110 }111 }.toString()112 assertThat(representation).isEqualTo("""{"data":{"name":"myName","description":"desc","status":null}}""")113 }114 @Test115 fun `array with all possible types of value`() {116 val representation = arr[117 "value",118 7.6,119 3.2f,120 34L,121 9,122 'e',123 12.toShort(),124 0x32,125 false,126 obj { },127 arr,128 arr["test"],129 arr[listOf("test", "from", "iterable")],130 null,131 SimpleObject,132 CustomizedKoson,133 rawJson("{}")134 ].toString()135 assertThat(representation).isValidJSON()136 assertThat(representation)137 .isEqualTo("""["value",7.6,3.2,34,9,"e",12,50,false,{},[],["test"],["test","from","iterable"],null,"SimpleObject",{"custom":11},{}]""")138 }139 object ContainsDoubleQuotesAndBackslashes {140 override fun toString(): String = """"un\for"tuna\te""""141 }142 object ContainsDoubleQuotes {143 override fun toString(): String = """"unfor"tunate""""144 }145 object ContainsBackslashes {146 override fun toString(): String = """\unfor\tunate\"""147 }148 object ContainsNewLines {149 override fun toString(): String = """unfor150 |tunate""".trimMargin()151 }152 @Nested153 inner class EdgeCases {154 @Test155 fun `array containing this as a value should render`() {156 val array = arr[this]157 val representation = array.toString()158 assertThat(representation).isValidJSON()159 assertThat(representation).startsWith("[")160 assertThat(representation).endsWith("]")161 }162 @Test163 fun `object with null as key should render`() {164 val obj = obj {165 null to "content"166 }167 val representation = obj.toString()168 assertThat(representation).isValidJSON()169 assertThat(representation).isEqualTo("{}")170 }171 @Test172 fun `object with value containing backslash char`() {173 val obj = obj {174 "content" to "va\\lue"175 }176 val representation = obj.toString()177 assertThat(representation).isValidJSON()178 assertThat(representation).isEqualTo("""{"content":"va\\lue"}""")179 }180 @Test181 fun `object with custom value containing backslash char`() {182 val obj = obj {183 "content" to ContainsBackslashes184 }185 val representation = obj.toString()186 assertThat(representation).isValidJSON()187 assertThat(representation).isEqualTo("""{"content":"\\unfor\\tunate\\"}""")188 }189 @Test190 fun `object with value containing doublequotes char`() {191 val obj = obj {192 "content" to "va\"lue"193 }194 val representation = obj.toString()195 assertThat(representation).isValidJSON()196 assertThat(representation).isEqualTo("""{"content":"va\"lue"}""")197 }198 @Test199 fun `object with custom value containing doublequotes char`() {200 val obj = obj {201 "content" to ContainsDoubleQuotes202 }203 val representation = obj.toString()204 assertThat(representation).isValidJSON()205 assertThat(representation).isEqualTo("""{"content":"\"unfor\"tunate\""}""")206 }207 @Test208 fun `object with custom value containing backslashes and doublequotes char`() {209 val obj = obj {210 "content" to ContainsDoubleQuotesAndBackslashes211 }212 val representation = obj.toString()213 assertThat(representation).isValidJSON()214 assertThat(representation).isEqualTo("""{"content":"\"un\\for\"tuna\\te\""}""")215 }216 @Test217 fun `object with value containing new line`() {218 val obj = obj {219 "content" to "va\nlue"220 }221 val representation = obj.toString()222 assertThat(representation).isValidJSON()223 assertThat(representation).isEqualTo("""{"content":"va\nlue"}""")224 }225 @Test226 fun `object with custom value containing new line`() {227 val obj = obj {228 "content" to ContainsNewLines229 }230 val representation = obj.toString()231 assertThat(representation).isValidJSON()232 assertThat(representation).isEqualTo("""{"content":"unfor\ntunate"}""")233 }234 @Test235 fun `object with key containing backslash char`() {236 val obj = obj {237 "va\\lue" to "content"238 }239 val representation = obj.toString()240 assertThat(representation).isValidJSON()241 assertThat(representation).isEqualTo("""{"va\\lue":"content"}""")242 }243 @Test244 fun `object with key containing doublequotes char`() {245 val obj = obj {246 "va\"lue" to "content"247 }248 val representation = obj.toString()249 assertThat(representation).isValidJSON()250 assertThat(representation).isEqualTo("""{"va\"lue":"content"}""")251 }252 @Test253 fun `object with key containing newline`() {254 val obj = obj {255 "va\nlue" to "content"256 }257 val representation = obj.toString()258 assertThat(representation).isValidJSON()259 assertThat(representation).isEqualTo("""{"va\nlue":"content"}""")260 }261 @Test262 fun `object with value containing backslashes and doublequotes chars`() {263 val obj = obj {264 "content" to "[}[]}\\,{][,]\"\"\",\",,[,}}}[]],[}#{}"265 }266 val representation = obj.toString()267 assertThat(representation).isValidJSON()268 assertThat(representation).isEqualTo("""{"content":"[}[]}\\,{][,]\"\"\",\",,[,}}}[]],[}#{}"}""")269 }270 @Test271 fun `object with key containing backslashes and doublequotes chars`() {272 val obj = obj {273 "[}[]}\\,{][,]\"\"\",\",,[,}}}[]],[}#{}" to "content"274 }275 val representation = obj.toString()276 assertThat(representation).isValidJSON()277 assertThat(representation).isEqualTo("""{"[}[]}\\,{][,]\"\"\",\",,[,}}}[]],[}#{}":"content"}""")278 }279 @Test280 fun `array containing backslash char`() {281 val array = arr["va\\lue"]282 val representation = array.toString()283 assertThat(representation).isValidJSON()284 assertThat(representation).isEqualTo("""["va\\lue"]""")285 }286 @Test287 fun `array containing doublequotes char`() {288 val array = arr["va\"lue"]289 val representation = array.toString()290 assertThat(representation).isValidJSON()291 assertThat(representation).isEqualTo("""["va\"lue"]""")292 }293 @Test294 fun `array containing newline char`() {295 val array = arr["va\nlue"]296 val representation = array.toString()297 assertThat(representation).isValidJSON()298 assertThat(representation).isEqualTo("""["va\nlue"]""")299 }300 @Test301 fun `array containing backslashes and doublequotes chars`() {302 val array = arr["[}[]}\\,{][,]\"\"\",\",,[,}}}[]],[}#{}"]303 val representation = array.toString()304 assertThat(representation).isValidJSON()305 assertThat(representation).isEqualTo("""["[}[]}\\,{][,]\"\"\",\",,[,}}}[]],[}#{}"]""")306 }307 }308 @Nested309 inner class ContainingCases {310 @Test311 fun `object containing array`() {312 val representation = obj { "array" to arr }.toString()313 assertThat(representation).isValidJSON()314 assertThat(representation).isEqualTo("""{"array":[]}""")315 }316 @Test317 fun `array containing object`() {318 val representation = arr[obj { }].toString()319 assertThat(representation).isValidJSON()320 assertThat(representation).isEqualTo("[{}]")321 }322 @Test323 fun `object containing object`() {324 val representation = obj { "object" to obj { } }.toString()325 assertThat(representation).isValidJSON()326 assertThat(representation).isEqualTo("""{"object":{}}""")327 }328 @Test329 fun `array containing array`() {330 val representation = arr[arr].toString()331 assertThat(representation).isValidJSON()332 assertThat(representation).isEqualTo("[[]]")333 }334 @Test335 @Suppress("UNUSED_EXPRESSION")336 fun `object not containing a to() should do nothing`() {337 val representation = obj { "content" }.toString()338 assertThat(representation).isValidJSON()339 assertThat(representation).isEqualTo("{}")340 }341 }342 @Nested343 inner class MoreComplexCases {344 @Test345 fun `constructing a bit more complex object`() {346 val obj = obj {347 "key" to 3.4348 "anotherKey" to arr["test", "test2", 1, 2.433, true]349 "nullsAreAllowedToo" to null350 "array" to arr[351 obj {352 "double" to 33.4353 "float" to 345f354 "long" to 21L355 "int" to 42356 "char" to 'a'357 "byte" to 0xAA358 "otherArray" to arr359 "simpleObject" to SimpleObject360 }361 ]362 }363 val representation = obj.toString()364 assertThat(representation).isValidJSON()365 assertThat(representation)366 .isEqualTo("""{"key":3.4,"anotherKey":["test","test2",1,2.433,true],"nullsAreAllowedToo":null,"array":[{"double":33.4,"float":345.0,"long":21,"int":42,"char":"a","byte":170,"otherArray":[],"simpleObject":"SimpleObject"}]}""")367 }368 @Test369 fun `contructing a bit more complex array`() {370 val array = arr["koson", 33.4, 345f, 21L, 42, 'a', 0x21,371 obj {372 "aKey" to "value"373 "insideArray" to arr374 "otherArray" to arr["element", SimpleObject, obj { }]375 }376 ]377 val representation = array.toString()378 assertThat(representation).isValidJSON()379 assertThat(representation)380 .isEqualTo("""["koson",33.4,345.0,21,42,"a",33,{"aKey":"value","insideArray":[],"otherArray":["element","SimpleObject",{}]}]""")381 }382 @Test383 fun `testing an object inlined`() {384 val obj =385 obj { "key" to 3.4; "anotherKey" to arr["test", "test2", 1, 2.433, true]; "nullsAreAllowedToo" to null }386 val representation = obj.toString()387 assertThat(representation).isValidJSON()388 assertThat(representation)389 .isEqualTo("""{"key":3.4,"anotherKey":["test","test2",1,2.433,true],"nullsAreAllowedToo":null}""")390 }391 }392 @Nested393 inner class ExceptionCases {394 @Test395 fun `obj pretty with negative spaces must throw an IAE`() {396 try {397 obj { }.pretty(-3)398 fail { "No exception was thrown" }399 } catch (iae: IllegalArgumentException) {400 assertThat(iae.message!!).isEqualTo("spaces Int must be positive, but was -3.")401 }402 }403 @Test404 fun `array pretty with negative spaces must throw an IAE`() {405 try {406 arr.pretty(-5)407 fail { "No exception was thrown" }408 } catch (iae: IllegalArgumentException) {409 assertThat(iae.message!!).isEqualTo("spaces Int must be positive, but was -5.")410 }411 }412 }413 @Nested414 inner class RuntimeNullables {415 @Test416 fun `object with all nullable types must render`() {417 val string: String? = null418 val double: Double? = null419 val float: Float? = null420 val long: Long? = null421 val int: Int? = null422 val char: Char? = null423 val short: Short? = null424 val byte: Byte? = null425 val boolean: Boolean? = null426 val date: Date? = null427 val obj = obj {428 "string" to string429 "double" to double430 "float" to float431 "long" to long432 "int" to int433 "char" to char434 "short" to short435 "byte" to byte436 "boolean" to boolean437 "date" to date438 }439 val representation = obj.toString()440 assertThat(representation).isValidJSON()441 assertThat(representation).isEqualTo("""{"string":null,"double":null,"float":null,"long":null,"int":null,"char":null,"short":null,"byte":null,"boolean":null,"date":null}""")442 }443 @Test444 fun `object with all nullable Java types must render`() {445 val obj = obj {446 "string" to NullableTypes.STRING447 "double" to NullableTypes.DOUBLE448 "float" to NullableTypes.FLOAT449 "long" to NullableTypes.LONG450 "int" to NullableTypes.INT451 "char" to NullableTypes.CHAR452 "short" to NullableTypes.SHORT453 "byte" to NullableTypes.BYTE454 "boolean" to NullableTypes.BOOLEAN455 "date" to NullableTypes.DATE456 }457 val representation = obj.toString()458 assertThat(representation).isValidJSON()459 assertThat(representation).isEqualTo("""{"string":null,"double":null,"float":null,"long":null,"int":null,"char":null,"short":null,"byte":null,"boolean":null,"date":null}""")460 }461 @Test462 fun `array with all nullable types must render`() {463 val string: String? = null464 val double: Double? = null465 val float: Float? = null466 val long: Long? = null467 val int: Int? = null468 val char: Char? = null469 val short: Short? = null470 val byte: Byte? = null471 val boolean: Boolean? = null472 val date: Date? = null473 val array = arr[474 string,475 double,476 float,477 long,478 int,479 char,480 short,481 byte,482 boolean,483 date484 ]485 val representation = array.toString()486 assertThat(representation).isValidJSON()487 assertThat(representation).isEqualTo("[null,null,null,null,null,null,null,null,null,null]")488 }489 @Test490 fun `array with all nullable Java types must render`() {491 val array = arr[492 NullableTypes.STRING,493 NullableTypes.DOUBLE,494 NullableTypes.FLOAT,495 NullableTypes.LONG,496 NullableTypes.INT,497 NullableTypes.CHAR,498 NullableTypes.SHORT,499 NullableTypes.BYTE,500 NullableTypes.BOOLEAN,501 NullableTypes.DATE502 ]503 val representation = array.toString()504 assertThat(representation).isValidJSON()505 assertThat(representation).isEqualTo("[null,null,null,null,null,null,null,null,null,null]")506 }507 }508 @Nested509 inner class RawJsonContents {510 @Test511 fun `object with inner raw object`() {512 val obj = obj {513 "jsonContent" to rawJson("""{"menu":{"id":"file","value":"File","popup":{"menuitem":[{"value":"New","onclick":"CreateNewDoc()"},{"value":"Open","onclick":"OpenDoc()"},{"value":"Close","onclick":"CloseDoc()"}]}}}""")514 }515 val representation = obj.toString()516 assertThat(representation).isValidJSON()517 assertThat(representation).isEqualTo("""{"jsonContent":{"menu":{"id":"file","value":"File","popup":{"menuitem":[{"value":"New","onclick":"CreateNewDoc()"},{"value":"Open","onclick":"OpenDoc()"},{"value":"Close","onclick":"CloseDoc()"}]}}}}""")518 }519 @Test520 fun `array with inner raw object`() {521 val array =522 arr[rawJson("""{"menu":{"id":"file","value":"File","popup":{"menuitem":[{"value":"New","onclick":"CreateNewDoc()"},{"value":"Open","onclick":"OpenDoc()"},{"value":"Close","onclick":"CloseDoc()"}]}}}""")]523 val representation = array.toString()524 assertThat(representation).isValidJSON()525 assertThat(representation).isEqualTo("""[{"menu":{"id":"file","value":"File","popup":{"menuitem":[{"value":"New","onclick":"CreateNewDoc()"},{"value":"Open","onclick":"OpenDoc()"},{"value":"Close","onclick":"CloseDoc()"}]}}}]""")526 }527 @Test528 fun `object with null inner raw object`() {529 val obj = obj {530 "jsonContent" to rawJson(null)531 }532 val representation = obj.toString()533 assertThat(representation).isValidJSON()534 assertThat(representation).isEqualTo("""{"jsonContent":null}""")535 }536 @Test537 fun `array with null inner raw object`() {538 val array = arr[rawJson(null)]539 val representation = array.toString()540 assertThat(representation).isValidJSON()541 assertThat(representation).isEqualTo("[null]")542 }543 @Test544 fun `object with rawJson must be inlined properly when containing windows CR`() {545 val obj = obj {546 "jsonContent" to rawJson("{\r\n \"menu\":{\r\n \"id\":\"file\",\r\n \"value\":\"File\",\r\n \"popup\":{\r\n \"menuitem\":[\r\n {\r\n \"value\":\"New\",\r\n \"onclick\":\"CreateNewDoc()\"\r\n },\r\n {\r\n \"value\":\"Open\",\r\n \"onclick\":\"OpenDoc()\"\r\n },\r\n {\r\n \"value\":\"Close\",\r\n \"onclick\":\"CloseDoc()\"\r\n }\r\n ]\r\n }\r\n }\r\n}")547 }548 val representation = obj.toString()549 assertThat(representation).isValidJSON()550 assertThat(representation).isEqualTo("""{"jsonContent":{"menu":{"id":"file","value":"File","popup":{"menuitem":[{"value":"New","onclick":"CreateNewDoc()"},{"value":"Open","onclick":"OpenDoc()"},{"value":"Close","onclick":"CloseDoc()"}]}}}}""")551 }552 @Test553 fun `array with rawJson must be inlined properly when containing windows CR`() {554 val array =555 arr[rawJson("{\r\n \"menu\":{\r\n \"id\":\"file\",\r\n \"value\":\"File\",\r\n \"popup\":{\r\n \"menuitem\":[\r\n {\r\n \"value\":\"New\",\r\n \"onclick\":\"CreateNewDoc()\"\r\n },\r\n {\r\n \"value\":\"Open\",\r\n \"onclick\":\"OpenDoc()\"\r\n },\r\n {\r\n \"value\":\"Close\",\r\n \"onclick\":\"CloseDoc()\"\r\n }\r\n ]\r\n }\r\n }\r\n}")]556 val representation = array.toString()557 assertThat(representation).isValidJSON()558 assertThat(representation).isEqualTo("""[{"menu":{"id":"file","value":"File","popup":{"menuitem":[{"value":"New","onclick":"CreateNewDoc()"},{"value":"Open","onclick":"OpenDoc()"},{"value":"Close","onclick":"CloseDoc()"}]}}}]""")559 }560 @Test561 fun `object with rawJson must be inlined properly when containing UNIX CR`() {562 val obj = obj {563 "jsonContent" to rawJson("{\n \"menu\":{\n \"id\":\"file\",\n \"value\":\"File\",\n \"popup\":{\n \"menuitem\":[\n {\n \"value\":\"New\",\n \"onclick\":\"CreateNewDoc()\"\n },\n {\n \"value\":\"Open\",\n \"onclick\":\"OpenDoc()\"\n },\n {\n \"value\":\"Close\",\n \"onclick\":\"CloseDoc()\"\n }\n ]\n }\n }\n}")564 }565 val representation = obj.toString()566 assertThat(representation).isValidJSON()567 assertThat(representation).isEqualTo("""{"jsonContent":{"menu":{"id":"file","value":"File","popup":{"menuitem":[{"value":"New","onclick":"CreateNewDoc()"},{"value":"Open","onclick":"OpenDoc()"},{"value":"Close","onclick":"CloseDoc()"}]}}}}""")568 }569 @Test570 fun `array with rawJson must be inlined properly when containing UNIX CR`() {571 val array =572 arr[rawJson("{\n \"menu\":{\n \"id\":\"file\",\n \"value\":\"File\",\n \"popup\":{\n \"menuitem\":[\n {\n \"value\":\"New\",\n \"onclick\":\"CreateNewDoc()\"\n },\n {\n \"value\":\"Open\",\n \"onclick\":\"OpenDoc()\"\n },\n {\n \"value\":\"Close\",\n \"onclick\":\"CloseDoc()\"\n }\n ]\n }\n }\n}")]573 val representation = array.toString()574 assertThat(representation).isValidJSON()575 assertThat(representation).isEqualTo("""[{"menu":{"id":"file","value":"File","popup":{"menuitem":[{"value":"New","onclick":"CreateNewDoc()"},{"value":"Open","onclick":"OpenDoc()"},{"value":"Close","onclick":"CloseDoc()"}]}}}]""")576 }577 @Test578 fun `rawJson with emptyString should display empty string`() {579 val representation = obj {580 "jsonContent" to rawJson("")581 }.toString()582 assertThat(representation).isValidJSON()583 assertThat(representation).isEqualTo("""{"jsonContent":""}""")584 }585 @Test586 fun `rawJson with whitespaces string should display empty string`() {587 val representation = obj {588 "jsonContent" to rawJson(" ")589 }.toString()590 assertThat(representation).isValidJSON()591 assertThat(representation).isEqualTo("""{"jsonContent":""}""")592 }593 }594 @Nested595 inner class PrettyPrints {596 private val cr = System.lineSeparator()!!597 @Test598 fun `must pretty print an object`() {599 val pretty = obj {600 "key" to 3.4601 "string" to "newline\n"602 "anotherKey" to arr["test", "test2", 1, 2.433, true]603 "nullsAreAllowedToo" to null604 "array" to arr[605 obj {606 "double" to 33.4607 "float" to 345f608 "long" to 21L609 "int" to 42610 "char" to 'a'611 "byte" to 0xAA612 "otherArray" to arr613 "simpleObject" to SimpleObject614 "custom" to CustomizedKoson615 "raw" to rawJson("[]")616 "objectInside" to obj {617 "to" to 34618 "too" to "Dog"619 }620 "innerArray" to arr[621 34, 44, "to", null622 ]623 }624 ]625 }.pretty()626 assertThat(pretty).isValidJSON()627 assertThat(pretty).isEqualTo(628 "{$cr" +629 " \"key\": 3.4,$cr" +630 " \"string\": \"newline\\n\",$cr" +631 " \"anotherKey\": [$cr" +632 " \"test\",$cr" +633 " \"test2\",$cr" +634 " 1,$cr" +635 " 2.433,$cr" +636 " true$cr" +637 " ],$cr" +638 " \"nullsAreAllowedToo\": null,$cr" +639 " \"array\": [$cr" +640 " {$cr" +641 " \"double\": 33.4,$cr" +642 " \"float\": 345.0,$cr" +643 " \"long\": 21,$cr" +644 " \"int\": 42,$cr" +645 " \"char\": \"a\",$cr" +646 " \"byte\": 170,$cr" +647 " \"otherArray\": [$cr" +648 " $cr" +649 " ],$cr" +650 " \"simpleObject\": \"SimpleObject\",$cr" +651 " \"custom\": {$cr" +652 " \"custom\": 11$cr" +653 " },$cr" +654 " \"raw\": [],$cr" +655 " \"objectInside\": {$cr" +656 " \"to\": 34,$cr" +657 " \"too\": \"Dog\"$cr" +658 " },$cr" +659 " \"innerArray\": [$cr" +660 " 34,$cr" +661 " 44,$cr" +662 " \"to\",$cr" +663 " null$cr" +664 " ]$cr" +665 " }$cr" +666 " ]$cr" +667 "}"668 )669 }670 @Test671 fun `must pretty print an array`() {672 val pretty = arr[673 obj {674 "key" to 3.4675 "anotherKey" to arr["test", "test2", 1, 2.433, true]676 "nullsAreAllowedToo" to null677 "array" to arr[678 obj {679 "double" to 33.4680 "float" to 345f681 "long" to 21L682 "int" to 42683 "char" to 'a'684 "byte" to 0xAA685 "otherArray" to arr686 "simpleObject" to SimpleObject687 "custom" to CustomizedKoson688 "raw" to rawJson("[]")689 "objectInside" to obj {690 "to" to 34691 "too" to "Dog"692 }693 "innerArray" to arr[694 34, 44, "to", null695 ]696 }697 ]698 }699 ].pretty()700 assertThat(pretty).isValidJSON()701 assertThat(pretty).isEqualTo(702 "[$cr" +703 " {$cr" +704 " \"key\": 3.4,$cr" +705 " \"anotherKey\": [$cr" +706 " \"test\",$cr" +707 " \"test2\",$cr" +708 " 1,$cr" +709 " 2.433,$cr" +710 " true$cr" +711 " ],$cr" +712 " \"nullsAreAllowedToo\": null,$cr" +713 " \"array\": [$cr" +714 " {$cr" +715 " \"double\": 33.4,$cr" +716 " \"float\": 345.0,$cr" +717 " \"long\": 21,$cr" +718 " \"int\": 42,$cr" +719 " \"char\": \"a\",$cr" +720 " \"byte\": 170,$cr" +721 " \"otherArray\": [$cr" +722 " $cr" +723 " ],$cr" +724 " \"simpleObject\": \"SimpleObject\",$cr" +725 " \"custom\": {$cr" +726 " \"custom\": 11$cr" +727 " },$cr" +728 " \"raw\": [],$cr" +729 " \"objectInside\": {$cr" +730 " \"to\": 34,$cr" +731 " \"too\": \"Dog\"$cr" +732 " },$cr" +733 " \"innerArray\": [$cr" +...

Full Screen

Full Screen

TypedHandlerTest.kt

Source:TypedHandlerTest.kt Github

copy

Full Screen

1/*2 * Copyright 2010-2015 JetBrains s.r.o.3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package org.jetbrains.kotlin.idea.editor17import com.intellij.psi.codeStyle.CodeStyleSettingsManager18import com.intellij.testFramework.EditorTestUtil19import com.intellij.testFramework.LightCodeInsightTestCase20import com.intellij.testFramework.LightPlatformCodeInsightTestCase21import com.intellij.testFramework.LightPlatformTestCase22import org.jetbrains.kotlin.idea.KotlinFileType23class TypedHandlerTest : LightCodeInsightTestCase() {24 private val dollar = '$'25 fun testTypeStringTemplateStart() = doCharTypeTest(26 '{',27 """val x = "$<caret>" """,28 """val x = "$dollar{}" """29 )30 fun testAutoIndentRightOpenBrace() = doCharTypeTest(31 '{',32 "fun test() {\n" +33 "<caret>\n" +34 "}",35 "fun test() {\n" +36 " {<caret>}\n" +37 "}"38 )39 fun testAutoIndentLeftOpenBrace() = doCharTypeTest(40 '{',41 "fun test() {\n" +42 " <caret>\n" +43 "}",44 "fun test() {\n" +45 " {<caret>}\n" +46 "}"47 )48 fun testTypeStringTemplateStartWithCloseBraceAfter() = doCharTypeTest(49 '{',50 """fun foo() { "$<caret>" }""",51 """fun foo() { "$dollar{}" }"""52 )53 fun testTypeStringTemplateStartBeforeString() = doCharTypeTest(54 '{',55 """fun foo() { "$<caret>something" }""",56 """fun foo() { "$dollar{}something" }"""57 )58 fun testKT3575() = doCharTypeTest(59 '{',60 """val x = "$<caret>]" """,61 """val x = "$dollar{}]" """62 )63 fun testAutoCloseBraceInFunctionDeclaration() = doCharTypeTest(64 '{',65 "fun foo() <caret>",66 "fun foo() {<caret>}"67 )68 fun testAutoCloseBraceInLocalFunctionDeclaration() = doCharTypeTest(69 '{',70 "fun foo() {\n" +71 " fun bar() <caret>\n" +72 "}",73 "fun foo() {\n" +74 " fun bar() {<caret>}\n" +75 "}"76 )77 fun testAutoCloseBraceInAssignment() = doCharTypeTest(78 '{',79 "fun foo() {\n" +80 " val a = <caret>\n" +81 "}",82 "fun foo() {\n" +83 " val a = {<caret>}\n" +84 "}"85 )86 fun testDoNotAutoCloseBraceInUnfinishedIfSurroundOnSameLine() = doCharTypeTest(87 '{',88 "fun foo() {\n" +89 " if() <caret>foo()\n" +90 "}",91 "fun foo() {\n" +92 " if() {foo()\n" +93 "}"94 )95 fun testDoNotAutoCloseBraceInUnfinishedElseSurroundOnSameLine() = doCharTypeTest(96 '{',97 "fun foo() {\n" +98 " if(true) {} else <caret>foo()\n" +99 "}",100 "fun foo() {\n" +101 " if(true) {} else {foo()\n" +102 "}"103 )104 fun testDoNotAutoCloseBraceInUnfinishedTryOnSameLine() = doCharTypeTest(105 '{',106 "fun foo() {\n" +107 " try <caret>foo()\n" +108 "}",109 "fun foo() {\n" +110 " try {foo()\n" +111 "}"112 )113 fun testDoNotAutoCloseBraceInUnfinishedCatchOnSameLine() = doCharTypeTest(114 '{',115 "fun foo() {\n" +116 " try {} catch (e: Exception) <caret>foo()\n" +117 "}",118 "fun foo() {\n" +119 " try {} catch (e: Exception) {foo()\n" +120 "}"121 )122 fun testDoNotAutoCloseBraceInUnfinishedFinallyOnSameLine() = doCharTypeTest(123 '{',124 "fun foo() {\n" +125 " try {} catch (e: Exception) finally <caret>foo()\n" +126 "}",127 "fun foo() {\n" +128 " try {} catch (e: Exception) finally {foo()\n" +129 "}"130 )131 fun testDoNotAutoCloseBraceInUnfinishedWhileSurroundOnSameLine() = doCharTypeTest(132 '{',133 "fun foo() {\n" +134 " while() <caret>foo()\n" +135 "}",136 "fun foo() {\n" +137 " while() {foo()\n" +138 "}"139 )140 fun testDoNotAutoCloseBraceInUnfinishedWhileSurroundOnNewLine() = doCharTypeTest(141 '{',142 "fun foo() {\n" +143 " while()\n" +144 "<caret>\n" +145 " foo()\n" +146 "}",147 "fun foo() {\n" +148 " while()\n" +149 " {\n" +150 " foo()\n" +151 "}"152 )153 fun testDoNotAutoCloseBraceInUnfinishedIfSurroundOnOtherLine() = doCharTypeTest(154 '{',155 "fun foo() {\n" +156 " if(true) <caret>\n" +157 " foo()\n" +158 "}",159 "fun foo() {\n" +160 " if(true) {<caret>\n" +161 " foo()\n" +162 "}"163 )164 fun testDoNotAutoCloseBraceInUnfinishedElseSurroundOnOtherLine() = doCharTypeTest(165 '{',166 "fun foo() {\n" +167 " if(true) {} else <caret>\n" +168 " foo()\n" +169 "}",170 "fun foo() {\n" +171 " if(true) {} else {<caret>\n" +172 " foo()\n" +173 "}"174 )175 fun testDoNotAutoCloseBraceInUnfinishedTryOnOtherLine() = doCharTypeTest(176 '{',177 "fun foo() {\n" +178 " try <caret>\n" +179 " foo()\n" +180 "}",181 "fun foo() {\n" +182 " try {<caret>\n" +183 " foo()\n" +184 "}"185 )186 fun testDoNotAutoCloseBraceInUnfinishedIfSurroundOnNewLine() = doCharTypeTest(187 '{',188 "fun foo() {\n" +189 " if(true)\n" +190 " <caret>\n" +191 " foo()\n" +192 "}",193 "fun foo() {\n" +194 " if(true)\n" +195 " {<caret>\n" +196 " foo()\n" +197 "}"198 )199 fun testDoNotAutoCloseBraceInUnfinishedElseSurroundOnNewLine() = doCharTypeTest(200 '{',201 "fun foo() {\n" +202 " if(true) {} else\n" +203 " <caret>\n" +204 " foo()\n" +205 "}",206 "fun foo() {\n" +207 " if(true) {} else\n" +208 " {<caret>\n" +209 " foo()\n" +210 "}"211 )212 fun testDoNotAutoCloseBraceInUnfinishedTryOnNewLine() = doCharTypeTest(213 '{',214 "fun foo() {\n" +215 " try\n" +216 " <caret>\n" +217 " foo()\n" +218 "}",219 "fun foo() {\n" +220 " try\n" +221 " {<caret>\n" +222 " foo()\n" +223 "}"224 )225 fun testAutoCloseBraceInsideFor() = doCharTypeTest(226 '{',227 "fun foo() {\n" +228 " for (elem in some.filter <caret>) {\n" +229 " }\n" +230 "}",231 "fun foo() {\n" +232 " for (elem in some.filter {<caret>}) {\n" +233 " }\n" +234 "}"235 )236 fun testAutoCloseBraceInsideForAfterCloseParen() = doCharTypeTest(237 '{',238 "fun foo() {\n" +239 " for (elem in some.foo(true) <caret>) {\n" +240 " }\n" +241 "}",242 "fun foo() {\n" +243 " for (elem in some.foo(true) {<caret>}) {\n" +244 " }\n" +245 "}"246 )247 fun testAutoCloseBraceBeforeIf() = doCharTypeTest(248 '{',249 "fun foo() {\n" +250 " <caret>if (true) {}\n" +251 "}",252 "fun foo() {\n" +253 " {<caret>if (true) {}\n" +254 "}"255 )256 fun testAutoCloseBraceInIfCondition() = doCharTypeTest(257 '{',258 "fun foo() {\n" +259 " if (some.hello (12) <caret>)\n" +260 "}",261 "fun foo() {\n" +262 " if (some.hello (12) {<caret>})\n" +263 "}"264 )265 fun testAutoInsertParenInStringLiteral() = doCharTypeTest(266 '(',267 """fun f() { println("$dollar{f<caret>}") }""",268 """fun f() { println("$dollar{f(<caret>)}") }"""269 )270 fun testAutoInsertParenInCode() = doCharTypeTest(271 '(',272 """fun f() { val a = f<caret> }""",273 """fun f() { val a = f(<caret>) }"""274 )275 fun testSplitStringByEnter() = doCharTypeTest(276 '\n',277 """val s = "foo<caret>bar"""",278 "val s = \"foo\" +\n" +279 " \"bar\""280 )281 fun testSplitStringByEnterEmpty() = doCharTypeTest(282 '\n',283 """val s = "<caret>"""",284 "val s = \"\" +\n" +285 " \"\""286 )287 fun testSplitStringByEnterBeforeEscapeSequence() = doCharTypeTest(288 '\n',289 """val s = "foo<caret>\nbar"""",290 "val s = \"foo\" +\n" +291 " \"\\nbar\""292 )293 fun testSplitStringByEnterBeforeSubstitution() = doCharTypeTest(294 '\n',295 """val s = "foo<caret>${dollar}bar"""",296 "val s = \"foo\" +\n" +297 " \"${dollar}bar\""298 )299 fun testSplitStringByEnterAddParentheses() = doCharTypeTest(300 '\n',301 """val l = "foo<caret>bar".length()""",302 "val l = (\"foo\" +\n" +303 " \"bar\").length()"304 )305 fun testSplitStringByEnterExistingParentheses() = doCharTypeTest(306 '\n',307 """val l = ("asdf" + "foo<caret>bar").length()""",308 "val l = (\"asdf\" + \"foo\" +\n" +309 " \"bar\").length()"310 )311 fun testTypeLtInFunDeclaration() {312 doLtGtTest("fun <caret>")313 }314 fun testTypeLtInOngoingConstructorCall() {315 doLtGtTest("fun test() { Collection<caret> }")316 }317 fun testTypeLtInClassDeclaration() {318 doLtGtTest("class Some<caret> {}")319 }320 fun testTypeLtInPropertyType() {321 doLtGtTest("val a: List<caret> ")322 }323 fun testTypeLtInExtensionFunctionReceiver() {324 doLtGtTest("fun <T> Collection<caret> ")325 }326 fun testTypeLtInFunParam() {327 doLtGtTest("fun some(a : HashSet<caret>)")328 }329 fun testTypeLtInFun() {330 doLtGtTestNoAutoClose("fun some() { <<caret> }")331 }332 fun testTypeLtInLess() {333 doLtGtTestNoAutoClose("fun some() { val a = 12; a <<caret> }")334 }335 fun testColonOfSuperTypeList() {336 doCharTypeTest(337 ':',338 """339 |open class A340 |class B341 |<caret>342 """,343 """344 |open class A345 |class B346 | :<caret>347 """)348 }349 fun testColonOfSuperTypeListInObject() {350 doCharTypeTest(351 ':',352 """353 |interface A354 |object B355 |<caret>356 """,357 """358 |interface A359 |object B360 | :<caret>361 """)362 }363 fun testColonOfSuperTypeListInCompanionObject() {364 doCharTypeTest(365 ':',366 """367 |interface A368 |class B {369 | companion object370 | <caret>371 |}372 """,373 """374 |interface A375 |class B {376 | companion object377 | :<caret>378 |}379 """)380 }381 fun testColonOfSuperTypeListBeforeBody() {382 doCharTypeTest(383 ':',384 """385 |open class A386 |class B387 |<caret> {388 |}389 """,390 """391 |open class A392 |class B393 | :<caret> {394 |}395 """)396 }397 fun testColonOfSuperTypeListNotNullIndent() {398 doCharTypeTest(399 ':',400 """401 |fun test() {402 | open class A403 | class B404 | <caret>405 |}406 """,407 """408 |fun test() {409 | open class A410 | class B411 | :<caret>412 |}413 """)414 }415 fun testChainCallContinueWithDot() {416 doCharTypeTest(417 '.',418 """419 |class Test{ fun test() = this }420 |fun some() {421 | Test()422 | <caret>423 |}424 """,425 """426 |class Test{ fun test() = this }427 |fun some() {428 | Test()429 | .<caret>430 |}431 """)432 }433 fun testChainCallContinueWithSafeCall() {434 doCharTypeTest(435 '.',436 """437 |class Test{ fun test() = this }438 |fun some() {439 | Test()440 | ?<caret>441 |}442 """,443 """444 |class Test{ fun test() = this }445 |fun some() {446 | Test()447 | ?.<caret>448 |}449 """)450 }451 fun testSpaceAroundRange() {452 doCharTypeTest(453 '.',454 """455 | val test = 1 <caret>456 """,457 """458 | val test = 1 .<caret>459 """460 )461 }462 fun testIndentBeforeElseWithBlock() {463 doCharTypeTest(464 '\n',465 """466 |fun test(b: Boolean) {467 | if (b) {468 | }<caret>469 | else if (!b) {470 | }471 |}472 """,473 """474 |fun test(b: Boolean) {475 | if (b) {476 | }477 | <caret>478 | else if (!b) {479 | }480 |}481 """482 )483 }484 fun testIndentBeforeElseWithoutBlock() {485 doCharTypeTest(486 '\n',487 """488 |fun test(b: Boolean) {489 | if (b)490 | foo()<caret>491 | else {492 | }493 |}494 """,495 """496 |fun test(b: Boolean) {497 | if (b)498 | foo()499 | <caret>500 | else {501 | }502 |}503 """504 )505 }506 fun testIndentOnFinishedVariableEndAfterEquals() {507 doCharTypeTest(508 '\n',509 """510 |fun test() {511 | val a =<caret>512 | foo()513 |}514 """,515 """516 |fun test() {517 | val a =518 | <caret>519 | foo()520 |}521 """522 )523 }524 fun testIndentNotFinishedVariableEndAfterEquals() {525 doCharTypeTest(526 '\n',527 """528 |fun test() {529 | val a =<caret>530 |}531 """,532 """533 |fun test() {534 | val a =535 | <caret>536 |}537 """538 )539 }540 fun testSmartEnterWithTabsOnConstructorParameters() {541 doCharTypeTest(542 '\n',543 """544 |class A(545 | a: Int,<caret>546 |)547 """,548 """549 |class A(550 | a: Int,551 | <caret>552 |)553 """,554 enableSmartEnterWithTabs()555 )556 }557 fun testSmartEnterWithTabsInMethodParameters() {558 doCharTypeTest(559 '\n',560 """561 |fun method(562 | arg1: String,<caret>563 |) {}564 """,565 """566 |fun method(567 | arg1: String,568 | <caret>569 |) {}570 """,571 enableSmartEnterWithTabs()572 )573 }574 fun testMoveThroughGT() {575 LightPlatformCodeInsightTestCase.configureFromFileText("a.kt", "val a: List<Set<Int<caret>>>")576 EditorTestUtil.performTypingAction(LightPlatformCodeInsightTestCase.getEditor(), '>')577 EditorTestUtil.performTypingAction(LightPlatformCodeInsightTestCase.getEditor(), '>')578 checkResultByText("val a: List<Set<Int>><caret>")579 }580 fun testCharClosingQuote() {581 doCharTypeTest('\'', "val c = <caret>", "val c = ''")582 }583 private fun enableSmartEnterWithTabs(): () -> Unit = {584 val project = LightPlatformTestCase.getProject()585 val indentOptions = CodeStyleSettingsManager.getInstance(project).currentSettings.getIndentOptions(KotlinFileType.INSTANCE)586 indentOptions.USE_TAB_CHARACTER = true587 indentOptions.SMART_TABS = true588 }589 private fun doCharTypeTest(ch: Char, beforeText: String, afterText: String, settingsModifier: (() -> Unit)? = null) {590 try {591 if (settingsModifier != null) {592 settingsModifier()593 }594 LightPlatformCodeInsightTestCase.configureFromFileText("a.kt", beforeText.trimMargin())595 EditorTestUtil.performTypingAction(LightPlatformCodeInsightTestCase.getEditor(), ch)596 checkResultByText(afterText.trimMargin())597 }598 finally {599 if (settingsModifier != null) {600 val project = LightPlatformTestCase.getProject()601 CodeStyleSettingsManager.getSettings(project).clearCodeStyleSettings()602 }603 }604 }605 private fun doLtGtTestNoAutoClose(initText: String) {606 doLtGtTest(initText, false)607 }608 private fun doLtGtTest(initText: String, shouldCloseBeInsert: Boolean) {609 LightPlatformCodeInsightTestCase.configureFromFileText("a.kt", initText)610 EditorTestUtil.performTypingAction(LightPlatformCodeInsightTestCase.getEditor(), '<')611 checkResultByText(if (shouldCloseBeInsert) initText.replace("<caret>", "<<caret>>") else initText.replace("<caret>", "<<caret>"))612 EditorTestUtil.performTypingAction(LightPlatformCodeInsightTestCase.getEditor(), EditorTestUtil.BACKSPACE_FAKE_CHAR)613 checkResultByText(initText)614 }615 private fun doLtGtTest(initText: String) {616 doLtGtTest(initText, true)617 }618}...

Full Screen

Full Screen

CIFParser.kt

Source:CIFParser.kt Github

copy

Full Screen

1package com.github.decyg.CrAgg.cif.parser2import org.parboiled.BaseParser3import org.parboiled.Rule4import org.parboiled.annotations.BuildParseTree5import org.parboiled.annotations.SuppressNode6import org.parboiled.annotations.SuppressSubnodes7import org.parboiled.support.Var8import org.parboiled.trees.MutableTreeNodeImpl9/**10 * This class represents an encoding of the formal grammar of CIF_Node as closely as possible given the original spec.11 *12 * Various liberties were taking during the development of this due to the inconsistencies found in the official13 * grammar. Such inconsistencies include mismatches brackets, non specific handling of whitespaces and EOL's.14 *15 * The version below can successfully parse a variety of CIF files fairly robustly16 *17 * It's encoded using the Parboiled library.18 */19@BuildParseTree20open class CIFParser : BaseParser<CIFParser.Companion.CIFNode>() {21 // Top level CIF_Node rules22 open fun CIF_Node() : Rule {23 val tempNode : Var<CIFNode> = Var(CIFNode("CIF_Node"))24 return Sequence(25 Optional(Comments()),26 Optional(WhiteSpace()),27 Optional(28 DataBlock_Node(),29 tempNode.set(tempNode.get().addChildBlind(pop())),30 ZeroOrMore(31 WhiteSpace(),32 DataBlock_Node(),33 tempNode.set(tempNode.get().addChildBlind(pop()))34 ),35 Optional(WhiteSpace())36 ),37 EOI,38 push(tempNode.get())39 )40 }41 open fun DataBlock_Node() : Rule {42 val tempNode : Var<CIFNode> = Var(CIFNode("DataBlock_Node"))43 return Sequence(44 DataBlockHeading(),45 tempNode.set(tempNode.get().addChildBlind(pop())),46 WhiteSpace(),47 ZeroOrMore(48 FirstOf(49 DataItems_Node(),50 SaveFrame_Node() // Doesn't usually fire51 ),52 tempNode.set(tempNode.get().addChildBlind(pop())),53 Optional(WhiteSpace())54 ),55 push(tempNode.get())56 )57 }58 open fun DataBlockHeading() : Rule {59 return Sequence(60 DATA_(),61 OneOrMore(NonBlankChar()),62 push(CIFNode("DataBlockHeading", CIFNode(match())))63 )64 }65 open fun SaveFrame_Node() : Rule {66 val tempNode : Var<CIFNode> = Var(CIFNode("SaveFrame_Node"))67 return Sequence(68 SaveFrameHeading(),69 tempNode.set(tempNode.get().addChildBlind(pop())),70 OneOrMore(71 WhiteSpace(),72 DataItems_Node(),73 tempNode.set(tempNode.get().addChildBlind(pop()))74 ),75 WhiteSpace(),76 SAVE_(),77 push(tempNode.get())78 )79 }80 open fun SaveFrameHeading() : Rule {81 return Sequence(82 SAVE_(),83 OneOrMore(NonBlankChar()),84 push(CIFNode("SaveFrameHeading", CIFNode(match())))85 )86 }87 open fun DataItems_Node() : Rule {88 return FirstOf(89 Sequence(90 Tag(),91 WhiteSpace(),92 Value(),93 push(CIFNode("DataItem", pop(1), pop()))94 ),95 Sequence(96 LoopHeader(),97 WhiteSpace(),98 LoopBody(),99 push(CIFNode("LoopedDataItem", pop(1), pop()))100 )101 )102 }103 @SuppressSubnodes104 open fun LoopHeader() : Rule {105 val tempNode : Var<CIFNode> = Var(CIFNode("LoopHeader"))106 return Sequence(107 LOOP_(),108 OneOrMore(109 WhiteSpace(),110 Tag(),111 tempNode.set(tempNode.get().addChildBlind(pop()))112 ),113 push(tempNode.get())114 )115 }116 @SuppressSubnodes117 open fun LoopBody() : Rule {118 val tempNode : Var<CIFNode> = Var(CIFNode("LoopBody"))119 return Sequence(120 ZeroOrMore(121 Value(),122 tempNode.set(tempNode.get().addChildBlind(pop())),123 WhiteSpace()124 ),125 push(tempNode.get())126 )127 }128 // Reserved words129 @SuppressNode130 open fun DATA_() : Rule {131 return Sequence(AnyOf("dD"), AnyOf("aA"), AnyOf("tT"), AnyOf("aA"), '_')132 }133 @SuppressNode134 open fun LOOP_() : Rule {135 return Sequence(AnyOf("lL"), AnyOf("oO"), AnyOf("oO"), AnyOf("pP"), '_')136 }137 @SuppressNode138 open fun GLOBAL_() : Rule {139 return Sequence(AnyOf("gG"), AnyOf("lL"), AnyOf("oO"), AnyOf("bB"), AnyOf("aA"), AnyOf("lL"), '_')140 }141 @SuppressNode142 open fun SAVE_() : Rule {143 return Sequence(AnyOf("sS"), AnyOf("aA"), AnyOf("vV"), AnyOf("eE"), '_')144 }145 @SuppressNode146 open fun STOP_() : Rule {147 return Sequence(AnyOf("sS"), AnyOf("tT"), AnyOf("oO"), AnyOf("pP"), '_')148 }149 @SuppressNode150 open fun ReservedString() : Rule {151 return FirstOf(152 DATA_(),153 LOOP_(),154 GLOBAL_(),155 SAVE_(),156 STOP_()157 )158 }159 // Tags and values160 @SuppressNode161 open fun Tag() : Rule {162 return Sequence(163 '_',164 OneOrMore(NonBlankChar()),165 push(CIFNode(match()))166 )167 }168 @SuppressNode169 open fun Value() : Rule {170 return FirstOf(171 Sequence(Numeric(), Test(WhiteSpace())), // pushing will be done in numeric172 Sequence('.', push(CIFNode(match()))), // push here173 Sequence('?', push(CIFNode(match()))), // push here174 Sequence(TextField(), Test(WhiteSpace())), // pushing will be done in TextField175 Sequence(TestNot(ReservedString()), CharString(), Test(WhiteSpace())) // pushing will be done in CharString176 )177 }178 // Numeric values179 // Rewrite of original, should match180 // 11, 11.11, 11.11e11, 11., +11.11e+11()181 @SuppressNode182 open fun Numeric() : Rule {183 return Sequence(184 Sequence(185 Optional(AnyOf("+-")),186 FirstOf(187 Sequence(188 ZeroOrMore(Digit()),189 '.',190 OneOrMore(Digit())191 ),192 Sequence(193 OneOrMore(Digit()),194 '.'195 ),196 OneOrMore(Digit())197 ),198 Optional(199 AnyOf("eE"),200 Optional(AnyOf("+-")),201 OneOrMore(Digit())202 ),203 Optional(204 '(',205 OneOrMore(Digit()),206 ')'207 ),208 Test(WhiteSpace())209 ),210 push(CIFNode(match()))211 )212 }213 @SuppressNode214 open fun Digit() : Rule {215 return CharRange('0', '9')216 }217 // Character strings and text fields218 @SuppressNode219 open fun CharString() : Rule {220 return FirstOf(221 SingleQuotedString(),222 DoubleQuotedString(),223 UnquotedString()224 )225 }226 @SuppressNode227 open fun UnquotedString() : Rule {228 val tempStr : Var<String> = Var("")229 return FirstOf(230 Sequence(231 Test(EOL()),232 Sequence(233 OrdinaryChar(),234 ZeroOrMore(NonBlankChar())235 ),236 push(CIFNode(match()))237 ),238 Sequence(239 Test(NotEOL()),240 FirstOf(241 Sequence(242 OrdinaryChar(),243 tempStr.set(match())244 ),245 ';'246 ),247 ZeroOrMore(NonBlankChar()),248 push(CIFNode("${tempStr.get()}${match()}"))249 )250 )251 }252 @SuppressNode253 open fun SingleQuotedString() : Rule {254 return Sequence(255 '\'',256 ZeroOrMore(257 AnyPrintChar(),258 TestNot(EOL())259 ),260 push(CIFNode(match())),261 '\''262 )263 }264 open fun DoubleQuotedString() : Rule {265 return Sequence(266 '\"',267 ZeroOrMore(268 AnyPrintChar(),269 TestNot(EOL())270 ),271 push(CIFNode(match())),272 '\"'273 )274 }275 open fun TextField() : Rule {276 return SemiColonTextField()277 }278 open fun SemiColonTextField() : Rule {279 val tempStr : Var<String> = Var("")280 return Sequence(281 ';',282 ZeroOrMore(283 AnyPrintChar()284 ),285 tempStr.set(match()),286 EOL(),287 ZeroOrMore(288 Optional(289 TextLeadChar(),290 ZeroOrMore(AnyPrintChar())291 ),292 EOL()293 ),294 tempStr.set("${tempStr.get()}\n${match()}"),295 ';',296 push(CIFNode(tempStr.get()))297 )298 }299 // Whitespace and comments300 @SuppressNode301 open fun WhiteSpace() : Rule {302 return OneOrMore(303 FirstOf(304 TokenizedComments(),305 ' ',306 '\t',307 EOL()308 )309 )310 }311 @SuppressNode312 open fun TokenizedComments() : Rule {313 return Sequence(314 OneOrMore(315 FirstOf(316 ' ',317 '\t',318 EOL()319 )320 ),321 Comments()322 )323 }324 // Decided not to match comments as a node as it's technically not relevant to the picked up data325 // Also because WhiteSpace are also technically interchangable with Comments which is a bit of a headache326 // A messy potential solution could be matching regularly here but just having a method up above called327 // appendComment or something that adds it to a top level Comment node328 open fun Comments() : Rule {329 return OneOrMore(330 '#',331 ZeroOrMore(AnyPrintChar()),332 EOL()333 )334 }335 /*open fun Comments() : Rule {336 var tempNode : Var<CIFNode> = Var(CIFNode("Comments"))337 return Sequence(338 OneOrMore(339 '#',340 ZeroOrMore(AnyPrintChar()),341 push(CIFNode(match())),342 tempNode.set(tempNode.get().addChildBlind(pop())),343 EOL()344 ),345 push(tempNode.get())346 )347 }*/348 // Character sets349 @SuppressNode350 open fun AnyPrintChar() : Rule {351 return FirstOf(352 OrdinaryChar(),353 AnyOf("\"#$'_ \t;[]")354 )355 }356 @SuppressNode357 open fun TextLeadChar() : Rule {358 return FirstOf(359 OrdinaryChar(),360 AnyOf("\"#$'_ \t[]")361 )362 }363 @SuppressNode364 open fun NonBlankChar() : Rule {365 return FirstOf(366 OrdinaryChar(),367 AnyOf("\"#$'_;[]")368 )369 }370 @SuppressNode371 open fun OrdinaryChar() : Rule {372 return FirstOf(373 CharRange('a', 'z'),374 CharRange('A', 'Z'),375 CharRange('0', '9'),376 AnyOf("!%&()*+,-./:<=>?@\\^`{|}~")377 )378 }379 // Misc380 @SuppressNode381 open fun EOL() : Rule {382 return FirstOf("\n", "\r\n", "\r")383 }384 @SuppressNode385 open fun NotEOL() : Rule {386 return TestNot(EOL())387 }388 // Helper objects389 companion object {390 /**391 * This is a Node implementation, inheriting from one of the Parboiled classes.392 * It's fairly simple as each node can store a [value] and a number of children of the type393 * [CIFNode] so it can be recursive. The reason i made my own impl rather than using an existing one was394 * because i wanted a way to add a node without an index or pass in a series of children at once.395 *396 * @property value the value of the node397 */398 class CIFNode(val value : String) : MutableTreeNodeImpl<CIFNode>() {399 constructor(value : String, vararg children : CIFNode) : this(value) {400 for ((i, v) in children.withIndex()){401 super.addChild(i, v)402 }403 }404 /**405 * Adds a child [CIFNode] object to the children list and returns itself for inline parser usage.406 */407 fun addChildBlind(child : CIFNode) : CIFNode {408 super.addChild(super.getChildren().count(), child)409 return this410 }411 override fun toString(): String {412 return value413 }414 }415 }416}...

Full Screen

Full Screen

SudokuSolver.kt

Source:SudokuSolver.kt Github

copy

Full Screen

...3class Solution {4 fun solveSudoku(board: Array<CharArray>) {5 val openCells = mutableListOf<OpenCell>()6 var cellsUpdated = 07 board.forEachIndexed { x, chars ->8 chars.forEachIndexed { y, c ->9 if (c == '.') {10 possibilities(x, y, board).also {11 if (it.size == 1) {12 println("cell found $x $y $it")13 board[x][y] = it.first().toString().first()14 cellsUpdated++15 } else {16// println("cell has multiple possibles $x $y $it")17 openCells.add(OpenCell(x, y, it))18 }19 }20 }21 }22 }23 if (cellsUpdated > 0) {24 solveSudoku(board)25 } else if (openCells.isNotEmpty()){26 openCells.sortBy { it.possibles.size }27 openCells.forEach {28 println("open cell = $it")29 }30 openCells.forEach { (x, y, ps) ->31 if (ps.isEmpty()) {32 println("impossible cell, dead end")33 return34 }35 ps.forEach { p ->36 println("try possible $x $y $p")37 board[x][y] = p.toString().first()38 board.print()39 solveSudoku(board)40 }41 }42 }43 }44 data class OpenCell(val x: Int, val y: Int, val possibles: List<Int>)45 private fun possibilities(x: Int, y: Int, board: Array<CharArray>): List<Int> {46 val rowValues = board[x].map { char ->47 Character.getNumericValue(char).let {48 if (it == -1) null else it49 }50 }.filterNotNull()51 val columnValues = board.mapNotNull { row ->52 Character.getNumericValue(row[y]).let {53 if (it == -1) null else it54 }55 }56 val squareValues = squareRangeForIndex(x).map { squareX ->57 squareRangeForIndex(y).map { squareY ->58 Character.getNumericValue(board[squareX][squareY]).let {59 if (it == -1) null else it60 }61 }62 }.flatten().filterNotNull()63 val values = (rowValues + columnValues + squareValues).distinct()64 val result = (1..9).filter {65 values.contains(it).not()66 }67 return result68 }69 fun squareRangeForIndex(index: Int) = when(index) {70 0,1,2 -> 0..271 3,4,5 -> 3..572 6,7,8 -> 6..873 else -> throw Exception("value out of range")74 }75}76data class Test(val start: List<CharArray>, val solution: List<CharArray>)77fun main() {78 val tests = listOf(79 Test(80 start = listOf(81 charArrayOf('5','3','.','.','7','.','.','.','.'),82 charArrayOf('6','.','.','1','9','5','.','.','.'),83 charArrayOf('.','9','8','.','.','.','.','6','.'),84 charArrayOf('8','.','.','.','6','.','.','.','3'),85 charArrayOf('4','.','.','8','.','3','.','.','1'),86 charArrayOf('7','.','.','.','2','.','.','.','6'),87 charArrayOf('.','6','.','.','.','.','2','8','.'),88 charArrayOf('.','.','.','4','1','9','.','.','5'),89 charArrayOf('.','.','.','.','8','.','.','7','9')90 ),91 solution = listOf(92 charArrayOf('5','3','4','6','7','8','9','1','2'),93 charArrayOf('6','7','2','1','9','5','3','4','8'),94 charArrayOf('1','9','8','3','4','2','5','6','7'),95 charArrayOf('8','5','9','7','6','1','4','2','3'),96 charArrayOf('4','2','6','8','5','3','7','9','1'),97 charArrayOf('7','1','3','9','2','4','8','5','6'),98 charArrayOf('9','6','1','5','3','7','2','8','4'),99 charArrayOf('2','8','7','4','1','9','6','3','5'),100 charArrayOf('3','4','5','2','8','6','1','7','9')101 )102 ),103 Test(104 start = listOf(105 charArrayOf('.','.','9','7','4','8','.','.','.'),106 charArrayOf('7','.','.','.','.','.','.','.','.'),107 charArrayOf('.','2','.','1','.','9','.','.','.'),108 charArrayOf('.','.','7','.','.','.','2','4','.'),109 charArrayOf('.','6','4','.','1','.','5','9','.'),110 charArrayOf('.','9','8','.','.','.','3','.','.'),111 charArrayOf('.','.','.','8','.','3','.','2','.'),112 charArrayOf('.','.','.','.','.','.','.','.','6'),113 charArrayOf('.','.','.','2','7','5','9','.','.')114 ),115 solution = listOf(116 charArrayOf('5','1','9','7','4','8','6','3','2'),117 charArrayOf('7','8','3','6','5','2','4','1','9'),118 charArrayOf('4','2','6','1','3','9','8','7','5'),119 charArrayOf('3','5','7','9','8','6','2','4','1'),120 charArrayOf('2','6','4','3','1','7','5','9','8'),121 charArrayOf('1','9','8','5','2','4','3','6','7'),122 charArrayOf('9','7','5','8','6','3','1','2','4'),123 charArrayOf('8','3','2','4','9','1','7','5','6'),124 charArrayOf('6','4','1','2','7','5','9','8','3')125 )126 )127 )128 val s = Solution()129 tests.forEach { test ->130 println("test = $test")131 val startArray = test.start.toTypedArray()132 s.solveSudoku(startArray)133 startArray.print()134 if (startArray.isSame(test.solution.toTypedArray()).not()) {135 println("test case $test failed")136 println("result")137 startArray.print()138 println("expected")139 test.solution.toTypedArray().print()140 throw Exception("test case $test failed")141 }142 }143}144fun Array<CharArray>.print() {145 forEachIndexed { idx, row ->146 println("$idx ${row.toList()}")147 }148}149fun Array<CharArray>.isSame(other: Array<CharArray>): Boolean {150 if (size != other.size) return false151 forEachIndexed { rowIndex, chars ->152 if (chars.size != other[rowIndex].size) return false153 chars.forEachIndexed { charIndex, c ->154 if (c != other[rowIndex][charIndex]) return false155 }156 }157 return true158}...

Full Screen

Full Screen

GrampaTests.kt

Source:GrampaTests.kt Github

copy

Full Screen

...13open class TestGrammar(val dummy: String?) : AbstractGrammar<String>() {14 constructor() : this(null)15 override fun start() = expr('a')16 protected open fun expr(c: Char): Rule<String> = choice(17 char(c),18 sequence(19 empty(),20 start(66),21 noop(),22 char('('),23 start(),24 char(')')25 )26 )27 protected open fun start(i: Int) = i * empty()28 protected open fun noop() = empty()29 open fun verifyRules() = start().apply {30 shouldBeInstanceOf<ChoiceRule<String>>()31 children.size shouldBe 232 children[0].shouldBeInstanceOf<CharPredicateRule<String>>()33 children[1].shouldBeInstanceOf<SequenceRule<String>>()34 children[1].children.size shouldBe 635 children[1].children[0].shouldBeInstanceOf<EmptyRule<String>>()36 children[1].children[1].shouldBeInstanceOf<RepeatRule<String>>()37 children[1].children[2].shouldBeInstanceOf<EmptyRule<String>>()38 children[1].children[3].shouldBeInstanceOf<CharPredicateRule<String>>()39 children[1].children[4].shouldBeInstanceOf<ChoiceRule<String>>()40 children[1].children[5].shouldBeInstanceOf<CharPredicateRule<String>>()41 children[1].children[4] shouldBe this42 }43}44class GrampaTests : StringSpec({45 "Create grammar" {46 TestGrammar::class.createGrammar().apply {47 dummy shouldBe null48 verifyRules()49 }50 TestGrammar::class.createGrammar("foo").apply {51 dummy shouldBe "foo"52 verifyRules()53 }54 shouldThrow<IllegalArgumentException> { TestGrammar::class.createGrammar(4711) }55 shouldThrow<IllegalArgumentException> { TestGrammar::class.createGrammar("foo", "bar") }56 }57 "Non-overridable rule method" {58 open class InvalidGrammar : AbstractGrammar<String>() {59 override fun start() = expr('a')60 private fun expr(c: Char) = char(c)61 }62 shouldThrow<IllegalArgumentException> { InvalidGrammar::class.createGrammar() }63 }64 "No no-arg constructor grammar" {65 open class NoDefaultCtorTestGrammar(dummy: String) : TestGrammar(dummy)66 shouldThrow<IllegalArgumentException> { NoDefaultCtorTestGrammar::class.createGrammar() }67 }68 "Final rule method grammar" {69 class FinalRuleMethodTestGrammar : TestGrammar() {70 override fun noop() = empty()71 }72 shouldThrow<IllegalArgumentException> { FinalRuleMethodTestGrammar::class.createGrammar() }73 }74 "Grammar inheritance" {75 open class SuperGrammar : TestGrammar() {76 override fun start(): Rule<String> = sequence(char('a'), start())77 override fun verifyRules() = start().apply {78 shouldBeInstanceOf<SequenceRule<String>>()79 children.size shouldBe 280 children[0].shouldBeInstanceOf<CharPredicateRule<String>>()81 children[1].shouldBeInstanceOf<SequenceRule<String>>()82 children[1] shouldBe this83 }84 }85 open class SubGrammar : SuperGrammar() {86 override fun start() = super.start().also { it.toString() }87 }88 SuperGrammar::class.createGrammar().verifyRules()89 SubGrammar::class.createGrammar().verifyRules()90 }...

Full Screen

Full Screen

Day10.kt

Source:Day10.kt Github

copy

Full Screen

...68}69fun calculateScore(completionString: String): Long {70 return completionString.toCharArray()71 .map { completionScore[it]!! }72 .fold(0L) { acc, charScore -> acc * 5 + charScore }73}...

Full Screen

Full Screen

ValidParentheses.kt

Source:ValidParentheses.kt Github

copy

Full Screen

2import com.google.common.truth.Truth3import org.junit.Test4import java.util.*5/**6Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.7An input string is valid if:8Open brackets must be closed by the same type of brackets.9Open brackets must be closed in the correct order.10 */11class ValidParentheses {12 private fun isValid(s: String): Boolean {13 if (s.isEmpty()) return true14 if (s.length % 2 == 1) return false15 val expectedChar = Stack<Char>()16 for (char in s) {17 if (char == '(') expectedChar.push(')')18 if (char == '[') expectedChar.push(']')19 if (char == '{') expectedChar.push('}')20 if (expectedChar.isEmpty()) return false21 22 if (char == ')' && expectedChar.pop() != ')') return false23 if (char == ']' && expectedChar.pop() != ']') return false24 if (char == '}' && expectedChar.pop() != '}') return false25 }26 return expectedChar.isEmpty()27 }28 @Test29 fun test1() {30 val input = "()"31 val result = isValid(input)32 Truth.assertThat(result).isTrue()33 }34 @Test35 fun test2() {36 val input = "(()"37 val result = isValid(input)38 Truth.assertThat(result).isFalse()...

Full Screen

Full Screen

HprofHeapGraphTest.kt

Source:HprofHeapGraphTest.kt Github

copy

Full Screen

...33 heapObject as HeapInstance34 assertThat(heapObject.instanceClassName).isEqualTo("SomeClass")35 }36 }37 @Test fun `char is correctly converted back`() {38 val heapDump = dump {39 "SomeClass" clazz { staticField["myChar"] = CharHolder('p') }40 }41 val myChar = heapDump.openHeapGraph().use { graph ->42 val myClass = graph.findClassByName("SomeClass")!!43 myClass.readStaticField("myChar")!!.value.asChar!!44 }45 assertThat(myChar).isEqualTo('p')46 }47}...

Full Screen

Full Screen

char

Using AI Code Generation

copy

Full Screen

1public class Test {2public static void main(String[] args) {3String s = "A";4char c = s.charAt(0);5System.out.println(c);6}7}83. Using substring() method9public class Test {10public static void main(String[] args) {11String s = "A";12String s1 = s.substring(0,1);13System.out.println(s1);14}15}164. Using toCharArray() method17public class Test {18public static void main(String[] args) {19String s = "A";20char c[] = s.toCharArray();21System.out.println(c[0]);22}23}245. Using getBytes() method25public class Test {26public static void main(String[] args) {27String s = "A";28byte b[] = s.getBytes();29System.out.println(b[0]);30}31}326. Using valueOf() method33public class Test {34public static void main(String[] args) {35char c = 'A';36String s = String.valueOf(c);37System.out.println(s);38}39}40public class Test {41public static void main(String[] args) {42String s = "A";43StringBuffer sb = new StringBuffer(s);44System.out.println(sb.charAt(0));45}46}47public class Test {48public static void main(String[] args) {49String s = "A";50StringBuilder sb = new StringBuilder(s);51System.out.println(sb.charAt(0));52}53}54public class Test {55public static void main(String[] args) {56String s = "A";57Character c = new Character(s.charAt(0));58System.out.println(c);59}60}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful