Skip to content

Commit 733dda7

Browse files
committed
Update golang docs
1 parent 6187407 commit 733dda7

1 file changed

Lines changed: 62 additions & 113 deletions

File tree

docs/technologies/go.md

Lines changed: 62 additions & 113 deletions
Original file line numberDiff line numberDiff line change
@@ -63,142 +63,91 @@ Evaluation script is actually what runs when the user on the codedamn playground
6363

6464
![](/images/common/lab-run-tests.png)
6565

66-
Since we have already written a pure evaluation script that runs and finally writes the JSON result to the `UNIT_TEST_OUTPUT_FILE` environment, all we have to do is trigger that script via Node.js.
67-
68-
The full path of the script is made available at run-time with another environment variable called `TEST_FILE_NAME`. Therefore, all we have to do is write the following in the evaluation script area:
66+
We have to write a boolean array to the file `$UNIT_TEST_OUTPUT_FILE`. Since go already has a builtin testing utility, we can use that as follows:
6967

7068
```sh
71-
node $TEST_FILE_NAME
72-
```
69+
#!/bin/bash
70+
set -e 1
7371

74-
This will make sure we run the full Node.js script and write the results properly for the playground IDE to read. It would look like the following:
72+
mv $TEST_FILE_NAME /home/damner/code/codedamn_evaluation_test.go
7573

76-
![](/images/html-css/lab-test-command.png)
74+
# run test
75+
cd /home/damner/code
76+
go mod init codedamn # assuming you used "codedamn" as the package
77+
go test -json -parallel 1 > codedamn_evaluation_output.json
7778

78-
**Note:** You can setup a full testing environment in this block of evaluation script (installing more packages, etc. if you want). However, your test file will be timed out **after 30 seconds**. Therefore, make sure, all of your testing can happen within 30 seconds.
79+
# process results file
80+
cat > processGoResults.js << EOF
81+
const fs = require('fs')
7982
80-
## Step 5 - Test file
83+
// Read the test results file into memory as a string
84+
const testResults = fs.readFileSync('./codedamn_evaluation_output.json', 'utf8').filter(Boolean)
85+
const lines = testResults.split('\n')
8186
82-
You will see a button named `Edit Test File` in the `Evaluation` tab. Click on it.
87+
// Create an empty array to store the pass/fail status of each test
88+
const results = []
8389
84-
![](/images/common/lab-edit-test.png)
90+
// Loop through each line and parse it as JSON and check if it is a result line
91+
lines.forEach(line => {
92+
const output = JSON.parse(line).Output?.trim()
93+
const valid = output === 'PASS' || output === 'FAIL'
94+
if(!valid) return
8595
86-
When you click on it, a new window will open. This is a test file area.
96+
const passed = output === 'PASS'
8797
88-
You can write anything here. Whatever script you write here, can be executed from the `Test command to run section` inside the evaluation tab we were in earlier.
98+
// Add the pass/fail status to the array
99+
results.push(passed)
100+
})
89101
90-
The point of having a file like this to provide you with a place where you can write your evaluation script.
102+
// Write results
103+
fs.writeFileSync(process.env.UNIT_TEST_OUTPUT_FILE, JSON.stringify(results))
104+
EOF
91105

92-
**For HTML/CSS labs, you can use the default test file of Node.js (Puppeteer) evaluation:**
106+
# process results
107+
node processGoResults.js
93108

