How to use executeCommand method in Appium Base Driver

Best JavaScript code snippet using appium-base-driver

Run Appium Base Driver automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

kumember.js

Source: kumember.js Github

copy
1import React, { Component } from "react";
2import UndoCommand from "./commands/UndoCommand";
3import RedoCommand from "./commands/RedoCommand";
4import BoldCommand from "./commands/BoldCommand";
5import CopyComand from "./commands/CopyCommand";
6import CutCommand from "./commands/CutCommand";
7import HeaderCommand from "./commands/HeadersTag";
8import ForegroundColorCommand from "./commands/ForegroundColorCommand";
9import BackgroundColorCommand from "./commands/BackgroundColorCommand";
10
11class Kumember extends Component {
12  constructor(props) {
13    super(props);
14    this.state = {
15      editor: false,
16      isPopupOpen: false,
17
18      foreColor: "#000",
19      backColor: "#fff"
20    };
21  }
22
23  componentDidMount() {
24    const editor = document.getElementById("kumember-editor");
25    editor.contentDocument.designMode = "on";
26    this.setState({
27      editor
28    });
29  }
30
31  executeCommand = (command, value) => {
32    this.state.editor.contentDocument.execCommand(command, false, value);
33
34    setTimeout(() => {
35      frames["kumember-editor"].document
36        .getElementsByTagName("body")[0]
37        .focus();
38    }, 50);
39  };
40
41  blurKumemberContentContainer = isBlur => {
42    let container = document.getElementById("kumember-content-container");
43  };
44
45  updatePopupState = status => {
46    this.setState({
47      isPopupOpen: status
48    });
49  };
50
51  onChangeBackColor = value => {
52    this.setState({
53      backColor: value
54    });
55  };
56
57  onChangeForeColor = value => {
58    this.setState({
59      foreColor: value
60    });
61  };
62
63  render() {
64    return (
65      <div className="kumember-layout-container">
66        <div className="kumember-header-container">
67          <button
68            className="uppercase main-button"
69            onClick={() => this.executeCommand("undo", null)}
70          >
71            <i className="fa fa-undo" aria-hidden="true"></i>
72          </button>
73          <button
74            className="uppercase main-button"
75            onClick={() => this.executeCommand("redo", null)}
76          >
77            <i className="fa fa-repeat" aria-hidden="true"></i>
78          </button>
79          <button
80            className="uppercase main-button"
81            onClick={() => this.executeCommand("copy", null)}
82          >
83            <i className="fa fa-files-o" aria-hidden="true"></i>
84          </button>
85          <button
86            className="uppercase main-button"
87            onClick={() => this.executeCommand("cut", null)}
88          >
89            <i className="fa fa-scissors" aria-hidden="true"></i>
90          </button>
91          <button
92            className="uppercase main-button"
93            onClick={() => this.executeCommand("bold", null)}
94          >
95            <i className="fa fa-bold" aria-hidden="true"></i>
96          </button>
97          <button
98            className="uppercase main-button"
99            onClick={() => this.executeCommand("italic", null)}
100          >
101            <i className="fa fa-italic" aria-hidden="true"></i>
102          </button>
103          <button
104            className="uppercase main-button"
105            onClick={() => this.executeCommand("strikeThrough", null)}
106          >
107            <i className="fa fa-strikethrough" aria-hidden="true"></i>
108          </button>
109          <button
110            className="uppercase main-button"
111            onClick={() => this.executeCommand("justtfyLeft", null)}
112          >
113            <i className="fa fa-align-left" aria-hidden="true"></i>
114          </button>
115          <button
116            className="uppercase main-button"
117            onClick={() => this.executeCommand("justifyCenter", null)}
118          >
119            <i className="fa fa-align-center" aria-hidden="true"></i>
120          </button>
121          <button
122            className="uppercase main-button"
123            onClick={() => this.executeCommand("justifyRight", null)}
124          >
125            <i className="fa fa-align-right" aria-hidden="true"></i>
126          </button>
127          <button
128            className="uppercase main-button"
129            onClick={() => this.executeCommand("justifyFull", null)}
130          >
131            <i className="fa fa-align-justify" aria-hidden="true"></i>
132          </button>
133          <button
134            className="uppercase main-button"
135            onClick={() => this.executeCommand("indent", null)}
136          >
137            <i className="fa fa-indent" aria-hidden="true"></i>
138          </button>
139          <button
140            className="uppercase main-button"
141            onClick={() => this.executeCommand("outdent", null)}
142          >
143            <i className="fa fa-dedent" aria-hidden="true"></i>
144          </button>
145          <button
146            className="uppercase main-button"
147            onClick={() => this.executeCommand("subscript", null)}
148          >
149            <i className="fa fa-subscript" aria-hidden="true"></i>
150          </button>
151          <button
152            className="uppercase main-button"
153            onClick={() => this.executeCommand("superscript", null)}
154          >
155            <i className="fa fa-superscript" aria-hidden="true"></i>
156          </button>
157          <button
158            className="uppercase main-button"
159            onClick={() => this.executeCommand("insertUnorderedList", null)}
160          >
161            <i className="fa fa-list-ul" aria-hidden="true"></i>
162          </button>
163          <button
164            className="uppercase main-button"
165            onClick={() => this.executeCommand("insertOrderedList", null)}
166          >
167            <i className="fa fa-list-ol" aria-hidden="true"></i>
168          </button>
169          <button
170            className="uppercase main-button"
171            onClick={() => this.executeCommand("insertParagraph", null)}
172          >
173            <i className="fa fa-paragraph" aria-hidden="true"></i>
174          </button>
175          <HeaderCommand
176            executeCommand={this.executeCommand}
177            updatePopupState={this.updatePopupState}
178          />
179          <ForegroundColorCommand
180            executeCommand={this.executeCommand}
181            updatePopupState={this.updatePopupState}
182            foreColor={this.state.foreColor}
183            backColor={this.state.backColor}
184            updatePropsState={this.onChangeForeColor}
185          />
186          <BackgroundColorCommand
187            executeCommand={this.executeCommand}
188            updatePopupState={this.updatePopupState}
189            foreColor={this.state.foreColor}
190            backColor={this.state.backColor}
191            updatePropsState={this.onChangeBackColor}
192          />
193
194          {/* <UndoCommand executeCommand={this.executeCommand} />
195                    <RedoCommand executeCommand={this.executeCommand} />
196                    <CopyComand executeCommand={this.executeCommand} />
197                    <CutCommand executeCommand={this.executeCommand} />
198                    <PasteCommand executeCommand={this.executeCommand} editor={this.state.editor} />
199                    <BoldCommand executeCommand={this.executeCommand} />
200                    <HeadersCommand executeCommand={this.executeCommand} />
201                    <button className="uppercase" onClick={() => this.executeCommand('backColor', '#dfa')}>Color</button>
202                    <button className="uppercase" onClick={() => this.executeCommand('copy', null)}>b</button>
203                    <button className="uppercase" onClick={() => this.executeCommand('cut', null)}>b</button>
204                    <button className="uppercase" onClick={() => this.executeCommand('delete', null)}>b</button>
205                    <button className="uppercase" onClick={() => this.executeCommand('foreColor', 'red')}>b</button>
206                    
207                    <button className="uppercase" onClick={() => this.executeCommand('bold', null)}>b</button>
208                    <button className="uppercase" onClick={() => this.executeCommand('bold', null)}>b</button> */}
209        </div>
210        <div
211          className="kumember-content-container"
212          id="kumember-content-container"
213        >
214          <iframe
215            className="kumember-editor"
216            name="kumember-editor"
217            id="kumember-editor"
218          ></iframe>
219          {this.state.isPopupOpen ? (
220            <div
221              style={{
222                backgroundColor: "#cdcdd0d1",
223                zIndex: 1000,
224                position: "absolute",
225                opacity: "0.6",
226                height: "100%"
227              }}
228              className="kumember-editor"
229            ></div>
230          ) : null}
231        </div>
232      </div>
233    );
234  }
235}
236
237export default Kumember;
238
Full Screen

test_common.js

Source: test_common.js Github

