How to use choices method in Kiwi

Best Python code snippet using Kiwi_python

choices_spec.js

Source:choices_spec.js Github

copy

Full Screen

1import 'whatwg-fetch';2import 'es6-promise';3import 'core-js/fn/object/assign';4import Choices from '../../assets/scripts/src/choices.js';5import itemReducer from '../../assets/scripts/src/reducers/items.js';6import choiceReducer from '../../assets/scripts/src/reducers/choices.js';7import {8 addItem as addItemAction,9 addChoice as addChoiceAction10} from '../../assets/scripts/src/actions/index.js';11describe('Choices', () => {12 describe('should initialize Choices', () => {13 beforeEach(function() {14 this.input = document.createElement('input');15 this.input.type = 'text';16 this.input.className = 'js-choices';17 document.body.appendChild(this.input);18 this.choices = new Choices(this.input);19 });20 afterEach(function() {21 this.choices.destroy();22 });23 it('should be defined', function() {24 expect(this.choices).toBeDefined();25 });26 it('should have initialised', function() {27 expect(this.choices.initialised).toBe(true);28 });29 it('should not re-initialise if passed element again', function() {30 const reinitialise = new Choices(this.choices.passedElement);31 spyOn(reinitialise, '_createTemplates');32 expect(reinitialise._createTemplates).not.toHaveBeenCalled();33 });34 it('should have a blank state', function() {35 expect(this.choices.currentState.items.length).toEqual(0);36 expect(this.choices.currentState.groups.length).toEqual(0);37 expect(this.choices.currentState.choices.length).toEqual(0);38 });39 it('should have config options', function() {40 expect(this.choices.config.silent).toEqual(jasmine.any(Boolean));41 expect(this.choices.config.items).toEqual(jasmine.any(Array));42 expect(this.choices.config.choices).toEqual(jasmine.any(Array));43 expect(this.choices.config.renderChoiceLimit).toEqual(jasmine.any(Number));44 expect(this.choices.config.maxItemCount).toEqual(jasmine.any(Number));45 expect(this.choices.config.addItems).toEqual(jasmine.any(Boolean));46 expect(this.choices.config.removeItems).toEqual(jasmine.any(Boolean));47 expect(this.choices.config.removeItemButton).toEqual(jasmine.any(Boolean));48 expect(this.choices.config.editItems).toEqual(jasmine.any(Boolean));49 expect(this.choices.config.duplicateItems).toEqual(jasmine.any(Boolean));50 expect(this.choices.config.delimiter).toEqual(jasmine.any(String));51 expect(this.choices.config.paste).toEqual(jasmine.any(Boolean));52 expect(this.choices.config.searchEnabled).toEqual(jasmine.any(Boolean));53 expect(this.choices.config.searchChoices).toEqual(jasmine.any(Boolean));54 expect(this.choices.config.searchFloor).toEqual(jasmine.any(Number));55 expect(this.choices.config.searchResultLimit).toEqual(jasmine.any(Number));56 expect(this.choices.config.searchFields).toEqual(jasmine.any(Array) || jasmine.any(String));57 expect(this.choices.config.position).toEqual(jasmine.any(String));58 expect(this.choices.config.regexFilter).toEqual(null);59 expect(this.choices.config.sortFilter).toEqual(jasmine.any(Function));60 expect(this.choices.config.shouldSort).toEqual(jasmine.any(Boolean));61 expect(this.choices.config.shouldSortItems).toEqual(jasmine.any(Boolean));62 expect(this.choices.config.placeholder).toEqual(jasmine.any(Boolean));63 expect(this.choices.config.placeholderValue).toEqual(null);64 expect(this.choices.config.searchPlaceholderValue).toEqual(null);65 expect(this.choices.config.prependValue).toEqual(null);66 expect(this.choices.config.appendValue).toEqual(null);67 expect(this.choices.config.renderSelectedChoices).toEqual(jasmine.any(String));68 expect(this.choices.config.loadingText).toEqual(jasmine.any(String));69 expect(this.choices.config.noResultsText).toEqual(jasmine.any(String));70 expect(this.choices.config.noChoicesText).toEqual(jasmine.any(String));71 expect(this.choices.config.itemSelectText).toEqual(jasmine.any(String));72 expect(this.choices.config.classNames).toEqual(jasmine.any(Object));73 expect(this.choices.config.callbackOnInit).toEqual(null);74 expect(this.choices.config.callbackOnCreateTemplates).toEqual(null);75 });76 it('should expose public methods', function() {77 expect(this.choices.init).toEqual(jasmine.any(Function));78 expect(this.choices.destroy).toEqual(jasmine.any(Function));79 expect(this.choices.render).toEqual(jasmine.any(Function));80 expect(this.choices.renderGroups).toEqual(jasmine.any(Function));81 expect(this.choices.renderItems).toEqual(jasmine.any(Function));82 expect(this.choices.renderChoices).toEqual(jasmine.any(Function));83 expect(this.choices.highlightItem).toEqual(jasmine.any(Function));84 expect(this.choices.unhighlightItem).toEqual(jasmine.any(Function));85 expect(this.choices.highlightAll).toEqual(jasmine.any(Function));86 expect(this.choices.unhighlightAll).toEqual(jasmine.any(Function));87 expect(this.choices.removeItemsByValue).toEqual(jasmine.any(Function));88 expect(this.choices.removeActiveItems).toEqual(jasmine.any(Function));89 expect(this.choices.removeHighlightedItems).toEqual(jasmine.any(Function));90 expect(this.choices.showDropdown).toEqual(jasmine.any(Function));91 expect(this.choices.hideDropdown).toEqual(jasmine.any(Function));92 expect(this.choices.toggleDropdown).toEqual(jasmine.any(Function));93 expect(this.choices.getValue).toEqual(jasmine.any(Function));94 expect(this.choices.setValue).toEqual(jasmine.any(Function));95 expect(this.choices.setValueByChoice).toEqual(jasmine.any(Function));96 expect(this.choices.setChoices).toEqual(jasmine.any(Function));97 expect(this.choices.disable).toEqual(jasmine.any(Function));98 expect(this.choices.enable).toEqual(jasmine.any(Function));99 expect(this.choices.ajax).toEqual(jasmine.any(Function));100 expect(this.choices.clearStore).toEqual(jasmine.any(Function));101 expect(this.choices.clearInput).toEqual(jasmine.any(Function));102 });103 it('should hide passed input', function() {104 expect(this.choices.passedElement.style.display).toEqual('none');105 });106 it('should create an outer container', function() {107 expect(this.choices.containerOuter).toEqual(jasmine.any(HTMLElement));108 });109 it('should create an inner container', function() {110 expect(this.choices.containerInner).toEqual(jasmine.any(HTMLElement));111 });112 it('should create a choice list', function() {113 expect(this.choices.choiceList).toEqual(jasmine.any(HTMLElement));114 });115 it('should create an item list', function() {116 expect(this.choices.itemList).toEqual(jasmine.any(HTMLElement));117 });118 it('should create an input', function() {119 expect(this.choices.input).toEqual(jasmine.any(HTMLElement));120 });121 it('should create a dropdown', function() {122 expect(this.choices.dropdown).toEqual(jasmine.any(HTMLElement));123 });124 it('should backup and recover original styles', function () {125 const origStyle = 'background-color: #ccc; margin: 5px padding: 10px;';126 this.choices.destroy();127 this.input.setAttribute('style', origStyle);128 this.choices = new Choices(this.input);129 let style = this.input.getAttribute('data-choice-orig-style');130 expect(style).toEqual(origStyle);131 this.choices.destroy();132 style = this.input.getAttribute('data-choice-orig-style');133 expect(style).toBeNull();134 style = this.input.getAttribute('style');135 expect(style).toEqual(origStyle);136 });137 });138 describe('should accept text inputs', function() {139 beforeEach(function() {140 this.input = document.createElement('input');141 this.input.type = 'text';142 this.input.className = 'js-choices';143 this.input.placeholder = 'Placeholder text';144 document.body.appendChild(this.input);145 });146 afterEach(function() {147 this.choices.destroy();148 });149 it('should apply placeholderValue to input', function() {150 this.choices = new Choices(this.input);151 expect(this.choices.input.placeholder).toEqual('Placeholder text');152 });153 it('should not apply searchPlaceholderValue to input', function() {154 this.choices = new Choices(this.input);155 expect(this.choices.input.placeholder).not.toEqual('Test');156 });157 it('should accept a user inputted value', function() {158 this.choices = new Choices(this.input);159 this.choices.input.focus();160 this.choices.input.value = 'test';161 this.choices._onKeyDown({162 target: this.choices.input,163 keyCode: 13,164 ctrlKey: false165 });166 expect(this.choices.currentState.items[0].value).toContain(this.choices.input.value);167 });168 it('should copy the passed placeholder to the cloned input', function() {169 this.choices = new Choices(this.input);170 expect(this.choices.input.placeholder).toEqual(this.input.placeholder);171 });172 it('should not allow duplicates if duplicateItems is false', function() {173 this.choices = new Choices(this.input, {174 duplicateItems: false,175 items: ['test 1'],176 });177 this.choices.input.focus();178 this.choices.input.value = 'test 1';179 this.choices._onKeyDown({180 target: this.choices.input,181 keyCode: 13,182 ctrlKey: false183 });184 expect(this.choices.currentState.items[this.choices.currentState.items.length - 1]).not.toContain(this.choices.input.value);185 });186 it('should filter input if regexFilter is passed', function() {187 this.choices = new Choices(this.input, {188 regexFilter: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,189 });190 this.choices.input.focus();191 this.choices.input.value = 'josh@joshuajohnson.co.uk';192 this.choices._onKeyDown({193 target: this.choices.input,194 keyCode: 13,195 ctrlKey: false196 });197 this.choices.input.focus();198 this.choices.input.value = 'not an email address';199 this.choices._onKeyDown({200 target: this.choices.input,201 keyCode: 13,202 ctrlKey: false203 });204 const lastItem = this.choices.currentState.items[this.choices.currentState.items.length - 1];205 expect(lastItem.value).toEqual('josh@joshuajohnson.co.uk');206 expect(lastItem.value).not.toEqual('not an email address');207 });208 it('should prepend and append values if passed', function() {209 this.choices = new Choices(this.input, {210 prependValue: 'item-',211 appendValue: '-value',212 });213 this.choices.input.focus();214 this.choices.input.value = 'test';215 this.choices._onKeyDown({216 target: this.choices.input,217 keyCode: 13,218 ctrlKey: false219 });220 const lastItem = this.choices.currentState.items[this.choices.currentState.items.length - 1];221 expect(lastItem.value).not.toEqual('test');222 expect(lastItem.value).toEqual('item-test-value');223 });224 });225 describe('should accept single select inputs', function() {226 beforeEach(function() {227 this.input = document.createElement('select');228 this.input.className = 'js-choices';229 this.input.placeholder = 'Placeholder text';230 for (let i = 1; i < 4; i++) {231 const option = document.createElement('option');232 option.value = `Value ${i}`;233 option.innerHTML = `Label ${i}`;234 this.input.appendChild(option);235 }236 document.body.appendChild(this.input);237 });238 afterEach(function() {239 this.choices.destroy();240 });241 it('should not apply placeholderValue to input', function() {242 this.choices = new Choices(this.input, {243 placeholderValue: 'Placeholder'244 });245 expect(this.choices.input.placeholder).not.toEqual('Placeholder');246 });247 it('should apply searchPlaceholderValue to input', function() {248 this.choices = new Choices(this.input, {249 searchPlaceholderValue: 'Placeholder'250 });251 expect(this.choices.input.placeholder).toEqual('Placeholder');252 });253 it('should open the choice list on focusing', function() {254 this.choices = new Choices(this.input);255 this.choices.input.focus();256 expect(this.choices.dropdown.classList).toContain(this.choices.config.classNames.activeState);257 });258 it('should select the first choice', function() {259 this.choices = new Choices(this.input);260 expect(this.choices.currentState.items[0].value).toContain('Value 1');261 });262 it('should highlight the choices on keydown', function() {263 this.choices = new Choices(this.input, {264 renderChoiceLimit: -1265 });266 this.choices.input.focus();267 for (let i = 0; i < 2; i++) {268 // Key down to third choice269 this.choices._onKeyDown({270 target: this.choices.input,271 keyCode: 40,272 ctrlKey: false,273 preventDefault: () => {}274 });275 }276 expect(this.choices.highlightPosition).toBe(2);277 });278 it('should select choice on enter key press', function() {279 this.choices = new Choices(this.input);280 this.choices.input.focus();281 // Key down to second choice282 this.choices._onKeyDown({283 target: this.choices.input,284 keyCode: 40,285 ctrlKey: false,286 preventDefault: () => {}287 });288 // Key down to select choice289 this.choices._onKeyDown({290 target: this.choices.input,291 keyCode: 13,292 ctrlKey: false,293 preventDefault: () => {}294 });295 expect(this.choices.currentState.items.length).toBe(2);296 });297 it('should trigger add/change event on selection', function() {298 this.choices = new Choices(this.input);299 const changeSpy = jasmine.createSpy('changeSpy');300 const addSpy = jasmine.createSpy('addSpy');301 const passedElement = this.choices.passedElement;302 passedElement.addEventListener('change', changeSpy);303 passedElement.addEventListener('addItem', addSpy);304 this.choices.input.focus();305 // Key down to second choice306 this.choices._onKeyDown({307 target: this.choices.input,308 keyCode: 40,309 ctrlKey: false,310 preventDefault: () => {}311 });312 // Key down to select choice313 this.choices._onKeyDown({314 target: this.choices.input,315 keyCode: 13,316 ctrlKey: false,317 preventDefault: () => {}318 });319 const returnValue = changeSpy.calls.mostRecent().args[0].detail.value;320 expect(returnValue).toEqual(jasmine.any(String));321 expect(changeSpy).toHaveBeenCalled();322 expect(addSpy).toHaveBeenCalled();323 });324 it('should open the dropdown on click', function() {325 this.choices = new Choices(this.input);326 const container = this.choices.containerOuter;327 this.choices._onClick({328 target: container,329 ctrlKey: false,330 preventDefault: () => {}331 });332 expect(document.activeElement === this.choices.input && container.classList.contains('is-open')).toBe(true);333 });334 it('should close the dropdown on double click', function() {335 this.choices = new Choices(this.input);336 const container = this.choices.containerOuter;337 const openState = this.choices.config.classNames.openState;338 this.choices._onClick({339 target: container,340 ctrlKey: false,341 preventDefault: () => {}342 });343 this.choices._onClick({344 target: container,345 ctrlKey: false,346 preventDefault: () => {}347 });348 expect(document.activeElement === this.choices.input && container.classList.contains(openState)).toBe(false);349 });350 it('should set scrolling flag and not hide dropdown when scrolling on IE', function() {351 this.choices = new Choices(this.input);352 this.choices.isIe11 = true;353 spyOn(this.choices, 'hideDropdown');354 const container = this.choices.containerOuter;355 const choiceList = this.choices.choiceList;356 // Click to open dropdown357 this.choices._onClick({358 target: container,359 ctrlKey: false,360 preventDefault: () => {}361 });362 // Hold mouse on scrollbar363 this.choices._onMouseDown({364 target: choiceList,365 ctrlKey: false,366 preventDefault: () => {}367 });368 expect(this.choices.isScrollingOnIe).toBe(true);369 expect(this.choices.hideDropdown).not.toHaveBeenCalled();370 });371 it('should trigger showDropdown on dropdown opening', function() {372 this.choices = new Choices(this.input);373 const container = this.choices.containerOuter;374 const showDropdownSpy = jasmine.createSpy('showDropdownSpy');375 const passedElement = this.choices.passedElement;376 passedElement.addEventListener('showDropdown', showDropdownSpy);377 this.choices.input.focus();378 this.choices._onClick({379 target: container,380 ctrlKey: false,381 preventDefault: () => {}382 });383 expect(showDropdownSpy).toHaveBeenCalled();384 });385 it('should trigger hideDropdown on dropdown closing', function() {386 this.choices = new Choices(this.input);387 const container = this.choices.containerOuter;388 const hideDropdownSpy = jasmine.createSpy('hideDropdownSpy');389 const passedElement = this.choices.passedElement;390 passedElement.addEventListener('hideDropdown', hideDropdownSpy);391 this.choices.input.focus();392 this.choices._onClick({393 target: container,394 ctrlKey: false,395 preventDefault: () => {}396 });397 this.choices._onClick({398 target: container,399 ctrlKey: false,400 preventDefault: () => {}401 });402 expect(hideDropdownSpy).toHaveBeenCalled();403 });404 it('should filter choices when searching', function() {405 this.choices = new Choices(this.input);406 const searchSpy = jasmine.createSpy('searchSpy');407 const passedElement = this.choices.passedElement;408 passedElement.addEventListener('search', searchSpy);409 this.choices.input.focus();410 this.choices.input.value = '3 ';411 // Key down to search412 this.choices._onKeyUp({413 target: this.choices.input,414 keyCode: 13,415 ctrlKey: false416 });417 const mostAccurateResult = this.choices.currentState.choices.filter(function (choice) {418 return choice.active;419 });420 expect(this.choices.isSearching && mostAccurateResult[0].value === 'Value 3').toBe(true);421 expect(searchSpy).toHaveBeenCalled();422 });423 it('shouldn\'t filter choices when searching', function() {424 this.choices = new Choices(this.input, {425 searchChoices: false426 });427 this.choices.setValue(['Javascript', 'HTML', 'Jasmine']);428 const searchSpy = jasmine.createSpy('searchSpy');429 const passedElement = this.choices.passedElement;430 passedElement.addEventListener('search', searchSpy);431 this.choices.input.focus();432 this.choices.input.value = 'Javascript';433 // Key down to search434 this.choices._onKeyUp({435 target: this.choices.input,436 keyCode: 13,437 ctrlKey: false438 });439 const activeOptions = this.choices.currentState.choices.filter(function(choice) {440 return choice.active;441 });442 expect(activeOptions.length).toEqual(this.choices.currentState.choices.length);443 expect(searchSpy).toHaveBeenCalled();444 });445 it('shouldn\'t sort choices if shouldSort is false', function() {446 this.choices = new Choices(this.input, {447 shouldSort: false,448 choices: [{449 value: 'Value 5',450 label: 'Label Five'451 }, {452 value: 'Value 6',453 label: 'Label Six'454 }, {455 value: 'Value 7',456 label: 'Label Seven'457 }, ],458 });459 expect(this.choices.currentState.choices[0].value).toEqual('Value 5');460 });461 it('should sort choices if shouldSort is true', function() {462 this.choices = new Choices(this.input, {463 shouldSort: true,464 choices: [{465 value: 'Value 5',466 label: 'Label Five'467 }, {468 value: 'Value 6',469 label: 'Label Six'470 }, {471 value: 'Value 7',472 label: 'Label Seven'473 }, ],474 });475 expect(this.choices.currentState.choices[0].value).toEqual('Value 1');476 });477 it('should set searchPlaceholderValue if set', function() {478 const dummyPlaceholder = 'Test placeholder';479 this.choices = new Choices(this.input, {480 searchPlaceholderValue: dummyPlaceholder481 });482 expect(this.choices.input.placeholder).toEqual(dummyPlaceholder);483 });484 });485 describe('should accept multiple select inputs', function() {486 beforeEach(function() {487 this.input = document.createElement('select');488 this.input.className = 'js-choices';489 this.input.setAttribute('multiple', '');490 for (let i = 1; i < 4; i++) {491 const option = document.createElement('option');492 option.value = `Value ${i}`;493 option.innerHTML = `Value ${i}`;494 if (i % 2) {495 option.selected = true;496 }497 this.input.appendChild(option);498 }499 document.body.appendChild(this.input);500 this.choices = new Choices(this.input, {501 placeholderValue: 'Placeholder text',502 searchPlaceholderValue: 'Test',503 choices: [{504 value: 'One',505 label: 'Label One',506 selected: true,507 disabled: false508 }, {509 value: 'Two',510 label: 'Label Two',511 disabled: true512 }, {513 value: 'Three',514 label: 'Label Three'515 }, ],516 });517 });518 afterEach(function() {519 this.choices.destroy();520 });521 it('should apply placeholderValue to input', function() {522 expect(this.choices.input.placeholder).toEqual('Placeholder text');523 });524 it('should not apply searchPlaceholderValue to input', function() {525 expect(this.choices.input.placeholder).not.toEqual('Test');526 });527 it('should add any pre-defined values', function() {528 expect(this.choices.currentState.items.length).toBeGreaterThan(1);529 });530 it('should add options defined in the config + pre-defined options', function() {531 expect(this.choices.currentState.choices.length).toEqual(6);532 });533 it('should add a placeholder defined in the config to the search input', function() {534 expect(this.choices.input.placeholder).toEqual('Placeholder text');535 });536 });537 describe('should handle public methods on select input types', function() {538 beforeEach(function() {539 this.input = document.createElement('select');540 this.input.className = 'js-choices';541 this.input.multiple = true;542 this.input.placeholder = 'Placeholder text';543 for (let i = 1; i < 10; i++) {544 const option = document.createElement('option');545 option.value = `Value ${i}`;546 option.innerHTML = `Value ${i}`;547 if (i % 2) {548 option.selected = true;549 }550 this.input.appendChild(option);551 }552 document.body.appendChild(this.input);553 this.choices = new Choices(this.input);554 });555 afterEach(function() {556 this.choices.destroy();557 });558 it('should handle highlightItem()', function() {559 const items = this.choices.currentState.items;560 const randomItem = items[Math.floor(Math.random() * items.length)];561 this.choices.highlightItem(randomItem);562 expect(randomItem.highlighted).toBe(true);563 });564 it('should handle unhighlightItem()', function() {565 const items = this.choices.currentState.items;566 const randomItem = items[Math.floor(Math.random() * items.length)];567 this.choices.unhighlightItem(randomItem);568 expect(randomItem.highlighted).toBe(false);569 });570 it('should handle highlightAll()', function() {571 const items = this.choices.currentState.items;572 this.choices.highlightAll();573 const unhighlightedItems = items.some((item) => item.highlighted === false);574 expect(unhighlightedItems).toBe(false);575 });576 it('should handle unhighlightAll()', function() {577 const items = this.choices.currentState.items;578 this.choices.unhighlightAll();579 const highlightedItems = items.some((item) => item.highlighted === true);580 expect(highlightedItems).toBe(false);581 });582 it('should handle removeHighlightedItems()', function() {583 const items = this.choices.currentState.items;584 this.choices.highlightAll();585 this.choices.removeHighlightedItems();586 const activeItems = items.some((item) => item.active === true);587 expect(activeItems).toBe(false);588 });589 it('should handle showDropdown()', function() {590 this.choices.showDropdown();591 const hasOpenState = this.choices.containerOuter.classList.contains(this.choices.config.classNames.openState);592 const hasAttr = this.choices.containerOuter.getAttribute('aria-expanded') === 'true';593 const hasActiveState = this.choices.dropdown.classList.contains(this.choices.config.classNames.activeState);594 expect(hasOpenState && hasAttr && hasActiveState).toBe(true);595 });596 it('should handle hideDropdown()', function() {597 this.choices.showDropdown();598 this.choices.hideDropdown();599 const hasOpenState = this.choices.containerOuter.classList.contains(this.choices.config.classNames.openState);600 const hasAttr = this.choices.containerOuter.getAttribute('aria-expanded') === 'true';601 const hasActiveState = this.choices.dropdown.classList.contains(this.choices.config.classNames.activeState);602 expect(hasOpenState && hasAttr && hasActiveState).toBe(false);603 });604 it('should handle toggleDropdown()', function() {605 spyOn(this.choices, 'hideDropdown');606 this.choices.showDropdown();607 this.choices.toggleDropdown();608 expect(this.choices.hideDropdown).toHaveBeenCalled();609 });610 it('should handle hideDropdown()', function() {611 this.choices.showDropdown();612 expect(this.choices.containerOuter.classList).toContain(this.choices.config.classNames.openState);613 });614 it('should handle getValue()', function() {615 const valueObjects = this.choices.getValue();616 const valueStrings = this.choices.getValue(true);617 expect(valueStrings[0]).toEqual(jasmine.any(String));618 expect(valueObjects[0]).toEqual(jasmine.any(Object));619 expect(valueObjects).toEqual(jasmine.any(Array));620 expect(valueObjects.length).toEqual(5);621 });622 it('should handle setValue()', function() {623 this.choices.setValue(['Set value 1', 'Set value 2', 'Set value 3']);624 const valueStrings = this.choices.getValue(true);625 expect(valueStrings[valueStrings.length - 1]).toBe('Set value 3');626 expect(valueStrings[valueStrings.length - 2]).toBe('Set value 2');627 expect(valueStrings[valueStrings.length - 3]).toBe('Set value 1');628 });629 it('should handle setValueByChoice()', function() {630 const choices = this.choices.store.getChoicesFilteredByActive();631 const randomChoice = choices[Math.floor(Math.random() * choices.length)];632 this.choices.highlightAll();633 this.choices.removeHighlightedItems();634 this.choices.setValueByChoice(randomChoice.value);635 const value = this.choices.getValue(true);636 expect(value[0]).toBe(randomChoice.value);637 });638 it('should handle setChoices()', function() {639 this.choices.setChoices([{640 label: 'Group one',641 id: 1,642 disabled: false,643 choices: [{644 value: 'Child One',645 label: 'Child One',646 selected: true647 }, {648 value: 'Child Two',649 label: 'Child Two',650 disabled: true651 }, {652 value: 'Child Three',653 label: 'Child Three'654 }, ]655 }, {656 label: 'Group two',657 id: 2,658 disabled: false,659 choices: [{660 value: 'Child Four',661 label: 'Child Four',662 disabled: true663 }, {664 value: 'Child Five',665 label: 'Child Five'666 }, {667 value: 'Child Six',668 label: 'Child Six'669 }, ]670 }], 'value', 'label');671 const groups = this.choices.currentState.groups;672 const choices = this.choices.currentState.choices;673 expect(groups[groups.length - 1].value).toEqual('Group two');674 expect(groups[groups.length - 2].value).toEqual('Group one');675 expect(choices[choices.length - 1].value).toEqual('Child Six');676 expect(choices[choices.length - 2].value).toEqual('Child Five');677 });678 it('should handle setChoices() with blank values', function() {679 this.choices.setChoices([{680 label: 'Choice one',681 value: 'one'682 }, {683 label: 'Choice two',684 value: ''685 }], 'value', 'label', true);686 const choices = this.choices.currentState.choices;687 expect(choices[0].value).toEqual('one');688 expect(choices[1].value).toEqual('');689 });690 it('should handle clearStore()', function() {691 this.choices.clearStore();692 expect(this.choices.currentState.items).toEqual([]);693 expect(this.choices.currentState.choices).toEqual([]);694 expect(this.choices.currentState.groups).toEqual([]);695 });696 it('should handle disable()', function() {697 this.choices.disable();698 expect(this.choices.input.disabled).toBe(true);699 expect(this.choices.containerOuter.classList.contains(this.choices.config.classNames.disabledState)).toBe(true);700 expect(this.choices.containerOuter.getAttribute('aria-disabled')).toBe('true');701 });702 it('should handle enable()', function() {703 this.choices.enable();704 expect(this.choices.input.disabled).toBe(false);705 expect(this.choices.containerOuter.classList.contains(this.choices.config.classNames.disabledState)).toBe(false);706 expect(this.choices.containerOuter.hasAttribute('aria-disabled')).toBe(false);707 });708 it('should handle ajax()', function() {709 spyOn(this.choices, 'ajax');710 this.choices.ajax((callback) => {711 fetch('https://restcountries.eu/rest/v1/all')712 .then((response) => {713 response.json().then((data) => {714 callback(data, 'alpha2Code', 'name');715 });716 })717 .catch((error) => {718 console.log(error);719 });720 });721 expect(this.choices.ajax).toHaveBeenCalledWith(jasmine.any(Function));722 });723 });724 describe('should handle public methods on select-one input types', function() {725 beforeEach(function() {726 this.input = document.createElement('select');727 this.input.className = 'js-choices';728 this.input.placeholder = 'Placeholder text';729 for (let i = 1; i < 10; i++) {730 const option = document.createElement('option');731 option.value = `Value ${i}`;732 option.innerHTML = `Value ${i}`;733 if (i % 2) {734 option.selected = true;735 }736 this.input.appendChild(option);737 }738 document.body.appendChild(this.input);739 this.choices = new Choices(this.input);740 });741 afterEach(function() {742 this.choices.destroy();743 });744 it('should handle disable()', function() {745 this.choices.disable();746 expect(this.choices.containerOuter.getAttribute('tabindex')).toBe('-1');747 });748 it('should handle enable()', function() {749 this.choices.enable();750 expect(this.choices.containerOuter.getAttribute('tabindex')).toBe('0');751 });752 });753 describe('should handle public methods on text input types', function() {754 beforeEach(function() {755 this.input = document.createElement('input');756 this.input.type = 'text';757 this.input.className = 'js-choices';758 this.input.value = 'Value 1, Value 2, Value 3, Value 4';759 document.body.appendChild(this.input);760 this.choices = new Choices(this.input);761 });762 afterEach(function() {763 this.choices.destroy();764 });765 it('should handle clearInput()', function() {766 this.choices.clearInput();767 expect(this.choices.input.value).toBe('');768 });769 it('should handle removeItemsByValue()', function() {770 const items = this.choices.currentState.items;771 const randomItem = items[Math.floor(Math.random() * items.length)];772 this.choices.removeItemsByValue(randomItem.value);773 expect(randomItem.active).toBe(false);774 });775 });776 describe('should react to config options', function() {777 beforeEach(function() {778 this.input = document.createElement('select');779 this.input.className = 'js-choices';780 this.input.setAttribute('multiple', '');781 for (let i = 1; i < 4; i++) {782 const option = document.createElement('option');783 option.value = `Value ${i}`;784 option.innerHTML = `Value ${i}`;785 if (i % 2) {786 option.selected = true;787 }788 this.input.appendChild(option);789 }790 document.body.appendChild(this.input);791 });792 afterEach(function() {793 this.choices.destroy();794 });795 it('should flip the dropdown', function() {796 this.choices = new Choices(this.input, {797 position: 'top',798 });799 const container = this.choices.containerOuter;800 this.choices.input.focus();801 expect(container.classList.contains(this.choices.config.classNames.flippedState)).toBe(true);802 });803 it('shouldn\'t flip the dropdown', function() {804 this.choices = new Choices(this.input, {805 position: 'bottom'806 });807 const container = this.choices.containerOuter;808 this.choices.input.focus();809 expect(container.classList.contains(this.choices.config.classNames.flippedState)).toBe(false);810 });811 it('should render selected choices', function() {812 this.choices = new Choices(this.input, {813 renderSelectedChoices: 'always',814 renderChoiceLimit: -1815 });816 const renderedChoices = this.choices.choiceList.querySelectorAll('.choices__item');817 expect(renderedChoices.length).toEqual(3);818 });819 it('shouldn\'t render selected choices', function() {820 this.choices = new Choices(this.input, {821 renderSelectedChoices: 'auto',822 renderChoiceLimit: -1823 });824 const renderedChoices = this.choices.choiceList.querySelectorAll('.choices__item');825 expect(renderedChoices.length).toEqual(1);826 });827 it('shouldn\'t render choices up to a render limit', function() {828 // Remove existing choices (to make test simpler)829 while (this.input.firstChild) {830 this.input.removeChild(this.input.firstChild);831 }832 this.choices = new Choices(this.input, {833 choices: [834 {835 value: 'Option 1',836 selected: false,837 },838 {839 value: 'Option 2',840 selected: false,841 },842 {843 value: 'Option 3',844 selected: false,845 },846 {847 value: 'Option 4',848 selected: false,849 },850 {851 value: 'Option 5',852 selected: false,853 },854 ],855 renderSelectedChoices: 'auto',856 renderChoiceLimit: 4857 });858 const renderedChoices = this.choices.choiceList.querySelectorAll('.choices__item');859 expect(renderedChoices.length).toEqual(4);860 });861 });862 describe('should allow custom properties provided by the user on items or choices', function() {863 it('should allow the user to supply custom properties for an item', function() {864 const randomItem = {865 id: 8999,866 choiceId: 9000,867 groupId: 9001,868 value: 'value',869 label: 'label',870 customProperties: {871 foo: 'bar'872 },873 placeholder: false,874 keyCode: null875 };876 const expectedState = [{877 id: randomItem.id,878 choiceId: randomItem.choiceId,879 groupId: randomItem.groupId,880 value: randomItem.value,881 label: randomItem.label,882 active: true,883 highlighted: false,884 customProperties: randomItem.customProperties,885 placeholder: false,886 keyCode: randomItem.keyCode887 }];888 const action = addItemAction(889 randomItem.value,890 randomItem.label,891 randomItem.id,892 randomItem.choiceId,893 randomItem.groupId,894 randomItem.customProperties,895 randomItem.keyCode896 );897 expect(itemReducer([], action)).toEqual(expectedState);898 });899 it('should allow the user to supply custom properties for a choice', function() {900 const randomChoice = {901 id: 123,902 elementId: 321,903 groupId: 213,904 value: 'value',905 label: 'label',906 disabled: false,907 customProperties: {908 foo: 'bar'909 },910 placeholder: false,911 keyCode: null912 };913 const expectedState = [{914 id: randomChoice.id,915 elementId: randomChoice.elementId,916 groupId: randomChoice.groupId,917 value: randomChoice.value,918 label: randomChoice.label,919 disabled: randomChoice.disabled,920 selected: false,921 active: true,922 score: 9999,923 customProperties: randomChoice.customProperties,924 placeholder: randomChoice.placeholder,925 keyCode: randomChoice.keyCode926 }];927 const action = addChoiceAction(928 randomChoice.value,929 randomChoice.label,930 randomChoice.id,931 randomChoice.groupId,932 randomChoice.disabled,933 randomChoice.elementId,934 randomChoice.customProperties,935 randomChoice.keyCode936 );937 expect(choiceReducer([], action)).toEqual(expectedState);938 });939 });940 describe('should allow custom properties provided by the user on items or choices', function() {941 beforeEach(function() {942 this.input = document.createElement('select');943 this.input.className = 'js-choices';944 this.input.setAttribute('multiple', '');945 document.body.appendChild(this.input);946 });947 afterEach(function() {948 this.choices.destroy();949 });950 it('should allow the user to supply custom properties for a choice that will be inherited by the item when the user selects the choice', function() {951 const expectedCustomProperties = {952 isBestOptionEver: true953 };954 this.choices = new Choices(this.input);955 this.choices.setChoices([{956 value: '42',957 label: 'My awesome choice',958 selected: false,959 disabled: false,960 customProperties: expectedCustomProperties961 }], 'value', 'label', true);962 this.choices.setValueByChoice('42');963 const selectedItems = this.choices.getValue();964 expect(selectedItems.length).toBe(1);965 expect(selectedItems[0].customProperties).toBe(expectedCustomProperties);966 });967 it('should allow the user to supply custom properties when directly creating a selected item', function() {968 const expectedCustomProperties = {969 isBestOptionEver: true970 };971 this.choices = new Choices(this.input);972 this.choices.setValue([{973 value: 'bar',974 label: 'foo',975 customProperties: expectedCustomProperties976 }]);977 const selectedItems = this.choices.getValue();978 expect(selectedItems.length).toBe(1);979 expect(selectedItems[0].customProperties).toBe(expectedCustomProperties);980 });981 });...

Full Screen

Full Screen

kii.py

Source:kii.py Github

copy

Full Screen

1from django.contrib.gis.db import models2from django.core.validators import MinValueValidator, MaxValueValidator3from django.utils.translation import ugettext_lazy as _4from .base import (5 NODATA,6 SKIP_CODES,7 YES_NO_CHOICES,8 MAX_YEAR,9 YEAR_CHOICES,10 KII_FREQ_CHOICES,11 MinValueBCValidator,12 MaxValueBCValidator,13 BaseModel,14 MonitoringStaff,15 Settlement,16)17from .fgd import FGD18class KIISurveyVersion(BaseModel):19 version = models.CharField(max_length=255)20 notes = models.TextField(blank=True)21 class Meta:22 ordering = ("id",)23 def __str__(self):24 return self.version25class KII(BaseModel):26 kiiid = models.IntegerField(primary_key=True)27 settlement = models.ForeignKey(Settlement, on_delete=models.PROTECT)28 kiicode = models.TextField(default=str(NODATA[0]))29 fgd = models.ForeignKey(FGD, on_delete=models.SET_NULL, null=True, blank=True)30 keyinformantrole = models.CharField(max_length=255, default=str(NODATA[0]))31 primaryinterviewer = models.ForeignKey(32 MonitoringStaff, on_delete=models.PROTECT, related_name="kii_primaryinterviewer"33 )34 secondaryinterviewer = models.ForeignKey(35 MonitoringStaff,36 on_delete=models.PROTECT,37 related_name="kii_secondaryinterviewer",38 default=NODATA[0],39 )40 kiidate = models.DateField(blank=True, null=True)41 kiiday = models.PositiveSmallIntegerField(42 validators=[MinValueValidator(1), MinValueValidator(31)],43 null=True,44 blank=True45 )46 kiimonth = models.PositiveSmallIntegerField(47 validators=[MinValueValidator(1), MinValueValidator(12)],48 null=True,49 blank=True50 )51 kiiyear = models.PositiveSmallIntegerField(52 choices=YEAR_CHOICES,53 validators=[MinValueBCValidator(2000), MaxValueBCValidator(MAX_YEAR)],54 null=True,55 blank=True56 )57 yearmonitoring = models.PositiveSmallIntegerField(58 choices=YEAR_CHOICES,59 validators=[MinValueBCValidator(2000), MaxValueBCValidator(MAX_YEAR)],60 default=NODATA[0],61 )62 starttime = models.TimeField(blank=True, null=True)63 endtime = models.TimeField(blank=True, null=True)64 kiiversion = models.ForeignKey(KIISurveyVersion, on_delete=models.PROTECT)65 mpahistoryl = models.TextField(default=str(NODATA[0]))66 mpahistory = models.TextField(default=str(NODATA[0]))67 pilotnzones = models.PositiveSmallIntegerField(default=NODATA[0])68 ecozone = models.PositiveSmallIntegerField(69 choices=YES_NO_CHOICES, default=NODATA[0]70 )71 soczone = models.PositiveSmallIntegerField(72 choices=YES_NO_CHOICES, default=NODATA[0]73 )74 druleeco = models.PositiveSmallIntegerField(75 choices=KII_FREQ_CHOICES, default=NODATA[0]76 )77 drulesoc = models.PositiveSmallIntegerField(78 choices=KII_FREQ_CHOICES, default=NODATA[0]79 )80 pilotnestedness = models.CharField(max_length=255, default=str(NODATA[0]))81 rulecomml = models.TextField(default=str(NODATA[0]))82 rulecomm = models.TextField(default=str(NODATA[0]))83 ruleawarel = models.TextField(default=str(NODATA[0]))84 ruleaware = models.TextField(default=str(NODATA[0]))85 rulepracticel = models.TextField(default=str(NODATA[0]))86 rulepractice = models.TextField(default=str(NODATA[0]))87 informalrulel = models.TextField(default=str(NODATA[0]))88 informalrule = models.TextField(default=str(NODATA[0]))89 ruleparticipationl = models.TextField(default=str(NODATA[0]))90 ruleparticipation = models.TextField(default=str(NODATA[0]))91 monitorl = models.TextField(default=str(NODATA[0]))92 monitor = models.TextField(default=str(NODATA[0]))93 penverbal = models.PositiveSmallIntegerField(94 choices=YES_NO_CHOICES, default=NODATA[0]95 )96 penwritten = models.PositiveSmallIntegerField(97 choices=YES_NO_CHOICES, default=NODATA[0]98 )99 penaccess = models.PositiveSmallIntegerField(100 choices=YES_NO_CHOICES, default=NODATA[0]101 )102 penequipment = models.PositiveSmallIntegerField(103 choices=YES_NO_CHOICES, default=NODATA[0]104 )105 penfines = models.PositiveSmallIntegerField(106 choices=YES_NO_CHOICES, default=NODATA[0]107 )108 penincarceraton = models.PositiveSmallIntegerField(109 choices=YES_NO_CHOICES, default=NODATA[0]110 )111 penother = models.PositiveSmallIntegerField(112 choices=YES_NO_CHOICES, default=NODATA[0]113 )114 penotherspecifyl = models.CharField(max_length=255, default=str(NODATA[0]))115 penotherspecify = models.CharField(max_length=255, default=str(NODATA[0]))116 penfreq = models.PositiveSmallIntegerField(117 choices=KII_FREQ_CHOICES, default=NODATA[0]118 )119 penprevious = models.PositiveSmallIntegerField(120 choices=YES_NO_CHOICES, default=NODATA[0]121 )122 peneco = models.PositiveSmallIntegerField(choices=YES_NO_CHOICES, default=NODATA[0])123 penecon = models.PositiveSmallIntegerField(124 choices=YES_NO_CHOICES, default=NODATA[0]125 )126 pensoc = models.PositiveSmallIntegerField(choices=YES_NO_CHOICES, default=NODATA[0])127 penwealth = models.PositiveSmallIntegerField(128 choices=YES_NO_CHOICES, default=NODATA[0]129 )130 penpower = models.PositiveSmallIntegerField(131 choices=YES_NO_CHOICES, default=NODATA[0]132 )133 penstatus = models.PositiveSmallIntegerField(134 choices=YES_NO_CHOICES, default=NODATA[0]135 )136 penfactorother = models.PositiveSmallIntegerField(137 choices=YES_NO_CHOICES, default=NODATA[0]138 )139 penfactorotherspecifyl = models.CharField(max_length=255, default=str(NODATA[0]))140 penfactorotherspecify = models.CharField(max_length=255, default=str(NODATA[0]))141 incened = models.PositiveSmallIntegerField(142 choices=YES_NO_CHOICES, default=NODATA[0]143 )144 incenskills = models.PositiveSmallIntegerField(145 choices=YES_NO_CHOICES, default=NODATA[0]146 )147 incenequipment = models.PositiveSmallIntegerField(148 choices=YES_NO_CHOICES, default=NODATA[0]149 )150 incenpurchase = models.PositiveSmallIntegerField(151 choices=YES_NO_CHOICES, default=NODATA[0]152 )153 incenloan = models.PositiveSmallIntegerField(154 choices=YES_NO_CHOICES, default=NODATA[0]155 )156 incenpayment = models.PositiveSmallIntegerField(157 choices=YES_NO_CHOICES, default=NODATA[0]158 )159 incenemploy = models.PositiveSmallIntegerField(160 choices=YES_NO_CHOICES, default=NODATA[0]161 )162 incenother = models.PositiveSmallIntegerField(163 choices=YES_NO_CHOICES, default=NODATA[0]164 )165 incenotherspecifyl = models.CharField(max_length=255, default=str(NODATA[0]))166 incenotherspecify = models.CharField(max_length=255, default=str(NODATA[0]))167 ecomonverbal = models.PositiveSmallIntegerField(168 choices=YES_NO_CHOICES, default=NODATA[0]169 )170 ecomonwritten = models.PositiveSmallIntegerField(171 choices=YES_NO_CHOICES, default=NODATA[0]172 )173 ecomonaccess = models.PositiveSmallIntegerField(174 choices=YES_NO_CHOICES, default=NODATA[0]175 )176 ecomonposition = models.PositiveSmallIntegerField(177 choices=YES_NO_CHOICES, default=NODATA[0]178 )179 ecomonequipment = models.PositiveSmallIntegerField(180 choices=YES_NO_CHOICES, default=NODATA[0]181 )182 ecomonfine = models.PositiveSmallIntegerField(183 choices=YES_NO_CHOICES, default=NODATA[0]184 )185 ecomonincarceration = models.PositiveSmallIntegerField(186 choices=YES_NO_CHOICES, default=NODATA[0]187 )188 ecomonother = models.PositiveSmallIntegerField(189 choices=YES_NO_CHOICES, default=NODATA[0]190 )191 ecomonotherspecifyl = models.CharField(max_length=255, default=str(NODATA[0]))192 ecomonotherspecify = models.CharField(max_length=255, default=str(NODATA[0]))193 socmonverbal = models.PositiveSmallIntegerField(194 choices=YES_NO_CHOICES, default=NODATA[0]195 )196 socmonwritten = models.PositiveSmallIntegerField(197 choices=YES_NO_CHOICES, default=NODATA[0]198 )199 socmonaccess = models.PositiveSmallIntegerField(200 choices=YES_NO_CHOICES, default=NODATA[0]201 )202 socmonposition = models.PositiveSmallIntegerField(203 choices=YES_NO_CHOICES, default=NODATA[0]204 )205 socmonequipment = models.PositiveSmallIntegerField(206 choices=YES_NO_CHOICES, default=NODATA[0]207 )208 socmonfine = models.PositiveSmallIntegerField(209 choices=YES_NO_CHOICES, default=NODATA[0]210 )211 socmonincarceration = models.PositiveSmallIntegerField(212 choices=YES_NO_CHOICES, default=NODATA[0]213 )214 socmonother = models.PositiveSmallIntegerField(215 choices=YES_NO_CHOICES, default=NODATA[0]216 )217 socmonotherspecifyl = models.CharField(max_length=255, default=str(NODATA[0]))218 socmonotherspecify = models.CharField(max_length=255, default=str(NODATA[0]))219 compmonverbal = models.PositiveSmallIntegerField(220 choices=YES_NO_CHOICES, default=NODATA[0]221 )222 compmonwritten = models.PositiveSmallIntegerField(223 choices=YES_NO_CHOICES, default=NODATA[0]224 )225 compmonaccess = models.PositiveSmallIntegerField(226 choices=YES_NO_CHOICES, default=NODATA[0]227 )228 compmonposition = models.PositiveSmallIntegerField(229 choices=YES_NO_CHOICES, default=NODATA[0]230 )231 compmonequipment = models.PositiveSmallIntegerField(232 choices=YES_NO_CHOICES, default=NODATA[0]233 )234 compmonfine = models.PositiveSmallIntegerField(235 choices=YES_NO_CHOICES, default=NODATA[0]236 )237 compmonincarceration = models.PositiveSmallIntegerField(238 choices=YES_NO_CHOICES, default=NODATA[0]239 )240 compmonother = models.PositiveSmallIntegerField(241 choices=YES_NO_CHOICES, default=NODATA[0]242 )243 compmonotherspecifyl = models.CharField(max_length=255, default=str(NODATA[0]))244 compmonotherspecify = models.CharField(max_length=255, default=str(NODATA[0]))245 penmonverbal = models.PositiveSmallIntegerField(246 choices=YES_NO_CHOICES, default=NODATA[0]247 )248 penmonwritten = models.PositiveSmallIntegerField(249 choices=YES_NO_CHOICES, default=NODATA[0]250 )251 penmonaccess = models.PositiveSmallIntegerField(252 choices=YES_NO_CHOICES, default=NODATA[0]253 )254 penmonposition = models.PositiveSmallIntegerField(255 choices=YES_NO_CHOICES, default=NODATA[0]256 )257 penmonequipment = models.PositiveSmallIntegerField(258 choices=YES_NO_CHOICES, default=NODATA[0]259 )260 penmonfine = models.PositiveSmallIntegerField(261 choices=YES_NO_CHOICES, default=NODATA[0]262 )263 penmonincarceration = models.PositiveSmallIntegerField(264 choices=YES_NO_CHOICES, default=NODATA[0]265 )266 penmonother = models.PositiveSmallIntegerField(267 choices=YES_NO_CHOICES, default=NODATA[0]268 )269 penmonotherspecifyl = models.CharField(max_length=255, default=str(NODATA[0]))270 penmonotherspecify = models.CharField(max_length=255, default=str(NODATA[0]))271 conflictresl = models.TextField(default=str(NODATA[0]))272 conflictres = models.TextField(default=str(NODATA[0]))273 ecoimpactl = models.TextField(default=str(NODATA[0]))274 ecoimpact = models.TextField(default=str(NODATA[0]))275 socimpactl = models.TextField(default=str(NODATA[0]))276 socimpact = models.TextField(default=str(NODATA[0]))277 contributionl = models.TextField(default=str(NODATA[0]))278 contribution = models.TextField(default=str(NODATA[0]))279 benefitl = models.TextField(default=str(NODATA[0]))280 benefit = models.TextField(default=str(NODATA[0]))281 ecoimpactcovidl = models.TextField(default=str(NODATA[0]))282 ecoimpactcovid = models.TextField(default=str(NODATA[0]))283 socimpactcovidl = models.TextField(default=str(NODATA[0]))284 socimpactcovid = models.TextField(default=str(NODATA[0]))285 mpaimpactcovidl = models.TextField(default=str(NODATA[0]))286 mpaimpactcovid = models.TextField(default=str(NODATA[0]))287 anyotherinfol = models.TextField(default=str(NODATA[0]))288 anyotherinfo = models.TextField(default=str(NODATA[0]))289 anyotherkil = models.TextField(default=str(NODATA[0]))290 anyotherki = models.TextField(default=str(NODATA[0]))291 anyotherdocsl = models.TextField(default=str(NODATA[0]))292 anyotherdocs = models.TextField(default=str(NODATA[0]))293 notesl = models.TextField(default=str(NODATA[0]))294 notes = models.TextField(default=str(NODATA[0]))295 dataentryid = models.ForeignKey(296 MonitoringStaff,297 on_delete=models.SET_NULL,298 null=True,299 blank=True,300 related_name="kii_staff_data_entry",301 )302 datacheckid = models.ForeignKey(303 MonitoringStaff,304 on_delete=models.SET_NULL,305 null=True,306 blank=True,307 related_name="kii_staff_data_check",308 )309 violationfreq = models.PositiveSmallIntegerField(310 default=NODATA[0], validators=[MinValueBCValidator(1), MaxValueBCValidator(999)]311 )312 @property313 def mpa(self):314 return self.settlement.mpa.mpaid315 class Meta:316 verbose_name = _("KII")317 verbose_name_plural = _("KIIs")318 def __str__(self):319 return str(self.pk)320class HabitatRule(BaseModel):321 habrulesid = models.IntegerField(primary_key=True)322 kii = models.ForeignKey(KII, on_delete=models.PROTECT)323 habnamel = models.CharField(max_length=255, default=str(NODATA[0]))324 habname = models.CharField(max_length=255, default=str(NODATA[0]))325 habrule = models.PositiveSmallIntegerField(326 choices=YES_NO_CHOICES, default=NODATA[0]327 )328 habspecificrulel = models.TextField(default=str(NODATA[0]))329 habspecificrule = models.TextField(default=str(NODATA[0]))330 notes = models.TextField(default=str(NODATA[0]))331 def __str__(self):332 return self.habname333class Right(BaseModel):334 KII_GOVT_SUPPORT_CHOICES = [335 (1, "Sangat menentang / Strongly oppose"),336 (2, "Menentang / Oppose"),337 (3, "Tidak menantang maupan mendukung / Neither oppose nor support"),338 (4, "Mendukung / Support"),339 (5, "Sangat mendukung / Strongly support"),340 ] + SKIP_CODES341 KII_RULE_INCLUDED_CHOICES = [342 (1, "Tidak dimasukkan / Not included"),343 (2, "Dimasukkan sebagian / Partially included"),344 (3, "Dimasukkan semua / Fully included"),345 ] + SKIP_CODES346 rightsid = models.IntegerField(primary_key=True)347 kii = models.ForeignKey(KII, on_delete=models.PROTECT)348 usernamel = models.CharField(max_length=255, default=str(NODATA[0]))349 username = models.CharField(max_length=255, default=str(NODATA[0]))350 userrule = models.PositiveSmallIntegerField(351 choices=YES_NO_CHOICES, default=NODATA[0]352 )353 userspecrulel = models.CharField(max_length=255, default=str(NODATA[0]))354 userspecrule = models.CharField(max_length=255, default=str(NODATA[0]))355 govtsupport = models.PositiveSmallIntegerField(356 choices=KII_GOVT_SUPPORT_CHOICES, default=NODATA[0]357 )358 userrulesinc = models.PositiveSmallIntegerField(359 choices=KII_RULE_INCLUDED_CHOICES, default=NODATA[0]360 )361 notes = models.TextField(default=str(NODATA[0]))362 def __str__(self):363 return self.userrule364class SpeciesRule(BaseModel):365 sppruleid = models.IntegerField(primary_key=True)366 kii = models.ForeignKey(KII, on_delete=models.PROTECT)367 speciescommonl = models.CharField(max_length=255, default=str(NODATA[0]))368 speciescommon = models.CharField(max_length=255, default=str(NODATA[0]))369 family = models.CharField(max_length=255, default=str(NODATA[0]))370 genus = models.CharField(max_length=255, default=str(NODATA[0]))371 species = models.CharField(max_length=255, default=str(NODATA[0]))372 spprule = models.PositiveSmallIntegerField(373 choices=YES_NO_CHOICES, default=NODATA[0]374 )375 sppspecificrulel = models.TextField(default=str(NODATA[0]))376 sppspecificrule = models.TextField(default=str(NODATA[0]))377 notes = models.TextField(default=str(NODATA[0]))378 def __str__(self):379 return self.spprule380class Zone(BaseModel):381 zoneid = models.IntegerField(primary_key=True)382 kii = models.ForeignKey(KII, on_delete=models.PROTECT)383 zonetypel = models.CharField(max_length=255, default=str(NODATA[0]))384 zonetype = models.CharField(max_length=255, default=str(NODATA[0]))385 zonequantity = models.PositiveSmallIntegerField(default=NODATA[0])386 zoneorg = models.CharField(max_length=255, default=str(NODATA[0]))387 zonecoord = models.PositiveSmallIntegerField(388 choices=KII_FREQ_CHOICES, default=NODATA[0]389 )390 notes = models.TextField(default=str(NODATA[0]))391 def __str__(self):...

Full Screen

Full Screen

test_bashcomplete.py

Source:test_bashcomplete.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2import click3from click._bashcomplete import get_choices4def choices_without_help(cli, args, incomplete):5 completions = get_choices(cli, 'dummy', args, incomplete)6 return [c[0] for c in completions]7def choices_with_help(cli, args, incomplete):8 return list(get_choices(cli, 'dummy', args, incomplete))9def test_single_command():10 @click.command()11 @click.option('--local-opt')12 def cli(local_opt):13 pass14 assert choices_without_help(cli, [], '-') == ['--local-opt']15 assert choices_without_help(cli, [], '') == []16def test_boolean_flag():17 @click.command()18 @click.option('--shout/--no-shout', default=False)19 def cli(local_opt):20 pass21 assert choices_without_help(cli, [], '-') == ['--shout', '--no-shout']22def test_multi_value_option():...

Full Screen

Full Screen

tests.py

Source:tests.py Github

copy

Full Screen

...112 cls.empty_choices = Choiceful._meta.get_field('empty_choices')113 cls.empty_choices_bool = Choiceful._meta.get_field('empty_choices_bool')114 cls.empty_choices_text = Choiceful._meta.get_field('empty_choices_text')115 cls.with_choices = Choiceful._meta.get_field('with_choices')116 def test_choices(self):117 self.assertIsNone(self.no_choices.choices)118 self.assertEqual(self.empty_choices.choices, ())119 self.assertEqual(self.with_choices.choices, [(1, 'A')])120 def test_flatchoices(self):121 self.assertEqual(self.no_choices.flatchoices, [])122 self.assertEqual(self.empty_choices.flatchoices, [])123 self.assertEqual(self.with_choices.flatchoices, [(1, 'A')])124 def test_check(self):125 self.assertEqual(Choiceful.check(), [])126 def test_invalid_choice(self):127 model_instance = None # Actual model instance not needed.128 self.no_choices.validate(0, model_instance)129 msg = "['Value 99 is not a valid choice.']"130 with self.assertRaisesMessage(ValidationError, msg):131 self.empty_choices.validate(99, model_instance)132 with self.assertRaisesMessage(ValidationError, msg):133 self.with_choices.validate(99, model_instance)134 def test_formfield(self):135 no_choices_formfield = self.no_choices.formfield()136 self.assertIsInstance(no_choices_formfield, forms.IntegerField)137 fields = (138 self.empty_choices, self.with_choices, self.empty_choices_bool,139 self.empty_choices_text,140 )141 for field in fields:142 with self.subTest(field=field):143 self.assertIsInstance(field.formfield(), forms.ChoiceField)144class GetFieldDisplayTests(SimpleTestCase):145 def test_choices_and_field_display(self):146 """147 get_choices() interacts with get_FIELD_display() to return the expected148 values.149 """150 self.assertEqual(Whiz(c=1).get_c_display(), 'First') # A nested value151 self.assertEqual(Whiz(c=0).get_c_display(), 'Other') # A top level value152 self.assertEqual(Whiz(c=9).get_c_display(), 9) # Invalid value153 self.assertIsNone(Whiz(c=None).get_c_display()) # Blank value154 self.assertEqual(Whiz(c='').get_c_display(), '') # Empty value155 self.assertEqual(WhizDelayed(c=0).get_c_display(), 'Other') # Delayed choices156 def test_get_FIELD_display_translated(self):157 """A translated display value is coerced to str."""158 val = Whiz(c=5).get_c_display()159 self.assertIsInstance(val, str)160 self.assertEqual(val, 'translated')161 def test_overriding_FIELD_display(self):162 class FooBar(models.Model):163 foo_bar = models.IntegerField(choices=[(1, 'foo'), (2, 'bar')])164 def get_foo_bar_display(self):165 return 'something'166 f = FooBar(foo_bar=1)167 self.assertEqual(f.get_foo_bar_display(), 'something')168 def test_overriding_inherited_FIELD_display(self):169 class Base(models.Model):170 foo = models.CharField(max_length=254, choices=[('A', 'Base A')])171 class Meta:172 abstract = True173 class Child(Base):174 foo = models.CharField(max_length=254, choices=[('A', 'Child A'), ('B', 'Child B')])175 self.assertEqual(Child(foo='A').get_foo_display(), 'Child A')176 self.assertEqual(Child(foo='B').get_foo_display(), 'Child B')177 def test_iterator_choices(self):178 """179 get_choices() works with Iterators.180 """181 self.assertEqual(WhizIter(c=1).c, 1) # A nested value182 self.assertEqual(WhizIter(c=9).c, 9) # Invalid value183 self.assertIsNone(WhizIter(c=None).c) # Blank value184 self.assertEqual(WhizIter(c='').c, '') # Empty value185 def test_empty_iterator_choices(self):186 """187 get_choices() works with empty iterators.188 """189 self.assertEqual(WhizIterEmpty(c="a").c, "a") # A nested value190 self.assertEqual(WhizIterEmpty(c="b").c, "b") # Invalid value191 self.assertIsNone(WhizIterEmpty(c=None).c) # Blank value192 self.assertEqual(WhizIterEmpty(c='').c, '') # Empty value193class GetChoicesTests(SimpleTestCase):194 def test_empty_choices(self):195 choices = []196 f = models.CharField(choices=choices)197 self.assertEqual(f.get_choices(include_blank=False), choices)198 def test_blank_in_choices(self):199 choices = [('', '<><>'), ('a', 'A')]200 f = models.CharField(choices=choices)201 self.assertEqual(f.get_choices(include_blank=True), choices)202 def test_blank_in_grouped_choices(self):203 choices = [204 ('f', 'Foo'),205 ('b', 'Bar'),206 ('Group', (207 ('', 'No Preference'),208 ('fg', 'Foo'),209 ('bg', 'Bar'),210 )),211 ]212 f = models.CharField(choices=choices)213 self.assertEqual(f.get_choices(include_blank=True), choices)214 def test_lazy_strings_not_evaluated(self):215 lazy_func = lazy(lambda x: 0 / 0, int) # raises ZeroDivisionError if evaluated.216 f = models.CharField(choices=[(lazy_func('group'), (('a', 'A'), ('b', 'B')))])217 self.assertEqual(f.get_choices(include_blank=True)[0], ('', '---------'))218class GetChoicesOrderingTests(TestCase):219 @classmethod220 def setUpTestData(cls):221 cls.foo1 = Foo.objects.create(a='a', d='12.35')222 cls.foo2 = Foo.objects.create(a='b', d='12.34')223 cls.bar1 = Bar.objects.create(a=cls.foo1, b='b')224 cls.bar2 = Bar.objects.create(a=cls.foo2, b='a')225 cls.field = Bar._meta.get_field('a')226 def assertChoicesEqual(self, choices, objs):227 self.assertEqual(choices, [(obj.pk, str(obj)) for obj in objs])228 def test_get_choices(self):229 self.assertChoicesEqual(230 self.field.get_choices(include_blank=False, ordering=('a',)),231 [self.foo1, self.foo2]232 )233 self.assertChoicesEqual(234 self.field.get_choices(include_blank=False, ordering=('-a',)),235 [self.foo2, self.foo1]236 )237 def test_get_choices_default_ordering(self):238 self.addCleanup(setattr, Foo._meta, 'ordering', Foo._meta.ordering)239 Foo._meta.ordering = ('d',)240 self.assertChoicesEqual(241 self.field.get_choices(include_blank=False),242 [self.foo2, self.foo1]243 )244 def test_get_choices_reverse_related_field(self):245 self.assertChoicesEqual(246 self.field.remote_field.get_choices(include_blank=False, ordering=('a',)),247 [self.bar1, self.bar2]248 )249 self.assertChoicesEqual(250 self.field.remote_field.get_choices(include_blank=False, ordering=('-a',)),251 [self.bar2, self.bar1]252 )253 def test_get_choices_reverse_related_field_default_ordering(self):254 self.addCleanup(setattr, Bar._meta, 'ordering', Bar._meta.ordering)255 Bar._meta.ordering = ('b',)256 self.assertChoicesEqual(257 self.field.remote_field.get_choices(include_blank=False),258 [self.bar2, self.bar1]259 )260class GetChoicesLimitChoicesToTests(TestCase):261 @classmethod262 def setUpTestData(cls):263 cls.foo1 = Foo.objects.create(a='a', d='12.34')264 cls.foo2 = Foo.objects.create(a='b', d='12.34')265 cls.bar1 = Bar.objects.create(a=cls.foo1, b='b')266 cls.bar2 = Bar.objects.create(a=cls.foo2, b='a')267 cls.field = Bar._meta.get_field('a')268 def assertChoicesEqual(self, choices, objs):269 self.assertEqual(choices, [(obj.pk, str(obj)) for obj in objs])270 def test_get_choices(self):271 self.assertChoicesEqual(272 self.field.get_choices(include_blank=False, limit_choices_to={'a': 'a'}),273 [self.foo1],274 )275 self.assertChoicesEqual(276 self.field.get_choices(include_blank=False, limit_choices_to={}),277 [self.foo1, self.foo2],278 )279 def test_get_choices_reverse_related_field(self):280 field = self.field.remote_field281 self.assertChoicesEqual(282 field.get_choices(include_blank=False, limit_choices_to={'b': 'b'}),283 [self.bar1],284 )285 self.assertChoicesEqual(286 field.get_choices(include_blank=False, limit_choices_to={}),287 [self.bar1, self.bar2],...

Full Screen

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Run Kiwi automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful