Best Python code snippet using autotest_python
roamJsonToBlocks.ts
Source:roamJsonToBlocks.ts  
1import { HOME_PATH, HOME_TOKEN } from '../../constants'2import { hashContext, hashThought, removeHome } from '../../util'3import { exportContext } from '../../selectors'4import { State, initialState } from '../initialState'5import { RoamBlock, RoamPage, roamJsonToBlocks } from '../roamJsonToBlocks'6import { importJSON } from '../importJSON'7import { SimplePath } from '../../types'8jest.mock('../timestamp', () => ({9  timestamp: () => '2020-11-02T01:11:58.869Z'10}))11const testData = [12  {13    title: 'Fruits',14    children: [15      {16        string: 'Apple',17        'create-email': 'test_create@gmail.com',18        'edit-email': 'test_edit@gmail.com',19        'create-time': 1600111381583,20        'edit-time': 1600111381580,21        uid: 'UK11200',22      },23      {24        string: 'Orange',25        'create-email': 'test_create@yahoo.com',26        'edit-email': 'test_edit@yahoo.com',27        'create-time': 1600111383054,28        'edit-time': 1600111383050,29        uid: 'UK11233',30      },31      {32        string: 'Banana',33        'create-email': 'test_create@icloud.com',34        'edit-email': 'test_edit@icloud.com',35        'create-time': 1600111383911,36        'edit-time': 1600111383910,37        uid: 'HMN_YQtZZ',38      }39    ],40  },41  {42    title: 'Veggies',43    children: [44      {45        string: 'Broccoli',46        'create-email': 'test_create@gmail.com',47        'edit-email': 'test_edit@gmail.com',48        'create-time': 1600111381600,49        'edit-time': 1600111381599,50        uid: 'BK11200',51      },52      {53        string: 'Spinach',54        'create-email': 'test_create@icloud.com',55        'edit-email': 'test_edit@icloud.com',56        'create-time': 1600111389054,57        'edit-time': 1600111389050,58        uid: 'BK11233',59      }60    ],61  }62]63/** Imports the given Roam's JSON format and exports it as plaintext. */64const importExport = (roamJson: RoamPage[]) => {65  const thoughtsJSON = roamJsonToBlocks(roamJson)66  const state = initialState()67  const {68    contextIndexUpdates: contextIndex,69    thoughtIndexUpdates: thoughtIndex,70  } = importJSON(state, HOME_PATH as SimplePath, thoughtsJSON, { skipRoot: false })71  const stateNew: State = {72    ...initialState(),73    thoughts: {74      ...state.thoughts,75      contextIndex,76      thoughtIndex,77    }78  }79  const exported = exportContext(stateNew, [HOME_TOKEN], 'text/plain')80  return removeHome(exported)81}82test('it should convert a flat Roam json into a list of thoughts', () => {83  const res = importExport(testData)84  expect(res)85    .toBe(`86- Fruits87  - Apple88    - =create-email89      - test_create@gmail.com90    - =edit-email91      - test_edit@gmail.com92  - Orange93    - =create-email94      - test_create@yahoo.com95    - =edit-email96      - test_edit@yahoo.com97  - Banana98    - =create-email99      - test_create@icloud.com100    - =edit-email101      - test_edit@icloud.com102- Veggies103  - Broccoli104    - =create-email105      - test_create@gmail.com106    - =edit-email107      - test_edit@gmail.com108  - Spinach109    - =create-email110      - test_create@icloud.com111    - =edit-email112      - test_edit@icloud.com113`)114})115test('it should convert a Roam json into a list of thoughts and subthoughts with correct indentation', () => {116  const testData = [117    {118      title: 'September 4th, 2020',119      children: [120        {121          string: 'A',122          'create-email': 'test_create@gmail.com',123          'create-time': 1600111381583,124          children: [125            {126              string: 'B',127              'create-email': 'test_create@gmail.com',128              'create-time': 1600111383054,129              children: [130                {131                  string: 'C',132                  'create-email': 'test_create@gmail.com',133                  'create-time': 1600111383911,134                  uid: 'HMN_YQtZZ',135                }],136              uid: 'JBXKlMcxh',137            }],138          uid: '0VQBPmUiy',139        }],140    },141    {142      title: 'September 5th, 2020',143      children: [144        {145          string: 'X',146          'create-email': 'test_create@gmail.com',147          'create-time': 1600111456859,148          children: [149            {150              string: 'Y',151              'create-email': 'test_create@gmail.com',152              'create-time': 1600111457621,153              children: [154                {155                  string: '[[September 4th, 2020]]',156                  'create-email': 'test_create@gmail.com',157                  'create-time': 1600111458385,158                  uid: 'Wt5NR3b56',159                }],160              uid: 'obXRTMWqJ',161            }],162          uid: 'Pu444IoIi',163        }],164    }]165  const res = importExport(testData)166  expect(res)167    .toBe(`168- September 4th, 2020169  - A170    - B171      - C172        - =create-email173          - test_create@gmail.com174      - =create-email175        - test_create@gmail.com176    - =create-email177      - test_create@gmail.com178- September 5th, 2020179  - X180    - Y181      - [[September 4th, 2020]]182        - =create-email183          - test_create@gmail.com184      - =create-email185        - test_create@gmail.com186    - =create-email187      - test_create@gmail.com188`)189})190test('it should save create-time as created and edit-time as lastUpdated', () => {191  const roamBlocks = testData.map(roamBlock => roamBlock.children).flat() as RoamBlock[]192  const blocks = roamJsonToBlocks(testData)193  const {194    contextIndexUpdates: contextIndex,195    thoughtIndexUpdates: thoughtIndex,196  } = importJSON(initialState(), HOME_PATH as SimplePath, blocks, { skipRoot: false })197  /** Gets the edit-time of a RoamBlock. */198  const editTimeOf = (value: string) => {199    const roamBlock = roamBlocks.find(roamBlock => roamBlock.string === value)200    if (!roamBlock) return null201    const editTimeOf = new Date(roamBlock['edit-time']!)202    return editTimeOf?.toISOString()203  }204  /** Gets the create-time of a RoamBlock. */205  const createTime = (value: string) => {206    const roamBlock = roamBlocks.find(roamBlock => roamBlock.string === value)207    if (!roamBlock) return null208    const editTimeOf = new Date(roamBlock['create-time']!)209    return editTimeOf?.toISOString()210  }211  expect(contextIndex).toMatchObject({212    // RoamPages acquire the edit time of their last child213    [hashContext(['Fruits'])]: { lastUpdated: editTimeOf('Banana') },214    [hashContext(['Veggies'])]: { lastUpdated: editTimeOf('Spinach') },215    // RoamBlocks use specified edit time216    [hashContext(['Fruits', 'Apple'])]: { lastUpdated: editTimeOf('Apple') },217    [hashContext(['Fruits', 'Orange'])]: { lastUpdated: editTimeOf('Orange') },218    [hashContext(['Fruits', 'Banana'])]: { lastUpdated: editTimeOf('Banana') },219    [hashContext(['Veggies', 'Broccoli'])]: { lastUpdated: editTimeOf('Broccoli') },220    [hashContext(['Veggies', 'Spinach'])]: { lastUpdated: editTimeOf('Spinach') },221  })222  expect(thoughtIndex).toMatchObject({223    // RoamPages acquire the edit time of their first child for thoughts224    // TODO: This differs from contextIndex incidentally. Should normalize the edit times used for contextIndex and thoughtIndex.225    [hashThought('Fruits')]: { created: createTime('Apple'), lastUpdated: editTimeOf('Apple') },226    [hashThought('Veggies')]: { created: createTime('Broccoli'), lastUpdated: editTimeOf('Broccoli') },227    // RoamBlocks use specified edit time228    [hashThought('Apple')]: { created: createTime('Apple'), lastUpdated: editTimeOf('Apple') },229    [hashThought('Orange')]: { created: createTime('Orange'), lastUpdated: editTimeOf('Orange') },230    [hashThought('Banana')]: { created: createTime('Banana'), lastUpdated: editTimeOf('Banana') },231    [hashThought('Broccoli')]: { created: createTime('Broccoli'), lastUpdated: editTimeOf('Broccoli') },232    [hashThought('Spinach')]: { created: createTime('Spinach'), lastUpdated: editTimeOf('Spinach') },233  })...test_guest_media.py
Source:test_guest_media.py  
...43    model.list.assert_called_once()44@patch('rfidsecuritysvc.api.guest_media.model')45def test_post(model):46    model.create.return_value = None47    assert api.post(m.test_create()) == (None, 201)48    model.create.assert_called_once_with(**m.test_create())49@patch('rfidsecuritysvc.api.guest_media.model')50def test_post_Duplicate(model):51    model.create.side_effect = DuplicateError52    assert api.post(m.test_create()) == (f'Media with media_id "{m.media.id} is already associated with a guest.', 409)53    model.create.assert_called_once_with(**m.test_create())54@patch('rfidsecuritysvc.api.guest_media.model')55def test_post_GuestNotFoundError(model):56    model.create.side_effect = GuestNotFoundError57    assert api.post(m.test_create()) == (f'No guest found with id "{m.guest.id}".', 400)58    model.create.assert_called_once_with(**m.test_create())59@patch('rfidsecuritysvc.api.guest_media.model')60def test_post_MediaNotFoundError(model):61    model.create.side_effect = MediaNotFoundError62    assert api.post(m.test_create()) == (f'No media found with id "{m.media.id}".', 400)63    model.create.assert_called_once_with(**m.test_create())64@patch('rfidsecuritysvc.api.guest_media.model')65def test_post_SoundNotFoundError(model):66    model.create.side_effect = SoundNotFoundError67    assert api.post(m.test_create()) == (f'No sound found with id "{m.sound.id}".', 400)68    model.create.assert_called_once_with(**m.test_create())69@patch('rfidsecuritysvc.api.guest_media.model')70def test_delete(model):71    model.delete.return_value = 172    assert api.delete(m.id) == (None, 200, {RECORD_COUNT_HEADER: 1})73    model.delete.assert_called_once_with(m.id)74@patch('rfidsecuritysvc.api.guest_media.model')75def test_put(model):76    model.update.return_value = 177    assert api.put(m.id, m.test_create()) == (None, 200, {RECORD_COUNT_HEADER: 1})78    model.update.assert_called_once_with(m.id, **m.test_create())79@patch('rfidsecuritysvc.api.guest_media.model')80def test_put_GuestNotFoundError(model):81    model.update.side_effect = GuestNotFoundError82    assert api.put(m.id, m.test_create()) == (f'No guest found with id "{m.guest.id}".', 400)83    model.update.assert_called_once_with(m.id, **m.test_create())84@patch('rfidsecuritysvc.api.guest_media.model')85def test_put_MediaNotFoundError(model):86    model.update.side_effect = MediaNotFoundError87    assert api.put(m.id, m.test_create()) == (f'No media found with id "{m.media.id}".', 400)88    model.update.assert_called_once_with(m.id, **m.test_create())89@patch('rfidsecuritysvc.api.guest_media.model')90def test_put_SoundNotFoundError(model):91    model.update.side_effect = SoundNotFoundError92    assert api.put(m.id, m.test_create()) == (f'No sound found with id "{m.sound.id}".', 400)93    model.update.assert_called_once_with(m.id, **m.test_create())94@patch('rfidsecuritysvc.api.guest_media.model')95def test_put_not_found(model):96    model.update.side_effect = NotFoundError97    assert api.put(m.id, m.test_create()) == (None, 201, {RECORD_COUNT_HEADER: 1})98    model.update.assert_called_once_with(m.id, **m.test_create())99    model.create.assert_called_once_with(**m.test_create())100@patch('rfidsecuritysvc.api.guest_media.model')101def test_put_not_found_duplicate(model):102    model.update.side_effect = NotFoundError103    model.create.side_effect = DuplicateError104    assert api.put(m.id, m.test_create()) == (f'Object with guest_id "{m.guest.id} and media_id "{m.media.id}" already exists.', 409,)105    model.update.assert_called_once_with(m.id, **m.test_create())106    model.create.assert_called_once_with(**m.test_create())107@patch('rfidsecuritysvc.api.guest_media.model')108def test_put_not_found_GuestNotFoundError(model):109    model.update.side_effect = NotFoundError110    model.create.side_effect = GuestNotFoundError111    assert api.put(m.id, m.test_create()) == (f'No guest found with id "{m.guest.id}".', 400,)112    model.update.assert_called_once_with(m.id, **m.test_create())113    model.create.assert_called_once_with(**m.test_create())114@patch('rfidsecuritysvc.api.guest_media.model')115def test_put_not_found_MediaNotFoundError(model):116    model.update.side_effect = NotFoundError117    model.create.side_effect = MediaNotFoundError118    assert api.put(m.id, m.test_create()) == (f'No media found with id "{m.media.id}".', 400,)119    model.update.assert_called_once_with(m.id, **m.test_create())120    model.create.assert_called_once_with(**m.test_create())121@patch('rfidsecuritysvc.api.guest_media.model')122def test_put_not_found_SoundNotFoundError(model):123    model.update.side_effect = NotFoundError124    model.create.side_effect = SoundNotFoundError125    assert api.put(m.id, m.test_create()) == (f'No sound found with id "{m.sound.id}".', 400,)126    model.update.assert_called_once_with(m.id, **m.test_create())...perm.py
Source:perm.py  
1from trac import perm2from trac.config import Configuration3from trac.core import *4from trac.test import EnvironmentStub5from trac.util import enum6import unittest7class DefaultPermissionStoreTestCase(unittest.TestCase):8    def setUp(self):9        self.env = EnvironmentStub(enable=[perm.DefaultPermissionStore,10                                           perm.DefaultPermissionGroupProvider])11        self.store = perm.DefaultPermissionStore(self.env)12    def test_simple_actions(self):13        db = self.env.get_db_cnx()14        cursor = db.cursor()15        cursor.executemany("INSERT INTO permission VALUES (%s,%s)", [16                           ('john', 'WIKI_MODIFY'), ('john', 'REPORT_ADMIN'),17                           ('kate', 'TICKET_CREATE')])18        self.assertEquals(['WIKI_MODIFY', 'REPORT_ADMIN'],19                          self.store.get_user_permissions('john'))20        self.assertEquals(['TICKET_CREATE'], self.store.get_user_permissions('kate'))21    def test_simple_group(self):22        db = self.env.get_db_cnx()23        cursor = db.cursor()24        cursor.executemany("INSERT INTO permission VALUES (%s,%s)", [25                           ('dev', 'WIKI_MODIFY'), ('dev', 'REPORT_ADMIN'),26                           ('john', 'dev')])27        self.assertEquals(['WIKI_MODIFY', 'REPORT_ADMIN'],28                          self.store.get_user_permissions('john'))29    def test_nested_groups(self):30        db = self.env.get_db_cnx()31        cursor = db.cursor()32        cursor.executemany("INSERT INTO permission VALUES (%s,%s)", [33                           ('dev', 'WIKI_MODIFY'), ('dev', 'REPORT_ADMIN'),34                           ('admin', 'dev'), ('john', 'admin')])35        self.assertEquals(['WIKI_MODIFY', 'REPORT_ADMIN'],36                          self.store.get_user_permissions('john'))37    def test_builtin_groups(self):38        db = self.env.get_db_cnx()39        cursor = db.cursor()40        cursor.executemany("INSERT INTO permission VALUES (%s,%s)", [41                           ('authenticated', 'WIKI_MODIFY'),42                           ('authenticated', 'REPORT_ADMIN'),43                           ('anonymous', 'TICKET_CREATE')])44        self.assertEquals(['WIKI_MODIFY', 'REPORT_ADMIN', 'TICKET_CREATE'],45                          self.store.get_user_permissions('john'))46        self.assertEquals(['TICKET_CREATE'],47                          self.store.get_user_permissions('anonymous'))48    def test_get_all_permissions(self):49        db = self.env.get_db_cnx()50        cursor = db.cursor()51        cursor.executemany("INSERT INTO permission VALUES (%s,%s)", [52                           ('dev', 'WIKI_MODIFY'), ('dev', 'REPORT_ADMIN'),53                           ('john', 'dev')])54        expected = [('dev', 'WIKI_MODIFY'),55                    ('dev', 'REPORT_ADMIN'),56                    ('john', 'dev')]57        for res in self.store.get_all_permissions():58            self.failIf(res not in expected)59class TestPermissionRequestor(Component):60    implements(perm.IPermissionRequestor)61    def get_permission_actions(self):62        return ['TEST_CREATE', 'TEST_DELETE', 'TEST_MODIFY',63                ('TEST_ADMIN', ['TEST_CREATE', 'TEST_DELETE',64                                'TEST_MODIFY'])]65class PermissionSystemTestCase(unittest.TestCase):66    def setUp(self):67        from trac.core import ComponentMeta68        self.env = EnvironmentStub(enable=[perm.PermissionSystem,69                                           perm.DefaultPermissionStore,70                                           TestPermissionRequestor])71        self.env.config.setdefault('trac', 'permission_store',72                                   'DefaultPermissionStore')73        self.perm = perm.PermissionSystem(self.env)74    def test_all_permissions(self):75        self.assertEqual({'TEST_CREATE': True, 'TEST_DELETE': True,76                          'TEST_MODIFY': True,  'TEST_ADMIN': True,77                          'TRAC_ADMIN': True},78                         self.perm.get_user_permissions())79    def test_simple_permissions(self):80        self.perm.grant_permission('bob', 'TEST_CREATE')81        self.perm.grant_permission('jane', 'TEST_DELETE')82        self.perm.grant_permission('jane', 'TEST_MODIFY')83        self.assertEqual({'TEST_CREATE': True},84                         self.perm.get_user_permissions('bob'))85        self.assertEqual({'TEST_DELETE': True, 'TEST_MODIFY': True},86                         self.perm.get_user_permissions('jane'))87    def test_meta_permissions(self):88        self.perm.grant_permission('bob', 'TEST_CREATE')89        self.perm.grant_permission('jane', 'TEST_ADMIN')90        self.assertEqual({'TEST_CREATE': True},91                         self.perm.get_user_permissions('bob'))92        self.assertEqual({'TEST_CREATE': True, 'TEST_DELETE': True,93                          'TEST_MODIFY': True,  'TEST_ADMIN': True},94                         self.perm.get_user_permissions('jane'))95    def test_get_all_permissions(self):96        self.perm.grant_permission('bob', 'TEST_CREATE')97        self.perm.grant_permission('jane', 'TEST_ADMIN')98        expected = [('bob', 'TEST_CREATE'),99                    ('jane', 'TEST_ADMIN')]100        for res in self.perm.get_all_permissions():101            self.failIf(res not in expected)102class PermTestCase(unittest.TestCase):103    def setUp(self):104        self.env = EnvironmentStub(enable=[perm.PermissionSystem,105                                           perm.DefaultPermissionStore,106                                           TestPermissionRequestor])107        # Add a few groups108        db = self.env.get_db_cnx()109        cursor = db.cursor()110        cursor.executemany("INSERT INTO permission VALUES(%s,%s)", [111                           ('employee', 'TEST_MODIFY'),112                           ('developer', 'TEST_ADMIN'),113                           ('developer', 'employee'),114                           ('bob', 'developer')])115        db.commit()116        self.env.config.setdefault('trac', 'permission_store',117                                   'DefaultPermissionStore')118        self.perm = perm.PermissionCache(self.env, 'bob')119    def test_has_permission(self):120        self.assertEqual(1, self.perm.has_permission('TEST_MODIFY'))121        self.assertEqual(1, self.perm.has_permission('TEST_ADMIN'))122        self.assertEqual(0, self.perm.has_permission('TRAC_ADMIN'))123    def test_assert_permission(self):124        self.perm.assert_permission('TEST_MODIFY')125        self.perm.assert_permission('TEST_ADMIN')126        self.assertRaises(perm.PermissionError,127                          self.perm.assert_permission, 'TRAC_ADMIN')128def suite():129    suite = unittest.TestSuite()130    suite.addTest(unittest.makeSuite(DefaultPermissionStoreTestCase, 'test'))131    suite.addTest(unittest.makeSuite(PermissionSystemTestCase, 'test'))132    suite.addTest(unittest.makeSuite(PermTestCase, 'test'))133    return suite134if __name__ == '__main__':...test_create.py
Source:test_create.py  
1import pytest2from fastapi.testclient import TestClient3from app.main import app4client = TestClient(app)5#sprinkler6@pytest.mark.order(1)7def test_create_sprinkler(test_create):8    response = test_create.put("/sprinkler", json={9            "description": "test_sprinkler_01",10            "active": True11        }12    )13    assert response.status_code == 20114@pytest.mark.order(1)15def test_create_sprinkler_wrong_value(test_create):16    response = test_create.put("/sprinkler", json={17            "description": "test_sprinkler_01_wrong_value",18            "active": 319        }20    )21    assert response.status_code == 42222#plant23@pytest.mark.order(1)24def test_create_plant(test_create):25    response = test_create.put("/plant", json={26            "description": "test_plant_01",27            "sprinkler_id": 1,28            "active": True29        }30    )31    assert response.status_code == 20132@pytest.mark.order(1)33def test_create_plant_inexist_sprinkler_id(test_create):34    response = test_create.put("/plant", json={35            "description": "test_plant_01_wrong_id",36            "sprinkler_id": 0,37            "active": True38        }39    )40    assert response.status_code == 40041@pytest.mark.order(1)42def test_create_plant_wrong_value(test_create):43    response = test_create.put("/plant", json={44            "description": "test_plant_01_wrong_value",45            "sprinkler_id": 1,46            "active": 347        }48    )49    assert response.status_code == 42250#water day51@pytest.mark.order(1)52def test_create_waterday(test_create):53    response = test_create.put("/waterday", json={54            "week_day": 0,55            "time_day": "12:30",56            "water_time": 50,57            "plant_id": 1,58            "active": True59        }60    )61    assert response.status_code == 20162@pytest.mark.order(1)63def test_create_waterday_wrong_week_day(test_create):64    response = test_create.put("/waterday", json={65            "week_day": 7,66            "time_day": "12:30",67            "water_time": 50,68            "plant_id": 1,69            "active": True70        }71    )72    assert response.status_code == 40073    assert response.json()["message"] == "Weekday must be between 0-6 (0: Monday/6: Sunday)"74    assert response.json()["exception"] == "Weekday 7 is invalid"75@pytest.mark.order(1)76def test_create_waterday_wrong_time_day(test_create):77    response = test_create.put("/waterday", json={78            "week_day": 0,79            "time_day": "1c:30",80            "water_time": 50,81            "plant_id": 1,82            "active": True83        }84    )85    assert response.status_code == 40086    assert response.json()["message"] == "Time Day must be in format HH:MM - 24 format"87    assert response.json()["exception"] == "time data '1c:30' does not match format '%H:%M'"88@pytest.mark.order(1)89def test_create_waterday_wrong_value_timeday(test_create):90    response = test_create.put("/waterday", json={91            "week_day": 0,92            "time_day": "12:30",93            "water_time": 'a',94            "plant_id": 1,95            "active": True96        }97    )98    assert response.status_code == 42299    100@pytest.mark.order(1)101def test_create_waterday_inextis_plant_id(test_create):102    response = test_create.put("/waterday", json={103            "week_day": 0,104            "time_day": "12:30",105            "water_time": 50,106            "plant_id": 0,107            "active": True108        }109    )110    assert response.status_code == 400111    assert response.json()["message"] == "Don't find plant_id specified"112    assert response.json()["exception"] == "plant_id 0 not found"113#log114@pytest.mark.order(1)115def test_create_log(test_create):116    response = test_create.put("/log", json={117            "plant_id": 1,118            "key": "OK"119        }120    )121    assert response.status_code == 201122@pytest.mark.order(1)123def test_create_log_inextis_plant_id(test_create):124    response = test_create.put("/log", json={125            "plant_id": 0,126            "key": "OK"127        }128    )129    assert response.status_code == 400130    assert response.json()["message"] == "Don't find plant_id specified"131    assert response.json()["exception"] == "plant_id 0 not found"132@pytest.mark.order(1)133def test_create_log_wrong_key(test_create):134    response = test_create.put("/log", json={135            "plant_id": 1,136            "key": "WRONG"137        }138    )139    assert response.status_code == 400140    assert response.json()["message"] == "Key must be OK or FAIL"...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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