copy
1// Copyright 2021 Alexandre Díaz <[email protected]>
2// License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
3
4odoo.define("terminal.tests.common", function (require) {
5    "use strict";
6
7    const TerminalTestSuite = require("terminal.tests");
8    const Utils = require("terminal.core.Utils");
9    const rpc = require("terminal.core.rpc");
10
11    TerminalTestSuite.include({
12        // Can't test 'lang'
13        // Can't test 'reload'
14        // Can't test 'debug'
15        // Can't test 'post': No endpoint to test
16        // Can't test 'jstest'
17        // Can't test 'logout'
18
19        onStartTests: function () {
20            // Get the last res.partner.industry id
21            const def = this._super.apply(this, arguments);
22            return def.then(() => {
23                return rpc
24                    .query({
25                        method: "search_read",
26                        domain: [],
27                        fields: ["id"],
28                        model: "res.partner.industry",
29                        limit: 1,
30                        orderBy: "id DESC",
31                        kwargs: {context: this.terminal._getContext()},
32                    })
33                    .then((result) => {
34                        this._last_res_id = result[0].id;
35                        return result;
36                    });
37            });
38        },
39        onEndTests: function () {
40            // Delete all records used in tests
41            const def = this._super.apply(this, arguments);
42            return def.then(() => {
43                return rpc
44                    .query({
45                        method: "search_read",
46                        domain: [["id", ">", this._last_res_id]],
47                        fields: ["id"],
48                        model: "res.partner.industry",
49                        orderBy: "id DESC",
50                        kwargs: {context: this.terminal._getContext()},
51                    })
52                    .then((result) => {
53                        const ids = _.map(result, "id");
54                        if (_.isEmpty(result)) {
55                            return result;
56                        }
57                        return rpc.query({
58                            method: "unlink",
59                            model: "res.partner.industry",
60                            args: [ids],
61                            kwargs: {context: this.terminal._getContext()},
62                        });
63                    });
64            });
65        },
66
67        onBeforeTest: function (test_name) {
68            const def = this._super.apply(this, arguments);
69            return def.then(() => {
70                if (
71                    test_name === "test_context" ||
72                    test_name === "test_context_no_arg"
73                ) {
74                    return this.terminal
75                        .executeCommand("context", false, true)
76                        .then((context) => {
77                            this._orig_context = context;
78                        });
79                } else if (
80                    test_name === "test_upgrade" ||
81                    test_name === "test_upgrade__no_arg"
82                ) {
83                    return this.terminal.executeCommand(
84                        "install -m sms",
85                        false,
86                        true
87                    );
88                } else if (
89                    test_name === "test_uninstall" ||
90                    test_name === "test_uninstall__no_arg"
91                ) {
92                    return this.terminal.executeCommand(
93                        "install -m sms",
94                        false,
95                        true
96                    );
97                }
98            });
99        },
100
101        onAfterTest: function (test_name) {
102            const def = this._super.apply(this, arguments);
103            return def.then(() => {
104                if (
105                    test_name === "test_context" ||
106                    test_name === "test_context_no_arg"
107                ) {
108                    return this.terminal.executeCommand(
109                        `context -o set -v '${JSON.stringify(
110                            this._orig_context
111                        )}'`,
112                        false,
113                        true
114                    );
115                } else if (
116                    test_name === "test_upgrade" ||
117                    test_name === "test_upgrade__no_arg"
118                ) {
119                    return this.terminal.executeCommand(
120                        "uninstall -m sms",
121                        false,
122                        true
123                    );
124                }
125            });
126        },
127
128        test_create: async function () {
129            await this.terminal.executeCommand(
130                "create -m res.partner.industry",
131                false,
132                true
133            );
134            await new Promise((resolve) => setTimeout(resolve, 800));
135            this.assertTrue(this.isFormOpen());
136            const record_id = await this.terminal.executeCommand(
137                `create -m res.partner.industry -v "{'name': '${_.uniqueId(
138                    "This is a Test #"
139                )}'}"`,
140                false,
141                true
142            );
143            this.assertTrue(record_id > 0);
144        },
145        test_create__no_arg: async function () {
146            await this.terminal.executeCommand(
147                "create res.partner.industry",
148                false,
149                true
150            );
151            await new Promise((resolve) => setTimeout(resolve, 800));
152            this.assertTrue(this.isFormOpen());
153            const record_id = await this.terminal.executeCommand(
154                `create res.partner.industry "{'name': '${_.uniqueId(
155                    "This is a Test #"
156                )}'}"`,
157                false,
158                true
159            );
160            this.assertTrue(record_id > 0);
161        },
162
163        test_unlink: async function () {
164            const record_id = await this.terminal.executeCommand(
165                `create -m res.partner.industry -v "{'name': '${_.uniqueId(
166                    "This is a Test #"
167                )}'}"`,
168                false,
169                true
170            );
171            const res = await this.terminal.executeCommand(
172                `unlink -m res.partner.industry -i ${record_id}`,
173                false,
174                true
175            );
176            this.assertTrue(res);
177        },
178        test_unlink__no_arg: async function () {
179            const record_id = await this.terminal.executeCommand(
180                `create res.partner.industry "{'name': '${_.uniqueId(
181                    "This is a Test #"
182                )}'}"`,
183                false,
184                true
185            );
186            const res = await this.terminal.executeCommand(
187                `unlink res.partner.industry ${record_id}`,
188                false,
189                true
190            );
191            this.assertTrue(res);
192        },
193
194        test_write: async function () {
195            const record_a_id = await this.terminal.executeCommand(
196                `create -m res.partner.industry -v "{'name': '${_.uniqueId(
197                    "This is a Test #"
198                )}'}"`,
199                false,
200                true
201            );
202            const record_b_id = await this.terminal.executeCommand(
203                `create -m res.partner.industry -v "{'name': '${_.uniqueId(
204                    "This is a Test #"
205                )}'}"`,
206                false,
207                true
208            );
209            let res = await this.terminal.executeCommand(
210                `write -m res.partner.industry -i ${record_b_id} -v "{'name': '${_.uniqueId(
211                    "Other name Test #"
212                )}'}"`,
213                false,
214                true
215            );
216            this.assertTrue(res);
217            res = await this.terminal.executeCommand(
218                `write -m res.partner.industry -i "${record_a_id}, ${record_b_id}" -v "{'name': '${_.uniqueId(
219                    "Other name Test #"
220                )}'}"`,
221                false,
222                true
223            );
224            this.assertTrue(res);
225        },
226        test_write__no_arg: async function () {
227            const record_a_id = await this.terminal.executeCommand(
228                `create -m res.partner.industry -v "{'name': '${_.uniqueId(
229                    "This is a Test #"
230                )}'}"`,
231                false,
232                true
233            );
234            const record_b_id = await this.terminal.executeCommand(
235                `create res.partner.industry "{'name': '${_.uniqueId(
236                    "This is a Test #"
237                )}'}"`,
238                false,
239                true
240            );
241            let res = await this.terminal.executeCommand(
242                `write res.partner.industry ${record_b_id} "{'name': '${_.uniqueId(
243                    "Other name Test #"
244                )}'}"`,
245                false,
246                true
247            );
248            this.assertTrue(res);
249            res = await this.terminal.executeCommand(
250                `write res.partner.industry "${record_a_id}, ${record_b_id}" "{'name': '${_.uniqueId(
251                    "Other name Test #"
252                )}'}"`,
253                false,
254                true
255            );
256            this.assertTrue(res);
257        },
258
259        test_search: async function () {
260            const res = await this.terminal.executeCommand(
261                "search -m res.partner.industry -f name -d \"[['id', '>', 1]]\" -l 3 -of 2 -o \"id desc\"",
262                false,
263                true
264            );
265            this.assertEqual(res.length, 3);
266        },
267        test_search__no_arg: async function () {
268            const res = await this.terminal.executeCommand(
269                "search res.partner.industry name \"[['id', '>', 1]]\" 4 2 \"id desc\"",
270                false,
271                true
272            );
273            this.assertEqual(res.length, 4);
274        },
275
276        test_call: async function () {
277            const res = await this.terminal.executeCommand(
278                "call -m res.partner -c can_edit_vat -a [1]",
279                false,
280                true
281            );
282            this.assertTrue(res);
283        },
284        test_call__no_arg: async function () {
285            const res = await this.terminal.executeCommand(
286                "call res.partner can_edit_vat [1]",
287                false,
288                true
289            );
290            this.assertTrue(res);
291        },
292
293        test_upgrade: async function () {
294            await Utils.asyncSleep(6000);
295            const res = await this.terminal.executeCommand(
296                "upgrade -m sms",
297                false,
298                true
299            );
300            this.assertEqual(res[0]?.name, "sms");
301            await Utils.asyncSleep(6000);
302        },
303        test_upgrade__no_arg: async function () {
304            await Utils.asyncSleep(6000);
305            const res = await this.terminal.executeCommand(
306                "upgrade sms",
307                false,
308                true
309            );
310            await Utils.asyncSleep(6000);
311            this.assertEqual(res[0]?.name, "sms");
312        },
313
314        test_install: async function () {
315            await Utils.asyncSleep(6000);
316            const res = await this.terminal.executeCommand(
317                "install -m sms",
318                false,
319                true
320            );
321            await Utils.asyncSleep(6000);
322            this.assertEqual(res[0]?.name, "sms");
323        },
324        test_install__no_arg: async function () {
325            await Utils.asyncSleep(6000);
326            const res = await this.terminal.executeCommand(
327                "install sms",
328                false,
329                true
330            );
331            await Utils.asyncSleep(6000);
332            this.assertEqual(res[0]?.name, "sms");
333        },
334
335        test_uninstall: async function () {
336            await Utils.asyncSleep(6000);
337            const res = await this.terminal.executeCommand(
338                "uninstall -m sms",
339                false,
340                true
341            );
342            await Utils.asyncSleep(6000);
343            this.assertEqual(res[0]?.name, "sms");
344        },
345        test_uninstall__no_arg: async function () {
346            await Utils.asyncSleep(6000);
347            const res = await this.terminal.executeCommand(
348                "uninstall sms",
349                false,
350                true
351            );
352            await Utils.asyncSleep(6000);
353            this.assertEqual(res[0]?.name, "sms");
354        },
355
356        test_action: async function () {
357            let res = await this.terminal.executeCommand(
358                "action -a 5",
359                false,
360                true
361            );
362            this.assertEqual(res.id, 5);
363            if (this.terminal._mode === this.terminal.MODES.BACKEND_NEW) {
364                res = await this.terminal.executeCommand(
365                    "action -a base.action_res_company_form",
366                    false,
367                    true
368                );
369                this.assertEqual(res.id, "base.action_res_company_form");
370                res = await this.terminal.executeCommand(
371                    "action -a \"{'type': 'ir.actions.act_window', 'res_model': 'res.currency', 'view_type': 'form', 'view_mode': 'form', 'views': [[false, 'form']], 'target': 'current', 'res_id': 1}\"",
372                    false,
373                    true
374                );
375                this.assertNotEmpty(res);
376            } else {
377                res = await this.terminal.executeCommand(
378                    "action -a base.action_res_company_form",
379                    false,
380                    true
381                );
382                this.assertEqual(res.xml_id, "base.action_res_company_form");
383                res = await this.terminal.executeCommand(
384                    "action -a \"{'type': 'ir.actions.act_window', 'res_model': 'res.currency', 'view_type': 'form', 'view_mode': 'form', 'views': [[false, 'form']], 'target': 'current', 'res_id': 1}\"",
385                    false,
386                    true
387                );
388                this.assertEqual(res.res_model, "res.currency");
389                this.assertEqual(res.res_id, 1);
390            }
391        },
392        test_action__no_arg: async function () {
393            let res = await this.terminal.executeCommand(
394                "action 5",
395                false,
396                true
397            );
398            this.assertEqual(res.id, 5);
399            if (this.terminal._mode === this.terminal.MODES.BACKEND_NEW) {
400                res = await this.terminal.executeCommand(
401                    "action base.action_res_company_form",
402                    false,
403                    true
404                );
405                this.assertEqual(res.id, "base.action_res_company_form");
406                res = await this.terminal.executeCommand(
407                    "action \"{'type': 'ir.actions.act_window', 'res_model': 'res.currency', 'view_type': 'form', 'view_mode': 'form', 'views': [[false, 'form']], 'target': 'current', 'res_id': 1}\"",
408                    false,
409                    true
410                );
411                this.assertNotEmpty(res);
412            } else {
413                res = await this.terminal.executeCommand(
414                    "action base.action_res_company_form",
415                    false,
416                    true
417                );
418                this.assertEqual(res.xml_id, "base.action_res_company_form");
419                res = await this.terminal.executeCommand(
420                    "action \"{'type': 'ir.actions.act_window', 'res_model': 'res.currency', 'view_type': 'form', 'view_mode': 'form', 'views': [[false, 'form']], 'target': 'current', 'res_id': 1}\"",
421                    false,
422                    true
423                );
424                this.assertEqual(res.res_model, "res.currency");
425                this.assertEqual(res.res_id, 1);
426            }
427        },
428
429        test_whoami: async function () {
430            const res = await this.terminal.executeCommand(
431                "whoami",
432                false,
433                true
434            );
435            this.assertEqual(res[0]?.login, "admin");
436        },
437
438        test_caf: async function () {
439            const res = await this.terminal.executeCommand(
440                "caf -m res.currency -f symbol -fi \"{'required': true}\"",
441                false,
442                true
443            );
444            this.assertNotEmpty(res.symbol);
445            this.assertEmpty(res.id);
446        },
447        test_caf__no_arg: async function () {
448            const res = await this.terminal.executeCommand(
449                "caf res.currency symbol \"{'required': true}\"",
450                false,
451                true
452            );
453            this.assertNotEmpty(res.symbol);
454            this.assertEmpty(res.id);
455        },
456
457        test_cam: async function () {
458            let res = await this.terminal.executeCommand(
459                "cam -m res.currency -o create",
460                false,
461                true
462            );
463            this.assertTrue(res);
464            res = await this.terminal.executeCommand(
465                "cam -m res.currency -o unlink",
466                false,
467                true
468            );
469            this.assertTrue(res);
470            res = await this.terminal.executeCommand(
471                "cam -m res.currency -o write",
472                false,
473                true
474            );
475            this.assertTrue(res);
476            res = await this.terminal.executeCommand(
477                "cam -m res.currency -o read",
478                false,
479                true
480            );
481            this.assertTrue(res);
482        },
483        test_cam__no_arg: async function () {
484            const res = await this.terminal.executeCommand(
485                "cam res.currency create",
486                false,
487                true
488            );
489            this.assertTrue(res);
490        },
491
492        test_lastseen: async function () {
493            // Only test that can be called
494            await this.terminal.executeCommand("lastseen", false, true);
495        },
496
497        test_read: async function () {
498            const res = await this.terminal.executeCommand(
499                "read -m res.currency -i 1 -f symbol",
500                false,
501                true
502            );
503            this.assertEqual(res[0]?.id, 1);
504            this.assertNotEmpty(res[0]?.symbol);
505            this.assertEmpty(res[0]?.display_name);
506        },
507        test_read__no_arg: async function () {
508            const res = await this.terminal.executeCommand(
509                "read res.currency 1 symbol",
510                false,
511                true
512            );
513            this.assertEqual(res[0]?.id, 1);
514            this.assertNotEmpty(res[0]?.symbol);
515            this.assertEmpty(res[0]?.display_name);
516        },
517
518        test_context: async function () {
519            let res = await this.terminal.executeCommand(
520                "context",
521                false,
522                true
523            );
524            this.assertIn(res, "uid");
525            res = await this.terminal.executeCommand(
526                "context -o read",
527                false,
528                true
529            );
530            this.assertIn(res, "uid");
531            // At the moment operations with the context are not possible in legacy mode
532            if (this.terminal._mode !== this.terminal.MODES.BACKEND_NEW) {
533                res = await this.terminal.executeCommand(
534                    "context -o write -v \"{'test_key': 'test_value'}\"",
535                    false,
536                    true
537                );
538                this.assertIn(res, "test_key");
539                res = await this.terminal.executeCommand(
540                    "context -o set -v \"{'test_key': 'test_value_change'}\"",
541                    false,
542                    true
543                );
544                this.assertEqual(res.test_key, "test_value_change");
545                res = await this.terminal.executeCommand(
546                    "context -o delete -v test_key",
547                    false,
548                    true
549                );
550                this.assertNotIn(res, "test_key");
551            }
552        },
553        test_context__no_arg: async function () {
554            let res = await this.terminal.executeCommand(
555                "context read",
556                false,
557                true
558            );
559            this.assertIn(res, "uid");
560            // At the moment operations with the context are not possible in legacy mode
561            if (this.terminal._mode !== this.terminal.MODES.BACKEND_NEW) {
562                res = await this.terminal.executeCommand(
563                    "context write \"{'test_key': 'test_value'}\"",
564                    false,
565                    true
566                );
567                this.assertIn(res, "test_key");
568                res = await this.terminal.executeCommand(
569                    "context set \"{'test_key': 'test_value_change'}\"",
570                    false,
571                    true
572                );
573                this.assertEqual(res.test_key, "test_value_change");
574                res = await this.terminal.executeCommand(
575                    "context delete test_key",
576                    false,
577                    true
578                );
579                this.assertNotIn(res, "test_key");
580            }
581        },
582
583        test_version: async function () {
584            const res = await this.terminal.executeCommand(
585                "version",
586                false,
587                true
588            );
589            this.assertTrue(res);
590        },
591
592        test_longpolling: async function () {
593            let res = await this.terminal.executeCommand(
594                "longpolling -o verbose",
595                false,
596                true
597            );
598            this.assertTrue(res);
599            res = await this.terminal.executeCommand(
600                "longpolling -o off",
601                false,
602                true
603            );
604            this.assertTrue(res);
605            res = await this.terminal.executeCommand(
606                "longpolling -o add_channel -p test_channel",
607                false,
608                true
609            );
610            this.assertTrue(res);
611            res = await this.terminal.executeCommand(
612                "longpolling -o del_channel -p test_channel",
613                false,
614                true
615            );
616            this.assertTrue(res);
617            res = await this.terminal.executeCommand(
618                "longpolling -o stop",
619                false,
620                true
621            );
622            this.assertTrue(res);
623            res = await this.terminal.executeCommand(
624                "longpolling -o start",
625                false,
626                true
627            );
628            this.assertTrue(res);
629        },
630        test_longpolling__no_arg: async function () {
631            let res = await this.terminal.executeCommand(
632                "longpolling verbose",
633                false,
634                true
635            );
636            this.assertTrue(res);
637            res = await this.terminal.executeCommand(
638                "longpolling off",
639                false,
640                true
641            );
642            this.assertTrue(res);
643            res = await this.terminal.executeCommand(
644                "longpolling add_channel test_channel",
645                false,
646                true
647            );
648            this.assertTrue(res);
649            res = await this.terminal.executeCommand(
650                "longpolling del_channel test_channel",
651                false,
652                true
653            );
654            this.assertTrue(res);
655            res = await this.terminal.executeCommand(
656                "longpolling stop",
657                false,
658                true
659            );
660            this.assertTrue(res);
661            res = await this.terminal.executeCommand(
662                "longpolling start",
663                false,
664                true
665            );
666            this.assertTrue(res);
667        },
668
669        _isLogin: async function (login) {
670            const res = await this.terminal.executeCommand(
671                "whoami",
672                false,
673                true
674            );
675            return res[0]?.login === login;
676        },
677
678        test_login: async function () {
679            // Get active database
680            // FIXME: This type of calls are ugly, maybe some day
681            // can scan the dependencies.
682            let res = await this.terminal.executeCommand(
683                "dblist --only-active",
684                false,
685                true
686            );
687            const dbname = res;
688            res = await this.terminal.executeCommand(
689                `login -d ${dbname} -u demo -p demo`,
690                false,
691                true
692            );
693            this.assertTrue(res);
694            this.assertTrue(this._isLogin("demo"));
695            res = await this.terminal.executeCommand(
696                `login -d ${dbname} -u #admin`,
697                false,
698                true
699            );
700            this.assertTrue(res);
701            this.assertTrue(this._isLogin("admin"));
702        },
703        test_login__no_arg: async function () {
704            // Get active database
705            // FIXME: This type of calls are ugly, maybe some day
706            // can scan the dependencies.
707            let res = await this.terminal.executeCommand(
708                "dblist --only-active",
709                false,
710                true
711            );
712            const dbname = res;
713            res = await this.terminal.executeCommand(
714                `login ${dbname} demo demo`,
715                false,
716                true
717            );
718            this.assertTrue(res);
719            this.assertTrue(this._isLogin("demo"));
720            res = await this.terminal.executeCommand(
721                `login ${dbname} #admin`,
722                false,
723                true
724            );
725            this.assertTrue(res);
726            this.assertTrue(this._isLogin("admin"));
727        },
728
729        test_uhg: async function () {
730            const res = await this.terminal.executeCommand(
731                "uhg -g base.group_user",
732                false,
733                true
734            );
735            this.assertTrue(res);
736        },
737        test_uhg__no_arg: async function () {
738            const res = await this.terminal.executeCommand(
739                "uhg base.group_user",
740                false,
741                true
742            );
743            this.assertTrue(res);
744        },
745
746        test_dblist: async function () {
747            let res = await this.terminal.executeCommand("dblist", false, true);
748            this.assertNotEmpty(res);
749
750            res = await this.terminal.executeCommand(
751                "dblist --only-active",
752                false,
753                true
754            );
755            this.assertTrue(typeof res === "string");
756        },
757
758        test_tour: async function () {
759            // This test is incomplete to avoid page reloads
760            const res = await this.terminal.executeCommand("tour", false, true);
761            this.assertNotEmpty(res);
762        },
763
764        test_json: async function () {
765            const res = await this.terminal.executeCommand(
766                "json -e /web_editor/get_assets_editor_resources -d \"{'key':'web.assets_backend'}\"",
767                false,
768                true
769            );
770            this.assertIn(res, "views");
771        },
772        test_json__no_arg: async function () {
773            const res = await this.terminal.executeCommand(
774                "json /web_editor/get_assets_editor_resources \"{'key':'web.assets_backend'}\"",
775                false,
776                true
777            );
778            this.assertIn(res, "views");
779        },
780
781        test_depends: async function () {
782            const res = await this.terminal.executeCommand(
783                "depends -m mail",
784                false,
785                true
786            );
787            this.assertNotEmpty(res);
788        },
789        test_depends__no_arg: async function () {
790            const res = await this.terminal.executeCommand(
791                "depends mail",
792                false,
793                true
794            );
795            this.assertNotEmpty(res);
796        },
797
798        test_ual: async function () {
799            const res = await this.terminal.executeCommand("ual", false, true);
800            this.assertTrue(res);
801        },
802
803        test_count: async function () {
804            const res = await this.terminal.executeCommand(
805                "count -m res.currency",
806                false,
807                true
808            );
809            this.assertTrue(res > 0);
810            const resb = await this.terminal.executeCommand(
811                "count -m res.currency -d \"[['symbol', '=', '$']]\"",
812                false,
813                true
814            );
815            this.assertTrue(resb < res);
816        },
817        test_count__no_arg: async function () {
818            const res = await this.terminal.executeCommand(
819                "count res.currency",
820                false,
821                true
822            );
823            this.assertTrue(res > 0);
824            const resb = await this.terminal.executeCommand(
825                "count res.currency \"[['symbol', '=', '$']]\"",
826                false,
827                true
828            );
829            this.assertTrue(resb < res);
830        },
831
832        test_ref: async function () {
833            const res = await this.terminal.executeCommand(
834                "ref -x base.main_company,base.model_res_partner",
835                false,
836                true
837            );
838            this.assertNotEmpty(res);
839            this.assertEqual(res.length, 2);
840        },
841        test_ref__no_arg: async function () {
842            const res = await this.terminal.executeCommand(
843                "ref base.main_company,base.model_res_partner",
844                false,
845                true
846            );
847            this.assertNotEmpty(res);
848            this.assertEqual(res.length, 2);
849        },
850
851        test_rpc: async function () {
852            const res = await this.terminal.executeCommand(
853                "rpc -o \"{'route': '/jsonrpc', 'method': 'server_version', 'params': {'service': 'db'}}\"",
854                false,
855                true
856            );
857            this.assertNotEmpty(res);
858        },
859        test_rpc__no_arg: async function () {
860            const res = await this.terminal.executeCommand(
861                "rpc \"{'route': '/jsonrpc', 'method': 'server_version', 'params': {'service': 'db'}}\"",
862                false,
863                true
864            );
865            this.assertNotEmpty(res);
866        },
867
868        test_metadata: async function () {
869            const res = await this.terminal.executeCommand(
870                "metadata -m res.partner -i 1",
871                false,
872                true
873            );
874            this.assertNotEmpty(res);
875            this.assertEqual(res.xmlid, "base.main_partner");
876        },
877        test_metadata__no_arg: async function () {
878            const res = await this.terminal.executeCommand(
879                "metadata res.partner 1",
880                false,
881                true
882            );
883            this.assertNotEmpty(res);
884            this.assertEqual(res.xmlid, "base.main_partner");
885        },
886    });
887});
888
Full Screen

