Best Python code snippet using hypothesis
tests.py
Source:tests.py  
...115        self.assertNotEqual(resp.content, '')116        content = json.loads(resp.content)117        self.assertIsInstance(content, list)118        self.assertEqual(len(content), MAX_LIMIT)119    def test_create_note(self):120        self.login()121        notes = self.create_notes(1)122        self.assertEqual(len(notes), 1)123        note_dict = notes[0].as_dict()124        excluded_fields = ['id', 'user_id', 'created', 'updated']125        note = dict([(k, v) for k, v in note_dict.items() if k not in excluded_fields])126        resp = self.client.post(self.url('notes_api_notes'),127                                json.dumps(note),128                                content_type='application/json',129                                HTTP_X_REQUESTED_WITH='XMLHttpRequest')130        self.assertEqual(resp.status_code, 303)131        self.assertEqual(len(resp.content), 0)132    def test_create_empty_notes(self):133        self.login()134        for empty_test in [None, [], '']:135            resp = self.client.post(self.url('notes_api_notes'),136                                    json.dumps(empty_test),137                                    content_type='application/json',138                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')139            self.assertEqual(resp.status_code, 400)140    def test_create_note_missing_ranges(self):141        self.login()142        notes = self.create_notes(1)143        self.assertEqual(len(notes), 1)144        note_dict = notes[0].as_dict()145        excluded_fields = ['id', 'user_id', 'created', 'updated'] + ['ranges']146        note = dict([(k, v) for k, v in note_dict.items() if k not in excluded_fields])147        resp = self.client.post(self.url('notes_api_notes'),148                                json.dumps(note),149                                content_type='application/json',150                                HTTP_X_REQUESTED_WITH='XMLHttpRequest')151        self.assertEqual(resp.status_code, 400)152    def test_read_note(self):153        self.login()154        notes = self.create_notes(3)155        self.assertEqual(len(notes), 3)156        for note in notes:157            resp = self.client.get(self.url('notes_api_note', {'note_id': note.pk}))158            self.assertEqual(resp.status_code, 200)159            self.assertNotEqual(resp.content, '')160            content = json.loads(resp.content)161            self.assertEqual(content['id'], note.pk)162            self.assertEqual(content['user_id'], note.user_id)163    def test_note_doesnt_exist_to_read(self):164        self.login()165        resp = self.client.get(self.url('notes_api_note', {166            'note_id': self.NOTE_ID_DOES_NOT_EXIST167        }))168        self.assertEqual(resp.status_code, 404)169        self.assertEqual(resp.content, '')170    def test_student_doesnt_have_permission_to_read_note(self):171        notes = self.create_notes(1)172        self.assertEqual(len(notes), 1)173        note = notes[0]174        # set the student id to a different student (not the one that created the notes)175        self.login(as_student=self.student2)176        resp = self.client.get(self.url('notes_api_note', {'note_id': note.pk}))177        self.assertEqual(resp.status_code, 403)178        self.assertEqual(resp.content, '')179    def test_delete_note(self):180        self.login()181        notes = self.create_notes(1)182        self.assertEqual(len(notes), 1)183        note = notes[0]184        resp = self.client.delete(self.url('notes_api_note', {185            'note_id': note.pk186        }))187        self.assertEqual(resp.status_code, 204)188        self.assertEqual(resp.content, '')189        with self.assertRaises(models.Note.DoesNotExist):190            models.Note.objects.get(pk=note.pk)191    def test_note_does_not_exist_to_delete(self):192        self.login()193        resp = self.client.delete(self.url('notes_api_note', {194            'note_id': self.NOTE_ID_DOES_NOT_EXIST195        }))196        self.assertEqual(resp.status_code, 404)197        self.assertEqual(resp.content, '')198    def test_student_doesnt_have_permission_to_delete_note(self):199        notes = self.create_notes(1)200        self.assertEqual(len(notes), 1)201        note = notes[0]202        self.login(as_student=self.student2)203        resp = self.client.delete(self.url('notes_api_note', {204            'note_id': note.pk205        }))206        self.assertEqual(resp.status_code, 403)207        self.assertEqual(resp.content, '')208        try:209            models.Note.objects.get(pk=note.pk)210        except models.Note.DoesNotExist:211            self.fail('note should exist and not be deleted because the student does not have permission to do so')212    def test_update_note(self):213        notes = self.create_notes(1)214        note = notes[0]215        updated_dict = note.as_dict()216        updated_dict.update({217            'text': 'itchy and scratchy',218            'tags': ['simpsons', 'cartoons', 'animation']219        })220        self.login()221        resp = self.client.put(self.url('notes_api_note', {'note_id': note.pk}),222                               json.dumps(updated_dict),223                               content_type='application/json',224                               HTTP_X_REQUESTED_WITH='XMLHttpRequest')225        self.assertEqual(resp.status_code, 303)226        self.assertEqual(resp.content, '')227        actual = models.Note.objects.get(pk=note.pk)228        actual_dict = actual.as_dict()229        for field in ['text', 'tags']:230            self.assertEqual(actual_dict[field], updated_dict[field])231    def test_search_note_params(self):232        self.login()233        total = 3234        notes = self.create_notes(total)235        invalid_uri = ''.join([note.uri for note in notes])236        tests = [{'limit': 0, 'offset': 0, 'expected_rows': total},237                 {'limit': 0, 'offset': 2, 'expected_rows': total - 2},238                 {'limit': 0, 'offset': total, 'expected_rows': 0},239                 {'limit': 1, 'offset': 0, 'expected_rows': 1},240                 {'limit': 2, 'offset': 0, 'expected_rows': 2},241                 {'limit': total, 'offset': 2, 'expected_rows': 1},242                 {'limit': total, 'offset': total, 'expected_rows': 0},243                 {'limit': total + 1, 'offset': total + 1, 'expected_rows': 0},244                 {'limit': total + 1, 'offset': 0, 'expected_rows': total},245                 {'limit': 0, 'offset': 0, 'uri': invalid_uri, 'expected_rows': 0, 'expected_total': 0}]246        for test in tests:247            params = dict([(k, str(test[k]))248                          for k in ('limit', 'offset', 'uri')249                          if k in test])250            resp = self.client.get(self.url('notes_api_search'),251                                   params,252                                   content_type='application/json',253                                   HTTP_X_REQUESTED_WITH='XMLHttpRequest')254            self.assertEqual(resp.status_code, 200)255            self.assertNotEqual(resp.content, '')256            content = json.loads(resp.content)257            for expected_key in ('total', 'rows'):258                self.assertTrue(expected_key in content)259            if 'expected_total' in test:260                self.assertEqual(content['total'], test['expected_total'])261            else:262                self.assertEqual(content['total'], total)263            self.assertEqual(len(content['rows']), test['expected_rows'])264            for row in content['rows']:265                self.assertTrue('id' in row)266class NoteTest(TestCase):267    def setUp(self):268        self.password = 'abc'269        self.student = User.objects.create_user('student', 'student@test.com', self.password)270        self.course_key = SlashSeparatedCourseKey('HarvardX', 'CB22x', 'The_Ancient_Greek_Hero')271        self.note = {272            'user': self.student,273            'course_id': self.course_key,274            'uri': '/',275            'text': 'foo',276            'quote': 'bar',277            'range_start': 0,278            'range_start_offset': 0,279            'range_end': 100,280            'range_end_offset': 0,281            'tags': 'a,b,c'282        }283    def test_clean_valid_note(self):284        reference_note = models.Note(**self.note)285        body = reference_note.as_dict()286        note = models.Note(course_id=self.course_key, user=self.student)287        try:288            note.clean(json.dumps(body))289            self.assertEqual(note.uri, body['uri'])290            self.assertEqual(note.text, body['text'])291            self.assertEqual(note.quote, body['quote'])292            self.assertEqual(note.range_start, body['ranges'][0]['start'])293            self.assertEqual(note.range_start_offset, body['ranges'][0]['startOffset'])294            self.assertEqual(note.range_end, body['ranges'][0]['end'])295            self.assertEqual(note.range_end_offset, body['ranges'][0]['endOffset'])296            self.assertEqual(note.tags, ','.join(body['tags']))297        except ValidationError:298            self.fail('a valid note should not raise an exception')299    def test_clean_invalid_note(self):300        note = models.Note(course_id=self.course_key, user=self.student)301        for empty_type in (None, '', 0, []):302            with self.assertRaises(ValidationError):303                note.clean(None)304        with self.assertRaises(ValidationError):305            note.clean(json.dumps({306                'text': 'foo',307                'quote': 'bar',308                'ranges': [{} for i in range(10)]  # too many ranges309            }))310    def test_as_dict(self):311        note = models.Note(course_id=self.course_key, user=self.student)312        d = note.as_dict()313        self.assertNotIsInstance(d, basestring)...transpose.py
Source:transpose.py  
1# tranpose.py2"""3Transpose dialog window.4This file is part of the program5LeMMA - a GUI Frontend for creating MMA files.6Note that this is NOT really an MMA editor, but rather a simple front-end to MMA7Please read help.txt and CHANGES for more information.8This program is free software: you can redistribute it and/or modify9it under the terms of the GNU General Public License as published by10the Free Software Foundation, either version 3 of the License, or11(at your option) any later version.12This program is distributed in the hope that it will be useful,13but WITHOUT ANY WARRANTY; without even the implied warranty of14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the15GNU General Public License for more details.16You should have received a copy of the GNU General Public License17along with this program.  If not, see <http://www.gnu.org/licenses/>.18Gek S. Low <geksiong@yahoo.com>19"""20from .GSTkWidgets import *21import re22import logging23NOTES = {24	'C': 0,25	'C#': 1, 'Db': 1,26	'D': 2,27	'D#': 3, 'Eb': 3,28	'E': 4,29	'F': 5,30	'F#': 6, 'Gb': 6,31	'G': 7,32	'G#': 8, 'Ab': 8,33	'A': 9,34	'A#': 10, 'Bb': 10,35	'B': 11,36	}37BASE_LETTERS = "CDEFGAB"38LETTERS = {39	'C': 0,40	'D': 1,41	'E': 2,42	'F': 3,43	'G': 4,44	'A': 5,45	'B': 6,46	}47SHARP_KEYS = ('C','C#','D','D#','E','F','F#','G','G#','A','A#','B')48FLAT_KEYS = ('C','Db','D','Eb','E','F','Gb','G','Ab','A','Bb','B')49def isValidKeySig(key):50	p = re.compile('^([A-G])([#b]{0,1})(\s*(m|min|maj|minor|major){0,1})$')51	m = p.match(key)52	if m != None:53		base = m.group(1)54		acc = m.group(2)55		suffix = m.group(3)56		if base+acc in ['Cb','E#','Fb','B#']:	# MMA seems to accept these keys though57			logging.debug("[isValidKeySig] Invalid current key: "+key)58			return False59	else:60		logging.debug("[isValidKeySig] Invalid current key: "+key)61		return False62	return True63# Transpose a note from currentKey to newKey64# Returns new note if no errors found65# otherwise returns the original note (i.e. no transpose)66def transposeNote(note, currentKey, newKey, dbl_acc=True):67	#print "Transpose", note, "from", currentKey, "to", newKey, "is",68	sharpKey = True69	# Determine note number70	# need to account for double accidentals here!71	pNote = re.compile('^([A-G])([#b]{0,2})')72	mNote = pNote.match(note)73	if mNote != None:74		baseNote = mNote.group(1)75		accNote = mNote.group(2)76	else:77		logging.debug("[transposeNote] Invalid note: " + note)78		return note79	noteNum = NOTES[baseNote]80	for ch in accNote:81		if ch == '#':82			noteNum += 183		if ch == 'b':84			noteNum -= 185	#print "Note Number: ", noteNum86	# Get base keys and major/minor87	p = re.compile('^([A-G])([#b]{0,1})(\s*(m|min|maj|minor|major){0,1})$')88	m1 = p.match(currentKey)89	if m1 != None:90		base1 = m1.group(1)91		acc1 = m1.group(2)92		suffix1 = m1.group(3)93		if base1+acc1 in ['Cb','E#','Fb','B#']:94			logging.debug("[transposeNote] Invalid current key: "+currentKey)95			return note	# don't transpose if invalid key96	else:97		logging.debug("[transposeNote] Invalid current key: "+currentKey)98		return note	# don't transpose if invalid key99	m2 = p.match(newKey)100	if m2 != None:101		base2 = m2.group(1)102		acc2 = m2.group(2)103		suffix2 = m2.group(3)104		if acc2 == 'b':105			sharpKey = False106		if base2+acc2 in ['Cb','E#','Fb','B#']:107			logging.debug("[transposeNote] Invalid new key: "+newKey)108			return note	# don't transpose if invalid key109	else:110		logging.debug("[transposeNote] Invalid new key: "+newKey)111		return note	# don't transpose if invalid key112	# don't want to support transpose between major/minor at this moment113	if suffix1 != suffix2:114		logging.debug("[transposeNote] Major/Minor doesn't match!")115		return note	# don't transpose if incompatible keys116	baseOffset = LETTERS[base2] - LETTERS[base1]117	actualOffset = NOTES[base2+acc2] - NOTES[base1+acc1]118	#print "Letter: ", baseOffset119	#print "Actual: ", actualOffset120	# Determine new base letter121	newNoteBase = ""122	newNoteBase = BASE_LETTERS[(LETTERS[baseNote] + baseOffset) % 7]123	#print newNoteBase124	# Adjust accidentals125	newActualNote = ""126	if sharpKey:127		newActualNote = SHARP_KEYS[(noteNum + actualOffset) % 12]128	else:129		newActualNote = FLAT_KEYS[(noteNum + actualOffset) % 12]130	#print newActualNote131	adjust = NOTES[newActualNote] - NOTES[newNoteBase]132	if adjust < -2:133		adjust += 12134	elif adjust > 2:135		adjust -= 12136	#print adjust137	newNote = newNoteBase138	if adjust == -1:139		newNote += 'b'140	elif adjust == -2:141		if dbl_acc == True:142			newNote += 'bb'143		else:144			newNote = newActualNote145	elif adjust == 1:146		newNote += '#'147	elif adjust == 2:148		if dbl_acc == True:149			newNote += '##'150		else:151			newNote = newActualNote152	elif adjust != 0:153		print('unexpected adjust value: ' , adjust)154	#print newNote155	return newNote156# Parse a line and transposes the notes157def transposeLine(line, currentKey, newKey, dbl_acc=True):158	def transposeMatch(match, currentKey=currentKey, newKey=newKey, dbl_acc=dbl_acc):159		return transposeNote(match.group(), currentKey, newKey, dbl_acc)160	pNote = re.compile('([A-G][#b]{0,2})')161	newLine = pNote.sub(transposeMatch,line)162	#print newLine163	return newLine164class TransposeDialog(SimpleDialogExt):165	def __init__(self, master=None, currentKey="C"):166		self.currentKey = currentKey167		self.newKey = ""168		self.selectedKey = StringVar()169		invalidKey = False170		p = re.compile('^([A-G][#b]{0,1})(\s*(m|min|maj|minor|major){0,1})$')171		m = p.match(currentKey)172		if m != None:173			self.keyBase = m.group(1)174			self.keySuffix = m.group(2)175			if self.keyBase in ['Cb','E#','Fb','B#']:176				invalidKey = True177		else:178			invalidKey = True179		if not invalidKey:180			SimpleDialogExt.__init__(self, master, title="Transpose song")181		else:182			tkinter.messagebox.showinfo("Invalid Key Signature", "Please use a valid key signature")183	def body(self, master):184		Label(master=master, text="Select a key signature").grid(row=0, column=0, sticky=NW)185		note_num = NOTES[self.keyBase]186		self.frame = Frame(master=master)187		self.frame.grid(row=1, column=0, sticky=EW)188		for index in range(12):189			if SHARP_KEYS[index] == FLAT_KEYS[index]:190				Radiobutton(master=self.frame, text=SHARP_KEYS[index] + self.keySuffix, variable=self.selectedKey, value=SHARP_KEYS[index] + self.keySuffix, indicatoron=False, width=15, padx=5, pady=5).grid(row=index, column=0, columnspan=2, sticky=EW)191			else:192				Radiobutton(master=self.frame, text=SHARP_KEYS[index] + self.keySuffix, variable=self.selectedKey, value=SHARP_KEYS[index] + self.keySuffix, indicatoron=False, width=15, padx=5, pady=5).grid(row=index, column=0, sticky=EW)193				Radiobutton(master=self.frame, text=FLAT_KEYS[index] + self.keySuffix, variable=self.selectedKey, value=FLAT_KEYS[index] + self.keySuffix, indicatoron=False, width=15, padx=5, pady=5).grid(row=index, column=1, sticky=EW)194		self.selectedKey.set(self.currentKey)195	def apply(self):196		self.newKey = self.selectedKey.get()197		return198# Testing199def main():200	transposeNote("D", "C", "Eb")201	transposeNote("B", "Am", "Em")202	transposeNote("C", "Dm", "Ebm")203	transposeNote("A#", "C", "G")204	transposeNote("Ab", "Bb", "Eb")205	transposeNote("E#", "C", "C#")206	transposeNote("E#", "C", "C#", dbl_acc = False)207	transposeNote("C", "B", "C")208	transposeLine("Cmaj7 Dm E7 F6 G", "B", "C")209if __name__ == "__main__":...index.js
Source:index.js  
1let noteTitle;2let noteText;3let saveNoteBtn;4let newNoteBtn;5let noteList;6if (window.location.pathname === '/notes') {7  noteTitle = document.querySelector('.note-title');8  noteText = document.querySelector('.note-textarea');9  saveNoteBtn = document.querySelector('.save-note');10  newNoteBtn = document.querySelector('.new-note');11  noteList = document.querySelectorAll('.list-container .list-group');12}13// Show an element14const show = (elem) => {15  elem.style.display = 'inline';16};17// Hide an element18const hide = (elem) => {19  elem.style.display = 'none';20};21// activeNote is used to keep track of the note in the textarea22let activeNote = {};23const getNotes = () =>24  fetch('/api/notes', {25    method: 'GET',26    headers: {27      'Content-Type': 'application/json',28    },29  });30const saveNote = (note) =>31  fetch('/api/notes', {32    method: 'POST',33    headers: {34      'Content-Type': 'application/json',35    },36    body: JSON.stringify(note),37  });38const deleteNote = (id) =>39  fetch(`/api/notes/${id}`, {40    method: 'DELETE',41    headers: {42      'Content-Type': 'application/json',43    },44  });45// displays active note on right column46const renderActiveNote = () => {47  hide(saveNoteBtn);48  // if active note exists, display note49  if (activeNote.id) {50    noteTitle.setAttribute('data-id', activeNote.id);51    noteTitle.value = activeNote.title;52    noteText.value = activeNote.text;53  }54  // else use placeholder text55  else {56    noteTitle.removeAttribute('data-id');57    noteTitle.value = '';58    noteText.value = '';59  }60};61const handleNoteSave = () => {62  debugger;63  let note;64  let noteId = noteTitle.getAttribute('data-id');65  if (noteId) {66    note = {67      title: noteTitle.value,68      text: noteText.value,69      id: noteId70    };71  } else {72    note = {73      title: noteTitle.value,74      text: noteText.value75    };76  };77  saveNote(note).then(() => {78    getAndRenderNotes();79    renderActiveNote();80  });81};82// Delete the clicked note83const handleNoteDelete = (e) => {84  // prevents the click listener for the list from being called when the button inside of it is clicked85  e.stopPropagation();86  const note = e.target;87  const noteId = JSON.parse(note.parentElement.getAttribute('data-note')).id;88  // removes deleted note from right column89  if (activeNote.id === noteId) {90    activeNote = {};91  }92  deleteNote(noteId).then(() => {93    getAndRenderNotes();94    renderActiveNote();95  });96};97// Sets the activeNote and displays it98const handleNoteView = (e) => {99  e.preventDefault();100  activeNote = JSON.parse(e.target.getAttribute('data-note'));101  renderActiveNote();102};103// Sets the activeNote to an empty object and allows the user to enter a new note104const handleNewNoteView = (e) => {105  activeNote = {};106  renderActiveNote();107};108// toggles save button on and off109const handleRenderSaveBtn = () => {110  if (!noteTitle.value.trim() || !noteText.value.trim()) {111    hide(saveNoteBtn);112  } else {113    show(saveNoteBtn);114  }115};116// Render the list of note titles117const renderNoteList = async (notes) => {118  let jsonNotes = await notes.json();119  if (window.location.pathname === '/notes') {120    noteList.forEach((el) => (el.innerHTML = ''));121  }122  let noteListItems = [];123  // Returns HTML element with or without a delete button124  const createLi = (text, delBtn = true) => {125    const liEl = document.createElement('li');126    liEl.classList.add('list-group-item');127    liEl.addEventListener('click', handleNoteView);128    const spanEl = document.createElement('span');129    spanEl.innerText = text;130    // spanEl.addEventListener('click', handleNoteView);131    liEl.append(spanEl);132    if (delBtn) {133      const delBtnEl = document.createElement('i');134      delBtnEl.classList.add(135        'fas',136        'fa-trash-alt',137        'float-right',138        'text-danger',139        'delete-note'140      );141      delBtnEl.addEventListener('click', handleNoteDelete);142      liEl.append(delBtnEl);143    }144    return liEl;145  };146  if (jsonNotes.length === 0) {147    noteListItems.push(createLi('No saved Notes', false));148  }149  jsonNotes.forEach((note) => {150    const li = createLi(note.title);151    li.dataset.note = JSON.stringify(note);152    noteListItems.push(li);153  });154  if (window.location.pathname === '/notes') {155    noteListItems.forEach((note) => noteList[0].append(note));156  }157};158// Gets notes from the db and renders them to the sidebar159const getAndRenderNotes = () => getNotes().then(renderNoteList);160if (window.location.pathname === '/notes') {161  saveNoteBtn.addEventListener('click', handleNoteSave);162  newNoteBtn.addEventListener('click', handleNewNoteView);163  noteTitle.addEventListener('keyup', handleRenderSaveBtn);164  noteText.addEventListener('keyup', handleRenderSaveBtn);165}...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!!