94-
![](/images/html-css/lab-test-file-dropdown.png)
109+
# remove files
110+
rm /home/damner/code/codedamn_evaluation_test.go codedamn_evaluation_output.json processGoResults.js
111+
```
95112

96-
The moment you select the Node.js (Puppeteer), the following code should appear in your editor:
113+
Let's explain what's going on here:
97114

98-
```js
99-
// !! Boilerplate code starts
100-
const fs = require('fs')
101-
const puppeteer = require('puppeteer')
102-
103-
async function run() {
104-
// results is a boolean[] that maps challenge results shown to user
105-
const results = []
106-
107-
// launch the headless browser for testing
108-
const browser = await puppeteer.launch({
109-
executablePath: '/usr/bin/google-chrome',
110-
headless: true,
111-
args: [
112-
'--no-sandbox',
113-
'--disable-setuid-sandbox',
114-
'--disable-dev-shm-usage',
115-
'--disable-accelerated-2d-canvas',
116-
'--no-first-run',
117-
'--no-zygote',
118-
'--single-process',
119-
'--disable-gpu',
120-
],
121-
})
122-
page = await browser.newPage()
123-
124-
// wait for server to come online
125-
await page.goto('http://localhost:1337')
126-
127-
// add jQuery and chai for unit testing support if you want
128-
await Promise.all([
129-
page.addScriptTag({
130-
url: 'https://code.jquery.com/jquery-3.5.1.slim.min.js',
131-
}),
132-
page.addScriptTag({
133-
url: 'https://cdnjs.cloudflare.com/ajax/libs/chai/4.2.0/chai.min.js',
134-
}),
135-
])
136-
137-
// !! Boilerplate code ends
138-
139-
// Start your tests here in individual try-catch block
140-
141-
try {
142-
await page.evaluate(async () => {
143-
const assert = window.chai.assert
144-
assert(
145-
document.body.innerHTML.toLowerCase().includes('hello world')
146-
)
147-
})
148-
console.log('Test #1 passed!')
149-
results.push(true)
150-
} catch (error) {
151-
console.log('Test #1 failed! Did you do <this>?')
152-
results.push(false)
153-
}
154-
155-
try {
156-
await page.evaluate(async () => {
157-
const assert = window.chai.assert
158-
assert(
159-
document.body.innerHTML
160-
.toLowerCase()
161-
.includes('hello world again')
162-
)
163-
})
164-
console.log('Test #1 passed!')
165-
results.push(true)
166-
} catch (error) {
167-
console.log('Test #1 failed! Did you do <this>?')
168-
results.push(false)
169-
}
170-
171-
// End your tests here
172-
fs.writeFileSync(process.env.UNIT_TEST_OUTPUT_FILE, JSON.stringify(results))
173-
await browser.close().catch((err) => {})
174-
175-
// Exit the process
176-
process.exit(0)
177-
}
178-
run()
179-
// !! Boilerplate code ends
180-
```
115+
- We copy our test script (that we will write in next step) in the same directory as user code `/home/damner/code`. This way we can access user packages comfortably.
116+
- We run `go mod init` since `go.mod` file is required to be present when you run `go test` utility. If you have already created a `go.mod` file (in the default repository file setup), this command would do nothing
117+
- We now run `go test` with `-json` and `-parallel 1` flag. We need `json` flag as we will parse it using a simple Node.js script written later. You can use Go for that parsing too (if you can write an equivalent). We need `-parallel 1` so that we process the tests in correct order (since the mapping of the boolean array here is linked to how tests would appear on frontend).
118+
- Go's test util output is stored in a file called `codedamn_evaluation_output.json`. This file technically is not a valid JSON since Go streams all output as individual JSON objects.
119+
- We finally run the Node.js script that splits the file `codedamn_evaluation_output.json` by newline. We parse individual lines as JSON and only process the objects where the `.Output` field in JSON is either `PASS` or `FAIL`.
120+
- Since we have `-parallel 1`, the output order would be preserved on how you wrote the tests.
121+
- We store this boolean array into the `$UNIT_TEST_OUTPUT_FILE` which is then visible to the end user.
181122

182-
Let us understand what is happening here exactly:
123+
**Note:** Be careful with the package imports in go, package name and test file location.
183124

184-
- Remember that we can code anything in this file and then execute it later. In this example, we're writing a Node.js script from scratch.
185-
- Remember that we already have puppeteer with headless chrome pre-installed in codedamn playgrounds for HTML/CSS. Therefore, we can import it directly.
186-
- In the first part of `run` function, we start a headless puppeteer browser.
187-
- We then visit `http://localhost:1337`. At this point, I would highly recommend you to read [How port mapping works for codedamn playgrounds](/docs/concepts/port-mapping), if you haven't yet.
188-
- From this point onwards, we have some `try-catch` blocks. But why? Because we want to populate an array `results` and then finally write this array to a file inside environment variable `UNIT_TEST_OUTPUT_FILE`
189-
- Let's say, `[true, false]` is written to the file `process.env.UNIT_TEST_OUTPUT_FILE`. In that case, the first challenge would be marked as passed in the IDE, and the second challenge would be marked as failed:
125+
## Step 5 - Test file
190126

191-
![](/images/html-css/playground-tests.png)
127+
You will see a button named `Edit Test File` in the `Evaluation` tab. Click on it.
192128

193-
- Whatever your mapping of final JSON boolean array written in `process.env.UNIT_TEST_OUTPUT_FILE` is, it is matched exactly to the results on the playground. For example, if the array written is `[true, false, true, true]`, the following would be the output on playground:
129+
![](/images/common/lab-edit-test.png)
194130

195-
![](/images/html-css/playground-tests-2.png)
131+
When you click on it, a new window will open. This is a test file area.
196132

197-
- **Note:** If your `results` array contain less values than challenges added back in the UI, the "extra" UI challenges would automatically stay as "false". If you add more challenges in test file, the results would be ignored. Therefore, it is **important** that the `results.length` is same as the number of challenges you added in the challenges UI.
133+
You can write anything here. Whatever script you write here, can be executed from the `Test command to run section` inside the evaluation tab we were in earlier.
198134

199-
- We then also add jQuery and chai for assisting with testing. Although it is not required as long as you can populate the `results` array properly.
135+
The point of having a file like this to provide you with a place where you can write your evaluation script. As we decided earlier, you can write a simple Go test here:
136+
137+
```go
138+
package codedamn
139+
140+
import "testing"
141+
142+
func TestAdd(t *testing.T) {
143+
got := add(2, 3)
144+
if got != 5 {
145+
t.Errorf("add(2, 3) = %d; want 5", got)
146+
}
147+
}
148+
```
200149

201-
This completes your evaluation script for the lab. Your lab is now almost ready for users.
150+
This file contains only one test at the moment that would give JSON output stream that will be processed further by our Node.js script earlier. This completes your evaluation script for the lab. Your lab is now almost ready for users.
202151

203152
## Setup Verified Solution (Recommended)
204153

0 commit comments

Comments
 (0)