robot.test.js

Source: robot.test.js Github

copy
1const {
2  MAX_X,
3  MOVE,
4  LEFT,
5  REPORT,
6  NORTH,
7  WEST,
8  SOUTH,
9  EAST,
10} = require("../src/constants.js");
11const createRobot = require("../src/robot.js");
12
13describe("test robot module", () => {
14  it("ignore commands until 1st valid PLACE command", () => {
15    const robot = createRobot();
16    let x, y, f;
17
18    robot.executeCommand("INVALID COMMAND 1");
19    robot.executeCommand("");
20    robot.executeCommand(MOVE);
21    robot.executeCommand(MOVE);
22    robot.executeCommand(LEFT);
23
24    ({ x, y, f } = robot.getCurrentPostion());
25    expect(x).toEqual(0);
26    expect(y).toEqual(0);
27    expect(f).toEqual("");
28
29    // 1st valid PLACE command after many ignored / invalid commands will be executed
30    robot.executeCommand("PLACE 2,3,EAST");
31    ({ x, y, f } = robot.getCurrentPostion());
32    expect(x).toEqual(2);
33    expect(y).toEqual(3);
34    expect(f).toEqual(EAST);
35  });
36
37  it("move that make robot falls will be prevented", () => {
38    const robot = createRobot();
39    let x, y, f;
40    // robot at the top NORTH EAST. MOVE commmand will make robot fall, so will be discarded
41    robot.executeCommand("PLACE 4,4,NORTH");
42    robot.executeCommand(MOVE);
43    ({ x, y, f } = robot.getCurrentPostion());
44    expect(x).toEqual(4);
45    expect(y).toEqual(4);
46    expect(f).toEqual(NORTH);
47
48    // robot at the origin, facing SOUTH. MOVE comand will make robot fall, so will be discarded
49    robot.executeCommand("PLACE 0,0,SOUTH");
50    robot.executeCommand(MOVE);
51    ({ x, y, f } = robot.getCurrentPostion());
52    expect(x).toEqual(0);
53    expect(y).toEqual(0);
54    expect(f).toEqual(SOUTH);
55  });
56
57  it("Movements causing robot to fall will be prevented, but further valid movements commands still be allowed", () => {
58    const robot = createRobot();
59    let x, y, f;
60
61    // robot at the top NORTH EAST.
62    robot.executeCommand("PLACE 4,4,NORTH");
63
64    // A MOVE commmand will make robot fall, so will be discarded
65    robot.executeCommand(MOVE);
66    ({ x, y, f } = robot.getCurrentPostion());
67    expect(x).toEqual(4);
68    expect(y).toEqual(4);
69    expect(f).toEqual(NORTH);
70
71    // LEFT command not causing robot to fall so will be executed
72    robot.executeCommand(LEFT);
73    ({ x, y, f } = robot.getCurrentPostion());
74    expect(x).toEqual(4);
75    expect(y).toEqual(4);
76    expect(f).toEqual(WEST);
77  });
78
79  it("PLACE command to position robot out of the table, will be discarded", () => {
80    const robot = createRobot();
81    robot.executeCommand("PLACE 5,5,NORTH");
82    const { x, y, f } = robot.getCurrentPostion();
83    expect(x).toEqual(0);
84    expect(y).toEqual(0);
85    expect(f).toEqual("");
86  });
87
88  it("commands in example 1", () => {
89    const robot = createRobot();
90    robot.executeCommand("PLACE 0,0,NORTH");
91    robot.executeCommand(MOVE);
92    robot.executeCommand(REPORT);
93
94    const { x, y, f } = robot.getCurrentPostion();
95    expect(x).toEqual(0);
96    expect(y).toEqual(1);
97    expect(f).toEqual(NORTH);
98  });
99
100  it("commands in example 2", () => {
101    const robot = createRobot();
102    robot.executeCommand("PLACE 0,0,NORTH");
103    robot.executeCommand(LEFT);
104    robot.executeCommand(REPORT);
105
106    const { x, y, f } = robot.getCurrentPostion();
107    expect(x).toEqual(0);
108    expect(y).toEqual(0);
109    expect(f).toEqual(WEST);
110  });
111
112  it("commands in example 3", () => {
113    const robot = createRobot();
114    robot.executeCommand("PLACE 1,2,EAST");
115    robot.executeCommand(MOVE);
116    robot.executeCommand(MOVE);
117    robot.executeCommand(LEFT);
118    robot.executeCommand(MOVE);
119    robot.executeCommand(REPORT);
120
121    const { x, y, f } = robot.getCurrentPostion();
122    expect(x).toEqual(3);
123    expect(y).toEqual(3);
124    expect(f).toEqual(NORTH);
125  });
126});
127
Full Screen

extension.test.js

Source: extension.test.js Github

copy
1import fs from "fs";
2import path from "path";
3import vscode from "vscode";
4import yaml from "js-yaml";
5import lockFile from "lockfile";
6import untildify from "untildify";
7
8import {activate, deactivate} from "../src/extension";
9import {
10    COMMAND,
11    NOTIFICATION,
12    SYNCIGNORE, 
13    getRepoInSyncMsg, 
14    getDirectoryIsSyncedMsg,
15    getDirectorySyncIgnoredMsg
16} from "../src/constants";
17import {
18    SignUpHandler,
19    SyncHandler,
20    trackFileHandler,
21    trackRepoHandler,
22    unSyncHandler,
23    openSyncIgnoreHandler
24} from "../src/handlers/commands_handler";
25import {createSystemDirectories} from "../src/utils/setup_utils";
26import {
27    addUser,
28    Config,
29    getConfigFilePath,
30    randomBaseRepoPath,
31    randomRepoPath,
32    setWorkspaceFolders
33} from "./helpers/helpers";
34import {logout} from "../src/utils/auth_utils";
35import { generateSettings } from "../src/settings";
36import { CodeSyncState, CODESYNC_STATES } from "../src/utils/state_utils";
37
38describe("Extension: activate",() => {
39    const baseRepoPath = randomBaseRepoPath();
40    const repoPath = randomRepoPath();
41    const configPath = getConfigFilePath(baseRepoPath);
42    const configData = {repos: {}};
43    configData.repos[repoPath] = {branches: {}};
44
45    beforeEach(() => {
46        jest.clearAllMocks();
47        setWorkspaceFolders(repoPath);
48        untildify.mockReturnValue(baseRepoPath);
49        createSystemDirectories();
50        fs.mkdirSync(repoPath, {recursive: true});
51        global.IS_CODESYNC_DEV = true;
52    });
53
54    afterEach(() => {
55        fs.rmSync(repoPath, { recursive: true, force: true });
56        fs.rmSync(baseRepoPath, { recursive: true, force: true });
57    });
58
59    test("Fresh Setup, no user, no repo opened", async () => {
60        setWorkspaceFolders("");
61        await activate(vscode.ExtensionContext);
62        expect(vscode.commands.executeCommand).toHaveBeenCalledTimes(5);
63        // showLogin should be true
64        expect(vscode.commands.executeCommand.mock.calls[0][0]).toStrictEqual("setContext");
65        expect(vscode.commands.executeCommand.mock.calls[0][1]).toStrictEqual("showLogIn");
66        expect(vscode.commands.executeCommand.mock.calls[0][2]).toStrictEqual(true);
67        // showConnectRepoView should be false
68        expect(vscode.commands.executeCommand.mock.calls[1][0]).toStrictEqual("setContext");
69        expect(vscode.commands.executeCommand.mock.calls[1][1]).toStrictEqual("showConnectRepoView");
70        expect(vscode.commands.executeCommand.mock.calls[1][2]).toStrictEqual(false);
71        // isSubDir should be false
72        expect(vscode.commands.executeCommand.mock.calls[2][0]).toStrictEqual("setContext");
73        expect(vscode.commands.executeCommand.mock.calls[2][1]).toStrictEqual("isSubDir");
74        expect(vscode.commands.executeCommand.mock.calls[2][2]).toStrictEqual(false);
75        // isSyncIgnored should be false
76        expect(vscode.commands.executeCommand.mock.calls[3][0]).toStrictEqual("setContext");
77        expect(vscode.commands.executeCommand.mock.calls[3][1]).toStrictEqual("isSyncIgnored");
78        expect(vscode.commands.executeCommand.mock.calls[3][2]).toStrictEqual(false);
79        // CodeSyncActivated should be true
80        expect(vscode.commands.executeCommand.mock.calls[4][0]).toStrictEqual("setContext");
81        expect(vscode.commands.executeCommand.mock.calls[4][1]).toStrictEqual("CodeSyncActivated");
82        expect(vscode.commands.executeCommand.mock.calls[4][2]).toStrictEqual(true);
83
84        // Register commands
85        expect(vscode.commands.registerCommand).toHaveBeenCalledTimes(7);
86        expect(vscode.commands.registerCommand.mock.calls[0][0]).toStrictEqual(COMMAND.triggerSignUp);
87        expect(vscode.commands.registerCommand.mock.calls[0][1]).toStrictEqual(SignUpHandler);
88        expect(vscode.commands.registerCommand.mock.calls[1][0]).toStrictEqual(COMMAND.triggerLogout);
89        expect(vscode.commands.registerCommand.mock.calls[1][1]).toStrictEqual(logout);
90        expect(vscode.commands.registerCommand.mock.calls[2][0]).toStrictEqual(COMMAND.triggerSync);
91        expect(vscode.commands.registerCommand.mock.calls[2][1]).toStrictEqual(SyncHandler);
92        expect(vscode.commands.registerCommand.mock.calls[3][0]).toStrictEqual(COMMAND.triggerUnsync);
93        expect(vscode.commands.registerCommand.mock.calls[3][1]).toStrictEqual(unSyncHandler);
94        expect(vscode.commands.registerCommand.mock.calls[4][0]).toStrictEqual(COMMAND.trackRepo);
95        expect(vscode.commands.registerCommand.mock.calls[4][1]).toStrictEqual(trackRepoHandler);
96        expect(vscode.commands.registerCommand.mock.calls[5][0]).toStrictEqual(COMMAND.trackFile);
97        expect(vscode.commands.registerCommand.mock.calls[5][1]).toStrictEqual(trackFileHandler);
98        expect(vscode.commands.registerCommand.mock.calls[6][0]).toStrictEqual(COMMAND.openSyncIgnore);
99        expect(vscode.commands.registerCommand.mock.calls[6][1]).toStrictEqual(openSyncIgnoreHandler);
100
101        // createStatusBarItem
102        expect(vscode.window.createStatusBarItem).toHaveBeenCalledTimes(1);
103
104        // Should show Welcome msg
105        expect(vscode.window.showInformationMessage).toHaveBeenCalledTimes(1);
106        expect(vscode.window.showInformationMessage.mock.calls[0][0]).toBe(NOTIFICATION.WELCOME_MSG);
107        expect(vscode.window.showInformationMessage.mock.calls[0][1]).toBe(NOTIFICATION.JOIN);
108        expect(vscode.window.showInformationMessage.mock.calls[0][2]).toBe(NOTIFICATION.IGNORE);
109
110        // Verify events listeners are registered just fine
111        // onDidChangeTextDocument
112        expect(vscode.workspace.onDidChangeTextDocument).toHaveBeenCalledTimes(1);
113        // onDidCreateFiles
114        expect(vscode.workspace.onDidCreateFiles).toHaveBeenCalledTimes(1);
115        // onDidRenameFiles
116        expect(vscode.workspace.onDidRenameFiles).toHaveBeenCalledTimes(1);
117    });
118
119    test("Fresh Setup, no active user, repo not synced", async () => {
120        addUser(baseRepoPath, false);
121        setWorkspaceFolders(repoPath);
122        await activate(vscode.ExtensionContext);
123        expect(vscode.commands.executeCommand).toHaveBeenCalledTimes(5);
124        // showLogin should be true
125        expect(vscode.commands.executeCommand.mock.calls[0][0]).toStrictEqual("setContext");
126        expect(vscode.commands.executeCommand.mock.calls[0][1]).toStrictEqual("showLogIn");
127        expect(vscode.commands.executeCommand.mock.calls[0][2]).toStrictEqual(true);
128        // showConnectRepoView should be true
129        expect(vscode.commands.executeCommand.mock.calls[1][0]).toStrictEqual("setContext");
130        expect(vscode.commands.executeCommand.mock.calls[1][1]).toStrictEqual("showConnectRepoView");
131        expect(vscode.commands.executeCommand.mock.calls[1][2]).toStrictEqual(true);
132        // isSubDir should be false
133        expect(vscode.commands.executeCommand.mock.calls[2][0]).toStrictEqual("setContext");
134        expect(vscode.commands.executeCommand.mock.calls[2][1]).toStrictEqual("isSubDir");
135        expect(vscode.commands.executeCommand.mock.calls[2][2]).toStrictEqual(false);
136        // isSyncIgnored should be false
137        expect(vscode.commands.executeCommand.mock.calls[3][0]).toStrictEqual("setContext");
138        expect(vscode.commands.executeCommand.mock.calls[3][1]).toStrictEqual("isSyncIgnored");
139        expect(vscode.commands.executeCommand.mock.calls[3][2]).toStrictEqual(false);
140
141        // Should show Welcome msg
142        expect(vscode.window.showInformationMessage).toHaveBeenCalledTimes(1);
143        expect(vscode.window.showInformationMessage.mock.calls[0][0]).toBe(NOTIFICATION.WELCOME_MSG);
144        expect(vscode.window.showInformationMessage.mock.calls[0][1]).toBe(NOTIFICATION.JOIN);
145        expect(vscode.window.showInformationMessage.mock.calls[0][2]).toBe(NOTIFICATION.IGNORE);
146    });
147
148    test("With user, repo not synced", async () => {
149        addUser(baseRepoPath);
150        await activate(vscode.ExtensionContext);
151        expect(vscode.commands.executeCommand).toHaveBeenCalledTimes(7);
152        // showLogin should be true
153        expect(vscode.commands.executeCommand.mock.calls[0][0]).toStrictEqual("setContext");
154        expect(vscode.commands.executeCommand.mock.calls[0][1]).toStrictEqual("showLogIn");
155        expect(vscode.commands.executeCommand.mock.calls[0][2]).toStrictEqual(false);
156        // showConnectRepoView should be true
157        expect(vscode.commands.executeCommand.mock.calls[1][0]).toStrictEqual("setContext");
158        expect(vscode.commands.executeCommand.mock.calls[1][1]).toStrictEqual("showConnectRepoView");
159        expect(vscode.commands.executeCommand.mock.calls[1][2]).toStrictEqual(true);
160        // isSubDir should be false
161        expect(vscode.commands.executeCommand.mock.calls[2][0]).toStrictEqual("setContext");
162        expect(vscode.commands.executeCommand.mock.calls[2][1]).toStrictEqual("isSubDir");
163        expect(vscode.commands.executeCommand.mock.calls[2][2]).toStrictEqual(false);
164        // isSyncIgnored should be false
165        expect(vscode.commands.executeCommand.mock.calls[3][0]).toStrictEqual("setContext");
166        expect(vscode.commands.executeCommand.mock.calls[3][1]).toStrictEqual("isSyncIgnored");
167        expect(vscode.commands.executeCommand.mock.calls[3][2]).toStrictEqual(false);
168
169        // Should show Welcome msg
170        expect(vscode.window.showInformationMessage).toHaveBeenCalledTimes(1);
171        expect(vscode.window.showInformationMessage.mock.calls[0][0]).toBe(NOTIFICATION.CONNECT_REPO);
172        expect(vscode.window.showInformationMessage.mock.calls[0][1]).toBe(NOTIFICATION.CONNECT);
173    });
174
175    test("With user, repo is disconnected", async () => {
176        addUser(baseRepoPath);
177        const _configData = JSON.parse(JSON.stringify(configData));
178        _configData.repos[repoPath].is_disconnected = true;
179        fs.writeFileSync(configPath, yaml.safeDump(_configData));
180        await activate(vscode.ExtensionContext);
181        expect(vscode.commands.executeCommand).toHaveBeenCalledTimes(7);
182        // showLogin should be true
183        expect(vscode.commands.executeCommand.mock.calls[0][0]).toStrictEqual("setContext");
184        expect(vscode.commands.executeCommand.mock.calls[0][1]).toStrictEqual("showLogIn");
185        expect(vscode.commands.executeCommand.mock.calls[0][2]).toStrictEqual(false);
186        // showConnectRepoView should be true
187        expect(vscode.commands.executeCommand.mock.calls[1][0]).toStrictEqual("setContext");
188        expect(vscode.commands.executeCommand.mock.calls[1][1]).toStrictEqual("showConnectRepoView");
189        expect(vscode.commands.executeCommand.mock.calls[1][2]).toStrictEqual(true);
190        // isSubDir should be false
191        expect(vscode.commands.executeCommand.mock.calls[2][0]).toStrictEqual("setContext");
192        expect(vscode.commands.executeCommand.mock.calls[2][1]).toStrictEqual("isSubDir");
193        expect(vscode.commands.executeCommand.mock.calls[2][2]).toStrictEqual(false);
194        // isSyncIgnored should be false
195        expect(vscode.commands.executeCommand.mock.calls[3][0]).toStrictEqual("setContext");
196        expect(vscode.commands.executeCommand.mock.calls[3][1]).toStrictEqual("isSyncIgnored");
197        expect(vscode.commands.executeCommand.mock.calls[3][2]).toStrictEqual(false);
198
199        // Should show Welcome msg
200        expect(vscode.window.showInformationMessage).toHaveBeenCalledTimes(1);
201        expect(vscode.window.showInformationMessage.mock.calls[0][0]).toBe(NOTIFICATION.CONNECT_REPO);
202        expect(vscode.window.showInformationMessage.mock.calls[0][1]).toBe(NOTIFICATION.CONNECT);
203    });
204
205    test("With user, repo is in sync", async () => {
206        const configUtil = new Config(repoPath, configPath);
207        configUtil.addRepo();
208        addUser(baseRepoPath);
209        await activate(vscode.ExtensionContext);
210        expect(vscode.commands.executeCommand).toHaveBeenCalledTimes(7);
211        // showLogin should be true
212        expect(vscode.commands.executeCommand.mock.calls[0][0]).toStrictEqual("setContext");
213        expect(vscode.commands.executeCommand.mock.calls[0][1]).toStrictEqual("showLogIn");
214        expect(vscode.commands.executeCommand.mock.calls[0][2]).toStrictEqual(false);
215        // showConnectRepoView should be true
216        expect(vscode.commands.executeCommand.mock.calls[1][0]).toStrictEqual("setContext");
217        expect(vscode.commands.executeCommand.mock.calls[1][1]).toStrictEqual("showConnectRepoView");
218        expect(vscode.commands.executeCommand.mock.calls[1][2]).toStrictEqual(false);
219        // isSubDir should be false
220        expect(vscode.commands.executeCommand.mock.calls[2][0]).toStrictEqual("setContext");
221        expect(vscode.commands.executeCommand.mock.calls[2][1]).toStrictEqual("isSubDir");
222        expect(vscode.commands.executeCommand.mock.calls[2][2]).toStrictEqual(false);
223        // isSyncIgnored should be false
224        expect(vscode.commands.executeCommand.mock.calls[3][0]).toStrictEqual("setContext");
225        expect(vscode.commands.executeCommand.mock.calls[3][1]).toStrictEqual("isSyncIgnored");
226        expect(vscode.commands.executeCommand.mock.calls[3][2]).toStrictEqual(false);
227
228        const msg = getRepoInSyncMsg(repoPath);
229        // Should show Welcome msg
230        expect(vscode.window.showInformationMessage).toHaveBeenCalledTimes(1);
231        expect(vscode.window.showInformationMessage.mock.calls[0][0]).toBe(msg);
232        expect(vscode.window.showInformationMessage.mock.calls[0][1]).toBe(NOTIFICATION.TRACK_IT);
233    });
234
235    test("With user, repo is sub directory and synced", async () => {
236        const configUtil = new Config(repoPath, configPath);
237        configUtil.addRepo();
238        addUser(baseRepoPath);
239        const subDir = path.join(repoPath, "directory");
240        setWorkspaceFolders(subDir);
241        await activate(vscode.ExtensionContext);
242        expect(vscode.commands.executeCommand).toHaveBeenCalledTimes(7);
243        // showLogin should be false
244        expect(vscode.commands.executeCommand.mock.calls[0][0]).toStrictEqual("setContext");
245        expect(vscode.commands.executeCommand.mock.calls[0][1]).toStrictEqual("showLogIn");
246        expect(vscode.commands.executeCommand.mock.calls[0][2]).toStrictEqual(false);
247        // showConnectRepoView should be false
248        expect(vscode.commands.executeCommand.mock.calls[1][0]).toStrictEqual("setContext");
249        expect(vscode.commands.executeCommand.mock.calls[1][1]).toStrictEqual("showConnectRepoView");
250        expect(vscode.commands.executeCommand.mock.calls[1][2]).toStrictEqual(false);
251        // isSubDir should be true
252        expect(vscode.commands.executeCommand.mock.calls[2][0]).toStrictEqual("setContext");
253        expect(vscode.commands.executeCommand.mock.calls[2][1]).toStrictEqual("isSubDir");
254        expect(vscode.commands.executeCommand.mock.calls[2][2]).toStrictEqual(true);
255        // isSyncIgnored should be false
256        expect(vscode.commands.executeCommand.mock.calls[3][0]).toStrictEqual("setContext");
257        expect(vscode.commands.executeCommand.mock.calls[3][1]).toStrictEqual("isSyncIgnored");
258        expect(vscode.commands.executeCommand.mock.calls[3][2]).toStrictEqual(false);
259
260        const msg = getDirectoryIsSyncedMsg(subDir, repoPath);
261        // Should show Welcome msg
262        expect(vscode.window.showInformationMessage).toHaveBeenCalledTimes(1);
263        expect(vscode.window.showInformationMessage.mock.calls[0][0]).toBe(msg);
264        expect(vscode.window.showInformationMessage.mock.calls[0][1]).toBe(NOTIFICATION.TRACK_PARENT_REPO);
265    });
266
267    test("With user, repo is sub directory and syncignored", async () => {
268        const subDirName = "directory";
269        const configUtil = new Config(repoPath, configPath);
270        configUtil.addRepo();
271        addUser(baseRepoPath);
272        // Add subDir to .syncignore
273        const syncignorePath = path.join(repoPath, SYNCIGNORE);
274        fs.writeFileSync(syncignorePath, subDirName);
275        const subDir = path.join(repoPath, subDirName);
276        setWorkspaceFolders(subDir);
277        await activate(vscode.ExtensionContext);
278        expect(vscode.commands.executeCommand).toHaveBeenCalledTimes(7);
279        // showLogin should be true
280        expect(vscode.commands.executeCommand.mock.calls[0][0]).toStrictEqual("setContext");
281        expect(vscode.commands.executeCommand.mock.calls[0][1]).toStrictEqual("showLogIn");
282        expect(vscode.commands.executeCommand.mock.calls[0][2]).toStrictEqual(false);
283        // showConnectRepoView should be true
284        expect(vscode.commands.executeCommand.mock.calls[1][0]).toStrictEqual("setContext");
285        expect(vscode.commands.executeCommand.mock.calls[1][1]).toStrictEqual("showConnectRepoView");
286        expect(vscode.commands.executeCommand.mock.calls[1][2]).toStrictEqual(true);
287        // isSubDir should be true
288        expect(vscode.commands.executeCommand.mock.calls[2][0]).toStrictEqual("setContext");
289        expect(vscode.commands.executeCommand.mock.calls[2][1]).toStrictEqual("isSubDir");
290        expect(vscode.commands.executeCommand.mock.calls[2][2]).toStrictEqual(true);
291        // isSyncIgnored should be false
292        expect(vscode.commands.executeCommand.mock.calls[3][0]).toStrictEqual("setContext");
293        expect(vscode.commands.executeCommand.mock.calls[3][1]).toStrictEqual("isSyncIgnored");
294        expect(vscode.commands.executeCommand.mock.calls[3][2]).toStrictEqual(true);
295
296        const msg = getDirectorySyncIgnoredMsg(subDir, repoPath);
297        // Should show Welcome msg
298        expect(vscode.window.showInformationMessage).toHaveBeenCalledTimes(1);
299        expect(vscode.window.showInformationMessage.mock.calls[0][0]).toBe(msg);
300        expect(vscode.window.showInformationMessage.mock.calls[0][1]).toBe(NOTIFICATION.OPEN_SYNCIGNORE);
301        expect(vscode.window.showInformationMessage.mock.calls[0][2]).toBe(NOTIFICATION.TRACK_PARENT_REPO);
302        expect(vscode.window.showInformationMessage.mock.calls[0][3]).toBe(NOTIFICATION.UNSYNC_PARENT_REPO);
303    });
304});
305
306describe("Extension: deactivate",() => {
307    const baseRepoPath = randomBaseRepoPath();
308    untildify.mockReturnValue(baseRepoPath);
309    const settings = generateSettings();
310
311    beforeEach(() => {
312        jest.clearAllMocks();
313        jest.spyOn(global.console, 'log');
314        untildify.mockReturnValue(baseRepoPath);
315        createSystemDirectories();
316        const settings = generateSettings();
317        lockFile.lockSync(settings.POPULATE_BUFFER_LOCK_FILE);
318        lockFile.lockSync(settings.DIFFS_SEND_LOCK_FILE);
319    });
320
321    afterEach(() => {
322        lockFile.unlockSync(settings.POPULATE_BUFFER_LOCK_FILE);
323        lockFile.unlockSync(settings.DIFFS_SEND_LOCK_FILE);
324        fs.rmSync(baseRepoPath, { recursive: true, force: true });
325    });
326
327    test("Acquried no lock", () => {
328        CodeSyncState.set(CODESYNC_STATES.POPULATE_BUFFER_LOCK_ACQUIRED, false);
329        CodeSyncState.set(CODESYNC_STATES.DIFFS_SEND_LOCK_ACQUIRED, false);
330        deactivate(vscode.ExtensionContext);
331        expect(console.log).toHaveBeenCalledTimes(0);
332        expect(lockFile.checkSync(settings.POPULATE_BUFFER_LOCK_FILE)).toBe(true);
333        expect(lockFile.checkSync(settings.DIFFS_SEND_LOCK_FILE)).toBe(true);
334    });
335
336    test("Acquried populateBuffer lock", () => {
337        CodeSyncState.set(CODESYNC_STATES.POPULATE_BUFFER_LOCK_ACQUIRED, true);
338        CodeSyncState.set(CODESYNC_STATES.DIFFS_SEND_LOCK_ACQUIRED, false);
339        deactivate(vscode.ExtensionContext);
340        expect(console.log).toHaveBeenCalledTimes(0);
341        expect(lockFile.checkSync(settings.POPULATE_BUFFER_LOCK_FILE)).toBe(false);
342        expect(lockFile.checkSync(settings.DIFFS_SEND_LOCK_FILE)).toBe(true);
343    });
344
345    test("Acquried diffsSend lock", () => {
346        CodeSyncState.set(CODESYNC_STATES.POPULATE_BUFFER_LOCK_ACQUIRED, false);
347        CodeSyncState.set(CODESYNC_STATES.DIFFS_SEND_LOCK_ACQUIRED, true);
348        deactivate(vscode.ExtensionContext);
349        expect(console.log).toHaveBeenCalledTimes(0);
350        expect(lockFile.checkSync(settings.POPULATE_BUFFER_LOCK_FILE)).toBe(true);
351        expect(lockFile.checkSync(settings.DIFFS_SEND_LOCK_FILE)).toBe(false);
352    });
353
354    test("Acquried both locks", () => {
355        CodeSyncState.set(CODESYNC_STATES.POPULATE_BUFFER_LOCK_ACQUIRED, true);
356        CodeSyncState.set(CODESYNC_STATES.DIFFS_SEND_LOCK_ACQUIRED, true);
357        deactivate(vscode.ExtensionContext);
358        expect(console.log).toHaveBeenCalledTimes(0);
359        expect(lockFile.checkSync(settings.POPULATE_BUFFER_LOCK_FILE)).toBe(false);
360        expect(lockFile.checkSync(settings.DIFFS_SEND_LOCK_FILE)).toBe(false);
361    });
362});
363
Full Screen

editing.js

Source: editing.js Github

copy
1const vscode = require('vscode');
2
3async function capitalizeWordForward() {
4    await vscode.commands.executeCommand("cursorWordEndRight");
5    await vscode.commands.executeCommand("cursorWordStartLeftSelect");
6    await vscode.commands.executeCommand("editor.action.transformToLowercase");
7    await vscode.commands.executeCommand("cancelSelection");
8    await vscode.commands.executeCommand("cursorRightSelect");
9    await vscode.commands.executeCommand("editor.action.transformToUppercase");
10    await vscode.commands.executeCommand("cursorWordStartRight");
11}
12
13async function capitalizeWordBackward() {
14    await vscode.commands.executeCommand("cursorWordLeft");
15    await vscode.commands.executeCommand("cursorWordStartRightSelect");
16    await vscode.commands.executeCommand("editor.action.transformToLowercase");
17    await vscode.commands.executeCommand("cursorWordStartLeft");
18    await vscode.commands.executeCommand("cursorRightSelect");
19    await vscode.commands.executeCommand("editor.action.transformToUppercase");
20    await vscode.commands.executeCommand("cursorWordStartLeft");
21}
22
23async function lowercaseWordForward() {
24    await vscode.commands.executeCommand("cursorWordEndRight");
25    await vscode.commands.executeCommand("cursorWordStartLeftSelect");
26    await vscode.commands.executeCommand("editor.action.transformToLowercase");
27    await vscode.commands.executeCommand("cancelSelection");
28    await vscode.commands.executeCommand("cursorWordStartRight");
29}
30
31async function lowercaseWordBackward() {
32    await vscode.commands.executeCommand("cursorWordLeft");
33    await vscode.commands.executeCommand("cursorWordStartRightSelect");
34    await vscode.commands.executeCommand("editor.action.transformToLowercase");
35    await vscode.commands.executeCommand("cursorWordStartLeft");
36}
37
38// join line with previous
39function joinLineWithPrevious() {
40    vscode.commands.executeCommand("cursorUp").then(() => {
41        vscode.commands.executeCommand("editor.action.joinLines");
42    });
43}
44
45/**
46 * There is a bug and these keys can not be bound.
47 * @see https://github.com/microsoft/vscode/issues/41024
48 * @see https://apple.stackexchange.com/questions/53417/how-to-disable-the-special-characters-shortcut-cmdoptiont-in-os-x-lion
49 */
50async function uppercaseWordForward() {
51    await vscode.commands.executeCommand("cursorWordEndRight");
52    await vscode.commands.executeCommand("cursorWordStartLeftSelect");
53    await vscode.commands.executeCommand("editor.action.transformToUppercase");
54    await vscode.commands.executeCommand("cancelSelection");
55    await vscode.commands.executeCommand("cursorWordStartRight");
56}
57
58async function uppercaseWordBackward() {
59    await vscode.commands.executeCommand("cursorWordLeft");
60    await vscode.commands.executeCommand("cursorWordStartRightSelect");
61    await vscode.commands.executeCommand("editor.action.transformToUppercase");
62    await vscode.commands.executeCommand("cursorWordStartLeft");
63}
64
65/**
66 * @param {vscode.ExtensionContext} context
67 */
68function setup(context) {
69    // uppercase
70    context.subscriptions.push(
71        vscode.commands.registerCommand('emacsify.editingUppercaseWordForward', uppercaseWordForward)
72    );
73    context.subscriptions.push(
74        vscode.commands.registerCommand('emacsify.editingUppercaseWordBackward', uppercaseWordBackward)
75    );
76
77    // capitalize
78    context.subscriptions.push(
79        vscode.commands.registerCommand('emacsify.editingCapitalizeWordForward', capitalizeWordForward)
80    );
81    context.subscriptions.push(
82        vscode.commands.registerCommand('emacsify.editingCapitalizeWordBackward', capitalizeWordBackward)
83    );
84
85    // lowercase
86    context.subscriptions.push(
87        vscode.commands.registerCommand('emacsify.editingLowercaseWordForward', lowercaseWordForward)
88    );
89    context.subscriptions.push(
90        vscode.commands.registerCommand('emacsify.editingLowercaseWordBackward', lowercaseWordBackward)
91    );
92
93    // join lines
94    context.subscriptions.push(
95        vscode.commands.registerCommand('emacsify.editingJoinLineWithPrevious', joinLineWithPrevious)
96    );
97}
98
99module.exports = {
100    setup
101}
102
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Appium Base Driver on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)